Compare commits

..

74 Commits

Author SHA1 Message Date
Daniel Volz 8c5deed4c2 feat: theme dropdown with system preference and comprehensive bottle-type fixes (#138)
- Replace dark/light toggle with Light/Dark/System dropdown menu
- System theme follows OS prefers-color-scheme setting
- Apply theme dropdown to shared schedule page
- Fix 7 packageType (bottle) bugs across stock calc, share, refills, export/import
- Fix planner bottle-type stock calculation and display
- Fix dailyRate double-counting with per-intake takenBy
- Fix About modal update check stale caching
- Fix intake reminder past-intake seeding and push title
- Fix phantom DB path in drizzle.config.ts
- Fix mobile dose field visibility
- Make medication name clickable in dashboard reminder bar
- Improve planner checkbox UX with inline tooltip
- Add 20+ new tests covering all fixes
2026-02-08 20:32:40 +01:00
github-actions[bot] b19bcf02c2 chore: update test count badges [skip ci] 2026-02-08 16:32:40 +00:00
Daniel Volz 27a9910dbd chore: release v1.8.8 (#137) 2026-02-08 17:29:37 +01:00
Daniel Volz eb2e445398 fix: correct stock calculation for both manual and automatic modes (#136)
Manual mode: Use takenAt timestamp instead of dose date-only comparison
to correctly distinguish doses taken before vs after stock correction
on the same day. Add polling race condition guard (mutationInFlightRef)
so Take/Undo immediately reflects in dashboard stock.

Automatic mode: Grid-align effectiveStart to the medication schedule
and use hybrid consumed calculation (time-based + early-taken doses)
for accurate stock counting.
2026-02-08 17:27:47 +01:00
Daniel Volz 61b8812808 ci: fix release workflow ordering and remove redundant workflows (#135)
- Tag builds now also set 'latest' Docker tag (fixes race condition where
  main-push build could overwrite latest with older version)
- Remove duplicate release.yml (create-release job in docker-build.yml
  already handles GitHub releases)
- Remove redundant version-bump.yml (release.sh already bumps versions
  in the release PR)
- Change update-test-badges.yml trigger to workflow_run after successful
  docker-build (prevents parallel execution and ensures correct ordering)
- Update agent instructions and CI documentation to reflect changes
2026-02-08 16:57:40 +01:00
Daniel Volz f7838bd919 chore: release v1.8.7 (#134) 2026-02-08 15:14:14 +01:00
github-actions[bot] b0fd3f4187 chore: update test count badges [skip ci] 2026-02-08 14:13:07 +00:00
Daniel Volz b91717fc19 fix: stock correction not working for bottle type and manual calculation mode (#133)
- Fix bottle type: submitStockCorrection used blister formula for baseTotal
  but getMedTotal uses only looseTablets for bottles. Now uses getPackageSize()
  which handles both types correctly.
- Fix manual mode: same-day taken doses were counted as consumed after a stock
  correction (>= comparison with date-only timestamps). Changed to > so doses
  on the correction day are excluded.
- Add agent instruction: only release-manager may create PRs/push/merge.
2026-02-08 15:12:17 +01:00
Daniel Volz a065adcd82 ci: remove redundant test jobs from docker-build workflow (#132)
Tests are already guaranteed by branch protection (test.yml must pass
before PR can be merged to main). Running them again in docker-build.yml
was redundant and slowed down image builds.

This reduces test runs from 3x to 2x per code change:
- test.yml on PR (required by branch protection)
- update-test-badges.yml on main push (needed for badge counts)

Docker image builds now start immediately after merge.
2026-02-08 15:05:33 +01:00
Daniel Volz 6edf2fa341 docs: add rule to keep README.md up to date after code changes (#131) 2026-02-08 14:45:30 +01:00
Daniel Volz 9e3d548536 chore: make release script non-interactive with CI retry logic (#130)
- Remove y/N confirmation prompt for automation
- Add wait_for_ci() with retry logic (polls until checks appear)
- Auto-detect git remote (origin or github)
- Remove unused /etc/nginx/conf.d tmpfs from compose
- Update release-manager agent docs to match
2026-02-08 14:13:11 +01:00
Daniel Volz e55e415a50 chore: release v1.8.6 (#129) 2026-02-08 14:06:03 +01:00
Daniel Volz 5253d14af7 fix: make frontend image self-contained for read-only filesystems (#128)
Revert Dockerfile to use /tmp redirect for envsubst output, so the image
works regardless of docker-compose.yml tmpfs configuration. Removes the
uid=101,gid=101 requirement from compose that was a breaking change.
2026-02-08 14:03:53 +01:00
github-actions[bot] 4f75d78a2b chore: update test count badges [skip ci] 2026-02-08 12:54:19 +00:00
Daniel Volz 8f9b65147b fix: use PAT for badge workflow to bypass branch protection (#127) 2026-02-08 13:53:19 +01:00
Daniel Volz 571ab00918 chore: release v1.8.5 (#126) 2026-02-08 13:35:52 +01:00
Daniel Volz 27f5478dad fix: clean up nginx read-only filesystem approach (#125)
Remove Dockerfile /tmp workaround hacks (NGINX_ENVSUBST_OUTPUT_DIR and sed).
Use tmpfs with uid=101,gid=101 in docker-compose.yml instead, so the
nginx user can write to /etc/nginx/conf.d directly under read_only: true.
2026-02-08 13:33:40 +01:00
Daniel Volz 5cd519be50 chore: release v1.8.4 (#124) 2026-02-08 13:12:58 +01:00
Daniel Volz e0c5eb4bf3 feat: simplify About modal with single version link to GitHub release (#123)
- Replace separate Frontend/Backend versions with single app version
- Version is now a clickable link to the GitHub release page
- Replace stopwatch SVG with actual app logo (favicon.svg)
- Fix update check UX: previous result stays visible during re-check
- Add 1s minimum delay for update check spinner visibility
- Reserve space for update result to prevent modal jumping
- Remove unused i18n keys (frontend/backend)
- Update release-manager docs with version link info
2026-02-08 13:09:33 +01:00
Daniel Volz aa92bcd96d fix: nginx read_only filesystem compatibility for envsubst (#122)
Redirect NGINX_ENVSUBST_OUTPUT_DIR to /tmp and update nginx.conf include
path so envsubst works with read_only: true in docker-compose.
Add tmpfs mount for /etc/nginx/conf.d for additional write layer.
2026-02-08 13:07:21 +01:00
Daniel Volz 1798a608bc fix: badge workflow commits directly instead of creating PRs (#121)
* fix: badge workflow commits directly instead of creating PRs

Replace peter-evans/create-pull-request with direct git push.
Removes need for pull-requests:write permission and the repo setting
'Allow GitHub Actions to create pull requests'.

Uses [skip ci] in commit message to avoid triggering itself.

* chore: trigger CI
2026-02-08 12:25:33 +01:00
Daniel Volz 2ec9db1c13 chore: release v1.8.3 (#120) 2026-02-08 12:09:52 +01:00
Daniel Volz 042f0cfb29 docs: add version files reminder to release manager agent (#119)
Document that both backend/package.json and frontend/package.json
must be updated before tagging a release, since the About modal
reads versions from these files.
2026-02-08 12:06:20 +01:00
Daniel Volz 78a0d3ac8e fix: use dynamic BACKEND_URL for nginx reverse proxy (#118)
Fixes #96

- nginx.conf converted to template processed by envsubst at container start
- BACKEND_URL env var (default: backend:3000) replaces hardcoded container name
- Docker DNS resolver used for dynamic upstream resolution
- Dockerfile copies nginx.conf as template to /etc/nginx/templates/

This prevents frontend breakage when users customize container names
in their docker-compose.yml.
2026-02-08 12:05:43 +01:00
Daniel Volz 7d6664e684 fix: auto-detect data directory in monorepo without DATA_DIR env var (#117)
- getDataDir() now detects monorepo by checking for ../docker-compose.yml
- DATA_DIR env var removed from .env and .env.example (no longer needed for local dev)
- Docker compose files explicitly set DATA_DIR=/app/data for containers
- Updated tests for monorepo detection logic
2026-02-08 12:04:09 +01:00
Daniel Volz 2a84a43654 fix: unify data directory for dev and prod environments (#116)
Add DATA_DIR env var support to configure the data directory path.
All hardcoded resolve(cwd, 'data') paths now use a central getDataDir()
function from db-utils.ts that checks DATA_DIR first, falling back to
resolve(cwd, 'data').

This prevents local dev (cd backend && npm run dev) from creating a
separate backend/data/ directory instead of using the root data/ folder.

Changes:
- Add getDataDir() to db-utils.ts as single source of truth
- Update all 8 source files that reference the data directory
- Add dotenv fallback to ../.env for local dev from backend/
- Add DATA_DIR documentation to .env.example
- Add 7 new tests for getDataDir and getDbPaths with DATA_DIR
- 493 tests pass, TypeScript clean
2026-02-08 11:20:55 +01:00
Daniel Volz 99bb9c3931 fix: backend planner phantom consumption + PUT stock reset (#115)
Two bugs in the backend medications route:

1. Planner /medications/usage had the same +1 phantom consumption bug
   that was fixed in the frontend (PR #109). After a stock correction,
   effectiveStart was set to max(blisterStart, correctionCutoff) instead
   of correctionCutoff + period, causing 1 dose to be immediately
   counted as consumed.

2. PUT /medications/:id did not reset stockAdjustment when stock fields
   (packCount, blistersPerPack, pillsPerBlister, looseTablets) changed.
   If a user edited stock values to correct their inventory, the old
   stockAdjustment offset was preserved, resulting in wrong totals.

Added 4 tests covering both scenarios.
2026-02-08 11:05:56 +01:00
Daniel Volz 6b3a7b4104 fix: prevent tests from creating stale backend/data directory (#112)
Extract DB utility functions (buildDbUrl, getDbPaths, ensureDataDirectory,
runAlterMigrations, etc.) from client.ts into db-utils.ts.

client.ts contained top-level initialization code (ensureDataDirectory,
createClient) that ran on every import. database.test.ts imported utility
functions from client.ts, which triggered the initialization as a side
effect — creating backend/data/ with a .write-test file and
medassist-ng.db every time tests ran.

Now database.test.ts imports from db-utils.ts (side-effect-free), and
client.ts re-exports everything for backward compatibility.
2026-02-07 14:14:10 +01:00
Daniel Volz 2d9cd0ad1a ci: add path filtering to skip unnecessary CI runs (#111)
test.yml: Use dorny/paths-filter to detect changed paths. Backend
tests only run when backend/**, biome.json, or the workflow itself
changes. Frontend build only runs when frontend/**, biome.json, or
the workflow changes. Jobs skipped via job-level 'if:' are treated
as passed by GitHub required checks.

codeql.yml: Only run on push/PR when JS/TS source files, package
files, or CodeQL config changes. Weekly schedule and manual dispatch
remain unfiltered.
2026-02-07 13:37:13 +01:00
Daniel Volz 098a7655a5 chore: add release-manager agent and move release docs (#110)
Create dedicated GitHub Copilot agent for release management with
4 tasks: branch/PR workflow, version determination, release execution,
and release notes writing.

Move release-specific instructions (workflow, release notes format,
breaking changes) from copilot-instructions.md to the agent file
to keep concerns separated.
2026-02-07 13:32:50 +01:00
Daniel Volz f73c79c6cf fix: stock correction no longer neutralized by phantom consumption (#109)
After correcting medication stock, the coverage calculation immediately
counted 1 dose as consumed (due to +1 in occurrences formula), which
neutralized small corrections like +1 pill.

Fix: start consumption counting from stockCorrectionCutoff + period
(the next scheduled dose) instead of from the correction time itself.

Added 3 frontend tests for stock correction scenarios and 6 backend
e2e tests for the PATCH /medications/:id/stock-adjustment endpoint.
2026-02-07 13:30:44 +01:00
Daniel Volz 06943f5831 fix: add pull-requests write permission to badge workflow (#108)
peter-evans/create-pull-request requires pull-requests: write permission
to create PRs via the GITHUB_TOKEN.
2026-02-07 12:41:26 +01:00
Daniel Volz 73b3eb6686 fix: replace event count limit with time-based window for past schedule (#107)
The groupedSchedule useMemo used slice(0, 2000) to limit events. With daily
medications having start dates far in the past, thousands of past events would
fill all 2000 slots, pushing today and future events completely out of the
display. This caused the past schedule to only show weekly medications (fewer
events) while daily medications appeared missing.

Replace the fixed count limit with a time-based window: only past events
within the scheduleDays window (30/90/180 days) are included. All today and
future events are always included regardless.

Coverage calculations are not affected as they use schedule.events directly.
2026-02-07 00:35:14 +01:00
Daniel Volz a4313afc34 fix: use PR instead of direct push for badge updates (#106)
Branch protection prevents direct pushes to main.
Use peter-evans/create-pull-request action instead.
2026-02-07 00:15:05 +01:00
Daniel Volz 690cb2ff74 fix: correct dose ID generation for empty takenBy arrays (#105)
The takenBy field is a string[]. Empty arrays [] are truthy in JavaScript,
causing d.takenBy ? [...] patterns to generate dose IDs with trailing
hyphens (e.g., '5-0-173...-') instead of base IDs ('5-0-173...').

This mismatch between ID generation and computeMissedPastDoseIds (which
correctly uses .length > 0) caused doses to always appear as missed.

Changes:
- Add expandDoseIds() helper function using correct .length > 0 check
- Replace 8 buggy inline patterns in DashboardPage.tsx
- Refactor SchedulePage.tsx to use shared expandDoseIds()
- Add backend startup repair to strip trailing hyphens from existing IDs
- Add 12 new tests (6 frontend + 6 backend)
2026-02-07 00:08:58 +01:00
Daniel Volz 21127b38ab fix: repair orphaned dose tracking IDs on startup (#104)
Add repairOrphanedDoseIds() function that runs during app startup
(after ALTER migrations) to fix dose tracking entries that became
invalid when medication schedules were changed before PR #103.

The function:
- Generates valid schedule dates for each medication's current intakes
- Detects dose_tracking entries whose dateOnlyMs doesn't match any
  valid schedule date
- Remaps orphaned doses to the nearest valid schedule date within
  half the intake interval
- Preserves person suffixes in dose IDs
- Is idempotent (safe to run on every startup)

This complements PR #103 which only migrates dose IDs on future edits.
The startup repair fixes existing broken data in production databases.

Includes 8 tests covering: valid doses unchanged, 1-day shift repair,
person suffix preservation, out-of-range detection, idempotency,
multi-medication handling, and legacy format fallback.
2026-02-06 22:59:40 +01:00
Daniel Volz f5f189e0a4 fix: migrate dose tracking IDs when intake schedule changes (#103)
When a medication's start date or interval changes, the generated dose
IDs shift (dateOnlyMs values change). Previously, doses marked as taken
under the old schedule were orphaned — they no longer matched the new
schedule's dose IDs, causing them to appear as missed.

Now the PUT /medications/:id endpoint:
1. Parses old intakes from the existing medication row
2. Detects which intake indices had schedule changes
3. Maps old dateOnlyMs values to the nearest new dateOnlyMs
4. Updates dose_tracking entries with the migrated IDs
5. Preserves person suffixes (e.g. -Alice) during migration

Also fixes the start-date cleanup to use date-only comparison,
preventing doses on the start date from being incorrectly deleted
when the start time is after midnight.

Adds 4 integration tests covering weekly day shift, person suffix
preservation, time-only changes, and interval changes.
2026-02-06 22:38:28 +01:00
Daniel Volz 43c5402592 fix: add workflow_dispatch trigger to test badge workflow (#102)
Allows manual triggering of the badge update workflow, useful when
the ANSI fix or other workflow-only changes need to take effect
without waiting for source code changes.
2026-02-06 22:27:01 +01:00
Daniel Volz 02bae889b4 fix: strip ANSI escape codes in test badge workflow (#101)
Vitest 4 outputs ANSI color codes in test results, which caused the
grep regex to fail when extracting test counts. The badge workflow
silently skipped the update, leaving stale counts in the README.

Add a sed pass to strip ANSI escape sequences before parsing.
2026-02-06 22:24:09 +01:00
Daniel Volz ae45054ab7 fix: reset stock adjustment offset on refill (#99)
- Reset stockAdjustment to 0 and lastStockCorrectionAt to now when
  a refill is added, so consumed-pill tracking restarts from the
  new base stock level
2026-02-06 22:04:14 +01:00
Daniel Volz 5818dcc00d feat: add checkbox to include consumption from today until planner start date (#98)
- Add 'Include consumption from today until start date' checkbox to planner
- When checked, usage calculation starts from today instead of max(today, startDate)
- Persist checkbox state in localStorage per user
- Add i18n translations (EN + DE)
- Update planner tests to use dynamic future dates
2026-02-06 22:01:01 +01:00
Daniel Volz 01deea1fa0 fix: dose tracking broken for per-intake takenBy and after medication edits (#100)
- Remove broken isDoseFromPreviousSchedule that falsely dismissed all past doses
  after any medication edit (compared dateOnlyMs < updatedAt incorrectly)
- Fix takenBy normalization in AppContext: event.takenBy (string|null) was passed
  through as-is via || operator instead of being properly converted to string[]
- Fix DashboardPage: 5 locations treated dose.takenBy as single string instead of
  iterating the array, causing per-person dose tracking to silently fail
- Extract isDoseDismissed and computeMissedPastDoseIds as pure testable functions
  from AppContext.tsx into utils/schedule.ts
- Update SharedSchedule.tsx to use shared isDoseDismissed from utils
- Add 22 regression tests covering isDoseDismissed, computeMissedPastDoseIds,
  and full dose-tracking-survives-medication-edit workflows
- Add 'fix bugs, don't test around them' rule to copilot instructions
2026-02-06 21:55:21 +01:00
Copilot 869b5774fb Add Playwright E2E testing infrastructure for local development (#95)
* Initial plan

* Add Playwright E2E testing infrastructure

- Add @playwright/test dependency
- Create playwright.config.ts with best practices configuration
- Create e2e test structure with fixtures and auth setup
- Add E2E tests for auth, dashboard, medications, and settings pages
- Add npm scripts for running E2E tests
- Update .gitignore for Playwright artifacts
- Add E2E test job to CI workflow
- Update vite.config.ts to support BACKEND_URL env variable
- Update biome.json to include e2e files in linting

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Remove waitForTimeout anti-pattern from E2E tests

Replace hard-coded timeouts with proper Playwright waiting strategies:
- Use waitForLoadState('networkidle') for page load
- Use element.waitFor() for dynamic elements
- Use expect assertions for state verification

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Remove E2E tests from CI workflow

E2E tests will only be run locally as requested.

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>
Co-authored-by: Daniel Volz <mail@danielvolz.org>
2026-02-05 08:26:08 +01:00
dependabot[bot] 7b88d71c8f build(deps): bump @isaacs/brace-expansion in /backend (#94)
Bumps @isaacs/brace-expansion from 5.0.0 to 5.0.1.

---
updated-dependencies:
- dependency-name: "@isaacs/brace-expansion"
  dependency-version: 5.0.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Daniel Volz <mail@danielvolz.org>
2026-02-05 07:53:32 +01:00
dependabot[bot] 6296aa1251 build(deps): bump fastify from 5.6.2 to 5.7.3 in /backend (#91)
Bumps [fastify](https://github.com/fastify/fastify) from 5.6.2 to 5.7.3.
- [Release notes](https://github.com/fastify/fastify/releases)
- [Commits](https://github.com/fastify/fastify/compare/v5.6.2...v5.7.3)

---
updated-dependencies:
- dependency-name: fastify
  dependency-version: 5.7.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-05 07:43:42 +01:00
Daniel Volz d2bf5e61c0 chore: release v1.7.1 (#93) 2026-02-03 05:58:54 +01:00
Daniel Volz 31a89356fe fix: prevent crash when takenBy is not an array (#92)
- Add Array.isArray() checks before calling .map() on dose.takenBy
- Fixes TypeError: dose.takenBy.map is not a function
- Affects AppContext missedPastDoseIds calculation
- Affects SchedulePage dose ID generation (3 locations)

This hotfix prevents the app from crashing when dose.takenBy
is null, undefined, or any non-array value.
2026-02-03 05:57:11 +01:00
Daniel Volz 9984392b76 chore: release v1.7.0 (#90) 2026-02-01 00:23:54 +01:00
Daniel Volz 571d94bf7e feat: Add package type support and per-intake takenBy (#89)
## Package Type Feature
- Add 'blister' and 'bottle' package types for medications
- Bottle type uses totalPills for capacity and looseTablets for current stock
- Blister type continues to use packCount/blistersPerPack/pillsPerBlister
- Add doseUnit field for flexible dosing (mg, ml, IU, etc.)
- Full UI support in medication form and detail modal

## Per-Intake TakenBy
- Move takenBy from medication level to individual intakes
- Each intake schedule can now be assigned to a different person
- Update scheduler-utils to handle per-intake takenBy
- Update SharedSchedule to filter by per-intake takenBy
- Backward compatible with existing medication data

## UI Improvements
- Add PasswordInput component with show/hide toggle
- Centralize stockThresholds in AppContext for consistent status display
- Fix SharedSchedule sync issues with per-intake takenBy
- Improve mobile editing experience

## Technical
- Add migrations 0004 and 0005 for schema changes
- Update all relevant tests (1064 tests passing)
- Maintain backward compatibility with ALTER migrations
2026-01-31 23:49:11 +01:00
Daniel Volz ac4b8151e4 fix: filter out doses from previous schedules in SharedSchedule (#88)
- Add updatedAt field to share API response
- Add isDoseFromPreviousSchedule check in SharedSchedule
- Don't count doses scheduled before medication update as missed
- Syncs SharedSchedule behavior with main app's AppContext logic
2026-01-31 08:54:09 +01:00
Daniel Volz b2026637db chore: release v1.6.5 (#87) 2026-01-30 22:27:41 +01:00
Daniel Volz 99ef5bd622 feat: streamline dashboard UI and improve refill reminder (#86)
- Hide Reorder Reminder card when reminders are enabled (avoids redundancy with Reminder Bar)
- Show all low stock medications in Reminder Bar instead of just the next one
- Rename 'Reorder' to 'Refill' throughout the app
- Make medication names clickable in Refill Reminder card (opens detail modal)
- Add daysLeft display for each low stock medication
- Update translations (EN + DE)
2026-01-30 22:21:05 +01:00
Daniel Volz 1dcd333fde feat: add account deletion feature (#85)
* feat: add account deletion feature

- Add DELETE /auth/me endpoint to delete user account and all data
- Add deleteAccount() method to AuthContext
- Add Delete Account button with confirmation modal in UserProfile
- Add danger zone styling (.btn-danger, .profile-danger-zone)
- Add i18n translations for EN and DE
- Add backend tests for account deletion endpoint
- Add timeout settings to frontend vitest.config.ts
- Reduce CI timeout for frontend tests (10min -> 5min)

* fix: improve delete account section layout

- Make profile modal scrollable with max-height
- Add proper horizontal margin to danger zone
- Align delete section with form content

* fix: use ConfirmModal component for delete account dialog

- Replace inline modal with existing ConfirmModal component
- Ensures consistent button styling across all modals
- Add UI consistency rule to AGENTS.md and copilot-instructions.md

* fix: consistent styling for delete account section

- Remove warning text (users know what delete means)
- Remove border-bottom from danger zone title (section has border-top)
- Update copilot-instructions and AGENTS.md with stricter UI consistency rules
- Remove unused deleteAccountHint i18n keys

* chore: remove pre-push test hook (CI handles tests)

Tests were running twice - in pre-push hook and GitHub CI.
Removing local pre-push tests since CI provides authoritative test results.
Use 'npm test' manually before pushing if you want local feedback.
2026-01-30 21:13:11 +01:00
Daniel Volz 9ed039724e fix: use test:run script and add timeouts to badge workflow (#84)
- Add test:run script to frontend package.json (consistent with backend)
- Use npm run test:run instead of npm run test -- --run
- Add timeout-minutes to prevent infinite hangs
2026-01-30 19:30:07 +01:00
Daniel Volz 156e54f0ea fix: add CI=true to test badge workflow (#83)
Frontend tests were running in watch mode without CI=true env var,
causing the workflow to hang for 30+ minutes.
2026-01-30 19:15:54 +01:00
Daniel Volz 47e8dfe9bc fix: use date-only timestamp for stable dose IDs (#82)
- Use date-only timestamp instead of full timestamp for dose ID generation
- Ensures changing intake times doesn't invalidate past dose tracking
- IDs are now immune to time configuration changes
2026-01-30 19:12:25 +01:00
Daniel Volz aed0b20875 refactor: deduplicate formatters and improve test mocks (#81)
- Consolidate duplicate date formatting utilities
- Use shared formatters across backend and frontend
- Clean up test mocks to use consistent test data
- Remove redundant formatting functions
2026-01-30 18:37:24 +01:00
Daniel Volz fcd1b79c56 chore: add .roo/, .roomodes, and AGENTS.md to .gitignore (#80)
* chore: add .roo/ to gitignore

* chore: add .roo/, .roomodes, and AGENTS.md to .gitignore
2026-01-30 18:35:00 +01:00
Daniel Volz e725700d10 fix: only count missed doses scheduled after medication update (#79)
When medication intake times change, dose IDs change (they include
timestamps). Previously, this caused all past doses to appear as
'missed' because the old 'taken' markers no longer matched.

Now doses are only counted as 'missed' if they were scheduled AFTER
the medication's last update (updatedAt). This means:
- Legitimately missed doses still show as missed (e.g., yesterday's
  dose not taken)
- Doses from before a schedule change are NOT counted as missed
  (they were from a previous schedule configuration)

Changes:
- AppContext: Add isDoseFromPreviousSchedule helper
- SchedulePage: Use context's missedPastDoseIds instead of local calc
- Update tests to include missedPastDoseIds in mocks
2026-01-25 20:45:11 +01:00
Daniel Volz 8685e802cd fix: add frontend tests to pre-push hook (#78) 2026-01-25 20:04:03 +01:00
Daniel Volz 1793f636bf docs: update release workflow instructions (#77)
- Remove reference to release script (not used)
- Document automatic version bump via GitHub Action
- Simplify release process description
2026-01-25 19:52:10 +01:00
Daniel Volz 9cf931f243 ci: add automatic version bump on GitHub release (#76)
Creates a workflow that triggers when a release is published and
automatically updates package.json versions in backend/ and frontend/
to match the release tag version.
2026-01-25 19:49:01 +01:00
Daniel Volz 85f4d2dd21 chore: update package.json versions to 1.6.0 (#75)
The release script created tag v1.6.0 but did not update the version
numbers in package.json files. This fix ensures the About modal
displays the correct version.
2026-01-25 19:36:19 +01:00
Daniel Volz 01283ebd15 chore: rename MedAssist to MedAssist-ng in all frontend UI (#74)
Update all visible text from 'MedAssist' to 'MedAssist-ng':
- Auth page titles (login, register)
- Loading/error/initializing states
- SharedSchedule page (loading, expired, error, footer)
- AboutModal fallback text
- i18n strings for export file validation (EN/DE)
- Related test expectations
2026-01-25 19:32:17 +01:00
Daniel Volz 18bcb96869 fix: add automatic retry for auth state fetch on connection errors (#73)
When the server is restarting (e.g., during tsx watch hot reload), the
initial auth state fetch may fail. This change adds automatic retry
logic (up to 3 attempts with 1s delay) to handle transient connection
errors gracefully instead of immediately showing the error screen.
2026-01-25 19:16:24 +01:00
Daniel Volz d516bdea7d fix: add credentials to all fetch calls for auth cookie support (#72)
* fix: add credentials to all fetch calls for auth cookie support

- Add credentials: include to useMedications.ts fetch calls
- Add credentials: include to MedicationsPage.tsx save function
- Add credentials: include to useSettings.ts settings update
- Add credentials: include to useShare.ts share generation
- Add credentials: include to DashboardPage.tsx reminder email
- Add credentials: include to PlannerPage.tsx usage calculation
- Make create-release workflow skip if release already exists

* fix: default to ntfy-style notifications for HTTP URLs

- Change notification logic to use plain text format by default
- Only use JSON format for known webhook services (Discord, Slack, Telegram, Gotify)
- This fixes ntfy URLs not being recognized when hostname doesn't contain 'ntfy'

* feat: highlight medication being edited

- Add blue border and background to the medication row being edited
- Show medication avatar and name in the edit form header
- Makes it easy to identify which medication is being edited when there are many

* fix: use proper URL parsing for webhook detection (CodeQL security fix)

Replace vulnerable .includes() URL checks with proper URL hostname
parsing to prevent bypass attacks (e.g., evil.com?hooks.slack.com).

Fixes CodeQL alerts #33 and #34 (js/incomplete-url-substring-sanitization)
2026-01-25 19:10:41 +01:00
Daniel Volz cab0fcbba7 feat: mobile UI improvements, biome linting, and reminder info display (#71)
* fix: make dismissed doses robust against schedule/timezone changes

- Store dismissedUntil date (YYYY-MM-DD) per medication instead of individual dose IDs
- Add POST /medications/dismiss-until endpoint to set dismissed date
- Add DELETE /medications/:id/dismiss-until endpoint to clear dismissed date
- Update frontend to use medication-level dismissedUntil for filtering
- Remove old dismissMissedDoses function from useDoses hook (was using dose IDs)
- Add backward-compatible ALTER TABLE migration for dismissed_until column
- Add 5 integration tests for dismiss-until functionality
- Update test schemas with new column

The old approach stored individual dose IDs which broke when schedule or timezone
settings changed (dose IDs contain timestamps). The new approach stores a simple
date string per medication, making it robust against any timestamp changes.

* chore: add Biome linter and Husky pre-commit hook

* chore: add unified biome config and pre-push hook

- Add root-level biome.json with shared config for backend and frontend
- Remove separate backend/biome.json and frontend/biome.json
- Add .husky/pre-push hook to run backend tests before push
- Update package.json lint-staged config to use root biome config

* feat(db): add reminder info columns to schema

- Add dismissed_until column to medications table
- Add last_reminder_med_name and last_reminder_taken_by to user_settings
- Generate Drizzle migration 0003
- Add backward-compatible ALTER migrations in client.ts

* feat(frontend): add unsaved changes warning

- Add UnsavedChangesContext for tracking unsaved form state
- Add useUnsavedChangesWarning hook for browser close warning
- Wrap App with UnsavedChangesProvider
- Add i18n translations for unsaved changes dialog (en/de)

* style: apply biome formatting across codebase

- Apply consistent formatting to all TypeScript files
- Organize imports alphabetically
- Use double quotes and tabs consistently
- Fix trailing commas (es5 style)
- Remove frontend/biome.json deletion (already deleted)

* fix(tests): add missing columns to test schemas

Add last_reminder_med_name and last_reminder_taken_by columns to
test CREATE TABLE statements in:
- planner.test.ts
- e2e-routes.test.ts
- integration.test.ts

Also improve runDrizzleMigrations to handle duplicate column errors
gracefully (returns warning instead of failing).

* fix(planner): add missing 'as unknown' type cast for request.user

* fix(security): address CodeQL XSS and SSRF warnings

- Escape all user-provided strings in email HTML templates
- Coerce numeric values with Number() to prevent type injection
- Add redirect:error to fetch() to prevent SSRF via redirect
- Document SSRF validation in settings.ts

* fix(security): refactor SSRF mitigation to reconstruct URL from validated components

CodeQL traces taint through validation functions that return the same string.
Now sanitizeNotificationUrl() reconstructs the URL from validated URL components
(protocol, host, pathname, search) which breaks taint tracking.

- Renamed to sanitizeNotificationUrl() to clarify it returns sanitized data
- Returns reconstructed URL built from URL() parsed components
- Extracts auth credentials separately instead of including in URL string
- Added isNtfy flag to avoid re-parsing the sanitized URL

* fix(security): add SSRF suppression comment for validated notification URL

The fetch() uses a URL that has been validated by sanitizeNotificationUrl():
- Only http/https protocols
- Blocks localhost and loopback IPs
- Blocks private IP ranges (10.x, 172.16-31.x, 192.168.x, 169.254.x)
- Blocks internal hostnames (.local, .internal, .lan)
- redirect: 'error' prevents redirect bypass

This is an intentional feature: users configure their own notification endpoints.
2026-01-25 18:01:35 +01:00
Daniel Volz ecdb9bcbe0 ci: auto-update test count badges in README (#70) 2026-01-23 22:36:26 +01:00
Daniel Volz 9b0d8037e7 docs: show test counts in README badges (454/454 backend, 611/611 frontend) (#69) 2026-01-23 22:27:27 +01:00
Daniel Volz a4d1dd215a docs: add CI status badges to README (#68) 2026-01-23 22:24:29 +01:00
Daniel Volz 8e2fd0a761 chore: release v1.5.0 (#67)
* chore: release v1.4.0

* feat: timezone-aware locale formatting

- Add TIMEZONE_TO_REGION map for 50+ timezones worldwide
- Combine app language with timezone region (e.g., en + Europe/Berlin → en-DE)
- Fix times displaying in wrong timezone (treated as UTC instead of local)
- Add parseLocalDateTime() to handle ISO strings without UTC conversion
- Users now get regional formatting (24h time, local date format) regardless of app language
- Swedish user with en-SE locale now gets yyyy-mm-dd format and 24h time
- German user with en-DE locale gets dd.mm.yyyy format and 24h time
- Add missing i18n translation key 'lastSent'
- Update all getSystemLocale() calls to pass app language parameter

* chore: release v1.5.0

* fix: timezone-independent test for CI (use 14:00 instead of 22:00)

* fix: make timezone test independent of server timezone
2026-01-23 21:42:57 +01:00
Copilot 0a4f8c5948 [WIP] Increase frontend test coverage to above 80% (#63)
* Initial plan

* refactor: simplify useMedicationForm tests to avoid memory issues

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Changes before error encountered

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* test: add comprehensive tests for SchedulePage, SettingsPage, MedicationsPage, and PlannerPage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* test: add SharedSchedule theme persistence tests

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* test: add comprehensive MobileEditModal tests

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* test: add comprehensive MedDetailModal tests

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* fix: use fixed timestamps in tests for deterministic behavior

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>
2026-01-23 07:36:44 +01:00
Daniel Volz fd055a3a2a Feat/frontend tests (#62)
* test(frontend): add vitest test infrastructure

- Add vitest, testing-library, jsdom dependencies
- Configure vitest with jsdom environment
- Add test setup with mocks for fetch, localStorage, matchMedia
- Set 75% coverage threshold

* Add frontend tests (#61)

* Initial plan

* Add frontend tests - utilities, hooks, and components (21% coverage)

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Add more component tests (Auth, AboutModal, ExportModal) and useRefill hook tests - 30% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Add useMedicationForm utility function tests - 30% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Add AppHeader tests and more schedule.ts tests - 32% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Changes before error encountered

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Fix page tests and add more tests - 326 tests passing, 34% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Add tests for ProfileModal, UserFilterModal, MedDetailModal - 361 tests, 36% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Add SharedSchedule tests - 366 tests, 39% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Expand page tests - 383 tests, 39% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Add MobileEditModal tests - 409 tests, 40% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Expand Dashboard and Schedule page tests - 427 tests, 40% coverage

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

* Fix code review issues - remove invalid remindEnabled property

Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>

---------

Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>
2026-01-22 10:25:11 +01:00
Daniel Volz 8718311876 refactor(frontend): modularize App.tsx into components, pages, hooks, and context (#60)
- Extract App.tsx from 764 lines to ~404 lines
- Create reusable components: MedDetailModal, MobileEditModal, ShareDialog, etc.
- Add AppContext for global state management
- Split pages: DashboardPage, MedicationsPage, SchedulePage, SettingsPage, PlannerPage
- Create custom hooks: useAuth, useMedications, useSettings, useDoses, useSchedule
- Add utility functions in separate modules
- Fix stock status logic (>30 days = green/normal)
- Fix reminder threshold calculation (use reminderDaysBefore not lowStockDays)
- Fix takenBy validation (send [] instead of null)
- Fix datetime format for blister start times (add Z suffix)
- Style 'All OK' status as green/bold

BREAKING: None - all existing functionality preserved
2026-01-22 05:38:34 +01:00
162 changed files with 50402 additions and 23393 deletions
+344
View File
@@ -0,0 +1,344 @@
---
name: release-manager
description: Manages the full release lifecycle - from branching and PRs through versioning and GitHub release notes. Use when code changes are complete and ready to ship.
argument-hint: Describe what was changed, e.g., "fix stock correction bug" or "new refill tracking feature"
---
# Release Manager Agent
You are the release manager for **MedAssist-ng**. Your job is to guide code from "done" to "released" following the project's strict branch protection, CI pipeline, and semantic versioning rules.
**All output (commits, PR titles, release notes) MUST be in English**, even if the user communicates in German.
## Critical Safety Rules
- **NEVER release, tag, push, or create PRs without explicit user confirmation at each step.** Always present your plan and wait for approval.
- **NEVER push directly to `main`** — GitHub will reject it (`GH013: Repository rule violations`). All changes go through Pull Requests.
- **NEVER skip CI checks.** Wait for all status checks to pass before merging.
---
## Task 1: Branch, PR, and Merge Workflow
When code changes (features or bug fixes) are complete and tested locally:
### Step 1: Verify Readiness
1. Check for uncommitted changes: `git status`
2. Ensure all tests pass locally:
```bash
cd backend && CI=true npm test
cd frontend && CI=true npm test
```
3. If tests fail, stop and fix them first.
### Step 2: Create Feature Branch
1. Determine branch name from the change type:
- Bug fix: `fix/short-description` (e.g., `fix/stock-correction-consumption`)
- Feature: `feat/short-description` (e.g., `feat/refill-tracking`)
- Chore: `chore/short-description`
2. Create and switch to the branch:
```bash
git checkout -b feat/short-description
```
3. Stage and commit changes with a conventional commit message:
```bash
git add .
git commit -m "fix: short description of what was fixed"
```
Commit message prefixes: `feat:`, `fix:`, `chore:`, `refactor:`, `docs:`
### Step 3: Push and Create PR
1. Push the branch:
```bash
git push -u origin feat/short-description
```
2. Create a Pull Request via GitHub CLI:
```bash
gh pr create --title "fix: short description" --body "Description of charges"
```
3. **Present the PR URL to the user and wait for confirmation.**
### Step 4: Wait for CI and Merge
1. Monitor CI status:
```bash
gh pr checks <PR_NUMBER> --watch
```
Required checks:
- ✅ `backend-test` (TypeScript type-check + vitest coverage)
- ✅ `frontend-build` (npm build)
2. If CI fails: analyze the failure, fix it, push again, and re-check.
3. Once CI is green, **ask the user for merge confirmation**, then:
```bash
gh pr merge <PR_NUMBER> --squash --delete-branch
```
4. Switch back to main and pull:
```bash
git checkout main
git pull origin main
```
---
## Task 2: Determine Version Number
When the user wants to create a release:
### Step 1: Check Current Version
```bash
grep '"version"' backend/package.json
```
Also check the latest git tag:
```bash
git tag --sort=-v:refname | head -5
```
### Step 2: Analyze Changes Since Last Release
```bash
git log $(git describe --tags --abbrev=0)..HEAD --oneline
```
Read through the commits to understand what changed.
### Step 3: Select SemVer Level
Apply these rules strictly:
| Change Type | Version Bump | Example |
|------------|-------------|---------|
| Bug fixes only, no new features | **patch** | `1.4.2` → `1.4.3` |
| New features (backward compatible) | **minor** | `1.4.2` → `1.5.0` |
| Breaking changes (DB schema without migration, removed ENV vars, changed API) | **major** | `1.4.2` → `2.0.0` |
**Guidelines:**
- When in doubt between patch and minor, prefer **minor** if any user-visible behavior is new.
- Bug fixes that also introduce small UX improvements = **patch**.
- Multiple bug fixes in one release = still **patch**.
- New UI sections, new API endpoints, new settings = **minor**.
- If a user can run `docker compose pull && docker compose up -d` without changing anything → NOT a breaking change.
**Present your version recommendation to the user with reasoning and wait for confirmation.**
---
## Task 3: Execute Release
Use the release script — it is **fully non-interactive** (no y/N prompts) and handles the entire flow automatically:
```bash
./scripts/release.sh <patch|minor|major|x.y.z>
```
The script performs these steps in order:
1. Checks out and updates `main`
2. Creates release branch `chore/release-X.Y.Z`
3. Bumps version in `backend/package.json` and `frontend/package.json`
4. Commits, pushes, and creates a PR
5. Waits for CI checks (with retry logic — polls every 15s, waits up to 10 minutes)
6. Merges the PR (squash + delete branch)
7. Creates a signed tag `vX.Y.Z` and pushes it
**The script auto-detects the git remote** (`origin` or `github`) and uses it consistently.
**CI wait behavior:** GitHub Actions can take 10-30 seconds before checks appear on a new PR. The script waits 20 seconds initially, then polls every 15 seconds until checks are registered, then watches them to completion. Maximum wait is 10 minutes.
**On failure:** If CI fails, the script exits with an error. The release branch and PR remain open for inspection. Fix the issue, push to the branch, and the PR will re-run CI. Then merge manually or re-run the script.
### Version Files (MANDATORY)
The version number is displayed in the **About modal** (Settings → About) as a single unified app version. This version is a **clickable link** pointing to the corresponding GitHub release (`https://github.com/DanielVolz/medassist-ng/releases/tag/vX.Y.Z`). The version is read from:
- **`backend/package.json`** → Backend version, returned by `/health` endpoint
- **`frontend/package.json`** → Frontend version, injected at build time via Vite's `__APP_VERSION__` define and used to construct the release link
**Both files MUST be updated to the new version before tagging a release.** If forgotten:
- The About modal will show the old version
- The version link will point to a non-existent GitHub release page
### Manual Release (if script is not available)
1. Create release branch:
```bash
git checkout main && git pull origin main
git checkout -b chore/release-X.Y.Z
```
2. Update versions in **both** `backend/package.json` and `frontend/package.json` to `X.Y.Z`
3. Commit, push, create PR, wait for CI, merge (same as Task 1)
4. Create signed tag:
```bash
git checkout main && git pull origin main
git tag -s "vX.Y.Z" -m "Release vX.Y.Z"
git push origin "vX.Y.Z"
```
### After Tagging
- The `docker-build.yml` workflow automatically builds and pushes Docker images to GHCR with both versioned tags (`1.8.7`, `1.8`) and `latest`.
- The `update-test-badges.yml` workflow runs automatically after a successful Docker build to update test count badges in the README.
- Track progress: `https://github.com/DanielVolz/medassist-ng/actions`
---
## Task 4: Write Release Notes
When the user asks to write release notes (MANDATORY for minor/major releases):
### Step 1: Gather Changes
```bash
git log vPREVIOUS..vNEW --oneline
```
Read the actual code changes (not just commit messages) to understand what was added or fixed.
### Step 2: Write Release Notes
**Release title:** Use just `vX.Y.Z` (e.g., `v1.4.1`), NOT "Release vX.Y.Z".
**Required structure:**
1. **"What's New"** (1-2 sentences): Brief intro explaining the main change
2. **"New Features" / "Bug Fixes" / "Improvements"**: Grouped bullet points with **bold feature names** and descriptions
3. **"Where to Find It"**: Tell users where they can access the new feature or see the fix
4. **Breaking Changes Warning** (if applicable): See below
**Style guidelines:**
- Use `### Heading` for sections
- Use **bold** for feature names in bullet points
- Keep descriptions on the same line as the feature name
- **No emojis** — do not use emoji in headings or bullet points
- **Include commit references** — each bullet point must end with the PR number (e.g., `(#136)`) or short commit hash (e.g., `(ab12cd3)`) linking to the commit/PR. Use PR numbers when available.
- Always end with "Where to Find It" section
- End with: `**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/vPREV...vNEW`
**ONLY include user-relevant changes.** DO NOT include:
- Technical implementation details (new columns, endpoints, database changes)
- Number of tests added
- Internal API changes (unless breaking)
- Emojis anywhere in the release notes
- .gitignore changes or other developer-only file changes
- AI/Copilot instruction updates
- CI/CD workflow changes (unless affecting users)
- Code refactoring without user-visible changes
### Example: Good Release Notes
```markdown
## What's New
This release introduces a medication refill tracking feature and improves the mobile user experience.
### New Features
- **Medication Refill**: Track when you refill your medications with a single click. Add full packs or individual pills and view complete refill history. (#120)
- **Automatic Stock Updates**: Stock levels are automatically recalculated after each refill. (#120)
- **Refill History**: Each medication shows a complete history of all refills with timestamps. (#122)
### Improvements
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability. (#125)
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices. (#125)
### Where to Find It
The refill button appears in the medication detail modal and in the edit form for each medication.
**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/v1.2.3...v1.3.0
```
### Breaking Changes Warning
If the update breaks existing configurations or stored data, it MUST be prominently warned:
**Breaking Changes include:**
- Database schema changes without automatic migration
- Removed or renamed ENV variables
- Changed API endpoints
- Incompatible `.env` format changes
- Loss of stored data after update
**Format:**
```markdown
## ⚠️ BREAKING CHANGES - Please read before updating!
**Database migration required**: This update changes the database schema.
Existing installations need to:
1. Create backup of `data/` folder
2. Stop containers
3. Perform update
4. If issues occur: Rollback using backup
**ENV variables changed**:
- `OLD_VAR` was renamed to `NEW_VAR`
- `REMOVED_VAR` is no longer supported
```
**What is NOT a Breaking Change:**
- ✅ New optional columns with DEFAULT values
- ✅ New ENV variables (with sensible defaults)
- ✅ New features that don't affect existing data
- ✅ Bug fixes that correct behavior
### Step 3: Publish
Present the release notes to the user. They will copy them to the GitHub release page or ask you to publish via:
```bash
gh release create vX.Y.Z --title "vX.Y.Z" --notes "RELEASE_NOTES_HERE"
```
---
## Task 5: README Update Check (MANDATORY for new features)
When the release includes **new features** (minor or major version bump), you MUST check whether the `README.md` needs to be updated **before** executing the release.
### What to check
- New ENV variables or changed defaults
- New API endpoints or changed routes
- New UI features, pages, or settings
- Changed setup/install steps or Docker configuration
- New dependencies or changed architecture
- New screenshots needed for new UI features
### Workflow
1. Review the changes included in the release
2. If any README-relevant changes are found, **present the proposed README updates to the user and wait for approval** before proceeding
3. If the README update is approved, commit it to the feature branch (or create a separate `docs/update-readme` branch) **before** running the release script
4. Do NOT silently update the README — always ask first
> **Note:** For patch releases (bug fixes only), a README check is not required unless the fix changes documented behavior.
---
## Complete Workflow Summary
```
Code complete & tests pass locally
1. Create feature branch (fix/... or feat/...)
2. Commit, push, create PR
3. Wait for CI (backend-test + frontend-build)
4. Merge PR to main (squash + delete branch)
Ready for release?
5. Check current version (git tag + package.json)
6. Analyze changes → determine SemVer level
7. If minor/major: check README.md for needed updates (Task 5)
8. Run ./scripts/release.sh <patch|minor|major>
(or manually: branch → version bump → PR → CI → merge → tag)
9. Write release notes (mandatory for minor/major)
10. Publish GitHub release
Docker images built automatically via CI
```
+17 -137
View File
@@ -4,9 +4,13 @@
- **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English. - **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English.
- **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action. - **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action.
- **NEVER create PRs without explicit permission**: Do NOT create Pull Requests, push branches, or merge code unless the user explicitly asks for it. Always present changes and wait for the user to confirm before any git operations that affect the remote repository. - **NEVER create PRs, push, or merge**: Only the **release-manager agent** (`@release-manager`) is allowed to create Pull Requests, push branches to the remote, or merge code. Regular agents and Copilot MUST NOT perform any git operations that affect the remote repository (no `git push`, no `gh pr create`, no `gh pr merge`). Present your local changes and tell the user to invoke `@release-manager` when ready to ship.
- **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository. - **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository.
- **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done. - **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done.
- **Remove old code when re-implementing**: When fixing a bug or re-implementing a feature that didn't work, ALWAYS remove the old/broken code completely. Never leave dead code, unused functions, or obsolete implementations in the codebase.
- **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests. When modifying existing features, update or add tests accordingly. If old tests become obsolete due to code changes, remove or update them.
- **Fix bugs, don't test around them**: If you discover incorrect behavior in the code while writing tests, ALWAYS fix the buggy code first, then write tests that verify the correct behavior. NEVER write tests that mimic or assert broken behavior. The user's time is finite and irreplaceable — every bug left unfixed wastes it.
- **Keep README.md up to date**: After implementing code changes, check whether the `README.md` needs to be updated (e.g., new features, changed ENV variables, new commands, changed architecture, new endpoints, updated screenshots). If changes are relevant to the README, **ask the user for confirmation** before updating it. Do NOT silently update the README — always present the proposed README changes and wait for approval. Examples of README-relevant changes: new ENV variables, new API endpoints, new UI features, changed setup/install steps, new dependencies, changed Docker configuration.
## Architecture Overview ## Architecture Overview
@@ -134,11 +138,16 @@ Push to main / Tag created
┌─────────────────────────────────────┐ ┌─────────────────────────────────────┐
│ docker-build.yml │ │ docker-build.yml │
─ backend-test (parallel) ─ build-and-push
│ ├─ frontend-build (parallel) │
│ └─ build-and-push (after tests) │
│ ├─ Build Docker images │ │ ├─ Build Docker images │
│ └─ Push to GHCR │ │ └─ Push to GHCR │
│ (Tag builds also set "latest") │
└─────────────────────────────────────┘
↓ After successful build
┌─────────────────────────────────────┐
│ update-test-badges.yml │
│ (workflow_run after docker-build) │
│ └─ Run tests, update badge counts │
└─────────────────────────────────────┘ └─────────────────────────────────────┘
``` ```
@@ -175,139 +184,9 @@ gh pr merge --squash --delete-branch
| File | Trigger | Purpose | | File | Trigger | Purpose |
|------|---------|--------| |------|---------|--------|
| `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures | | `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures |
| `.github/workflows/docker-build.yml` | Push to main, Tags | Tests + Build and push Docker images | | `.github/workflows/docker-build.yml` | Push to main, Tags | Build and push Docker images (+ create GitHub release on tags) |
| `.github/workflows/update-test-badges.yml` | After successful docker-build | Update test count badges in README |
### Adding New Code - Checklist | `.github/workflows/codeql.yml` | Push to main, PRs, Weekly | Security analysis |
1. ✅ Implement feature
2. ✅ Write tests for the feature
3. ✅ Run `npm run test:coverage` locally
4. ✅ Coverage must not decrease
5. ✅ Create and push feature branch
6. ✅ Create Pull Request
7. ✅ Wait until CI is green
8. ✅ Merge PR (branch is automatically deleted)
## GitHub Releases
> ⚠️ **IMPORTANT**: All GitHub Releases must be written in **English**!
### Release Workflow (MANDATORY for minor/major releases)
The `main` branch is protected - releases must go through the automated release script.
**Release Process:**
```bash
# 1. Run release script (creates PR, waits for CI, merges, creates tag)
./scripts/release.sh [patch|minor|major]
# 2. GitHub Actions creates a DRAFT release automatically
# 3. User asks AI to write release notes:
# "Write the release notes for vX.Y.Z"
# 4. AI writes descriptive release notes following the style guide below
# 5. User publishes the draft release with the written notes
```
> ⚠️ **MANDATORY for minor and major releases**: The AI assistant MUST write proper descriptive release notes!
> Do NOT just publish the auto-generated commit list. Follow the process above.
**AI Assistant Release Notes Workflow:**
1. When user asks to write release notes for a version:
- Check commits since previous tag: `git log vPREV..vNEW --oneline`
- Read through the changes to understand what was added/fixed
- Write release notes following the style guide below
- Present the notes to the user for copying to GitHub
### Creating Release Notes
> ⚠️ **MANDATORY**: GitHub Releases MUST contain a written message!
> Not just auto-generated commit lists, but a brief descriptive text.
**Keep it informative but concise.** Users want to know what changed and where to find it.
**Required structure of release notes:**
1. **"What's New"** (1-2 sentences): Brief intro explaining the main change
2. **"New Features" / "Improvements"**: Grouped bullet points with **bold feature names** and descriptions
3. **"Where to Find It"**: Tell users where they can access the new feature
4. **Breaking Changes Warning** (if applicable): See below
**Style guidelines:**
- Use `### Heading` for sections (New Features, Improvements, Security, etc.)
- Use **bold** for feature names in bullet points
- Keep descriptions on the same line as the feature name
- Minimal emoji usage (sparingly, not on every line)
- Always end with "Where to Find It" section
**DO NOT include:**
- ❌ Technical implementation details (new columns, endpoints, database changes)
- ❌ Number of tests added
- ❌ Internal API changes (unless breaking)
- ❌ Excessive emoji on every bullet point
**Example of good release notes:**
```markdown
## What's New
This release introduces a medication refill tracking feature and improves the mobile user experience.
### New Features
- **Medication Refill**: Track when you refill your medications with a single click. Add full packs or individual pills and view complete refill history.
- **Automatic Stock Updates**: Stock levels are automatically recalculated after each refill.
- **Refill History**: Each medication shows a complete history of all refills with timestamps.
### Mobile Improvements
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability.
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices.
### Where to Find It
The refill button appears in the medication detail modal and in the edit form for each medication.
**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/v1.2.3...v1.3.0
```
### Breaking Changes Warning (CRITICAL!)
> ⚠️ **MANDATORY**: If an update breaks existing configurations or stored data, it MUST be prominently warned about in the release notes!
**Breaking Changes include:**
- Database schema changes without automatic migration
- Removed or renamed ENV variables
- Changed API endpoints
- Incompatible `.env` format changes
- Loss of stored data after update
**Format for Breaking Changes:**
```markdown
## ⚠️ BREAKING CHANGES - Please read before updating!
**Database migration required**: This update changes the database schema.
Existing installations need to:
1. Create backup of `data/` folder
2. Stop containers
3. Perform update
4. If issues occur: Rollback using backup
**ENV variables changed**:
- `OLD_VAR` was renamed to `NEW_VAR`
- `REMOVED_VAR` is no longer supported
**Medication data**: Intake schedules with only one time entry will be automatically
migrated. Please verify all times are correct after update.
```
**What is NOT a Breaking Change:**
- ✅ New optional columns with DEFAULT values
- ✅ New ENV variables (with sensible defaults)
- ✅ New features that don't affect existing data
- ✅ Bug fixes that correct behavior
**Rule of thumb**: If a user can simply run `docker compose pull && docker compose up -d`
without adjusting anything → Not a Breaking Change.
## Key Patterns ## Key Patterns
@@ -495,6 +374,7 @@ Example: `5-0-1735344000000` = Medication 5, Blister 0, timestamp
- **API responses**: Return objects directly, Fastify serializes to JSON - **API responses**: Return objects directly, Fastify serializes to JSON
- **Environment**: Copy `.env.example``.env`, secrets must be 10+ chars - **Environment**: Copy `.env.example``.env`, secrets must be 10+ chars
- **i18n**: All UI text via `t('key')` function, translations in `frontend/src/i18n/*.json` - **i18n**: All UI text via `t('key')` function, translations in `frontend/src/i18n/*.json`
- **UI Consistency**: Always use existing components for modals, buttons, and forms. For confirmation dialogs, use `ConfirmModal` component. Never create inline modals with custom button styling - all UI elements must match the existing design system. When adding new sections to existing components, ensure font sizes, spacing, margins, and button styles match exactly with other sections. Check existing CSS classes before creating new ones.
## Database Schema Changes (IMPORTANT: Backward Compatibility!) ## Database Schema Changes (IMPORTANT: Backward Compatibility!)
+22
View File
@@ -3,8 +3,30 @@ name: "CodeQL"
on: on:
push: push:
branches: [main] branches: [main]
paths:
- '**.js'
- '**.ts'
- '**.tsx'
- '**.jsx'
- 'backend/package.json'
- 'backend/package-lock.json'
- 'frontend/package.json'
- 'frontend/package-lock.json'
- '.github/codeql/**'
- '.github/workflows/codeql.yml'
pull_request: pull_request:
branches: [main] branches: [main]
paths:
- '**.js'
- '**.ts'
- '**.tsx'
- '**.jsx'
- 'backend/package.json'
- 'backend/package-lock.json'
- 'frontend/package.json'
- 'frontend/package-lock.json'
- '.github/codeql/**'
- '.github/workflows/codeql.yml'
schedule: schedule:
- cron: "0 6 * * 1" # Weekly on Monday at 6am UTC - cron: "0 6 * * 1" # Weekly on Monday at 6am UTC
workflow_dispatch: # Allow manual trigger workflow_dispatch: # Allow manual trigger
+24 -43
View File
@@ -25,50 +25,15 @@ env:
jobs: jobs:
# ============================================================================= # =============================================================================
# Run Tests First # Build and Push Docker Images
# ============================================================================= # Tests are NOT run here — branch protection on main requires all PR checks
backend-test: # (backend-test + frontend-build from test.yml) to pass before merge.
name: Backend Tests # Tags are created from main, so code is already tested.
runs-on: ubuntu-latest #
permissions: # Tag builds (v*) always set "latest" in addition to the semver tags.
contents: read # This ensures "latest" always points to the most recent release.
defaults:
run:
working-directory: backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: backend/package-lock.json
- run: npm ci
- run: npx tsc --noEmit
- run: npm run test:run
frontend-build:
name: Frontend Build
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- run: npm ci
- run: npm run build
# =============================================================================
# Build and Push Docker Images (only after tests pass)
# ============================================================================= # =============================================================================
build-and-push: build-and-push:
needs: [backend-test, frontend-build]
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: read contents: read
@@ -106,7 +71,7 @@ jobs:
type=semver,pattern={{version}} type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}} type=semver,pattern={{major}}.{{minor}}
type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }} type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
- name: Build and push - name: Build and push
uses: docker/build-push-action@v5 uses: docker/build-push-action@v5
@@ -137,13 +102,28 @@ jobs:
with: with:
fetch-depth: 0 # Fetch all history for changelog generation fetch-depth: 0 # Fetch all history for changelog generation
- name: Check if release exists
id: check_release
run: |
CURRENT_TAG=${GITHUB_REF#refs/tags/}
if gh release view "$CURRENT_TAG" &>/dev/null; then
echo "exists=true" >> $GITHUB_OUTPUT
echo "Release $CURRENT_TAG already exists, skipping creation"
else
echo "exists=false" >> $GITHUB_OUTPUT
fi
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Get previous tag - name: Get previous tag
if: steps.check_release.outputs.exists == 'false'
id: prev_tag id: prev_tag
run: | run: |
PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "") PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
echo "tag=${PREV_TAG}" >> $GITHUB_OUTPUT echo "tag=${PREV_TAG}" >> $GITHUB_OUTPUT
- name: Generate changelog - name: Generate changelog
if: steps.check_release.outputs.exists == 'false'
id: changelog id: changelog
run: | run: |
CURRENT_TAG=${GITHUB_REF#refs/tags/} CURRENT_TAG=${GITHUB_REF#refs/tags/}
@@ -172,6 +152,7 @@ jobs:
echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${CURRENT_TAG}" >> changelog.md echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${CURRENT_TAG}" >> changelog.md
- name: Create GitHub Release - name: Create GitHub Release
if: steps.check_release.outputs.exists == 'false'
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:
body_path: changelog.md body_path: changelog.md
-78
View File
@@ -1,78 +0,0 @@
name: Create Release
on:
push:
tags: ['v*']
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get version info
id: version
run: |
CURRENT_TAG=${GITHUB_REF#refs/tags/}
VERSION=${CURRENT_TAG#v}
echo "tag=$CURRENT_TAG" >> $GITHUB_OUTPUT
echo "version=$VERSION" >> $GITHUB_OUTPUT
# Get previous tag
PREV_TAG=$(git tag --sort=-v:refname | grep -A1 "^${CURRENT_TAG}$" | tail -1)
if [ "$PREV_TAG" = "$CURRENT_TAG" ]; then
PREV_TAG=""
fi
echo "previous_tag=$PREV_TAG" >> $GITHUB_OUTPUT
- name: Generate release template
run: |
cat > release_notes.md << 'EOF'
## What's New
<!--
Write 1-2 sentences describing the main changes in this release.
Example: This release introduces a medication refill tracking feature and improves the mobile user experience.
-->
### New Features
<!-- List new features with **bold** names and descriptions -->
- **Feature Name**: Description of the feature
### Improvements
<!-- List improvements and fixes -->
- **Improvement**: Description
### Where to Find It
<!-- Tell users where they can access new features -->
---
## Docker Images
```bash
docker pull ghcr.io/danielvolz/medassist-ng-backend:${{ steps.version.outputs.version }}
docker pull ghcr.io/danielvolz/medassist-ng-frontend:${{ steps.version.outputs.version }}
```
**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/${{ steps.version.outputs.previous_tag }}...${{ steps.version.outputs.tag }}
EOF
- name: Create Draft Release
uses: softprops/action-gh-release@v1
with:
body_path: release_notes.md
draft: true
generate_release_notes: false
name: "Release ${{ steps.version.outputs.tag }}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+38 -2
View File
@@ -10,10 +10,38 @@ permissions:
jobs: jobs:
# ============================================================================= # =============================================================================
# Backend Tests # Detect which paths changed to skip unnecessary jobs
# =============================================================================
changes:
name: Detect Changes
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
outputs:
backend: ${{ steps.filter.outputs.backend }}
frontend: ${{ steps.filter.outputs.frontend }}
steps:
- uses: dorny/paths-filter@v3
id: filter
with:
filters: |
backend:
- 'backend/**'
- 'biome.json'
- '.github/workflows/test.yml'
frontend:
- 'frontend/**'
- 'biome.json'
- '.github/workflows/test.yml'
# =============================================================================
# Backend Tests (skipped if no backend-related files changed)
# ============================================================================= # =============================================================================
backend-test: backend-test:
name: Backend Tests name: Backend Tests
needs: changes
if: needs.changes.outputs.backend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: read contents: read
@@ -35,6 +63,9 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Lint
run: npm run lint
- name: TypeScript type check - name: TypeScript type check
run: npx tsc --noEmit run: npx tsc --noEmit
@@ -50,10 +81,12 @@ jobs:
retention-days: 7 retention-days: 7
# ============================================================================= # =============================================================================
# Frontend Build Validation # Frontend Build Validation (skipped if no frontend-related files changed)
# ============================================================================= # =============================================================================
frontend-build: frontend-build:
name: Frontend Build name: Frontend Build
needs: changes
if: needs.changes.outputs.frontend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: read contents: read
@@ -75,5 +108,8 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Lint
run: npm run lint
- name: TypeScript type check & build - name: TypeScript type check & build
run: npm run build run: npm run build
+103
View File
@@ -0,0 +1,103 @@
name: Update Test Badges
on:
workflow_dispatch:
workflow_run:
workflows: ["Build and Push Docker Images"]
types: [completed]
branches: [main]
permissions:
contents: write
jobs:
update-badges:
name: Update Test Count Badges
runs-on: ubuntu-latest
# Only run after successful docker builds, not failed ones
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ secrets.BADGE_TOKEN || secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: '**/package-lock.json'
- name: Install backend dependencies
working-directory: backend
run: npm ci
- name: Install frontend dependencies
working-directory: frontend
run: npm ci
- name: Run backend tests and capture count
id: backend-tests
working-directory: backend
timeout-minutes: 5
env:
CI: true
run: |
OUTPUT=$(npm run test:run 2>&1) || true
echo "$OUTPUT"
# Strip ANSI escape codes, then extract "Tests X passed" from output
CLEAN=$(echo "$OUTPUT" | sed 's/\x1b\[[0-9;]*m//g')
PASSED=$(echo "$CLEAN" | grep -oP 'Tests\s+\K\d+(?=\s+passed)' | tail -1)
echo "count=$PASSED" >> $GITHUB_OUTPUT
- name: Run frontend tests and capture count
id: frontend-tests
working-directory: frontend
timeout-minutes: 5
env:
CI: true
run: |
OUTPUT=$(npm run test:run 2>&1) || true
echo "$OUTPUT"
# Strip ANSI escape codes, then extract "Tests X passed" from output
CLEAN=$(echo "$OUTPUT" | sed 's/\x1b\[[0-9;]*m//g')
PASSED=$(echo "$CLEAN" | grep -oP 'Tests\s+\K\d+(?=\s+passed)' | tail -1)
echo "count=$PASSED" >> $GITHUB_OUTPUT
- name: Update README badges
run: |
BACKEND_COUNT="${{ steps.backend-tests.outputs.count }}"
FRONTEND_COUNT="${{ steps.frontend-tests.outputs.count }}"
echo "Backend tests: $BACKEND_COUNT"
echo "Frontend tests: $FRONTEND_COUNT"
# Only update if we got valid counts
if [[ -n "$BACKEND_COUNT" && -n "$FRONTEND_COUNT" ]]; then
# URL encode the slash for shields.io
BACKEND_BADGE="https://img.shields.io/badge/Backend_Tests-${BACKEND_COUNT}%2F${BACKEND_COUNT}-brightgreen?logo=vitest"
FRONTEND_BADGE="https://img.shields.io/badge/Frontend_Tests-${FRONTEND_COUNT}%2F${FRONTEND_COUNT}-brightgreen?logo=vitest"
# Update README using sed
sed -i "s|https://img.shields.io/badge/Backend_Tests-[^\"]*|$BACKEND_BADGE|g" README.md
sed -i "s|https://img.shields.io/badge/Frontend_Tests-[^\"]*|$FRONTEND_BADGE|g" README.md
echo "Updated badges in README.md"
else
echo "Could not extract test counts, skipping update"
exit 0
fi
- name: Commit and push badge updates
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add README.md
if git diff --cached --quiet; then
echo "No badge changes to commit"
else
git commit -m "chore: update test count badges [skip ci]"
git push
fi
+10
View File
@@ -18,6 +18,12 @@ build/
coverage/ coverage/
.nyc_output/ .nyc_output/
# Playwright
/frontend/playwright-report/
/frontend/test-results/
/frontend/e2e/.auth/
/frontend/blob-report/
# =================== # ===================
# Environment # Environment
# =================== # ===================
@@ -71,3 +77,7 @@ Thumbs.db
*.local *.local
.cache/ .cache/
.turbo/ .turbo/
.roo/
.roomodes
AGENTS.md
docs/TECH_STACK.md
+1
View File
@@ -0,0 +1 @@
npx lint-staged
+5
View File
@@ -17,6 +17,11 @@
<img src="https://img.shields.io/badge/Docker-Ready-2496ED?logo=docker" alt="Docker" /> <img src="https://img.shields.io/badge/Docker-Ready-2496ED?logo=docker" alt="Docker" />
</p> </p>
<p align="center">
<img src="https://img.shields.io/badge/Backend_Tests-494%2F494-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
<img src="https://img.shields.io/badge/Frontend_Tests-653%2F653-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
</p>
### 🤖 AI-Generated Code ### 🤖 AI-Generated Code
> This app was 100% coded with Claude Opus 4.5. Use at your own risk. > This app was 100% coded with Claude Opus 4.5. Use at your own risk.
+35
View File
@@ -0,0 +1,35 @@
# Dependencies
node_modules/
# Build outputs
dist/
coverage/
# Development files
*.log
npm-debug.log*
# Test files
src/test/
*.test.ts
vitest.config.ts
# Local data (mounted as volume in production)
data/
# IDE
.vscode/
.idea/
# OS files
.DS_Store
Thumbs.db
# Git
.git/
.gitignore
# Docker
Dockerfile
.dockerignore
docker-compose*.yml
+1 -1
View File
@@ -5,6 +5,6 @@ export default defineConfig({
out: "./drizzle", out: "./drizzle",
dialect: "sqlite", dialect: "sqlite",
dbCredentials: { dbCredentials: {
url: process.env.DATABASE_URL || "./data/medassist.db", url: process.env.DATABASE_URL || "./data/medassist-ng.db",
}, },
}); });
@@ -0,0 +1,3 @@
ALTER TABLE `medications` ADD `dismissed_until` text;--> statement-breakpoint
ALTER TABLE `user_settings` ADD `last_reminder_med_name` text;--> statement-breakpoint
ALTER TABLE `user_settings` ADD `last_reminder_taken_by` text;
@@ -0,0 +1,3 @@
-- Add package type support (blister vs bottle)
ALTER TABLE medications ADD COLUMN package_type TEXT DEFAULT 'blister' NOT NULL;
ALTER TABLE medications ADD COLUMN total_pills INTEGER;
@@ -0,0 +1,3 @@
-- Add dose_unit column and intakes JSON array for per-intake takenBy support
ALTER TABLE `medications` ADD `dose_unit` text(20) DEFAULT 'mg';--> statement-breakpoint
ALTER TABLE `medications` ADD `intakes_json` text DEFAULT '[]' NOT NULL;
+855
View File
@@ -0,0 +1,855 @@
{
"version": "6",
"dialect": "sqlite",
"id": "4f1d8273-1e60-4da1-9bfc-bd51c2784836",
"prevId": "098ee506-e43d-4ccb-bee5-c387905695ab",
"tables": {
"dose_tracking": {
"name": "dose_tracking",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"dose_id": {
"name": "dose_id",
"type": "text(255)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"taken_at": {
"name": "taken_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%s','now'))"
},
"marked_by": {
"name": "marked_by",
"type": "text(100)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"dismissed": {
"name": "dismissed",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
}
},
"indexes": {},
"foreignKeys": {
"dose_tracking_user_id_users_id_fk": {
"name": "dose_tracking_user_id_users_id_fk",
"tableFrom": "dose_tracking",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"medications": {
"name": "medications",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text(100)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"generic_name": {
"name": "generic_name",
"type": "text(100)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"taken_by_json": {
"name": "taken_by_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"pack_count": {
"name": "pack_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 1
},
"blisters_per_pack": {
"name": "blisters_per_pack",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 1
},
"pills_per_blister": {
"name": "pills_per_blister",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 1
},
"loose_tablets": {
"name": "loose_tablets",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"stock_adjustment": {
"name": "stock_adjustment",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"last_stock_correction_at": {
"name": "last_stock_correction_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pill_weight_mg": {
"name": "pill_weight_mg",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"usage_json": {
"name": "usage_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"every_json": {
"name": "every_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"start_json": {
"name": "start_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"image_url": {
"name": "image_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"expiry_date": {
"name": "expiry_date",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"notes": {
"name": "notes",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"intake_reminders_enabled": {
"name": "intake_reminders_enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"dismissed_until": {
"name": "dismissed_until",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {},
"foreignKeys": {
"medications_user_id_users_id_fk": {
"name": "medications_user_id_users_id_fk",
"tableFrom": "medications",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"refill_history": {
"name": "refill_history",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"medication_id": {
"name": "medication_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"packs_added": {
"name": "packs_added",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"loose_pills_added": {
"name": "loose_pills_added",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"refill_date": {
"name": "refill_date",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%s','now'))"
}
},
"indexes": {},
"foreignKeys": {
"refill_history_medication_id_medications_id_fk": {
"name": "refill_history_medication_id_medications_id_fk",
"tableFrom": "refill_history",
"tableTo": "medications",
"columnsFrom": [
"medication_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"refill_history_user_id_users_id_fk": {
"name": "refill_history_user_id_users_id_fk",
"tableFrom": "refill_history",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"refresh_tokens": {
"name": "refresh_tokens",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"token_id": {
"name": "token_id",
"type": "text(255)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"rotated_at": {
"name": "rotated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"revoked": {
"name": "revoked",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {
"refresh_tokens_token_id_unique": {
"name": "refresh_tokens_token_id_unique",
"columns": [
"token_id"
],
"isUnique": true
}
},
"foreignKeys": {
"refresh_tokens_user_id_users_id_fk": {
"name": "refresh_tokens_user_id_users_id_fk",
"tableFrom": "refresh_tokens",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"share_tokens": {
"name": "share_tokens",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"token": {
"name": "token",
"type": "text(64)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"taken_by": {
"name": "taken_by",
"type": "text(100)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"schedule_days": {
"name": "schedule_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 30
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"share_tokens_token_unique": {
"name": "share_tokens_token_unique",
"columns": [
"token"
],
"isUnique": true
}
},
"foreignKeys": {
"share_tokens_user_id_users_id_fk": {
"name": "share_tokens_user_id_users_id_fk",
"tableFrom": "share_tokens",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user_settings": {
"name": "user_settings",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email_enabled": {
"name": "email_enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"notification_email": {
"name": "notification_email",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"email_stock_reminders": {
"name": "email_stock_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"email_intake_reminders": {
"name": "email_intake_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"shoutrrr_enabled": {
"name": "shoutrrr_enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"shoutrrr_url": {
"name": "shoutrrr_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"shoutrrr_stock_reminders": {
"name": "shoutrrr_stock_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"shoutrrr_intake_reminders": {
"name": "shoutrrr_intake_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"reminder_days_before": {
"name": "reminder_days_before",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 7
},
"repeat_daily_reminders": {
"name": "repeat_daily_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"skip_reminders_for_taken_doses": {
"name": "skip_reminders_for_taken_doses",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"repeat_reminders_enabled": {
"name": "repeat_reminders_enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"reminder_repeat_interval_minutes": {
"name": "reminder_repeat_interval_minutes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 30
},
"max_nagging_reminders": {
"name": "max_nagging_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 5
},
"low_stock_days": {
"name": "low_stock_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 30
},
"normal_stock_days": {
"name": "normal_stock_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 90
},
"high_stock_days": {
"name": "high_stock_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 180
},
"expiry_warning_days": {
"name": "expiry_warning_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 90
},
"language": {
"name": "language",
"type": "text(10)",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'en'"
},
"stock_calculation_mode": {
"name": "stock_calculation_mode",
"type": "text(20)",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'automatic'"
},
"last_auto_email_sent": {
"name": "last_auto_email_sent",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_notification_type": {
"name": "last_notification_type",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_notification_channel": {
"name": "last_notification_channel",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_reminder_med_name": {
"name": "last_reminder_med_name",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_reminder_taken_by": {
"name": "last_reminder_taken_by",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {
"user_settings_user_id_unique": {
"name": "user_settings_user_id_unique",
"columns": [
"user_id"
],
"isUnique": true
}
},
"foreignKeys": {
"user_settings_user_id_users_id_fk": {
"name": "user_settings_user_id_users_id_fk",
"tableFrom": "user_settings",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"username": {
"name": "username",
"type": "text(100)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"password_hash": {
"name": "password_hash",
"type": "text(255)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"avatar_url": {
"name": "avatar_url",
"type": "text(255)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"auth_provider": {
"name": "auth_provider",
"type": "text(50)",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'local'"
},
"oidc_subject": {
"name": "oidc_subject",
"type": "text(255)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"is_active": {
"name": "is_active",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"last_login_at": {
"name": "last_login_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {
"users_username_unique": {
"name": "users_username_unique",
"columns": [
"username"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+886
View File
@@ -0,0 +1,886 @@
{
"version": "6",
"dialect": "sqlite",
"id": "fb61e5fd-152d-4e61-8836-e2fd1d28e3f0",
"prevId": "4f1d8273-1e60-4da1-9bfc-bd51c2784836",
"tables": {
"dose_tracking": {
"name": "dose_tracking",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"dose_id": {
"name": "dose_id",
"type": "text(255)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"taken_at": {
"name": "taken_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%s','now'))"
},
"marked_by": {
"name": "marked_by",
"type": "text(100)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"dismissed": {
"name": "dismissed",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
}
},
"indexes": {},
"foreignKeys": {
"dose_tracking_user_id_users_id_fk": {
"name": "dose_tracking_user_id_users_id_fk",
"tableFrom": "dose_tracking",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"medications": {
"name": "medications",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text(100)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"generic_name": {
"name": "generic_name",
"type": "text(100)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"taken_by_json": {
"name": "taken_by_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"package_type": {
"name": "package_type",
"type": "text(20)",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'blister'"
},
"pack_count": {
"name": "pack_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 1
},
"blisters_per_pack": {
"name": "blisters_per_pack",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 1
},
"pills_per_blister": {
"name": "pills_per_blister",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 1
},
"total_pills": {
"name": "total_pills",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"loose_tablets": {
"name": "loose_tablets",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"stock_adjustment": {
"name": "stock_adjustment",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"last_stock_correction_at": {
"name": "last_stock_correction_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"pill_weight_mg": {
"name": "pill_weight_mg",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"dose_unit": {
"name": "dose_unit",
"type": "text(20)",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "'mg'"
},
"usage_json": {
"name": "usage_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"every_json": {
"name": "every_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"start_json": {
"name": "start_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"intakes_json": {
"name": "intakes_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"image_url": {
"name": "image_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"expiry_date": {
"name": "expiry_date",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"notes": {
"name": "notes",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"intake_reminders_enabled": {
"name": "intake_reminders_enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"dismissed_until": {
"name": "dismissed_until",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {},
"foreignKeys": {
"medications_user_id_users_id_fk": {
"name": "medications_user_id_users_id_fk",
"tableFrom": "medications",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"refill_history": {
"name": "refill_history",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"medication_id": {
"name": "medication_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"packs_added": {
"name": "packs_added",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"loose_pills_added": {
"name": "loose_pills_added",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"refill_date": {
"name": "refill_date",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%s','now'))"
}
},
"indexes": {},
"foreignKeys": {
"refill_history_medication_id_medications_id_fk": {
"name": "refill_history_medication_id_medications_id_fk",
"tableFrom": "refill_history",
"tableTo": "medications",
"columnsFrom": [
"medication_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"refill_history_user_id_users_id_fk": {
"name": "refill_history_user_id_users_id_fk",
"tableFrom": "refill_history",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"refresh_tokens": {
"name": "refresh_tokens",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"token_id": {
"name": "token_id",
"type": "text(255)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"rotated_at": {
"name": "rotated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"revoked": {
"name": "revoked",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {
"refresh_tokens_token_id_unique": {
"name": "refresh_tokens_token_id_unique",
"columns": [
"token_id"
],
"isUnique": true
}
},
"foreignKeys": {
"refresh_tokens_user_id_users_id_fk": {
"name": "refresh_tokens_user_id_users_id_fk",
"tableFrom": "refresh_tokens",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"share_tokens": {
"name": "share_tokens",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"token": {
"name": "token",
"type": "text(64)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"taken_by": {
"name": "taken_by",
"type": "text(100)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"schedule_days": {
"name": "schedule_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 30
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"share_tokens_token_unique": {
"name": "share_tokens_token_unique",
"columns": [
"token"
],
"isUnique": true
}
},
"foreignKeys": {
"share_tokens_user_id_users_id_fk": {
"name": "share_tokens_user_id_users_id_fk",
"tableFrom": "share_tokens",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user_settings": {
"name": "user_settings",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email_enabled": {
"name": "email_enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"notification_email": {
"name": "notification_email",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"email_stock_reminders": {
"name": "email_stock_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"email_intake_reminders": {
"name": "email_intake_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"shoutrrr_enabled": {
"name": "shoutrrr_enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"shoutrrr_url": {
"name": "shoutrrr_url",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"shoutrrr_stock_reminders": {
"name": "shoutrrr_stock_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"shoutrrr_intake_reminders": {
"name": "shoutrrr_intake_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"reminder_days_before": {
"name": "reminder_days_before",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 7
},
"repeat_daily_reminders": {
"name": "repeat_daily_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"skip_reminders_for_taken_doses": {
"name": "skip_reminders_for_taken_doses",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"repeat_reminders_enabled": {
"name": "repeat_reminders_enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"reminder_repeat_interval_minutes": {
"name": "reminder_repeat_interval_minutes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 30
},
"max_nagging_reminders": {
"name": "max_nagging_reminders",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 5
},
"low_stock_days": {
"name": "low_stock_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 30
},
"normal_stock_days": {
"name": "normal_stock_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 90
},
"high_stock_days": {
"name": "high_stock_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 180
},
"expiry_warning_days": {
"name": "expiry_warning_days",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 90
},
"language": {
"name": "language",
"type": "text(10)",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'en'"
},
"stock_calculation_mode": {
"name": "stock_calculation_mode",
"type": "text(20)",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'automatic'"
},
"last_auto_email_sent": {
"name": "last_auto_email_sent",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_notification_type": {
"name": "last_notification_type",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_notification_channel": {
"name": "last_notification_channel",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_reminder_med_name": {
"name": "last_reminder_med_name",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_reminder_taken_by": {
"name": "last_reminder_taken_by",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {
"user_settings_user_id_unique": {
"name": "user_settings_user_id_unique",
"columns": [
"user_id"
],
"isUnique": true
}
},
"foreignKeys": {
"user_settings_user_id_users_id_fk": {
"name": "user_settings_user_id_users_id_fk",
"tableFrom": "user_settings",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"username": {
"name": "username",
"type": "text(100)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"password_hash": {
"name": "password_hash",
"type": "text(255)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"avatar_url": {
"name": "avatar_url",
"type": "text(255)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"auth_provider": {
"name": "auth_provider",
"type": "text(50)",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'local'"
},
"oidc_subject": {
"name": "oidc_subject",
"type": "text(255)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"is_active": {
"name": "is_active",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"last_login_at": {
"name": "last_login_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {
"users_username_unique": {
"name": "users_username_unique",
"columns": [
"username"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+21
View File
@@ -22,6 +22,27 @@
"when": 1768736677092, "when": 1768736677092,
"tag": "0002_add_last_stock_correction_at", "tag": "0002_add_last_stock_correction_at",
"breakpoints": true "breakpoints": true
},
{
"idx": 3,
"version": "6",
"when": 1769354512857,
"tag": "0003_add_reminder_info_columns",
"breakpoints": true
},
{
"idx": 4,
"version": "6",
"when": 1769886564000,
"tag": "0004_add_package_type",
"breakpoints": true
},
{
"idx": 5,
"version": "6",
"when": 1769893708813,
"tag": "0005_add_intakes_json",
"breakpoints": true
} }
] ]
} }
+174 -16
View File
@@ -1,12 +1,12 @@
{ {
"name": "medassist-ng-backend", "name": "medassist-ng-backend",
"version": "1.1.0", "version": "1.8.8",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "medassist-ng-backend", "name": "medassist-ng-backend",
"version": "1.1.0", "version": "1.8.8",
"dependencies": { "dependencies": {
"@fastify/cookie": "^10.0.1", "@fastify/cookie": "^10.0.1",
"@fastify/cors": "^10.0.1", "@fastify/cors": "^10.0.1",
@@ -20,12 +20,13 @@
"argon2": "^0.40.0", "argon2": "^0.40.0",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"drizzle-orm": "^0.45.1", "drizzle-orm": "^0.45.1",
"fastify": "^5.0.0", "fastify": "^5.7.3",
"nodemailer": "^7.0.11", "nodemailer": "^7.0.11",
"openid-client": "^6.8.1", "openid-client": "^6.8.1",
"zod": "^3.23.8" "zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^2.3.12",
"@types/node": "^22.7.4", "@types/node": "^22.7.4",
"@types/nodemailer": "^6.4.21", "@types/nodemailer": "^6.4.21",
"@types/supertest": "^6.0.2", "@types/supertest": "^6.0.2",
@@ -785,6 +786,169 @@
"node": ">=18" "node": ">=18"
} }
}, },
"node_modules/@biomejs/biome": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.3.12.tgz",
"integrity": "sha512-AR7h4aSlAvXj7TAajW/V12BOw2EiS0AqZWV5dGozf4nlLoUF/ifvD0+YgKSskT0ylA6dY1A8AwgP8kZ6yaCQnA==",
"dev": true,
"license": "MIT OR Apache-2.0",
"bin": {
"biome": "bin/biome"
},
"engines": {
"node": ">=14.21.3"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/biome"
},
"optionalDependencies": {
"@biomejs/cli-darwin-arm64": "2.3.12",
"@biomejs/cli-darwin-x64": "2.3.12",
"@biomejs/cli-linux-arm64": "2.3.12",
"@biomejs/cli-linux-arm64-musl": "2.3.12",
"@biomejs/cli-linux-x64": "2.3.12",
"@biomejs/cli-linux-x64-musl": "2.3.12",
"@biomejs/cli-win32-arm64": "2.3.12",
"@biomejs/cli-win32-x64": "2.3.12"
}
},
"node_modules/@biomejs/cli-darwin-arm64": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.3.12.tgz",
"integrity": "sha512-cO6fn+KiMBemva6EARDLQBxeyvLzgidaFRJi8G7OeRqz54kWK0E+uSjgFaiHlc3DZYoa0+1UFE8mDxozpc9ieg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-darwin-x64": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.3.12.tgz",
"integrity": "sha512-/fiF/qmudKwSdvmSrSe/gOTkW77mHHkH8Iy7YC2rmpLuk27kbaUOPa7kPiH5l+3lJzTUfU/t6x1OuIq/7SGtxg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-arm64": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.3.12.tgz",
"integrity": "sha512-nbOsuQROa3DLla5vvsTZg+T5WVPGi9/vYxETm9BOuLHBJN3oWQIg3MIkE2OfL18df1ZtNkqXkH6Yg9mdTPem7A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-arm64-musl": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.3.12.tgz",
"integrity": "sha512-aqkeSf7IH+wkzFpKeDVPSXy9uDjxtLpYA6yzkYsY+tVjwFFirSuajHDI3ul8en90XNs1NA0n8kgBrjwRi5JeyA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-x64": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.3.12.tgz",
"integrity": "sha512-CQtqrJ+qEEI8tgRSTjjzk6wJAwfH3wQlkIGsM5dlecfRZaoT+XCms/mf7G4kWNexrke6mnkRzNy6w8ebV177ow==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-x64-musl": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.3.12.tgz",
"integrity": "sha512-kVGWtupRRsOjvw47YFkk5mLiAdpCPMWBo1jOwAzh+juDpUb2sWarIp+iq+CPL1Wt0LLZnYtP7hH5kD6fskcxmg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-win32-arm64": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.3.12.tgz",
"integrity": "sha512-Re4I7UnOoyE4kHMqpgtG6UvSBGBbbtvsOvBROgCCoH7EgANN6plSQhvo2W7OCITvTp7gD6oZOyZy72lUdXjqZg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-win32-x64": {
"version": "2.3.12",
"resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.3.12.tgz",
"integrity": "sha512-qqGVWqNNek0KikwPZlOIoxtXgsNGsX+rgdEzgw82Re8nF02W+E2WokaQhpF5TdBh/D/RQ3TLppH+otp6ztN0lw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@drizzle-team/brocli": { "node_modules/@drizzle-team/brocli": {
"version": "0.10.2", "version": "0.10.2",
"resolved": "https://registry.npmjs.org/@drizzle-team/brocli/-/brocli-0.10.2.tgz", "resolved": "https://registry.npmjs.org/@drizzle-team/brocli/-/brocli-0.10.2.tgz",
@@ -2018,9 +2182,9 @@
} }
}, },
"node_modules/@isaacs/brace-expansion": { "node_modules/@isaacs/brace-expansion": {
"version": "5.0.0", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz", "resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.1.tgz",
"integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==", "integrity": "sha512-WMz71T1JS624nWj2n2fnYAuPovhv7EUhk69R6i9dsVyzxt5eM3bjwvgk9L+APE1TRscGysAVMANkB0jh0LQZrQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@isaacs/balanced-match": "^4.0.1" "@isaacs/balanced-match": "^4.0.1"
@@ -2079,7 +2243,6 @@
"resolved": "https://registry.npmjs.org/@libsql/client/-/client-0.10.0.tgz", "resolved": "https://registry.npmjs.org/@libsql/client/-/client-0.10.0.tgz",
"integrity": "sha512-2ERn08T4XOVx34yBtUPq0RDjAdd9TJ5qNH/izugr208ml2F94mk92qC64kXyDVQINodWJvp3kAdq6P4zTtCZ7g==", "integrity": "sha512-2ERn08T4XOVx34yBtUPq0RDjAdd9TJ5qNH/izugr208ml2F94mk92qC64kXyDVQINodWJvp3kAdq6P4zTtCZ7g==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@libsql/core": "^0.10.0", "@libsql/core": "^0.10.0",
"@libsql/hrana-client": "^0.6.2", "@libsql/hrana-client": "^0.6.2",
@@ -4579,7 +4742,6 @@
"dev": true, "dev": true,
"hasInstallScript": true, "hasInstallScript": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"esbuild": "bin/esbuild" "esbuild": "bin/esbuild"
}, },
@@ -4769,9 +4931,9 @@
} }
}, },
"node_modules/fastify": { "node_modules/fastify": {
"version": "5.6.2", "version": "5.7.3",
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.6.2.tgz", "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.7.3.tgz",
"integrity": "sha512-dPugdGnsvYkBlENLhCgX8yhyGCsCPrpA8lFWbTNU428l+YOnLgYHR69hzV8HWPC79n536EqzqQtvhtdaCE0dKg==", "integrity": "sha512-QHzWSmTNUg9Ba8tNXzb92FTH77K+c8yeQPH80EeSIc9wyZj85jbPisMP0rwmyKv8oJwUFPe1UpN8HkNIXwCnUQ==",
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -4784,7 +4946,7 @@
], ],
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@fastify/ajv-compiler": "^4.0.0", "@fastify/ajv-compiler": "^4.0.5",
"@fastify/error": "^4.0.0", "@fastify/error": "^4.0.0",
"@fastify/fast-json-stringify-compiler": "^5.0.0", "@fastify/fast-json-stringify-compiler": "^5.0.0",
"@fastify/proxy-addr": "^5.0.0", "@fastify/proxy-addr": "^5.0.0",
@@ -5776,7 +5938,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -6538,7 +6699,6 @@
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "~0.27.0", "esbuild": "~0.27.0",
"get-tsconfig": "^4.7.5" "get-tsconfig": "^4.7.5"
@@ -6602,7 +6762,6 @@
"integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==", "integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.27.0", "esbuild": "^0.27.0",
"fdir": "^6.5.0", "fdir": "^6.5.0",
@@ -6678,7 +6837,6 @@
"integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==", "integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@vitest/expect": "4.0.16", "@vitest/expect": "4.0.16",
"@vitest/mocker": "4.0.16", "@vitest/mocker": "4.0.16",
+8 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "medassist-ng-backend", "name": "medassist-ng-backend",
"version": "1.4.1", "version": "1.8.8",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
@@ -10,7 +10,11 @@
"migrate": "tsx src/db/migrate.ts", "migrate": "tsx src/db/migrate.ts",
"test": "vitest", "test": "vitest",
"test:run": "vitest run", "test:run": "vitest run",
"test:coverage": "vitest run --coverage" "test:coverage": "vitest run --coverage",
"lint": "npx biome check .",
"lint:fix": "npx biome check --write .",
"format": "npx biome format --write .",
"check": "npx biome check . && tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@fastify/cookie": "^10.0.1", "@fastify/cookie": "^10.0.1",
@@ -25,12 +29,13 @@
"argon2": "^0.40.0", "argon2": "^0.40.0",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"drizzle-orm": "^0.45.1", "drizzle-orm": "^0.45.1",
"fastify": "^5.0.0", "fastify": "^5.7.3",
"nodemailer": "^7.0.11", "nodemailer": "^7.0.11",
"openid-client": "^6.8.1", "openid-client": "^6.8.1",
"zod": "^3.23.8" "zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^2.3.12",
"@types/node": "^22.7.4", "@types/node": "^22.7.4",
"@types/nodemailer": "^6.4.21", "@types/nodemailer": "^6.4.21",
"@types/supertest": "^6.0.2", "@types/supertest": "^6.0.2",
+52 -139
View File
@@ -1,144 +1,37 @@
import { createClient, Client } from "@libsql/client"; import { existsSync, statSync } from "node:fs";
import { drizzle } from "drizzle-orm/libsql"; import { resolve } from "node:path";
import { migrate } from "drizzle-orm/libsql/migrator"; import { type Client, createClient } from "@libsql/client";
import { existsSync, mkdirSync, accessSync, constants, statSync, writeFileSync } from "fs";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
import dotenv from "dotenv"; import dotenv from "dotenv";
import { drizzle } from "drizzle-orm/libsql";
dotenv.config({ path: process.env.DOTENV_PATH || ".env" }); // Import utilities from db-utils (side-effect-free)
import {
ensureDataDirectory,
ensureDefaultUser,
getDataDir,
getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations,
runDrizzleMigrations,
} from "./db-utils.js";
// Get migrations folder path (relative to this file's location) // Re-export all utilities so existing imports from client.ts keep working
const __filename = fileURLToPath(import.meta.url); export {
const __dirname = dirname(__filename); buildDbUrl,
const migrationsFolder = resolve(__dirname, "../../drizzle"); ensureDataDirectory,
ensureDefaultUser,
getDataDir,
getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations,
runDrizzleMigrations,
} from "./db-utils.js";
// ============================================================================= // Load .env: try cwd first, then parent dir (for local dev running from backend/)
// Exported utility functions for testing const envPath = process.env.DOTENV_PATH || (existsSync(".env") ? ".env" : "../.env");
// ============================================================================= dotenv.config({ path: envPath });
/** Build the database URL from a path */
export function buildDbUrl(dbPath: string): string {
return `file:${dbPath}`;
}
/** Get data directory and database path */
export function getDbPaths(cwd: string = process.cwd()): { dataDir: string; dbPath: string; url: string } {
const dataDir = resolve(cwd, "data");
const dbPath = resolve(dataDir, "medassist-ng.db");
const url = buildDbUrl(dbPath);
return { dataDir, dbPath, url };
}
/** Ensure data directory exists and is writable */
export function ensureDataDirectory(dataDir: string): { success: boolean; error?: string } {
try {
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true });
}
// Check if directory is writable
accessSync(dataDir, constants.W_OK);
// Try to create a test file to verify write access
const testFile = resolve(dataDir, ".write-test");
writeFileSync(testFile, "test");
return { success: true };
} catch (err: any) {
return { success: false, error: err.message };
}
}
/** Run drizzle-kit migrations on the database */
export async function runDrizzleMigrations(database: ReturnType<typeof drizzle>): Promise<{ success: boolean; error?: string }> {
try {
await migrate(database, { migrationsFolder });
return { success: true };
} catch (err: any) {
return { success: false, error: err.message };
}
}
/** Run ALTER TABLE migrations for backward compatibility with older databases */
export async function runAlterMigrations(client: Client): Promise<{ success: boolean; errors: string[] }> {
const errors: string[] = [];
// These add new columns to existing tables (silently fail if column already exists)
const alterMigrations = [
// Added in v1.x - repeat reminders and nagging settings
`ALTER TABLE user_settings ADD COLUMN skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0`,
`ALTER TABLE user_settings ADD COLUMN repeat_reminders_enabled integer NOT NULL DEFAULT 0`,
`ALTER TABLE user_settings ADD COLUMN reminder_repeat_interval_minutes integer NOT NULL DEFAULT 30`,
`ALTER TABLE user_settings ADD COLUMN max_nagging_reminders integer NOT NULL DEFAULT 5`,
// Added in v1.2.3 - dismiss missed doses without deducting stock
`ALTER TABLE dose_tracking ADD COLUMN dismissed integer NOT NULL DEFAULT 0`,
// Added in v1.3.x - stock calculation mode (automatic/manual)
`ALTER TABLE user_settings ADD COLUMN stock_calculation_mode text NOT NULL DEFAULT 'automatic'`,
// Added for stock correction - hidden offset that doesn't affect looseTablets
`ALTER TABLE medications ADD COLUMN stock_adjustment integer NOT NULL DEFAULT 0`,
// Added for stock correction - timestamp to ignore consumed doses before correction
`ALTER TABLE medications ADD COLUMN last_stock_correction_at integer`,
];
for (const sql of alterMigrations) {
try {
await client.execute(sql);
} catch (e: any) {
// Silently ignore "duplicate column" errors - column already exists
if (!e.message?.includes("duplicate column")) {
errors.push(e.message);
}
}
}
// Create tables that might be missing (silently fail if already exists)
const createTableMigrations = [
// Added in v1.3.x - refill history tracking
`CREATE TABLE IF NOT EXISTS refill_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
medication_id INTEGER NOT NULL REFERENCES medications(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
packs_added INTEGER NOT NULL DEFAULT 0,
loose_pills_added INTEGER NOT NULL DEFAULT 0,
refill_date INTEGER NOT NULL DEFAULT (strftime('%s','now'))
)`,
];
for (const sql of createTableMigrations) {
try {
await client.execute(sql);
} catch (e: any) {
// Silently ignore "table already exists" errors
if (!e.message?.includes("already exists")) {
errors.push(e.message);
}
}
}
return { success: errors.length === 0, errors };
}
/** Ensure default user exists for auth-disabled mode */
export async function ensureDefaultUser(client: Client, authEnabled: boolean): Promise<boolean> {
if (authEnabled) {
return false; // No default user needed
}
try {
const result = await client.execute("SELECT id FROM users WHERE id = 1");
if (result.rows.length === 0) {
await client.execute(
"INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')"
);
return true; // Created
}
return false; // Already exists
} catch (e: any) {
console.error(`[DB] Error creating default user:`, e.message);
return false;
}
}
// ============================================================================= // =============================================================================
// Database initialization (runs on import) // Database initialization (runs on import)
@@ -183,10 +76,12 @@ export const db = drizzle(client);
// Auto-run migrations (self-healing database) // Auto-run migrations (self-healing database)
async function runMigrations() { async function runMigrations() {
// Run drizzle-kit generated migrations // Run drizzle-kit generated migrations
console.log(`[DB] Running drizzle migrations from: ${migrationsFolder}`); console.log(`[DB] Running drizzle migrations...`);
const migrateResult = await runDrizzleMigrations(db); const migrateResult = await runDrizzleMigrations(db);
if (!migrateResult.success) { if (!migrateResult.success) {
console.error(`[DB] Migration error:`, migrateResult.error); console.error(`[DB] Migration error:`, migrateResult.error);
} else if (migrateResult.warning) {
console.log(`[DB] Migration warning:`, migrateResult.warning);
} else { } else {
console.log(`[DB] Drizzle migrations completed`); console.log(`[DB] Drizzle migrations completed`);
} }
@@ -194,10 +89,28 @@ async function runMigrations() {
// Run ALTER TABLE migrations for backward compatibility // Run ALTER TABLE migrations for backward compatibility
const alterResult = await runAlterMigrations(client); const alterResult = await runAlterMigrations(client);
if (alterResult.errors.length > 0) { if (alterResult.errors.length > 0) {
alterResult.errors.forEach(err => console.error(`[DB] ALTER migration error:`, err)); alterResult.errors.forEach((err) => console.error(`[DB] ALTER migration error:`, err));
} }
console.log(`[DB] Tables verified/created`); console.log(`[DB] Tables verified/created`);
// Repair dose IDs with trailing hyphens (from frontend takenBy bug)
const trailingResult = await repairTrailingHyphenDoseIds(client);
if (trailingResult.repaired > 0) {
console.log(`[DB] Repaired ${trailingResult.repaired} dose IDs with trailing hyphens`);
}
if (trailingResult.errors.length > 0) {
trailingResult.errors.forEach((err) => console.error(`[DB] Trailing-hyphen repair error:`, err));
}
// Repair orphaned dose tracking IDs from past schedule changes
const repairResult = await repairOrphanedDoseIds(client);
if (repairResult.repaired > 0) {
console.log(`[DB] Repaired ${repairResult.repaired} orphaned dose tracking IDs`);
}
if (repairResult.errors.length > 0) {
repairResult.errors.forEach((err) => console.error(`[DB] Dose repair error:`, err));
}
// If auth is disabled, ensure a default user exists (ID=1) // If auth is disabled, ensure a default user exists (ID=1)
const authEnabled = process.env.AUTH_ENABLED === "true"; const authEnabled = process.env.AUTH_ENABLED === "true";
const created = await ensureDefaultUser(client, authEnabled); const created = await ensureDefaultUser(client, authEnabled);
+352
View File
@@ -0,0 +1,352 @@
/**
* Pure utility functions for database operations.
* Separated from client.ts to allow importing without triggering
* top-level database initialization side effects.
*/
import { accessSync, constants, existsSync, mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import type { Client } from "@libsql/client";
import type { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator";
import { parseIntakesJson, parseLocalDateTime } from "../utils/scheduler-utils.js";
// Get migrations folder path (relative to this file's location)
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const migrationsFolder = resolve(__dirname, "../../drizzle");
// =============================================================================
// Path & Directory utilities
// =============================================================================
/**
* Get the data directory path.
*
* Resolution order:
* 1. DATA_DIR env var (set by docker-compose for containers)
* 2. Monorepo detection: if ../docker-compose.yml exists, we're in backend/
* subdirectory → use ../data (project root's data folder)
* 3. Fallback: resolve(cwd, "data") (running from project root or standalone)
*/
export function getDataDir(cwd: string = process.cwd()): string {
// Docker containers set DATA_DIR explicitly
if (process.env.DATA_DIR) return resolve(process.env.DATA_DIR);
// Local dev: detect if we're in backend/ subdirectory of the monorepo
if (existsSync(resolve(cwd, "..", "docker-compose.yml"))) {
return resolve(cwd, "..", "data");
}
// Default: data/ relative to cwd (running from project root)
return resolve(cwd, "data");
}
/** Build the database URL from a path */
export function buildDbUrl(dbPath: string): string {
return `file:${dbPath}`;
}
/** Get data directory and database path */
export function getDbPaths(cwd: string = process.cwd()): { dataDir: string; dbPath: string; url: string } {
const dataDir = getDataDir(cwd);
const dbPath = resolve(dataDir, "medassist-ng.db");
const url = buildDbUrl(dbPath);
return { dataDir, dbPath, url };
}
/** Ensure data directory exists and is writable */
export function ensureDataDirectory(dataDir: string): { success: boolean; error?: string } {
try {
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true });
}
// Check if directory is writable
accessSync(dataDir, constants.W_OK);
// Try to create a test file to verify write access
const testFile = resolve(dataDir, ".write-test");
writeFileSync(testFile, "test");
return { success: true };
} catch (err: any) {
return { success: false, error: err.message };
}
}
// =============================================================================
// Migration utilities
// =============================================================================
/** Run drizzle-kit migrations on the database */
export async function runDrizzleMigrations(
database: ReturnType<typeof drizzle>
): Promise<{ success: boolean; error?: string; warning?: string }> {
try {
await migrate(database, { migrationsFolder });
return { success: true };
} catch (err: any) {
// If the error is "duplicate column", it means the schema is already up-to-date
// This happens when ALTER migrations in client.ts have already added the columns
// We consider this a success with a warning, not a failure
if (err.message?.includes("duplicate column")) {
return { success: true, warning: `Schema already up-to-date: ${err.message}` };
}
return { success: false, error: err.message };
}
}
/** Run ALTER TABLE migrations for backward compatibility with older databases */
export async function runAlterMigrations(client: Client): Promise<{ success: boolean; errors: string[] }> {
const errors: string[] = [];
// These add new columns to existing tables (silently fail if column already exists)
const alterMigrations = [
// Added in v1.x - repeat reminders and nagging settings
`ALTER TABLE user_settings ADD COLUMN skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0`,
`ALTER TABLE user_settings ADD COLUMN repeat_reminders_enabled integer NOT NULL DEFAULT 0`,
`ALTER TABLE user_settings ADD COLUMN reminder_repeat_interval_minutes integer NOT NULL DEFAULT 30`,
`ALTER TABLE user_settings ADD COLUMN max_nagging_reminders integer NOT NULL DEFAULT 5`,
// Added in v1.2.3 - dismiss missed doses without deducting stock
`ALTER TABLE dose_tracking ADD COLUMN dismissed integer NOT NULL DEFAULT 0`,
// Added in v1.3.x - stock calculation mode (automatic/manual)
`ALTER TABLE user_settings ADD COLUMN stock_calculation_mode text NOT NULL DEFAULT 'automatic'`,
// Added for stock correction - hidden offset that doesn't affect looseTablets
`ALTER TABLE medications ADD COLUMN stock_adjustment integer NOT NULL DEFAULT 0`,
// Added for stock correction - timestamp to ignore consumed doses before correction
`ALTER TABLE medications ADD COLUMN last_stock_correction_at integer`,
// Added in v1.5.1 - dismiss past doses until date (robust against timestamp changes)
`ALTER TABLE medications ADD COLUMN dismissed_until text`,
// Added for more detailed reminder info display
`ALTER TABLE user_settings ADD COLUMN last_reminder_med_name text`,
`ALTER TABLE user_settings ADD COLUMN last_reminder_taken_by text`,
// Added for package type support (blister vs bottle)
`ALTER TABLE medications ADD COLUMN package_type text NOT NULL DEFAULT 'blister'`,
`ALTER TABLE medications ADD COLUMN total_pills integer`,
// Added for dose unit selection (mg, g, mcg, ml, IU, etc.)
`ALTER TABLE medications ADD COLUMN dose_unit text DEFAULT 'mg'`,
// Added for intake-level takenBy: unified intakes structure
`ALTER TABLE medications ADD COLUMN intakes_json text NOT NULL DEFAULT '[]'`,
];
for (const sql of alterMigrations) {
try {
await client.execute(sql);
} catch (e: any) {
// Silently ignore "duplicate column" errors - column already exists
if (!e.message?.includes("duplicate column")) {
errors.push(e.message);
}
}
}
// Create tables that might be missing (silently fail if already exists)
const createTableMigrations = [
// Added in v1.3.x - refill history tracking
`CREATE TABLE IF NOT EXISTS refill_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
medication_id INTEGER NOT NULL REFERENCES medications(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
packs_added INTEGER NOT NULL DEFAULT 0,
loose_pills_added INTEGER NOT NULL DEFAULT 0,
refill_date INTEGER NOT NULL DEFAULT (strftime('%s','now'))
)`,
];
for (const sql of createTableMigrations) {
try {
await client.execute(sql);
} catch (e: any) {
// Silently ignore "table already exists" errors
if (!e.message?.includes("already exists")) {
errors.push(e.message);
}
}
}
return { success: errors.length === 0, errors };
}
// =============================================================================
// User utilities
// =============================================================================
/** Ensure default user exists for auth-disabled mode */
export async function ensureDefaultUser(client: Client, authEnabled: boolean): Promise<boolean> {
if (authEnabled) {
return false; // No default user needed
}
try {
const result = await client.execute("SELECT id FROM users WHERE id = 1");
if (result.rows.length === 0) {
await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')");
return true; // Created
}
return false; // Already exists
} catch (e: any) {
console.error(`[DB] Error creating default user:`, e.message);
return false;
}
}
// =============================================================================
// Startup repair: fix orphaned dose tracking IDs from past schedule changes
// =============================================================================
const MS_PER_DAY = 86_400_000;
/**
* Repair dose IDs that have a trailing hyphen caused by a frontend bug where
* `[].toString()` produced an empty string, resulting in IDs like "5-0-1729123200000-"
* instead of "5-0-1729123200000". This strips trailing hyphens from all dose IDs.
*
* This function is idempotent - safe to run on every startup.
*/
export async function repairTrailingHyphenDoseIds(client: Client): Promise<{ repaired: number; errors: string[] }> {
const errors: string[] = [];
let repaired = 0;
try {
const result = await client.execute(
"UPDATE dose_tracking SET dose_id = RTRIM(dose_id, '-') WHERE dose_id LIKE '%-'"
);
repaired = result.rowsAffected;
} catch (e: any) {
errors.push(`Trailing-hyphen repair failed: ${e.message}`);
}
return { repaired, errors };
}
/**
* Repair orphaned dose tracking IDs that no longer match the current intake schedule.
* This fixes dose IDs that became invalid when a medication's schedule was changed
* BEFORE the on-edit migration (PR #103) was introduced.
*
* For each medication, generates all valid schedule dateOnlyMs values from each intake's
* start date up to today, then checks all dose_tracking entries. Any dose whose timestamp
* doesn't match a valid schedule date is remapped to the nearest valid date.
*
* This function is idempotent - safe to run on every startup.
*/
export async function repairOrphanedDoseIds(client: Client): Promise<{ repaired: number; errors: string[] }> {
const errors: string[] = [];
let repaired = 0;
try {
// Get all medications
const medsResult = await client.execute(
"SELECT id, intakes_json, usage_json, every_json, start_json, intake_reminders_enabled FROM medications"
);
if (medsResult.rows.length === 0) return { repaired, errors };
// Get all dose tracking entries
const dosesResult = await client.execute("SELECT id, dose_id FROM dose_tracking");
if (dosesResult.rows.length === 0) return { repaired, errors };
// Build a map of medId → dose entries for quick lookup
const dosesByMed = new Map<number, Array<{ id: number; doseId: string }>>();
for (const row of dosesResult.rows) {
const doseId = row.dose_id as string;
const parts = doseId.split("-");
if (parts.length < 3) continue;
const medId = parseInt(parts[0], 10);
if (Number.isNaN(medId)) continue;
if (!dosesByMed.has(medId)) dosesByMed.set(medId, []);
dosesByMed.get(medId)!.push({ id: row.id as number, doseId });
}
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
for (const med of medsResult.rows) {
const medId = med.id as number;
const medDoses = dosesByMed.get(medId);
if (!medDoses || medDoses.length === 0) continue;
// Parse intakes
const intakes = parseIntakesJson(
med.intakes_json as string | null,
{
usageJson: (med.usage_json as string) || "[]",
everyJson: (med.every_json as string) || "[]",
startJson: (med.start_json as string) || "[]",
},
(med.intake_reminders_enabled as number) === 1
);
if (intakes.length === 0) continue;
// For each intake index, build the set of valid dateOnlyMs values
const validDatesByIntake = new Map<number, Set<number>>();
for (let idx = 0; idx < intakes.length; idx++) {
const intake = intakes[idx];
const start = parseLocalDateTime(intake.start);
const every = intake.every;
if (every <= 0 || Number.isNaN(start.getTime())) continue;
const validDates = new Set<number>();
for (let d = new Date(start); d <= today; d.setDate(d.getDate() + every)) {
validDates.add(new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime());
}
validDatesByIntake.set(idx, validDates);
}
// Check each dose entry
for (const dose of medDoses) {
const parts = dose.doseId.split("-");
if (parts.length < 3) continue;
const intakeIdx = parseInt(parts[1], 10);
const dateOnlyMs = parseInt(parts[2], 10);
if (Number.isNaN(intakeIdx) || Number.isNaN(dateOnlyMs)) continue;
const validDates = validDatesByIntake.get(intakeIdx);
if (!validDates) continue; // Unknown intake index - skip
// Check if this dose's timestamp is valid
if (validDates.has(dateOnlyMs)) continue; // Already valid - nothing to do
// Orphaned dose - find the nearest valid schedule date
const intake = intakes[intakeIdx];
if (!intake) continue;
const halfInterval = (intake.every * MS_PER_DAY) / 2;
let bestMatch: number | null = null;
let bestDist = Infinity;
for (const validDate of validDates) {
const dist = Math.abs(validDate - dateOnlyMs);
if (dist < bestDist && dist <= halfInterval) {
bestDist = dist;
bestMatch = validDate;
}
}
if (bestMatch !== null) {
// Rebuild dose ID with new timestamp, preserving person suffix
const personSuffix = parts.length > 3 ? `-${parts.slice(3).join("-")}` : "";
const newDoseId = `${medId}-${intakeIdx}-${bestMatch}${personSuffix}`;
try {
await client.execute({
sql: "UPDATE dose_tracking SET dose_id = ? WHERE id = ?",
args: [newDoseId, dose.id],
});
repaired++;
} catch (e: any) {
errors.push(`Failed to repair dose ${dose.id}: ${e.message}`);
}
}
}
}
} catch (e: any) {
errors.push(`Repair failed: ${e.message}`);
}
return { repaired, errors };
}
+13 -8
View File
@@ -1,11 +1,14 @@
import { createClient, Client } from "@libsql/client"; import { existsSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { type Client, createClient } from "@libsql/client";
import dotenv from "dotenv";
import { drizzle } from "drizzle-orm/libsql"; import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator"; import { migrate } from "drizzle-orm/libsql/migrator";
import dotenv from "dotenv";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
dotenv.config({ path: process.env.DOTENV_PATH || ".env" }); // Load .env: try cwd first, then parent dir (for local dev running from backend/)
const envPath = process.env.DOTENV_PATH || (existsSync(".env") ? ".env" : "../.env");
dotenv.config({ path: envPath });
// Get migrations folder path (relative to this file's location) // Get migrations folder path (relative to this file's location)
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
@@ -18,11 +21,13 @@ const migrationsFolder = resolve(__dirname, "../../drizzle");
/** Split SQL string into individual statements (for backwards compatibility with tests) */ /** Split SQL string into individual statements (for backwards compatibility with tests) */
export function splitSQLStatements(sql: string): string[] { export function splitSQLStatements(sql: string): string[] {
return sql.split(';').filter(s => s.trim().length > 0); return sql.split(";").filter((s) => s.trim().length > 0);
} }
/** Execute drizzle migrations on a database */ /** Execute drizzle migrations on a database */
export async function executeMigration(client: Client): Promise<{ success: boolean; executed: number; errors: string[] }> { export async function executeMigration(
client: Client
): Promise<{ success: boolean; executed: number; errors: string[] }> {
const errors: string[] = []; const errors: string[] = [];
const db = drizzle(client); const db = drizzle(client);
@@ -48,7 +53,7 @@ export function getStatementPreview(stmt: string, maxLength: number = 50): strin
if (trimmed.length <= maxLength) { if (trimmed.length <= maxLength) {
return trimmed; return trimmed;
} }
return trimmed.substring(0, maxLength) + "..."; return `${trimmed.substring(0, maxLength)}...`;
} }
// ============================================================================= // =============================================================================
+35 -12
View File
@@ -1,5 +1,5 @@
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
import { sql } from "drizzle-orm"; import { sql } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
// ============================================================================= // =============================================================================
// Users - Simple auth, no roles (every user is equal) // Users - Simple auth, no roles (every user is equal)
@@ -22,24 +22,32 @@ export const users = sqliteTable("users", {
// ============================================================================= // =============================================================================
export const medications = sqliteTable("medications", { export const medications = sqliteTable("medications", {
id: integer("id").primaryKey({ autoIncrement: true }), id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
name: text("name", { length: 100 }).notNull(), name: text("name", { length: 100 }).notNull(),
genericName: text("generic_name", { length: 100 }), genericName: text("generic_name", { length: 100 }),
takenByJson: text("taken_by_json").notNull().default("[]"), // JSON array of person names takenByJson: text("taken_by_json").notNull().default("[]"), // JSON array of person names
packageType: text("package_type", { length: 20 }).notNull().default("blister"), // 'blister' or 'bottle'
packCount: integer("pack_count").notNull().default(1), packCount: integer("pack_count").notNull().default(1),
blistersPerPack: integer("blisters_per_pack").notNull().default(1), blistersPerPack: integer("blisters_per_pack").notNull().default(1),
pillsPerBlister: integer("pills_per_blister").notNull().default(1), pillsPerBlister: integer("pills_per_blister").notNull().default(1),
looseTablets: integer("loose_tablets").notNull().default(0), // TRUE loose pills (user-entered) totalPills: integer("total_pills"), // For bottle type: total capacity of the container
looseTablets: integer("loose_tablets").notNull().default(0), // For blister: extra loose pills; for bottle: current stock
stockAdjustment: integer("stock_adjustment").notNull().default(0), // Hidden offset from stock corrections stockAdjustment: integer("stock_adjustment").notNull().default(0), // Hidden offset from stock corrections
lastStockCorrectionAt: integer("last_stock_correction_at", { mode: "timestamp" }), // When stock was last corrected - consumed doses before this don't count lastStockCorrectionAt: integer("last_stock_correction_at", { mode: "timestamp" }), // When stock was last corrected - consumed doses before this don't count
pillWeightMg: integer("pill_weight_mg"), pillWeightMg: integer("pill_weight_mg"),
usageJson: text("usage_json").notNull().default("[]"), doseUnit: text("dose_unit", { length: 20 }).default("mg"), // Unit for the dose (mg, g, mcg, ml, IU, etc.)
everyJson: text("every_json").notNull().default("[]"), usageJson: text("usage_json").notNull().default("[]"), // DEPRECATED: Use intakesJson instead
startJson: text("start_json").notNull().default("[]"), everyJson: text("every_json").notNull().default("[]"), // DEPRECATED: Use intakesJson instead
startJson: text("start_json").notNull().default("[]"), // DEPRECATED: Use intakesJson instead
// New unified intakes structure: [{usage, every, start, takenBy, intakeRemindersEnabled}]
intakesJson: text("intakes_json").notNull().default("[]"),
imageUrl: text("image_url"), imageUrl: text("image_url"),
expiryDate: text("expiry_date"), expiryDate: text("expiry_date"),
notes: text("notes"), notes: text("notes"),
intakeRemindersEnabled: integer("intake_reminders_enabled", { mode: "boolean" }).notNull().default(false), intakeRemindersEnabled: integer("intake_reminders_enabled", { mode: "boolean" }).notNull().default(false),
dismissedUntil: text("dismissed_until"), // ISO date string (e.g. "2026-01-23") - all past doses until this date are dismissed
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`), updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
}); });
@@ -48,7 +56,10 @@ export const medications = sqliteTable("medications", {
// ============================================================================= // =============================================================================
export const userSettings = sqliteTable("user_settings", { export const userSettings = sqliteTable("user_settings", {
id: integer("id").primaryKey({ autoIncrement: true }), id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id").notNull().unique().references(() => users.id, { onDelete: "cascade" }), userId: integer("user_id")
.notNull()
.unique()
.references(() => users.id, { onDelete: "cascade" }),
// Email notifications // Email notifications
emailEnabled: integer("email_enabled", { mode: "boolean" }).notNull().default(false), emailEnabled: integer("email_enabled", { mode: "boolean" }).notNull().default(false),
notificationEmail: text("notification_email"), notificationEmail: text("notification_email"),
@@ -79,6 +90,8 @@ export const userSettings = sqliteTable("user_settings", {
lastAutoEmailSent: text("last_auto_email_sent"), lastAutoEmailSent: text("last_auto_email_sent"),
lastNotificationType: text("last_notification_type"), lastNotificationType: text("last_notification_type"),
lastNotificationChannel: text("last_notification_channel"), lastNotificationChannel: text("last_notification_channel"),
lastReminderMedName: text("last_reminder_med_name"),
lastReminderTakenBy: text("last_reminder_taken_by"),
// Timestamps // Timestamps
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`), updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
}); });
@@ -88,7 +101,9 @@ export const userSettings = sqliteTable("user_settings", {
// ============================================================================= // =============================================================================
export const refreshTokens = sqliteTable("refresh_tokens", { export const refreshTokens = sqliteTable("refresh_tokens", {
id: integer("id").primaryKey({ autoIncrement: true }), id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
tokenId: text("token_id", { length: 255 }).notNull().unique(), tokenId: text("token_id", { length: 255 }).notNull().unique(),
expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(), expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
rotatedAt: integer("rotated_at", { mode: "timestamp" }), rotatedAt: integer("rotated_at", { mode: "timestamp" }),
@@ -101,7 +116,9 @@ export const refreshTokens = sqliteTable("refresh_tokens", {
// ============================================================================= // =============================================================================
export const shareTokens = sqliteTable("share_tokens", { export const shareTokens = sqliteTable("share_tokens", {
id: integer("id").primaryKey({ autoIncrement: true }), id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
token: text("token", { length: 64 }).notNull().unique(), token: text("token", { length: 64 }).notNull().unique(),
takenBy: text("taken_by", { length: 100 }).notNull(), takenBy: text("taken_by", { length: 100 }).notNull(),
scheduleDays: integer("schedule_days").notNull().default(30), scheduleDays: integer("schedule_days").notNull().default(30),
@@ -114,7 +131,9 @@ export const shareTokens = sqliteTable("share_tokens", {
// ============================================================================= // =============================================================================
export const doseTracking = sqliteTable("dose_tracking", { export const doseTracking = sqliteTable("dose_tracking", {
id: integer("id").primaryKey({ autoIncrement: true }), id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
doseId: text("dose_id", { length: 255 }).notNull(), // e.g. "med-5-1-86400000-1735200000000" doseId: text("dose_id", { length: 255 }).notNull(), // e.g. "med-5-1-86400000-1735200000000"
takenAt: integer("taken_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s','now'))`), takenAt: integer("taken_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s','now'))`),
markedBy: text("marked_by", { length: 100 }), // null = user, "Daniel" = via share link markedBy: text("marked_by", { length: 100 }), // null = user, "Daniel" = via share link
@@ -126,8 +145,12 @@ export const doseTracking = sqliteTable("dose_tracking", {
// ============================================================================= // =============================================================================
export const refillHistory = sqliteTable("refill_history", { export const refillHistory = sqliteTable("refill_history", {
id: integer("id").primaryKey({ autoIncrement: true }), id: integer("id").primaryKey({ autoIncrement: true }),
medicationId: integer("medication_id").notNull().references(() => medications.id, { onDelete: "cascade" }), medicationId: integer("medication_id")
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), .notNull()
.references(() => medications.id, { onDelete: "cascade" }),
userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
packsAdded: integer("packs_added").notNull().default(0), packsAdded: integer("packs_added").notNull().default(0),
loosePillsAdded: integer("loose_pills_added").notNull().default(0), loosePillsAdded: integer("loose_pills_added").notNull().default(0),
refillDate: integer("refill_date", { mode: "timestamp" }).notNull().default(sql`(strftime('%s','now'))`), refillDate: integer("refill_date", { mode: "timestamp" }).notNull().default(sql`(strftime('%s','now'))`),
+78 -5
View File
@@ -1,6 +1,68 @@
// Backend translations for notifications // Backend translations for notifications
export type Language = "en" | "de"; export type Language = "en" | "de";
/**
* Map timezone to region code (ISO 3166-1 alpha-2).
* This allows combining app language with regional formatting.
*/
const TIMEZONE_TO_REGION: Record<string, string> = {
// Europe
"Europe/Berlin": "DE",
"Europe/Vienna": "AT",
"Europe/Zurich": "CH",
"Europe/London": "GB",
"Europe/Dublin": "IE",
"Europe/Paris": "FR",
"Europe/Madrid": "ES",
"Europe/Rome": "IT",
"Europe/Amsterdam": "NL",
"Europe/Brussels": "BE",
"Europe/Warsaw": "PL",
"Europe/Prague": "CZ",
"Europe/Stockholm": "SE",
"Europe/Oslo": "NO",
"Europe/Copenhagen": "DK",
"Europe/Helsinki": "FI",
"Europe/Athens": "GR",
"Europe/Lisbon": "PT",
"Europe/Moscow": "RU",
"Europe/Kiev": "UA",
"Europe/Kyiv": "UA",
"Europe/Budapest": "HU",
"Europe/Bucharest": "RO",
// Americas
"America/New_York": "US",
"America/Chicago": "US",
"America/Denver": "US",
"America/Los_Angeles": "US",
"America/Phoenix": "US",
"America/Toronto": "CA",
"America/Vancouver": "CA",
"America/Mexico_City": "MX",
"America/Sao_Paulo": "BR",
"America/Buenos_Aires": "AR",
// Asia/Pacific
"Asia/Tokyo": "JP",
"Asia/Shanghai": "CN",
"Asia/Hong_Kong": "HK",
"Asia/Singapore": "SG",
"Asia/Seoul": "KR",
"Asia/Dubai": "AE",
"Asia/Kolkata": "IN",
"Australia/Sydney": "AU",
"Australia/Melbourne": "AU",
"Pacific/Auckland": "NZ",
};
/**
* Get region code from TZ environment variable.
*/
function getRegionFromTimezone(): string | undefined {
const tz = process.env.TZ;
if (!tz) return undefined;
return TIMEZONE_TO_REGION[tz];
}
type TranslationKeys = { type TranslationKeys = {
// Stock reminder email // Stock reminder email
stockReminder: { stockReminder: {
@@ -94,7 +156,7 @@ const translations: Record<Language, TranslationKeys> = {
push: { push: {
stockTitle: "MedAssist-ng: 1 Medication Running Low", stockTitle: "MedAssist-ng: 1 Medication Running Low",
stockTitleMultiple: "MedAssist-ng: {count} Medications Running Low", stockTitleMultiple: "MedAssist-ng: {count} Medications Running Low",
intakeTitle: "💊 Medication Reminder in {minutes} min", intakeTitle: "💊 Reminder: Medication intake in {minutes} min",
pillsLeft: "{count} pills", pillsLeft: "{count} pills",
daysLeft: "{count} days left", daysLeft: "{count} days left",
pillsAt: "{count} pills at {time}", pillsAt: "{count} pills at {time}",
@@ -127,7 +189,8 @@ const translations: Record<Language, TranslationKeys> = {
runsOut: "Aufgebraucht", runsOut: "Aufgebraucht",
}, },
footer: "🤖 Automatische Erinnerung von MedAssist-ng", footer: "🤖 Automatische Erinnerung von MedAssist-ng",
repeatDailyNote: "Sie erhalten diese tägliche Erinnerung, weil 'Täglich wiederholen' in den Einstellungen aktiviert ist.", repeatDailyNote:
"Sie erhalten diese tägliche Erinnerung, weil 'Täglich wiederholen' in den Einstellungen aktiviert ist.",
}, },
intakeReminder: { intakeReminder: {
subject: "MedAssist-ng: Einnahme-Erinnerung - {medications}", subject: "MedAssist-ng: Einnahme-Erinnerung - {medications}",
@@ -147,7 +210,7 @@ const translations: Record<Language, TranslationKeys> = {
push: { push: {
stockTitle: "MedAssist-ng: 1 Medikament wird knapp", stockTitle: "MedAssist-ng: 1 Medikament wird knapp",
stockTitleMultiple: "MedAssist-ng: {count} Medikamente werden knapp", stockTitleMultiple: "MedAssist-ng: {count} Medikamente werden knapp",
intakeTitle: "💊 Einnahme-Erinnerung in {minutes} Min.", intakeTitle: "💊 Erinnerung: Medikamenteneinnahme in {minutes} Min.",
pillsLeft: "{count} Tabletten", pillsLeft: "{count} Tabletten",
daysLeft: "{count} Tage übrig", daysLeft: "{count} Tage übrig",
pillsAt: "{count} Tabletten um {time}", pillsAt: "{count} Tabletten um {time}",
@@ -181,12 +244,22 @@ export function t(template: string, params: Record<string, string | number> = {}
return result; return result;
} }
// Get date locale for toLocaleDateString /**
* Get locale for formatting based on language and timezone region.
* Combines language (en/de) with region from timezone (DE/US/etc.)
* Example: lang=en + TZ=Europe/Berlin en-DE (English text, German format = 24h time)
*/
export function getDateLocale(language: Language): string { export function getDateLocale(language: Language): string {
const region = getRegionFromTimezone();
if (region) {
return `${language}-${region}`;
}
// Fallback: use language default
switch (language) { switch (language) {
case "de": case "de":
return "de-DE"; return "de-DE";
case "en":
default: default:
return "en-US"; return "en-US";
} }
+22 -21
View File
@@ -1,46 +1,47 @@
import Fastify, { FastifyInstance } from "fastify"; import { existsSync } from "node:fs";
import helmet from "@fastify/helmet"; import { resolve } from "node:path";
import cors from "@fastify/cors";
import rateLimit from "@fastify/rate-limit";
import sensible from "@fastify/sensible";
import cookie from "@fastify/cookie"; import cookie from "@fastify/cookie";
import cors from "@fastify/cors";
import helmet from "@fastify/helmet";
import jwt from "@fastify/jwt"; import jwt from "@fastify/jwt";
import fastifyMultipart from "@fastify/multipart"; import fastifyMultipart from "@fastify/multipart";
import rateLimit from "@fastify/rate-limit";
import sensible from "@fastify/sensible";
import fastifyStatic from "@fastify/static"; import fastifyStatic from "@fastify/static";
import { resolve } from "path"; import Fastify, { type FastifyInstance } from "fastify";
import { existsSync } from "fs";
import { env } from "./plugins/env.js";
import { migrationsReady } from "./db/client.js"; import { migrationsReady } from "./db/client.js";
import { healthRoutes } from "./routes/health.js"; import { getDataDir } from "./db/db-utils.js";
import { env } from "./plugins/env.js";
import { authRoutes } from "./routes/auth.js"; import { authRoutes } from "./routes/auth.js";
import { oidcRoutes } from "./routes/oidc.js";
import { medicationRoutes } from "./routes/medications.js";
import { settingsRoutes } from "./routes/settings.js";
import { plannerRoutes } from "./routes/planner.js";
import { shareRoutes } from "./routes/share.js";
import { doseRoutes } from "./routes/doses.js"; import { doseRoutes } from "./routes/doses.js";
import { exportRoutes } from "./routes/export.js"; import { exportRoutes } from "./routes/export.js";
import { healthRoutes } from "./routes/health.js";
import { medicationRoutes } from "./routes/medications.js";
import { oidcRoutes } from "./routes/oidc.js";
import { plannerRoutes } from "./routes/planner.js";
import { refillRoutes } from "./routes/refills.js"; import { refillRoutes } from "./routes/refills.js";
import { startReminderScheduler } from "./services/reminder-scheduler.js"; import { settingsRoutes } from "./routes/settings.js";
import { shareRoutes } from "./routes/share.js";
import { startIntakeReminderScheduler } from "./services/intake-reminder-scheduler.js"; import { startIntakeReminderScheduler } from "./services/intake-reminder-scheduler.js";
import { startReminderScheduler } from "./services/reminder-scheduler.js";
// Re-export utilities from server-config for external use // Re-export utilities from server-config for external use
export { export {
parseCorsOrigins, buildAppConfig,
buildBaseCookieOptions, buildBaseCookieOptions,
buildRefreshCookieOptions, buildRefreshCookieOptions,
buildAppConfig,
ensureImagesDirectory, ensureImagesDirectory,
getJwtConfig, getJwtConfig,
parseCorsOrigins,
} from "./utils/server-config.js"; } from "./utils/server-config.js";
import { import {
parseCorsOrigins, buildAppConfig,
buildBaseCookieOptions, buildBaseCookieOptions,
buildRefreshCookieOptions, buildRefreshCookieOptions,
buildAppConfig,
ensureImagesDirectory, ensureImagesDirectory,
getJwtConfig, getJwtConfig,
parseCorsOrigins,
} from "./utils/server-config.js"; } from "./utils/server-config.js";
/** Create and configure Fastify app (without starting) */ /** Create and configure Fastify app (without starting) */
@@ -66,7 +67,7 @@ export async function createApp(options?: {
accessTtlMinutes: options?.accessTtlMinutes ?? 15, accessTtlMinutes: options?.accessTtlMinutes ?? 15,
refreshTtlDays: options?.refreshTtlDays ?? 7, refreshTtlDays: options?.refreshTtlDays ?? 7,
isProduction: options?.isProduction ?? false, isProduction: options?.isProduction ?? false,
imagesDir: options?.imagesDir ?? resolve(process.cwd(), "data/images"), imagesDir: options?.imagesDir ?? resolve(getDataDir(), "images"),
}; };
const app = Fastify({ const app = Fastify({
@@ -88,7 +89,7 @@ export async function createApp(options?: {
await app.register(sensible); await app.register(sensible);
await app.register(helmet); await app.register(helmet);
await app.register(cors, { origin: opts.corsOrigins, credentials: true }); await app.register(cors, { origin: opts.corsOrigins, credentials: true });
await app.register(rateLimit, { max: 100, timeWindow: "1 minute" }); await app.register(rateLimit, { max: 300, timeWindow: "1 minute" });
await app.register(cookie, { secret: opts.cookieSecret }); await app.register(cookie, { secret: opts.cookieSecret });
// JWT plugin // JWT plugin
+5 -5
View File
@@ -1,8 +1,8 @@
import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify"; import { count, eq, sql } from "drizzle-orm";
import { env } from "./env.js"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { users } from "../db/schema.js"; import { users } from "../db/schema.js";
import { sql, count, eq } from "drizzle-orm"; import { env } from "./env.js";
// ============================================================================= // =============================================================================
// Anonymous User - Used when AUTH_ENABLED=false // Anonymous User - Used when AUTH_ENABLED=false
@@ -87,7 +87,7 @@ export interface RequestUser {
/** /**
* Optional auth - verifies JWT if present, but doesn't require it * Optional auth - verifies JWT if present, but doesn't require it
*/ */
export async function optionalAuth(request: FastifyRequest, reply: FastifyReply) { export async function optionalAuth(request: FastifyRequest, _reply: FastifyReply) {
if (!env.AUTH_ENABLED) { if (!env.AUTH_ENABLED) {
return; return;
} }
@@ -100,7 +100,7 @@ export async function optionalAuth(request: FastifyRequest, reply: FastifyReply)
try { try {
const decoded = await request.jwtVerify<{ sub: number; username: string }>(); const decoded = await request.jwtVerify<{ sub: number; username: string }>();
const [user] = await db.select().from(users).where(sql`${users.id} = ${decoded.sub}`); const [user] = await db.select().from(users).where(sql`${users.id} = ${decoded.sub}`);
if (user && user.isActive) { if (user?.isActive) {
request.user = { request.user = {
id: user.id, id: user.id,
username: user.username, username: user.username,
+33 -10
View File
@@ -1,11 +1,17 @@
import { z } from "zod"; import { existsSync } from "node:fs";
import dotenv from "dotenv"; import dotenv from "dotenv";
import { z } from "zod";
dotenv.config({ path: process.env.DOTENV_PATH || ".env" }); // Load .env: try cwd first, then parent dir (for local dev running from backend/)
const envPath = process.env.DOTENV_PATH || (existsSync(".env") ? ".env" : "../.env");
dotenv.config({ path: envPath });
const EnvSchema = z.object({ const EnvSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("production"), NODE_ENV: z.enum(["development", "production", "test"]).default("production"),
PORT: z.string().transform((v) => parseInt(v, 10)).default("3000"), PORT: z
.string()
.transform((v) => parseInt(v, 10))
.default("3000"),
CORS_ORIGINS: z.string().default("http://localhost:5173,http://localhost:4173"), CORS_ORIGINS: z.string().default("http://localhost:5173,http://localhost:4173"),
LOG_LEVEL: z.string().default("info"), LOG_LEVEL: z.string().default("info"),
@@ -13,31 +19,48 @@ const EnvSchema = z.object({
// Auth Configuration // Auth Configuration
// ========================================================================== // ==========================================================================
// Master switch: Enable/disable authentication (default: disabled for easy setup) // Master switch: Enable/disable authentication (default: disabled for easy setup)
AUTH_ENABLED: z.string().transform((v) => v === "true").default("false"), AUTH_ENABLED: z
.string()
.transform((v) => v === "true")
.default("false"),
// Allow new user registrations (auto-enabled if no users exist) // Allow new user registrations (auto-enabled if no users exist)
REGISTRATION_ENABLED: z.string().transform((v) => v === "true").default("false"), REGISTRATION_ENABLED: z
.string()
.transform((v) => v === "true")
.default("false"),
// Disable local auth when using SSO only // Disable local auth when using SSO only
// JWT Secrets - only required when AUTH_ENABLED=true // JWT Secrets - only required when AUTH_ENABLED=true
JWT_SECRET: z.string().min(10).optional(), JWT_SECRET: z.string().min(10).optional(),
REFRESH_SECRET: z.string().min(10).optional(), REFRESH_SECRET: z.string().min(10).optional(),
COOKIE_SECRET: z.string().min(10).optional(), COOKIE_SECRET: z.string().min(10).optional(),
// Token TTL settings // Token TTL settings
ACCESS_TOKEN_TTL_MINUTES: z.string().transform((v) => parseInt(v, 10)).default("15"), ACCESS_TOKEN_TTL_MINUTES: z
REFRESH_TOKEN_TTL_DAYS: z.string().transform((v) => parseInt(v, 10)).default("7"), .string()
.transform((v) => parseInt(v, 10))
.default("15"),
REFRESH_TOKEN_TTL_DAYS: z
.string()
.transform((v) => parseInt(v, 10))
.default("7"),
// ========================================================================== // ==========================================================================
// OIDC SSO Configuration (Pocket ID, Authelia, etc.) // OIDC SSO Configuration (Pocket ID, Authelia, etc.)
// ========================================================================== // ==========================================================================
OIDC_ENABLED: z.string().transform((v) => v === "true").default("false"), OIDC_ENABLED: z
.string()
.transform((v) => v === "true")
.default("false"),
OIDC_ISSUER_URL: z.string().url().optional(), // e.g., https://auth.example.com OIDC_ISSUER_URL: z.string().url().optional(), // e.g., https://auth.example.com
OIDC_CLIENT_ID: z.string().optional(), OIDC_CLIENT_ID: z.string().optional(),
OIDC_CLIENT_SECRET: z.string().optional(), OIDC_CLIENT_SECRET: z.string().optional(),
OIDC_REDIRECT_URI: z.string().url().optional(), // e.g., https://medassist.example.com/api/auth/oidc/callback OIDC_REDIRECT_URI: z.string().url().optional(), // e.g., https://medassist.example.com/api/auth/oidc/callback
OIDC_SCOPES: z.string().default("openid profile email"), OIDC_SCOPES: z.string().default("openid profile email"),
OIDC_AUTO_CREATE_USERS: z.string().transform((v) => v === "true").default("true"), OIDC_AUTO_CREATE_USERS: z
.string()
.transform((v) => v === "true")
.default("true"),
OIDC_USERNAME_CLAIM: z.string().default("preferred_username"), // or 'email', 'sub' OIDC_USERNAME_CLAIM: z.string().default("preferred_username"), // or 'email', 'sub'
OIDC_PROVIDER_NAME: z.string().default("SSO"), // Display name for UI button OIDC_PROVIDER_NAME: z.string().default("SSO"), // Display name for UI button
}); });
+126 -60
View File
@@ -1,11 +1,11 @@
import { FastifyInstance } from "fastify"; import { randomBytes } from "node:crypto";
import { z } from "zod";
import argon2 from "argon2"; import argon2 from "argon2";
import { randomBytes } from "crypto";
import { db } from "../db/client.js";
import { users, refreshTokens } from "../db/schema.js";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { env } from "../plugins/env.js"; import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { refreshTokens, users } from "../db/schema.js";
import { getAuthState, requireAuth } from "../plugins/auth.js"; import { getAuthState, requireAuth } from "../plugins/auth.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
@@ -51,11 +51,13 @@ const sensitiveRateLimitConfig = {
// Validation Schemas // Validation Schemas
// ============================================================================= // =============================================================================
const registerSchema = z.object({ const registerSchema = z.object({
username: z.string() username: z
.string()
.min(3, "Username must be at least 3 characters") .min(3, "Username must be at least 3 characters")
.max(50, "Username must be at most 50 characters") .max(50, "Username must be at most 50 characters")
.regex(/^[a-zA-Z0-9_-]+$/, "Username can only contain letters, numbers, underscores, and hyphens"), .regex(/^[a-zA-Z0-9_-]+$/, "Username can only contain letters, numbers, underscores, and hyphens"),
password: z.string() password: z
.string()
.min(8, "Password must be at least 8 characters") .min(8, "Password must be at least 8 characters")
.max(128, "Password must be at most 128 characters"), .max(128, "Password must be at most 128 characters"),
}); });
@@ -68,7 +70,8 @@ const loginSchema = z.object({
const updateProfileSchema = z.object({ const updateProfileSchema = z.object({
currentPassword: z.string().optional(), currentPassword: z.string().optional(),
newPassword: z.string() newPassword: z
.string()
.min(8, "Password must be at least 8 characters") .min(8, "Password must be at least 8 characters")
.max(128, "Password must be at most 128 characters") .max(128, "Password must be at most 128 characters")
.optional(), .optional(),
@@ -84,17 +87,21 @@ export async function authRoutes(app: FastifyInstance) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// GET /auth/state - Public auth state (needed before login) // GET /auth/state - Public auth state (needed before login)
// Exempt from rate limit - lightweight state check called frequently
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.get("/auth/state", async () => { app.get("/auth/state", { config: { rateLimit: false } }, async () => {
return getAuthState(); return getAuthState();
}); });
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /auth/register - User registration // POST /auth/register - User registration
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.post<{ Body: z.infer<typeof registerSchema> }>("/auth/register", { app.post<{ Body: z.infer<typeof registerSchema> }>(
"/auth/register",
{
config: { rateLimit: sensitiveRateLimitConfig }, config: { rateLimit: sensitiveRateLimitConfig },
}, async (request, reply) => { },
async (request, reply) => {
// Check auth state // Check auth state
const state = await getAuthState(); const state = await getAuthState();
@@ -115,7 +122,7 @@ export async function authRoutes(app: FastifyInstance) {
if (!parsed.success) { if (!parsed.success) {
return reply.status(400).send({ return reply.status(400).send({
error: parsed.error.errors[0]?.message ?? "Invalid input", error: parsed.error.errors[0]?.message ?? "Invalid input",
code: "VALIDATION_ERROR" code: "VALIDATION_ERROR",
}); });
} }
@@ -131,11 +138,14 @@ export async function authRoutes(app: FastifyInstance) {
const passwordHash = await argon2.hash(password, ARGON2_OPTIONS); const passwordHash = await argon2.hash(password, ARGON2_OPTIONS);
// Create user // Create user
const [newUser] = await db.insert(users).values({ const [newUser] = await db
.insert(users)
.values({
username, username,
passwordHash, passwordHash,
authProvider: "local", authProvider: "local",
}).returning(); })
.returning();
app.log.info(`User registered: ${username}`); app.log.info(`User registered: ${username}`);
@@ -147,14 +157,18 @@ export async function authRoutes(app: FastifyInstance) {
}, },
message: "Account created", message: "Account created",
}); });
}); }
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /auth/login - User login // POST /auth/login - User login
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.post<{ Body: z.infer<typeof loginSchema> }>("/auth/login", { app.post<{ Body: z.infer<typeof loginSchema> }>(
"/auth/login",
{
config: { rateLimit: sensitiveRateLimitConfig }, config: { rateLimit: sensitiveRateLimitConfig },
}, async (request, reply) => { },
async (request, reply) => {
const state = await getAuthState(); const state = await getAuthState();
if (!state.authEnabled) { if (!state.authEnabled) {
@@ -169,7 +183,7 @@ export async function authRoutes(app: FastifyInstance) {
if (!parsed.success) { if (!parsed.success) {
return reply.status(400).send({ return reply.status(400).send({
error: "Invalid credentials", error: "Invalid credentials",
code: "VALIDATION_ERROR" code: "VALIDATION_ERROR",
}); });
} }
@@ -204,9 +218,7 @@ export async function authRoutes(app: FastifyInstance) {
} }
// Update last login // Update last login
await db.update(users) await db.update(users).set({ lastLoginAt: new Date(), updatedAt: new Date() }).where(eq(users.id, user.id));
.set({ lastLoginAt: new Date(), updatedAt: new Date() })
.where(eq(users.id, user.id));
// Generate tokens // Generate tokens
const accessToken = app.jwt.sign( const accessToken = app.jwt.sign(
@@ -249,14 +261,18 @@ export async function authRoutes(app: FastifyInstance) {
avatarUrl: user.avatarUrl, avatarUrl: user.avatarUrl,
}, },
}); });
}); }
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /auth/refresh - Refresh access token // POST /auth/refresh - Refresh access token
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.post("/auth/refresh", { app.post(
"/auth/refresh",
{
config: { rateLimit: authRateLimitConfig }, config: { rateLimit: authRateLimitConfig },
}, async (request, reply) => { },
async (request, reply) => {
const refreshTokenCookie = request.cookies.refresh_token; const refreshTokenCookie = request.cookies.refresh_token;
if (!refreshTokenCookie) { if (!refreshTokenCookie) {
return reply.status(401).send({ error: "No refresh token", code: "NO_REFRESH_TOKEN" }); return reply.status(401).send({ error: "No refresh token", code: "NO_REFRESH_TOKEN" });
@@ -264,14 +280,12 @@ export async function authRoutes(app: FastifyInstance) {
try { try {
// Verify refresh token // Verify refresh token
const decoded = app.jwt.verify<{ sub: number; jti: string }>( const decoded = app.jwt.verify<{ sub: number; jti: string }>(refreshTokenCookie, {
refreshTokenCookie, key: app.config.refreshSecret,
{ key: app.config.refreshSecret } });
);
// Check if token exists and is valid // Check if token exists and is valid
const [token] = await db.select().from(refreshTokens) const [token] = await db.select().from(refreshTokens).where(eq(refreshTokens.tokenId, decoded.jti));
.where(eq(refreshTokens.tokenId, decoded.jti));
if (!token || token.revoked || token.expiresAt < new Date()) { if (!token || token.revoked || token.expiresAt < new Date()) {
return reply.status(401).send({ error: "Invalid refresh token", code: "INVALID_REFRESH_TOKEN" }); return reply.status(401).send({ error: "Invalid refresh token", code: "INVALID_REFRESH_TOKEN" });
@@ -284,7 +298,8 @@ export async function authRoutes(app: FastifyInstance) {
} }
// Rotate refresh token (revoke old, create new) // Rotate refresh token (revoke old, create new)
await db.update(refreshTokens) await db
.update(refreshTokens)
.set({ revoked: true, rotatedAt: new Date() }) .set({ revoked: true, rotatedAt: new Date() })
.where(eq(refreshTokens.id, token.id)); .where(eq(refreshTokens.id, token.id));
@@ -312,31 +327,29 @@ export async function authRoutes(app: FastifyInstance) {
.setCookie("access_token", newAccessToken, app.config.cookieOptions) .setCookie("access_token", newAccessToken, app.config.cookieOptions)
.setCookie("refresh_token", newRefreshToken, app.config.refreshCookieOptions) .setCookie("refresh_token", newRefreshToken, app.config.refreshCookieOptions)
.send({ ok: true }); .send({ ok: true });
} catch { } catch {
return reply.status(401).send({ error: "Invalid refresh token", code: "INVALID_REFRESH_TOKEN" }); return reply.status(401).send({ error: "Invalid refresh token", code: "INVALID_REFRESH_TOKEN" });
} }
}); }
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /auth/logout - Logout (revoke refresh token) // POST /auth/logout - Logout (revoke refresh token)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.post("/auth/logout", { app.post(
"/auth/logout",
{
config: { rateLimit: authRateLimitConfig }, config: { rateLimit: authRateLimitConfig },
}, async (request, reply) => { },
async (request, reply) => {
const refreshTokenCookie = request.cookies.refresh_token; const refreshTokenCookie = request.cookies.refresh_token;
if (refreshTokenCookie) { if (refreshTokenCookie) {
try { try {
const decoded = app.jwt.verify<{ jti: string }>( const decoded = app.jwt.verify<{ jti: string }>(refreshTokenCookie, { key: app.config.refreshSecret });
refreshTokenCookie,
{ key: app.config.refreshSecret }
);
// Revoke the refresh token // Revoke the refresh token
await db.update(refreshTokens) await db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.tokenId, decoded.jti));
.set({ revoked: true })
.where(eq(refreshTokens.tokenId, decoded.jti));
} catch { } catch {
// Invalid token, ignore // Invalid token, ignore
} }
@@ -346,7 +359,8 @@ export async function authRoutes(app: FastifyInstance) {
.clearCookie("access_token", app.config.cookieOptions) .clearCookie("access_token", app.config.cookieOptions)
.clearCookie("refresh_token", app.config.refreshCookieOptions) .clearCookie("refresh_token", app.config.refreshCookieOptions)
.send({ ok: true }); .send({ ok: true });
}); }
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// GET /auth/me - Get current user profile // GET /auth/me - Get current user profile
@@ -375,10 +389,13 @@ export async function authRoutes(app: FastifyInstance) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// PUT /auth/me - Update current user profile // PUT /auth/me - Update current user profile
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.put<{ Body: z.infer<typeof updateProfileSchema> }>("/auth/me", { app.put<{ Body: z.infer<typeof updateProfileSchema> }>(
"/auth/me",
{
preHandler: requireAuth, preHandler: requireAuth,
config: { rateLimit: authRateLimitConfig }, config: { rateLimit: authRateLimitConfig },
}, async (request, reply) => { },
async (request, reply) => {
const authUser = request.user as unknown as AuthUser | null; const authUser = request.user as unknown as AuthUser | null;
if (!authUser) { if (!authUser) {
return reply.status(401).send({ error: "Not authenticated" }); return reply.status(401).send({ error: "Not authenticated" });
@@ -388,7 +405,7 @@ export async function authRoutes(app: FastifyInstance) {
if (!parsed.success) { if (!parsed.success) {
return reply.status(400).send({ return reply.status(400).send({
error: parsed.error.errors[0]?.message ?? "Invalid input", error: parsed.error.errors[0]?.message ?? "Invalid input",
code: "VALIDATION_ERROR" code: "VALIDATION_ERROR",
}); });
} }
@@ -424,15 +441,19 @@ export async function authRoutes(app: FastifyInstance) {
await db.update(users).set(updates).where(eq(users.id, user.id)); await db.update(users).set(updates).where(eq(users.id, user.id));
return { ok: true, message: "Profile updated" }; return { ok: true, message: "Profile updated" };
}); }
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /auth/avatar - Upload user avatar // POST /auth/avatar - Upload user avatar
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.post("/auth/avatar", { app.post(
"/auth/avatar",
{
preHandler: requireAuth, preHandler: requireAuth,
config: { rateLimit: authRateLimitConfig }, config: { rateLimit: authRateLimitConfig },
}, async (request, reply) => { },
async (request, reply) => {
const authUser = request.user as unknown as AuthUser | null; const authUser = request.user as unknown as AuthUser | null;
if (!authUser) { if (!authUser) {
return reply.status(401).send({ error: "Not authenticated" }); return reply.status(401).send({ error: "Not authenticated" });
@@ -454,9 +475,9 @@ export async function authRoutes(app: FastifyInstance) {
const filename = `avatar_${authUser.id}_${Date.now()}.${ext}`; const filename = `avatar_${authUser.id}_${Date.now()}.${ext}`;
// Save file // Save file
const fs = await import("fs/promises"); const fs = await import("node:fs/promises");
const path = await import("path"); const path = await import("node:path");
const imagesDir = path.join(process.cwd(), "data", "images"); const imagesDir = path.join(getDataDir(), "images");
await fs.mkdir(imagesDir, { recursive: true }); await fs.mkdir(imagesDir, { recursive: true });
const buffer = await data.toBuffer(); const buffer = await data.toBuffer();
@@ -476,15 +497,19 @@ export async function authRoutes(app: FastifyInstance) {
await db.update(users).set({ avatarUrl: filename, updatedAt: new Date() }).where(eq(users.id, authUser.id)); await db.update(users).set({ avatarUrl: filename, updatedAt: new Date() }).where(eq(users.id, authUser.id));
return { ok: true, avatarUrl: filename }; return { ok: true, avatarUrl: filename };
}); }
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// DELETE /auth/avatar - Delete user avatar // DELETE /auth/avatar - Delete user avatar
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.delete("/auth/avatar", { app.delete(
"/auth/avatar",
{
preHandler: requireAuth, preHandler: requireAuth,
config: { rateLimit: authRateLimitConfig }, config: { rateLimit: authRateLimitConfig },
}, async (request, reply) => { },
async (request, reply) => {
const authUser = request.user as unknown as AuthUser | null; const authUser = request.user as unknown as AuthUser | null;
if (!authUser) { if (!authUser) {
return reply.status(401).send({ error: "Not authenticated" }); return reply.status(401).send({ error: "Not authenticated" });
@@ -496,10 +521,10 @@ export async function authRoutes(app: FastifyInstance) {
} }
// Delete file // Delete file
const fs = await import("fs/promises"); const fs = await import("node:fs/promises");
const path = await import("path"); const path = await import("node:path");
try { try {
await fs.unlink(path.join(process.cwd(), "data", "images", user.avatarUrl)); await fs.unlink(path.join(getDataDir(), "images", user.avatarUrl));
} catch { } catch {
// Ignore if file doesn't exist // Ignore if file doesn't exist
} }
@@ -508,5 +533,46 @@ export async function authRoutes(app: FastifyInstance) {
await db.update(users).set({ avatarUrl: null, updatedAt: new Date() }).where(eq(users.id, authUser.id)); await db.update(users).set({ avatarUrl: null, updatedAt: new Date() }).where(eq(users.id, authUser.id));
return { ok: true }; return { ok: true };
}); }
);
// ---------------------------------------------------------------------------
// DELETE /auth/me - Delete user account and all data
// ---------------------------------------------------------------------------
app.delete(
"/auth/me",
{
preHandler: requireAuth,
config: { rateLimit: sensitiveRateLimitConfig },
},
async (request, reply) => {
const authUser = request.user as unknown as AuthUser | null;
if (!authUser) {
return reply.status(401).send({ error: "Not authenticated" });
}
// Delete avatar file if exists
const [user] = await db.select().from(users).where(eq(users.id, authUser.id));
if (user?.avatarUrl) {
const fs = await import("node:fs/promises");
const path = await import("node:path");
try {
await fs.unlink(path.join(getDataDir(), "images", user.avatarUrl));
} catch {
// Ignore if file doesn't exist
}
}
// Delete user - cascade delete handles all related data
await db.delete(users).where(eq(users.id, authUser.id));
app.log.info(`User deleted account: ${authUser.username} (ID: ${authUser.id})`);
// Clear auth cookies
return reply
.clearCookie("access_token", app.config.cookieOptions)
.clearCookie("refresh_token", app.config.refreshCookieOptions)
.send({ ok: true, message: "Account deleted" });
}
);
} }
+56 -84
View File
@@ -1,9 +1,9 @@
import { FastifyInstance } from "fastify"; import { and, eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { doseTracking, shareTokens } from "../db/schema.js"; import { doseTracking, shareTokens } from "../db/schema.js";
import { eq, and, inArray } from "drizzle-orm"; import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { requireAuth, getAnonymousUserId } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
@@ -24,7 +24,7 @@ const dismissDosesSchema = z.object({
// Helper to get user ID from request // Helper to get user ID from request
// Returns anonymous user ID when auth is disabled // Returns anonymous user ID when auth is disabled
async function getUserId(request: any, reply: any): Promise<number> { async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
// If auth is disabled, use the anonymous user // If auth is disabled, use the anonymous user
if (!env.AUTH_ENABLED) { if (!env.AUTH_ENABLED) {
return getAnonymousUserId(); return getAnonymousUserId();
@@ -45,16 +45,11 @@ export async function doseRoutes(app: FastifyInstance) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// GET /doses/taken - PROTECTED: Get all taken doses for the user // GET /doses/taken - PROTECTED: Get all taken doses for the user
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.get( app.get("/doses/taken", { preHandler: requireAuth }, async (request, reply) => {
"/doses/taken",
{ preHandler: requireAuth },
async (request, reply) => {
const userId = await getUserId(request, reply); const userId = await getUserId(request, reply);
// Get all taken doses for this user (no time limit) // Get all taken doses for this user (no time limit)
const doses = await db.select() const doses = await db.select().from(doseTracking).where(eq(doseTracking.userId, userId));
.from(doseTracking)
.where(eq(doseTracking.userId, userId));
return { return {
doses: doses.map((d) => ({ doses: doses.map((d) => ({
@@ -64,8 +59,7 @@ export async function doseRoutes(app: FastifyInstance) {
dismissed: d.dismissed ?? false, dismissed: d.dismissed ?? false,
})), })),
}; };
} });
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /doses/taken - PROTECTED: Mark a dose as taken // POST /doses/taken - PROTECTED: Mark a dose as taken
@@ -86,14 +80,10 @@ export async function doseRoutes(app: FastifyInstance) {
const { doseId } = parsed.data; const { doseId } = parsed.data;
// Check if already marked // Check if already marked
const [existing] = await db.select() const [existing] = await db
.select()
.from(doseTracking) .from(doseTracking)
.where( .where(and(eq(doseTracking.userId, userId), eq(doseTracking.doseId, doseId)));
and(
eq(doseTracking.userId, userId),
eq(doseTracking.doseId, doseId)
)
);
if (existing) { if (existing) {
return { success: true, message: "Already marked" }; return { success: true, message: "Already marked" };
@@ -121,12 +111,19 @@ export async function doseRoutes(app: FastifyInstance) {
const { doseId } = request.params; const { doseId } = request.params;
await db.delete(doseTracking).where( // Check if this dose was dismissed
and( const [existing] = await db
eq(doseTracking.userId, userId), .select()
eq(doseTracking.doseId, doseId) .from(doseTracking)
) .where(and(eq(doseTracking.userId, userId), eq(doseTracking.doseId, doseId)));
);
if (existing?.dismissed) {
// Already dismissed - keep the record as-is
// The dose stays dismissed, we just acknowledge the undo request
} else {
// Not dismissed - delete the record entirely
await db.delete(doseTracking).where(and(eq(doseTracking.userId, userId), eq(doseTracking.doseId, doseId)));
}
return { success: true }; return { success: true };
} }
@@ -154,26 +151,18 @@ export async function doseRoutes(app: FastifyInstance) {
let dismissedCount = 0; let dismissedCount = 0;
for (const doseId of doseIds) { for (const doseId of doseIds) {
// Check if already exists (taken or dismissed) // Check if already exists (taken or dismissed)
const [existing] = await db.select() const [existing] = await db
.select()
.from(doseTracking) .from(doseTracking)
.where( .where(and(eq(doseTracking.userId, userId), eq(doseTracking.doseId, doseId)));
and(
eq(doseTracking.userId, userId),
eq(doseTracking.doseId, doseId)
)
);
if (existing) { if (existing) {
// Already exists - update to dismissed if not already // Already exists - update to dismissed if not already
if (!existing.dismissed) { if (!existing.dismissed) {
await db.update(doseTracking) await db
.update(doseTracking)
.set({ dismissed: true }) .set({ dismissed: true })
.where( .where(and(eq(doseTracking.userId, userId), eq(doseTracking.doseId, doseId)));
and(
eq(doseTracking.userId, userId),
eq(doseTracking.doseId, doseId)
)
);
dismissedCount++; dismissedCount++;
} }
} else { } else {
@@ -195,46 +184,33 @@ export async function doseRoutes(app: FastifyInstance) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// DELETE /doses/dismiss - PROTECTED: Clear all dismissed doses (un-dismiss) // DELETE /doses/dismiss - PROTECTED: Clear all dismissed doses (un-dismiss)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.delete( app.delete("/doses/dismiss", { preHandler: requireAuth }, async (request, reply) => {
"/doses/dismiss",
{ preHandler: requireAuth },
async (request, reply) => {
const userId = await getUserId(request, reply); const userId = await getUserId(request, reply);
// Delete all dismissed-only records (not taken ones) // Delete all dismissed-only records (not taken ones)
// For taken+dismissed, just remove the dismissed flag // For taken+dismissed, just remove the dismissed flag
const dismissed = await db.select() const dismissed = await db
.select()
.from(doseTracking) .from(doseTracking)
.where( .where(and(eq(doseTracking.userId, userId), eq(doseTracking.dismissed, true)));
and(
eq(doseTracking.userId, userId),
eq(doseTracking.dismissed, true)
)
);
for (const d of dismissed) { for (const d of dismissed) {
if (d.markedBy !== null || d.takenAt) { if (d.markedBy !== null || d.takenAt) {
// This was also marked as taken - just remove dismissed flag // This was also marked as taken - just remove dismissed flag
await db.update(doseTracking) await db.update(doseTracking).set({ dismissed: false }).where(eq(doseTracking.id, d.id));
.set({ dismissed: false })
.where(eq(doseTracking.id, d.id));
} else { } else {
// This was only dismissed - delete it // This was only dismissed - delete it
await db.delete(doseTracking) await db.delete(doseTracking).where(eq(doseTracking.id, d.id));
.where(eq(doseTracking.id, d.id));
} }
} }
return { success: true, clearedCount: dismissed.length }; return { success: true, clearedCount: dismissed.length };
} });
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// GET /share/:token/doses - PUBLIC: Get taken doses for a share link // GET /share/:token/doses - PUBLIC: Get taken doses for a share link
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.get<{ Params: { token: string } }>( app.get<{ Params: { token: string } }>("/share/:token/doses", async (request, reply) => {
"/share/:token/doses",
async (request, reply) => {
const { token } = request.params; const { token } = request.params;
// Find share token // Find share token
@@ -244,9 +220,7 @@ export async function doseRoutes(app: FastifyInstance) {
} }
// Get all taken doses for this user (no time limit) // Get all taken doses for this user (no time limit)
const doses = await db.select() const doses = await db.select().from(doseTracking).where(eq(doseTracking.userId, share.userId));
.from(doseTracking)
.where(eq(doseTracking.userId, share.userId));
return { return {
doses: doses.map((d) => ({ doses: doses.map((d) => ({
@@ -256,8 +230,7 @@ export async function doseRoutes(app: FastifyInstance) {
dismissed: d.dismissed ?? false, dismissed: d.dismissed ?? false,
})), })),
}; };
} });
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /share/:token/doses - PUBLIC: Mark a dose as taken via share link // POST /share/:token/doses - PUBLIC: Mark a dose as taken via share link
@@ -283,14 +256,10 @@ export async function doseRoutes(app: FastifyInstance) {
} }
// Check if already marked // Check if already marked
const [existing] = await db.select() const [existing] = await db
.select()
.from(doseTracking) .from(doseTracking)
.where( .where(and(eq(doseTracking.userId, share.userId), eq(doseTracking.doseId, doseId)));
and(
eq(doseTracking.userId, share.userId),
eq(doseTracking.doseId, doseId)
)
);
if (existing) { if (existing) {
return { success: true, message: "Already marked" }; return { success: true, message: "Already marked" };
@@ -310,9 +279,7 @@ export async function doseRoutes(app: FastifyInstance) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// DELETE /share/:token/doses/:doseId - PUBLIC: Unmark a dose via share link // DELETE /share/:token/doses/:doseId - PUBLIC: Unmark a dose via share link
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.delete<{ Params: { token: string; doseId: string } }>( app.delete<{ Params: { token: string; doseId: string } }>("/share/:token/doses/:doseId", async (request, reply) => {
"/share/:token/doses/:doseId",
async (request, reply) => {
const { token, doseId } = request.params; const { token, doseId } = request.params;
// Find share token // Find share token
@@ -321,14 +288,19 @@ export async function doseRoutes(app: FastifyInstance) {
return reply.notFound("Share link not found"); return reply.notFound("Share link not found");
} }
await db.delete(doseTracking).where( // Check if this dose was dismissed
and( const [existing] = await db
eq(doseTracking.userId, share.userId), .select()
eq(doseTracking.doseId, doseId) .from(doseTracking)
) .where(and(eq(doseTracking.userId, share.userId), eq(doseTracking.doseId, doseId)));
);
if (existing?.dismissed) {
// Already dismissed - keep the record as-is
} else {
// Not dismissed - delete the record entirely
await db.delete(doseTracking).where(and(eq(doseTracking.userId, share.userId), eq(doseTracking.doseId, doseId)));
}
return { success: true }; return { success: true };
} });
);
} }
+85 -67
View File
@@ -1,16 +1,18 @@
import { FastifyInstance } from "fastify"; import { randomBytes } from "node:crypto";
import { z } from "zod"; import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { randomBytes } from "crypto"; import { extname, resolve } from "node:path";
import { db } from "../db/client.js";
import { medications, userSettings, doseTracking, shareTokens } from "../db/schema.js";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { requireAuth, getAnonymousUserId } from "../plugins/auth.js"; import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { doseTracking, medications, shareTokens, userSettings } from "../db/schema.js";
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
import { resolve, extname } from "path"; import { parseIntakesJson, parseTakenByJson } from "../utils/scheduler-utils.js";
import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync } from "fs";
const IMAGES_DIR = resolve(process.cwd(), "data/images"); const IMAGES_DIR = resolve(getDataDir(), "images");
// ============================================================================= // =============================================================================
// Export Format Version (bump this when format changes) // Export Format Version (bump this when format changes)
@@ -26,6 +28,7 @@ const scheduleSchema = z.object({
every: z.number().int().min(1), every: z.number().int().min(1),
start: z.string(), // ISO datetime string start: z.string(), // ISO datetime string
remind: z.boolean().optional().default(false), remind: z.boolean().optional().default(false),
takenBy: z.string().nullable().optional(), // Per-intake takenBy (new field)
}); });
const inventorySchema = z.object({ const inventorySchema = z.object({
@@ -34,6 +37,7 @@ const inventorySchema = z.object({
pillsPerBlister: z.number().int().min(1).default(1), pillsPerBlister: z.number().int().min(1).default(1),
looseTablets: z.number().int().min(0).default(0), looseTablets: z.number().int().min(0).default(0),
stockAdjustment: z.number().int().default(0), // Manual stock correction stockAdjustment: z.number().int().default(0), // Manual stock correction
packageType: z.enum(["blister", "bottle"]).default("blister"),
}); });
const medicationExportSchema = z.object({ const medicationExportSchema = z.object({
@@ -43,6 +47,7 @@ const medicationExportSchema = z.object({
takenBy: z.array(z.string()).default([]), takenBy: z.array(z.string()).default([]),
inventory: inventorySchema, inventory: inventorySchema,
pillWeightMg: z.number().int().nullable().optional(), pillWeightMg: z.number().int().nullable().optional(),
doseUnit: z.enum(["mg", "g", "mcg", "ml", "IU", "units", "drops", "puffs"]).default("mg"),
schedules: z.array(scheduleSchema).default([]), schedules: z.array(scheduleSchema).default([]),
expiryDate: z.string().nullable().optional(), expiryDate: z.string().nullable().optional(),
notes: z.string().nullable().optional(), notes: z.string().nullable().optional(),
@@ -68,7 +73,8 @@ const shareLinkSchema = z.object({
regenerateToken: z.boolean().default(true), regenerateToken: z.boolean().default(true),
}); });
const settingsExportSchema = z.object({ const settingsExportSchema = z
.object({
// Email notifications // Email notifications
emailEnabled: z.boolean().default(false), emailEnabled: z.boolean().default(false),
notificationEmail: z.string().nullable().optional(), notificationEmail: z.string().nullable().optional(),
@@ -93,7 +99,8 @@ const settingsExportSchema = z.object({
// UI preferences // UI preferences
language: z.string().default("en"), language: z.string().default("en"),
stockCalculationMode: z.enum(["automatic", "manual"]).default("automatic"), stockCalculationMode: z.enum(["automatic", "manual"]).default("automatic"),
}).optional(); })
.optional();
const importDataSchema = z.object({ const importDataSchema = z.object({
version: z.string(), version: z.string(),
@@ -123,37 +130,24 @@ async function getUserId(request: any, reply: any): Promise<number> {
return authUser.id; return authUser.id;
} }
// Parse takenByJson safely // Parse intakes from DB format to export format (with per-intake takenBy)
function parseTakenByJson(takenByJson: string | null | undefined): string[] { function parseIntakesForExport(
if (!takenByJson) return []; row: typeof medications.$inferSelect
try { ): Array<{ usage: number; every: number; start: string; remind: boolean; takenBy: string | null }> {
const parsed = JSON.parse(takenByJson); // Use the new parseIntakesJson which falls back to legacy format
return Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string" && s.trim()) : []; const intakes = parseIntakesJson(
} catch { row.intakesJson,
return []; { usageJson: row.usageJson, everyJson: row.everyJson, startJson: row.startJson },
} row.intakeRemindersEnabled ?? false
} );
// Parse blisters from DB format to export format return intakes.map((intake) => ({
function parseBlistersForExport(row: typeof medications.$inferSelect): Array<{ usage: number; every: number; start: string; remind: boolean }> { usage: intake.usage,
try { every: intake.every,
const usage = JSON.parse(row.usageJson || "[]") as number[]; start: intake.start,
const every = JSON.parse(row.everyJson || "[]") as number[]; remind: intake.intakeRemindersEnabled,
const start = JSON.parse(row.startJson || "[]") as string[]; takenBy: intake.takenBy, // Per-intake takenBy
const len = Math.min(usage.length, every.length, start.length); }));
const schedules: Array<{ usage: number; every: number; start: string; remind: boolean }> = [];
for (let i = 0; i < len; i++) {
schedules.push({
usage: usage[i],
every: every[i],
start: start[i],
remind: row.intakeRemindersEnabled ?? false,
});
}
return schedules;
} catch {
return [];
}
} }
// Read image file and convert to base64 data URL // Read image file and convert to base64 data URL
@@ -209,7 +203,9 @@ function base64ToImage(base64: string, medicationId: number): string | null {
// Parse dose ID to extract medication ID and timestamp // Parse dose ID to extract medication ID and timestamp
// Format: "{medicationId}-{blisterIndex}-{timestampMs}" or "{medicationId}-{blisterIndex}-{timestampMs}-{person}" // Format: "{medicationId}-{blisterIndex}-{timestampMs}" or "{medicationId}-{blisterIndex}-{timestampMs}-{person}"
function parseDoseId(doseId: string): { medicationId: number; blisterIndex: number; timestampMs: number; person: string | null } | null { function parseDoseId(
doseId: string
): { medicationId: number; blisterIndex: number; timestampMs: number; person: string | null } | null {
const parts = doseId.split("-"); const parts = doseId.split("-");
if (parts.length < 3) return null; if (parts.length < 3) return null;
@@ -217,7 +213,7 @@ function parseDoseId(doseId: string): { medicationId: number; blisterIndex: numb
const blisterIndex = parseInt(parts[1], 10); const blisterIndex = parseInt(parts[1], 10);
const timestampMs = parseInt(parts[2], 10); const timestampMs = parseInt(parts[2], 10);
if (isNaN(medicationId) || isNaN(blisterIndex) || isNaN(timestampMs)) return null; if (Number.isNaN(medicationId) || Number.isNaN(blisterIndex) || Number.isNaN(timestampMs)) return null;
// Check if there's a person suffix (4th part onwards, could be multi-part name) // Check if there's a person suffix (4th part onwards, could be multi-part name)
const person = parts.length > 3 ? parts.slice(3).join("-") : null; const person = parts.length > 3 ? parts.slice(3).join("-") : null;
@@ -241,9 +237,7 @@ export async function exportRoutes(app: FastifyInstance) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// GET /export - Export all user data // GET /export - Export all user data
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.get<{ Querystring: { includeSensitive?: string; includeImages?: string } }>( app.get<{ Querystring: { includeSensitive?: string; includeImages?: string } }>("/export", async (request, reply) => {
"/export",
async (request, reply) => {
const userId = await getUserId(request, reply); const userId = await getUserId(request, reply);
const includeSensitive = request.query.includeSensitive === "true"; const includeSensitive = request.query.includeSensitive === "true";
const includeImages = request.query.includeImages !== "false"; // Default to true const includeImages = request.query.includeImages !== "false"; // Default to true
@@ -261,11 +255,11 @@ export async function exportRoutes(app: FastifyInstance) {
let lastStockCorrectionAtIso: string | null = null; let lastStockCorrectionAtIso: string | null = null;
if (med.lastStockCorrectionAt) { if (med.lastStockCorrectionAt) {
try { try {
if (med.lastStockCorrectionAt instanceof Date && !isNaN(med.lastStockCorrectionAt.getTime())) { if (med.lastStockCorrectionAt instanceof Date && !Number.isNaN(med.lastStockCorrectionAt.getTime())) {
lastStockCorrectionAtIso = med.lastStockCorrectionAt.toISOString(); lastStockCorrectionAtIso = med.lastStockCorrectionAt.toISOString();
} else if (typeof med.lastStockCorrectionAt === "number" || typeof med.lastStockCorrectionAt === "string") { } else if (typeof med.lastStockCorrectionAt === "number" || typeof med.lastStockCorrectionAt === "string") {
const d = new Date(med.lastStockCorrectionAt); const d = new Date(med.lastStockCorrectionAt);
lastStockCorrectionAtIso = !isNaN(d.getTime()) ? d.toISOString() : null; lastStockCorrectionAtIso = !Number.isNaN(d.getTime()) ? d.toISOString() : null;
} }
} catch { } catch {
lastStockCorrectionAtIso = null; lastStockCorrectionAtIso = null;
@@ -283,9 +277,11 @@ export async function exportRoutes(app: FastifyInstance) {
pillsPerBlister: med.pillsPerBlister ?? 1, pillsPerBlister: med.pillsPerBlister ?? 1,
looseTablets: med.looseTablets ?? 0, looseTablets: med.looseTablets ?? 0,
stockAdjustment: med.stockAdjustment ?? 0, stockAdjustment: med.stockAdjustment ?? 0,
packageType: med.packageType ?? "blister",
}, },
pillWeightMg: med.pillWeightMg, pillWeightMg: med.pillWeightMg,
schedules: parseBlistersForExport(med), doseUnit: med.doseUnit ?? "mg",
schedules: parseIntakesForExport(med),
expiryDate: med.expiryDate, expiryDate: med.expiryDate,
notes: med.notes, notes: med.notes,
intakeRemindersEnabled: med.intakeRemindersEnabled ?? false, intakeRemindersEnabled: med.intakeRemindersEnabled ?? false,
@@ -297,7 +293,8 @@ export async function exportRoutes(app: FastifyInstance) {
// 2. Load all dose tracking entries // 2. Load all dose tracking entries
const doses = await db.select().from(doseTracking).where(eq(doseTracking.userId, userId)); const doses = await db.select().from(doseTracking).where(eq(doseTracking.userId, userId));
const exportDoseHistory = doses.map((dose) => { const exportDoseHistory = doses
.map((dose) => {
const parsed = parseDoseId(dose.doseId); const parsed = parseDoseId(dose.doseId);
if (!parsed) return null; if (!parsed) return null;
@@ -307,11 +304,11 @@ export async function exportRoutes(app: FastifyInstance) {
// Safely convert takenAt to ISO string // Safely convert takenAt to ISO string
let takenAtIso: string; let takenAtIso: string;
try { try {
if (dose.takenAt instanceof Date && !isNaN(dose.takenAt.getTime())) { if (dose.takenAt instanceof Date && !Number.isNaN(dose.takenAt.getTime())) {
takenAtIso = dose.takenAt.toISOString(); takenAtIso = dose.takenAt.toISOString();
} else if (typeof dose.takenAt === "number" || typeof dose.takenAt === "string") { } else if (typeof dose.takenAt === "number" || typeof dose.takenAt === "string") {
const d = new Date(dose.takenAt); const d = new Date(dose.takenAt);
takenAtIso = !isNaN(d.getTime()) ? d.toISOString() : new Date().toISOString(); takenAtIso = !Number.isNaN(d.getTime()) ? d.toISOString() : new Date().toISOString();
} else { } else {
takenAtIso = new Date().toISOString(); takenAtIso = new Date().toISOString();
} }
@@ -323,7 +320,7 @@ export async function exportRoutes(app: FastifyInstance) {
let scheduledTimeIso: string; let scheduledTimeIso: string;
try { try {
const d = new Date(parsed.timestampMs); const d = new Date(parsed.timestampMs);
scheduledTimeIso = !isNaN(d.getTime()) ? d.toISOString() : new Date().toISOString(); scheduledTimeIso = !Number.isNaN(d.getTime()) ? d.toISOString() : new Date().toISOString();
} catch { } catch {
scheduledTimeIso = new Date().toISOString(); scheduledTimeIso = new Date().toISOString();
} }
@@ -337,12 +334,14 @@ export async function exportRoutes(app: FastifyInstance) {
dismissed: dose.dismissed ?? false, dismissed: dose.dismissed ?? false,
takenByPerson: parsed.person, takenByPerson: parsed.person,
}; };
}).filter((d): d is NonNullable<typeof d> => d !== null); })
.filter((d): d is NonNullable<typeof d> => d !== null);
// 3. Load user settings // 3. Load user settings
const [settings] = await db.select().from(userSettings).where(eq(userSettings.userId, userId)); const [settings] = await db.select().from(userSettings).where(eq(userSettings.userId, userId));
const exportSettings = settings ? { const exportSettings = settings
? {
emailEnabled: settings.emailEnabled, emailEnabled: settings.emailEnabled,
notificationEmail: settings.notificationEmail, notificationEmail: settings.notificationEmail,
emailStockReminders: settings.emailStockReminders, emailStockReminders: settings.emailStockReminders,
@@ -363,7 +362,8 @@ export async function exportRoutes(app: FastifyInstance) {
highStockDays: settings.highStockDays, highStockDays: settings.highStockDays,
language: settings.language, language: settings.language,
stockCalculationMode: settings.stockCalculationMode, stockCalculationMode: settings.stockCalculationMode,
} : undefined; }
: undefined;
// 4. Load share links // 4. Load share links
const shares = await db.select().from(shareTokens).where(eq(shareTokens.userId, userId)); const shares = await db.select().from(shareTokens).where(eq(shareTokens.userId, userId));
@@ -373,11 +373,11 @@ export async function exportRoutes(app: FastifyInstance) {
let expiresAtIso: string | null = null; let expiresAtIso: string | null = null;
if (share.expiresAt) { if (share.expiresAt) {
try { try {
if (share.expiresAt instanceof Date && !isNaN(share.expiresAt.getTime())) { if (share.expiresAt instanceof Date && !Number.isNaN(share.expiresAt.getTime())) {
expiresAtIso = share.expiresAt.toISOString(); expiresAtIso = share.expiresAt.toISOString();
} else if (typeof share.expiresAt === "number" || typeof share.expiresAt === "string") { } else if (typeof share.expiresAt === "number" || typeof share.expiresAt === "string") {
const d = new Date(share.expiresAt); const d = new Date(share.expiresAt);
expiresAtIso = !isNaN(d.getTime()) ? d.toISOString() : null; expiresAtIso = !Number.isNaN(d.getTime()) ? d.toISOString() : null;
} }
} catch { } catch {
expiresAtIso = null; expiresAtIso = null;
@@ -409,8 +409,7 @@ export async function exportRoutes(app: FastifyInstance) {
reply.header("Content-Disposition", `attachment; filename="${filename}"`); reply.header("Content-Disposition", `attachment; filename="${filename}"`);
return exportData; return exportData;
} });
);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /import - Import user data (replaces all existing data!) // POST /import - Import user data (replaces all existing data!)
@@ -447,7 +446,11 @@ export async function exportRoutes(app: FastifyInstance) {
if (med.imageUrl) { if (med.imageUrl) {
const imagePath = resolve(IMAGES_DIR, med.imageUrl); const imagePath = resolve(IMAGES_DIR, med.imageUrl);
if (existsSync(imagePath)) { if (existsSync(imagePath)) {
try { unlinkSync(imagePath); } catch { /* ignore */ } try {
unlinkSync(imagePath);
} catch {
/* ignore */
}
} }
} }
} }
@@ -462,20 +465,34 @@ export async function exportRoutes(app: FastifyInstance) {
const exportIdToNewId = new Map<string, number>(); const exportIdToNewId = new Map<string, number>();
for (const med of importData.medications) { for (const med of importData.medications) {
// Convert schedules back to JSON arrays // Convert schedules to both legacy and new formats
const usageJson = JSON.stringify(med.schedules.map((s) => s.usage)); const usageJson = JSON.stringify(med.schedules.map((s) => s.usage));
const everyJson = JSON.stringify(med.schedules.map((s) => s.every)); const everyJson = JSON.stringify(med.schedules.map((s) => s.every));
const startJson = JSON.stringify(med.schedules.map((s) => s.start)); const startJson = JSON.stringify(med.schedules.map((s) => s.start));
const takenByJson = JSON.stringify(med.takenBy); const takenByJson = JSON.stringify(med.takenBy);
// Build intakesJson array (new unified format with per-intake takenBy)
const intakesJson = JSON.stringify(
med.schedules.map((s) => ({
usage: s.usage,
every: s.every,
start: s.start,
takenBy: s.takenBy || null,
intakeRemindersEnabled: s.remind ?? false,
}))
);
// Check if any schedule has remind enabled // Check if any schedule has remind enabled
const intakeRemindersEnabled = med.schedules.some((s) => s.remind) || med.intakeRemindersEnabled; const intakeRemindersEnabled = med.schedules.some((s) => s.remind) || med.intakeRemindersEnabled;
const [inserted] = await db.insert(medications).values({ const [inserted] = await db
.insert(medications)
.values({
userId, userId,
name: med.name, name: med.name,
genericName: med.genericName || null, genericName: med.genericName || null,
takenByJson, takenByJson,
packageType: med.inventory.packageType ?? "blister",
packCount: med.inventory.packCount, packCount: med.inventory.packCount,
blistersPerPack: med.inventory.blistersPerPack, blistersPerPack: med.inventory.blistersPerPack,
pillsPerBlister: med.inventory.pillsPerBlister, pillsPerBlister: med.inventory.pillsPerBlister,
@@ -483,6 +500,8 @@ export async function exportRoutes(app: FastifyInstance) {
stockAdjustment: med.inventory.stockAdjustment ?? 0, stockAdjustment: med.inventory.stockAdjustment ?? 0,
lastStockCorrectionAt: med.lastStockCorrectionAt ? new Date(med.lastStockCorrectionAt) : null, lastStockCorrectionAt: med.lastStockCorrectionAt ? new Date(med.lastStockCorrectionAt) : null,
pillWeightMg: med.pillWeightMg || null, pillWeightMg: med.pillWeightMg || null,
doseUnit: med.doseUnit ?? "mg",
intakesJson,
usageJson, usageJson,
everyJson, everyJson,
startJson, startJson,
@@ -490,7 +509,8 @@ export async function exportRoutes(app: FastifyInstance) {
notes: med.notes || null, notes: med.notes || null,
intakeRemindersEnabled, intakeRemindersEnabled,
imageUrl: null, // Will be set after image is saved imageUrl: null, // Will be set after image is saved
}).returning(); })
.returning();
// Save mapping // Save mapping
exportIdToNewId.set(med._exportId, inserted.id); exportIdToNewId.set(med._exportId, inserted.id);
@@ -499,9 +519,7 @@ export async function exportRoutes(app: FastifyInstance) {
if (med.image) { if (med.image) {
const imageUrl = base64ToImage(med.image, inserted.id); const imageUrl = base64ToImage(med.image, inserted.id);
if (imageUrl) { if (imageUrl) {
await db.update(medications) await db.update(medications).set({ imageUrl }).where(eq(medications.id, inserted.id));
.set({ imageUrl })
.where(eq(medications.id, inserted.id));
} }
} }
} }
+6 -5
View File
@@ -1,7 +1,7 @@
import { FastifyInstance } from "fastify"; import { readFileSync } from "node:fs";
import { readFileSync } from "fs"; import { dirname, resolve } from "node:path";
import { resolve, dirname } from "path"; import { fileURLToPath } from "node:url";
import { fileURLToPath } from "url"; import type { FastifyInstance } from "fastify";
// Read version from package.json at startup // Read version from package.json at startup
const __dirname = dirname(fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -10,7 +10,8 @@ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
const backendVersion = packageJson.version || "unknown"; const backendVersion = packageJson.version || "unknown";
export async function healthRoutes(app: FastifyInstance) { export async function healthRoutes(app: FastifyInstance) {
app.get("/health", async () => ({ // Exempt from rate limit - lightweight health check
app.get("/health", { config: { rateLimit: false } }, async () => ({
status: "ok", status: "ok",
version: backendVersion, version: backendVersion,
smtpConfigured: Boolean(process.env.SMTP_HOST), smtpConfigured: Boolean(process.env.SMTP_HOST),
+517 -106
View File
@@ -1,67 +1,59 @@
import { FastifyInstance } from "fastify"; import { createWriteStream, existsSync, unlinkSync } from "node:fs";
import { extname, resolve } from "node:path";
import { pipeline } from "node:stream/promises";
import { and, eq, like } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { medications, doseTracking } from "../db/schema.js"; import { getDataDir } from "../db/db-utils.js";
import { eq, and, like, sql } from "drizzle-orm"; import { doseTracking, medications } from "../db/schema.js";
import { createWriteStream, existsSync, unlinkSync } from "fs"; import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { resolve, extname } from "path";
import { pipeline } from "stream/promises";
import { requireAuth, getAnonymousUserId } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
import { type Intake, parseIntakesJson, parseLocalDateTime, parseTakenByJson } from "../utils/scheduler-utils.js";
const IMAGES_DIR = resolve(process.cwd(), "data/images"); const IMAGES_DIR = resolve(getDataDir(), "images");
// New intake schema with per-intake takenBy
const intakeSchema = z.object({
usage: z.number().nonnegative(),
every: z.number().int().min(1),
start: z.string().datetime({ local: true }),
takenBy: z.string().trim().max(100).nullable().optional(), // Person for this specific intake
intakeRemindersEnabled: z.boolean().default(false), // Per-intake reminder setting
});
// Legacy blister schema (for backward compatibility during transition)
const blisterSchema = z.object({ const blisterSchema = z.object({
usage: z.number().nonnegative(), usage: z.number().nonnegative(),
every: z.number().int().min(1), every: z.number().int().min(1),
start: z.string().datetime(), start: z.string().datetime({ local: true }),
}); });
const medicationSchema = z.object({ const packageTypeSchema = z.enum(["blister", "bottle"]).default("blister");
const doseUnitSchema = z.enum(["mg", "g", "mcg", "ml", "IU", "units", "drops", "puffs"]).default("mg");
const medicationSchema = z
.object({
name: z.string().trim().min(1).max(100), name: z.string().trim().min(1).max(100),
genericName: z.string().trim().max(100).nullable().optional(), genericName: z.string().trim().max(100).nullable().optional(),
takenBy: z.array(z.string().trim().max(100)).default([]), // Array of person names takenBy: z.array(z.string().trim().max(100)).default([]), // Medication-level takenBy (fallback)
packageType: packageTypeSchema,
packCount: z.number().int().min(0).default(1), packCount: z.number().int().min(0).default(1),
blistersPerPack: z.number().int().min(1).default(1), blistersPerPack: z.number().int().min(1).default(1),
pillsPerBlister: z.number().int().min(1).default(1), pillsPerBlister: z.number().int().min(1).default(1),
totalPills: z.number().int().min(1).nullable().optional(), // For bottle type: total capacity
looseTablets: z.number().int().min(0).default(0), looseTablets: z.number().int().min(0).default(0),
pillWeightMg: z.number().int().min(1).nullable().optional(), pillWeightMg: z.number().nonnegative().nullable().optional(),
doseUnit: doseUnitSchema,
expiryDate: z.string().nullable().optional(), expiryDate: z.string().nullable().optional(),
notes: z.string().max(2000).nullable().optional(), notes: z.string().max(2000).nullable().optional(),
intakeRemindersEnabled: z.boolean().default(false), intakeRemindersEnabled: z.boolean().default(false), // Medication-level (deprecated, kept for backward compat)
blisters: z.array(blisterSchema).min(1).max(12), // Accept either new intakes format or legacy blisters format
}); intakes: z.array(intakeSchema).min(1).max(12).optional(),
blisters: z.array(blisterSchema).min(1).max(12).optional(), // Legacy format
function zipBlisters(usage: number[], every: number[], start: string[]) { })
const len = Math.min(usage.length, every.length, start.length); .refine((data) => data.intakes || data.blisters, { message: "Either 'intakes' or 'blisters' must be provided" });
const blisters: Array<{ usage: number; every: number; start: string }> = [];
for (let i = 0; i < len; i++) {
blisters.push({ usage: usage[i], every: every[i], start: start[i] });
}
return blisters;
}
function parseBlisters(row: typeof medications.$inferSelect) {
try {
const usage = JSON.parse(row.usageJson) as number[];
const every = JSON.parse(row.everyJson) as number[];
const start = JSON.parse(row.startJson) as string[];
return zipBlisters(usage, every, start);
} catch (err) {
return [];
}
}
function parseTakenByJson(takenByJson: string | null | undefined): string[] {
if (!takenByJson) return [];
try {
const parsed = JSON.parse(takenByJson);
return Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string" && s.trim()) : [];
} catch {
return [];
}
}
export async function medicationRoutes(app: FastifyInstance) { export async function medicationRoutes(app: FastifyInstance) {
// All medication routes require auth // All medication routes require auth
@@ -69,7 +61,7 @@ export async function medicationRoutes(app: FastifyInstance) {
// Helper to get user ID from request // Helper to get user ID from request
// Returns anonymous user ID when auth is disabled // Returns anonymous user ID when auth is disabled
async function getUserId(request: any, reply: any): Promise<number> { async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
// If auth is disabled, use the anonymous user // If auth is disabled, use the anonymous user
if (!env.AUTH_ENABLED) { if (!env.AUTH_ENABLED) {
return getAnonymousUserId(); return getAnonymousUserId();
@@ -87,25 +79,40 @@ export async function medicationRoutes(app: FastifyInstance) {
app.get("/medications", async (request, reply) => { app.get("/medications", async (request, reply) => {
const userId = await getUserId(request, reply); const userId = await getUserId(request, reply);
const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id); const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id);
return rows.map((row) => ({ return rows.map((row) => {
// Parse intakes from new format, falling back to legacy
const intakes = parseIntakesJson(
row.intakesJson,
{ usageJson: row.usageJson, everyJson: row.everyJson, startJson: row.startJson },
row.intakeRemindersEnabled ?? false
);
return {
id: row.id, id: row.id,
name: row.name, name: row.name,
genericName: row.genericName, genericName: row.genericName,
takenBy: parseTakenByJson(row.takenByJson), takenBy: parseTakenByJson(row.takenByJson),
packageType: row.packageType ?? "blister",
packCount: row.packCount ?? 1, packCount: row.packCount ?? 1,
blistersPerPack: row.blistersPerPack ?? 1, blistersPerPack: row.blistersPerPack ?? 1,
pillsPerBlister: row.pillsPerBlister ?? 1, pillsPerBlister: row.pillsPerBlister ?? 1,
totalPills: row.totalPills ?? null,
looseTablets: row.looseTablets ?? 0, looseTablets: row.looseTablets ?? 0,
stockAdjustment: row.stockAdjustment ?? 0, stockAdjustment: row.stockAdjustment ?? 0,
lastStockCorrectionAt: row.lastStockCorrectionAt?.toISOString() ?? null, lastStockCorrectionAt: row.lastStockCorrectionAt?.toISOString() ?? null,
pillWeightMg: row.pillWeightMg, pillWeightMg: row.pillWeightMg,
blisters: parseBlisters(row), doseUnit: row.doseUnit ?? "mg",
intakes, // New unified format with per-intake takenBy
// Legacy blisters format (for backward compat with frontend during transition)
blisters: intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start })),
imageUrl: row.imageUrl, imageUrl: row.imageUrl,
expiryDate: row.expiryDate, expiryDate: row.expiryDate,
notes: row.notes, notes: row.notes,
intakeRemindersEnabled: row.intakeRemindersEnabled ?? false, intakeRemindersEnabled: row.intakeRemindersEnabled ?? false,
dismissedUntil: row.dismissedUntil ?? null,
updatedAt: row.updatedAt, updatedAt: row.updatedAt,
})); };
});
}); });
app.post("/medications", async (req, reply) => { app.post("/medications", async (req, reply) => {
@@ -113,10 +120,54 @@ export async function medicationRoutes(app: FastifyInstance) {
if (!parsed.success) return reply.status(400).send(parsed.error.format()); if (!parsed.success) return reply.status(400).send(parsed.error.format());
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
const { name, genericName, takenBy, packCount, blistersPerPack, pillsPerBlister, looseTablets, pillWeightMg, expiryDate, notes, intakeRemindersEnabled, blisters } = parsed.data; const {
const usageJson = JSON.stringify(blisters.map((s) => s.usage)); name,
const everyJson = JSON.stringify(blisters.map((s) => s.every)); genericName,
const startJson = JSON.stringify(blisters.map((s) => s.start)); takenBy,
packageType,
packCount,
blistersPerPack,
pillsPerBlister,
totalPills,
looseTablets,
pillWeightMg,
doseUnit,
expiryDate,
notes,
intakeRemindersEnabled,
intakes: inputIntakes,
blisters: inputBlisters,
} = parsed.data;
// Convert to unified intakes format
let intakes: Intake[];
if (inputIntakes) {
// New format with per-intake takenBy
intakes = inputIntakes.map((i) => ({
usage: i.usage,
every: i.every,
start: i.start,
takenBy: i.takenBy || null,
intakeRemindersEnabled: i.intakeRemindersEnabled ?? false,
}));
} else if (inputBlisters) {
// Legacy format - convert to new format
intakes = inputBlisters.map((b) => ({
usage: b.usage,
every: b.every,
start: b.start,
takenBy: null, // No per-intake takenBy from legacy
intakeRemindersEnabled: intakeRemindersEnabled ?? false,
}));
} else {
return reply.status(400).send({ error: "Either 'intakes' or 'blisters' must be provided" });
}
// Store both formats for backward compatibility
const intakesJson = JSON.stringify(intakes);
const usageJson = JSON.stringify(intakes.map((s) => s.usage));
const everyJson = JSON.stringify(intakes.map((s) => s.every));
const startJson = JSON.stringify(intakes.map((s) => s.start));
const takenByJson = JSON.stringify(takenBy || []); const takenByJson = JSON.stringify(takenBy || []);
const [inserted] = await db const [inserted] = await db
@@ -126,14 +177,18 @@ export async function medicationRoutes(app: FastifyInstance) {
name, name,
genericName: genericName || null, genericName: genericName || null,
takenByJson, takenByJson,
packageType: packageType ?? "blister",
packCount, packCount,
blistersPerPack, blistersPerPack,
pillsPerBlister, pillsPerBlister,
totalPills: totalPills || null,
looseTablets, looseTablets,
pillWeightMg: pillWeightMg || null, pillWeightMg: pillWeightMg || null,
doseUnit: doseUnit ?? "mg",
expiryDate: expiryDate || null, expiryDate: expiryDate || null,
notes: notes || null, notes: notes || null,
intakeRemindersEnabled: intakeRemindersEnabled ?? false, intakeRemindersEnabled: intakeRemindersEnabled ?? false,
intakesJson,
usageJson, usageJson,
everyJson, everyJson,
startJson, startJson,
@@ -145,14 +200,18 @@ export async function medicationRoutes(app: FastifyInstance) {
name: inserted.name, name: inserted.name,
genericName: inserted.genericName, genericName: inserted.genericName,
takenBy: parseTakenByJson(inserted.takenByJson), takenBy: parseTakenByJson(inserted.takenByJson),
packageType: inserted.packageType ?? "blister",
packCount: inserted.packCount, packCount: inserted.packCount,
blistersPerPack: inserted.blistersPerPack, blistersPerPack: inserted.blistersPerPack,
pillsPerBlister: inserted.pillsPerBlister, pillsPerBlister: inserted.pillsPerBlister,
totalPills: inserted.totalPills ?? null,
looseTablets: inserted.looseTablets, looseTablets: inserted.looseTablets,
stockAdjustment: inserted.stockAdjustment ?? 0, stockAdjustment: inserted.stockAdjustment ?? 0,
lastStockCorrectionAt: inserted.lastStockCorrectionAt?.toISOString() ?? null, lastStockCorrectionAt: inserted.lastStockCorrectionAt?.toISOString() ?? null,
pillWeightMg: inserted.pillWeightMg, pillWeightMg: inserted.pillWeightMg,
blisters, doseUnit: inserted.doseUnit ?? "mg",
intakes,
blisters: intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start })),
imageUrl: inserted.imageUrl, imageUrl: inserted.imageUrl,
expiryDate: inserted.expiryDate, expiryDate: inserted.expiryDate,
notes: inserted.notes, notes: inserted.notes,
@@ -170,79 +229,238 @@ export async function medicationRoutes(app: FastifyInstance) {
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
// Verify ownership // Verify ownership
const [existing] = await db.select().from(medications).where(and(eq(medications.id, idNum), eq(medications.userId, userId))); const [existing] = await db
.select()
.from(medications)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound(); if (!existing) return reply.notFound();
const { name, genericName, takenBy, packCount, blistersPerPack, pillsPerBlister, looseTablets, pillWeightMg, expiryDate, notes, intakeRemindersEnabled, blisters } = parsed.data; const {
const usageJson = JSON.stringify(blisters.map((s) => s.usage)); name,
const everyJson = JSON.stringify(blisters.map((s) => s.every)); genericName,
const startJson = JSON.stringify(blisters.map((s) => s.start)); takenBy,
packageType,
packCount,
blistersPerPack,
pillsPerBlister,
totalPills,
looseTablets,
pillWeightMg,
doseUnit,
expiryDate,
notes,
intakeRemindersEnabled,
intakes: inputIntakes,
blisters: inputBlisters,
} = parsed.data;
// Convert to unified intakes format
let intakes: Intake[];
if (inputIntakes) {
// New format with per-intake takenBy
intakes = inputIntakes.map((i) => ({
usage: i.usage,
every: i.every,
start: i.start,
takenBy: i.takenBy || null,
intakeRemindersEnabled: i.intakeRemindersEnabled ?? false,
}));
} else if (inputBlisters) {
// Legacy format - convert to new format
intakes = inputBlisters.map((b) => ({
usage: b.usage,
every: b.every,
start: b.start,
takenBy: null, // No per-intake takenBy from legacy
intakeRemindersEnabled: intakeRemindersEnabled ?? false,
}));
} else {
return reply.status(400).send({ error: "Either 'intakes' or 'blisters' must be provided" });
}
// Store both formats for backward compatibility
const intakesJson = JSON.stringify(intakes);
const usageJson = JSON.stringify(intakes.map((s) => s.usage));
const everyJson = JSON.stringify(intakes.map((s) => s.every));
const startJson = JSON.stringify(intakes.map((s) => s.start));
const takenByJson = JSON.stringify(takenBy || []); const takenByJson = JSON.stringify(takenBy || []);
// If stock-defining fields changed, reset stockAdjustment so the new
// base stock reflects actual inventory. This prevents the old
// correction offset from skewing the total after an edit.
const stockFieldsChanged =
existing.packCount !== packCount ||
existing.blistersPerPack !== blistersPerPack ||
existing.pillsPerBlister !== pillsPerBlister ||
(existing.looseTablets ?? 0) !== (looseTablets ?? 0);
const stockResetFields = stockFieldsChanged ? { stockAdjustment: 0, lastStockCorrectionAt: new Date() } : {};
const result = await db const result = await db
.update(medications) .update(medications)
.set({ .set({
name, name,
genericName: genericName || null, genericName: genericName || null,
takenByJson, takenByJson,
packageType: packageType ?? "blister",
packCount, packCount,
blistersPerPack, blistersPerPack,
pillsPerBlister, pillsPerBlister,
totalPills: totalPills || null,
looseTablets, looseTablets,
pillWeightMg: pillWeightMg || null, pillWeightMg: pillWeightMg || null,
doseUnit: doseUnit ?? "mg",
expiryDate: expiryDate || null, expiryDate: expiryDate || null,
notes: notes || null, notes: notes || null,
intakeRemindersEnabled: intakeRemindersEnabled ?? false, intakeRemindersEnabled: intakeRemindersEnabled ?? false,
intakesJson,
usageJson, usageJson,
everyJson, everyJson,
startJson, startJson,
updatedAt: new Date(), updatedAt: new Date(),
...stockResetFields,
}) })
.where(and(eq(medications.id, idNum), eq(medications.userId, userId))) .where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
.returning(); .returning();
if (!result.length) return reply.notFound(); if (!result.length) return reply.notFound();
// Clean up dose tracking entries that are before the earliest start date // ---------------------------------------------------------------
// This ensures consistency when the user changes the start date // Migrate dose tracking IDs when intake schedule changes
const earliestStart = Math.min(...blisters.map(b => new Date(b.start).getTime())); // ---------------------------------------------------------------
if (!Number.isNaN(earliestStart)) { // Parse old intakes from the existing medication row
// Get all dose tracking entries for this medication and filter out invalid ones const oldIntakes = parseIntakesJson(
const allDoses = await db.select().from(doseTracking) existing.intakesJson,
.where(and( { usageJson: existing.usageJson, everyJson: existing.everyJson, startJson: existing.startJson },
eq(doseTracking.userId, userId), existing.intakeRemindersEnabled
like(doseTracking.doseId, `${idNum}-%`) );
));
// Find doses with timestamps before the earliest start date // Get all dose tracking entries for this medication
const dosesToDelete = allDoses.filter(dose => { const allDoses = await db
.select()
.from(doseTracking)
.where(and(eq(doseTracking.userId, userId), like(doseTracking.doseId, `${idNum}-%`)));
if (allDoses.length > 0) {
// Build migration map: for each intake index, map old dateOnlyMs → new dateOnlyMs
const now = new Date();
const migrationEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const MS_PER_DAY = 86_400_000;
for (let idx = 0; idx < Math.max(oldIntakes.length, intakes.length); idx++) {
const oldIntake = oldIntakes[idx];
const newIntake = intakes[idx];
// Skip if this intake index doesn't exist in both old and new
if (!oldIntake || !newIntake) continue;
const oldStart = parseLocalDateTime(oldIntake.start);
const newStart = parseLocalDateTime(newIntake.start);
const oldEvery = oldIntake.every;
const newEvery = newIntake.every;
// Check if start date or interval changed (time-of-day changes don't matter for dateOnlyMs)
const oldStartDateOnly = new Date(oldStart.getFullYear(), oldStart.getMonth(), oldStart.getDate()).getTime();
const newStartDateOnly = new Date(newStart.getFullYear(), newStart.getMonth(), newStart.getDate()).getTime();
if (oldStartDateOnly === newStartDateOnly && oldEvery === newEvery) {
continue; // No schedule change that affects dose IDs
}
// Build set of new valid dateOnlyMs values for this intake
const newDates = new Set<number>();
for (let d = new Date(newStart); d <= migrationEnd; d.setDate(d.getDate() + newEvery)) {
newDates.add(new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime());
}
// Build set of old dateOnlyMs values with mapping to nearest new date
const oldToNewMap = new Map<number, number>();
for (let d = new Date(oldStart); d <= migrationEnd; d.setDate(d.getDate() + oldEvery)) {
const oldDateMs = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
// Find the closest new date within ±(newEvery/2) days
const halfInterval = (newEvery * MS_PER_DAY) / 2;
let bestMatch: number | null = null;
let bestDist = Infinity;
for (const newDateMs of newDates) {
const dist = Math.abs(newDateMs - oldDateMs);
if (dist < bestDist && dist <= halfInterval) {
bestDist = dist;
bestMatch = newDateMs;
}
}
if (bestMatch !== null && bestMatch !== oldDateMs) {
oldToNewMap.set(oldDateMs, bestMatch);
// Remove matched new date to prevent double-mapping
newDates.delete(bestMatch);
}
}
// Apply migrations to dose tracking entries
if (oldToNewMap.size > 0) {
const prefix = `${idNum}-${idx}-`;
const dosesToMigrate = allDoses.filter((d) => d.doseId.startsWith(prefix));
for (const dose of dosesToMigrate) {
const parts = dose.doseId.split("-");
if (parts.length >= 3) {
const oldTimestamp = parseInt(parts[2], 10);
const newTimestamp = oldToNewMap.get(oldTimestamp);
if (newTimestamp !== undefined) {
// Replace the timestamp in the dose ID, keeping any person suffix
const newDoseId = `${idNum}-${idx}-${newTimestamp}${parts.length > 3 ? `-${parts.slice(3).join("-")}` : ""}`;
await db.update(doseTracking).set({ doseId: newDoseId }).where(eq(doseTracking.id, dose.id));
}
}
}
}
}
// Also clean up dose tracking entries before the earliest new start date
const earliestStartDate = intakes.reduce((min, b) => {
const d = parseLocalDateTime(b.start);
// Use date-only (midnight) to match dose ID format
const dateOnly = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
return dateOnly < min ? dateOnly : min;
}, Infinity);
if (!Number.isNaN(earliestStartDate)) {
// Re-fetch after possible migrations
const updatedDoses = await db
.select()
.from(doseTracking)
.where(and(eq(doseTracking.userId, userId), like(doseTracking.doseId, `${idNum}-%`)));
const dosesToDelete = updatedDoses.filter((dose) => {
const parts = dose.doseId.split("-"); const parts = dose.doseId.split("-");
if (parts.length >= 3) { if (parts.length >= 3) {
const timestamp = parseInt(parts[2], 10); const timestamp = parseInt(parts[2], 10);
return !Number.isNaN(timestamp) && timestamp < earliestStart; return !Number.isNaN(timestamp) && timestamp < earliestStartDate;
} }
return false; return false;
}); });
// Delete invalid doses
for (const dose of dosesToDelete) { for (const dose of dosesToDelete) {
await db.delete(doseTracking).where(eq(doseTracking.id, dose.id)); await db.delete(doseTracking).where(eq(doseTracking.id, dose.id));
} }
} }
}
return { return {
id: result[0].id, id: result[0].id,
name: result[0].name, name: result[0].name,
genericName: result[0].genericName, genericName: result[0].genericName,
takenBy: parseTakenByJson(result[0].takenByJson), takenBy: parseTakenByJson(result[0].takenByJson),
packageType: result[0].packageType ?? "blister",
packCount: result[0].packCount, packCount: result[0].packCount,
blistersPerPack: result[0].blistersPerPack, blistersPerPack: result[0].blistersPerPack,
pillsPerBlister: result[0].pillsPerBlister, pillsPerBlister: result[0].pillsPerBlister,
totalPills: result[0].totalPills ?? null,
looseTablets: result[0].looseTablets, looseTablets: result[0].looseTablets,
stockAdjustment: result[0].stockAdjustment ?? 0, stockAdjustment: result[0].stockAdjustment ?? 0,
lastStockCorrectionAt: result[0].lastStockCorrectionAt?.toISOString() ?? null, lastStockCorrectionAt: result[0].lastStockCorrectionAt?.toISOString() ?? null,
pillWeightMg: result[0].pillWeightMg, pillWeightMg: result[0].pillWeightMg,
blisters, doseUnit: result[0].doseUnit ?? "mg",
intakes,
blisters: intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start })),
imageUrl: result[0].imageUrl, imageUrl: result[0].imageUrl,
expiryDate: result[0].expiryDate, expiryDate: result[0].expiryDate,
notes: result[0].notes, notes: result[0].notes,
@@ -253,14 +471,19 @@ export async function medicationRoutes(app: FastifyInstance) {
// Stock correction endpoint - only updates stockAdjustment, preserves looseTablets // Stock correction endpoint - only updates stockAdjustment, preserves looseTablets
// Also sets lastStockCorrectionAt so consumed doses before this point don't count // Also sets lastStockCorrectionAt so consumed doses before this point don't count
app.patch<{ Params: { id: string }; Body: { stockAdjustment: number } }>("/medications/:id/stock-adjustment", async (req, reply) => { app.patch<{ Params: { id: string }; Body: { stockAdjustment: number } }>(
"/medications/:id/stock-adjustment",
async (req, reply) => {
const idNum = Number(req.params.id); const idNum = Number(req.params.id);
if (Number.isNaN(idNum)) return reply.badRequest("Invalid id"); if (Number.isNaN(idNum)) return reply.badRequest("Invalid id");
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
// Verify ownership // Verify ownership
const [existing] = await db.select().from(medications).where(and(eq(medications.id, idNum), eq(medications.userId, userId))); const [existing] = await db
.select()
.from(medications)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound(); if (!existing) return reply.notFound();
const { stockAdjustment } = req.body as { stockAdjustment: number }; const { stockAdjustment } = req.body as { stockAdjustment: number };
@@ -284,7 +507,8 @@ export async function medicationRoutes(app: FastifyInstance) {
lastStockCorrectionAt: result[0].lastStockCorrectionAt?.toISOString() ?? null, lastStockCorrectionAt: result[0].lastStockCorrectionAt?.toISOString() ?? null,
updatedAt: result[0].updatedAt, updatedAt: result[0].updatedAt,
}; };
}); }
);
app.delete<{ Params: { id: string } }>("/medications/:id", async (req, reply) => { app.delete<{ Params: { id: string } }>("/medications/:id", async (req, reply) => {
const idNum = Number(req.params.id); const idNum = Number(req.params.id);
@@ -293,7 +517,10 @@ export async function medicationRoutes(app: FastifyInstance) {
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
// Delete associated image if exists (with ownership check) // Delete associated image if exists (with ownership check)
const [existing] = await db.select().from(medications).where(and(eq(medications.id, idNum), eq(medications.userId, userId))); const [existing] = await db
.select()
.from(medications)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound(); if (!existing) return reply.notFound();
if (existing.imageUrl) { if (existing.imageUrl) {
@@ -301,7 +528,10 @@ export async function medicationRoutes(app: FastifyInstance) {
if (existsSync(imagePath)) unlinkSync(imagePath); if (existsSync(imagePath)) unlinkSync(imagePath);
} }
const deleted = await db.delete(medications).where(and(eq(medications.id, idNum), eq(medications.userId, userId))).returning(); const deleted = await db
.delete(medications)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
.returning();
if (!deleted.length) return reply.notFound(); if (!deleted.length) return reply.notFound();
return reply.status(204).send(); return reply.status(204).send();
}); });
@@ -312,7 +542,10 @@ export async function medicationRoutes(app: FastifyInstance) {
if (Number.isNaN(idNum)) return reply.badRequest("Invalid id"); if (Number.isNaN(idNum)) return reply.badRequest("Invalid id");
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
const [existing] = await db.select().from(medications).where(and(eq(medications.id, idNum), eq(medications.userId, userId))); const [existing] = await db
.select()
.from(medications)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound(); if (!existing) return reply.notFound();
const data = await req.file(); const data = await req.file();
@@ -335,7 +568,10 @@ export async function medicationRoutes(app: FastifyInstance) {
if (existsSync(oldPath)) unlinkSync(oldPath); if (existsSync(oldPath)) unlinkSync(oldPath);
} }
await db.update(medications).set({ imageUrl: filename, updatedAt: new Date() }).where(and(eq(medications.id, idNum), eq(medications.userId, userId))); await db
.update(medications)
.set({ imageUrl: filename, updatedAt: new Date() })
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
return { success: true, imageUrl: filename }; return { success: true, imageUrl: filename };
}); });
@@ -346,7 +582,10 @@ export async function medicationRoutes(app: FastifyInstance) {
if (Number.isNaN(idNum)) return reply.badRequest("Invalid id"); if (Number.isNaN(idNum)) return reply.badRequest("Invalid id");
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
const [existing] = await db.select().from(medications).where(and(eq(medications.id, idNum), eq(medications.userId, userId))); const [existing] = await db
.select()
.from(medications)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound(); if (!existing) return reply.notFound();
if (existing.imageUrl) { if (existing.imageUrl) {
@@ -354,15 +593,22 @@ export async function medicationRoutes(app: FastifyInstance) {
if (existsSync(filepath)) unlinkSync(filepath); if (existsSync(filepath)) unlinkSync(filepath);
} }
await db.update(medications).set({ imageUrl: null, updatedAt: new Date() }).where(and(eq(medications.id, idNum), eq(medications.userId, userId))); await db
.update(medications)
.set({ imageUrl: null, updatedAt: new Date() })
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
return reply.status(204).send(); return reply.status(204).send();
}); });
app.post("/medications/usage", async (req, reply) => { app.post("/medications/usage", async (req, reply) => {
const schema = z.object({ startDate: z.string().datetime(), endDate: z.string().datetime() }); const schema = z.object({
startDate: z.string().datetime(),
endDate: z.string().datetime(),
includeUntilStart: z.boolean().optional().default(false),
});
const parsed = schema.safeParse(req.body); const parsed = schema.safeParse(req.body);
if (!parsed.success) return reply.status(400).send(parsed.error.format()); if (!parsed.success) return reply.status(400).send(parsed.error.format());
const { startDate, endDate } = parsed.data; const { startDate, endDate, includeUntilStart } = parsed.data;
const start = new Date(startDate); const start = new Date(startDate);
const end = new Date(endDate); const end = new Date(endDate);
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end <= start) { if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end <= start) {
@@ -371,66 +617,231 @@ export async function medicationRoutes(app: FastifyInstance) {
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id); const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id);
// Get all taken doses for this user to calculate actual consumption
const takenDoses = await db
.select()
.from(doseTracking)
.where(and(eq(doseTracking.userId, userId), eq(doseTracking.dismissed, false)));
// Create a map of medication ID to taken dose count
const takenDosesMap = new Map<number, { blisterIdx: number; usage: number }[]>();
takenDoses.forEach((dose) => {
const parts = dose.doseId.split("-");
if (parts.length >= 3) {
const medId = parseInt(parts[0], 10);
const blisterIdx = parseInt(parts[1], 10);
if (!Number.isNaN(medId) && !Number.isNaN(blisterIdx)) {
if (!takenDosesMap.has(medId)) {
takenDosesMap.set(medId, []);
}
takenDosesMap.get(medId)!.push({ blisterIdx, usage: 0 }); // usage filled later
}
}
});
// Use current time as the reference point for "available" stock
const now = new Date(); const now = new Date();
const payload = rows.map((row) => { const payload = rows.map((row) => {
const blisters = parseBlisters(row); // Parse intakes from new format, falling back to legacy
const usageTotal = calculateUsageInRange(blisters, start, end); const intakes = parseIntakesJson(
row.intakesJson,
{ usageJson: row.usageJson, everyJson: row.everyJson, startJson: row.startJson },
row.intakeRemindersEnabled ?? false
);
const blisters = intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start }));
const pillsPerBlister = row.pillsPerBlister ?? 1; const pillsPerBlister = row.pillsPerBlister ?? 1;
const packCount = row.packCount ?? 1; const packCount = row.packCount ?? 1;
const blistersPerPack = row.blistersPerPack ?? 1; const blistersPerPack = row.blistersPerPack ?? 1;
const looseTablets = row.looseTablets ?? 0; const looseTablets = row.looseTablets ?? 0;
const stockAdjustment = row.stockAdjustment ?? 0; const stockAdjustment = row.stockAdjustment ?? 0;
const originalTotalPills = packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment; const packageType = row.packageType ?? "blister";
// Calculate consumption up to now (same logic as frontend) // For bottle type, looseTablets IS the current stock (no blister math)
const originalTotalPills =
packageType === "bottle"
? looseTablets + stockAdjustment
: packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
// Calculate consumption based on ACTUAL taken doses from dose_tracking
// This ensures Planner shows the same "current stock" as the Dashboard/Modal
// Use the same logic as frontend: generate expected doses and check which are marked
const stockCorrectionCutoff = row.lastStockCorrectionAt ? new Date(row.lastStockCorrectionAt).getTime() : 0;
// Build a Set of taken dose IDs for quick lookup
const takenDoseIds = new Set(
takenDoses
.filter((dose) => {
const parts = dose.doseId.split("-");
return parts.length >= 3 && parseInt(parts[0], 10) === row.id;
})
.map((dose) => dose.doseId)
);
// Count consumed pills by generating expected doses and checking if they're taken
let consumedUntilNow = 0; let consumedUntilNow = 0;
blisters.forEach((blister) => {
const blisterStart = new Date(blister.start);
if (Number.isNaN(blisterStart.getTime()) || blisterStart > now) return;
const msPerDay = 86400000; const msPerDay = 86400000;
blisters.forEach((blister, blisterIdx) => {
const blisterStart = parseLocalDateTime(blister.start);
if (Number.isNaN(blisterStart.getTime())) return;
const period = Math.max(1, blister.every) * msPerDay; const period = Math.max(1, blister.every) * msPerDay;
const occurrences = Math.floor((now.getTime() - blisterStart.getTime()) / period) + 1;
consumedUntilNow += occurrences * blister.usage; // After a stock correction, start counting from the NEXT scheduled
// dose, because the user's pill count already reflects all
// consumption up to the correction time.
let effectiveStart: number;
if (stockCorrectionCutoff > 0 && stockCorrectionCutoff >= blisterStart.getTime()) {
effectiveStart = stockCorrectionCutoff + period;
} else {
effectiveStart = blisterStart.getTime();
}
if (effectiveStart > now.getTime()) return;
const occurrences = Math.floor((now.getTime() - effectiveStart) / period) + 1;
// Get the people for this intake (from intakes array or medication takenBy)
const takenByJson = row.takenByJson ? JSON.parse(row.takenByJson) : [];
const intake = intakes[blisterIdx];
const intakePerson = intake?.takenBy;
const peopleForThisIntake: (string | null)[] = intakePerson
? [intakePerson]
: takenByJson.length > 0
? takenByJson
: [null];
// Generate expected dose IDs and check if they're taken
for (let i = 0; i < occurrences; i++) {
const doseDate = new Date(effectiveStart + i * period);
const dateOnlyMs = new Date(doseDate.getFullYear(), doseDate.getMonth(), doseDate.getDate()).getTime();
const baseDoseId = `${row.id}-${blisterIdx}-${dateOnlyMs}`;
// Check if each person has taken this dose
for (const person of peopleForThisIntake) {
const doseId = person ? `${baseDoseId}-${person}` : baseDoseId;
if (takenDoseIds.has(doseId)) {
consumedUntilNow += blister.usage;
}
}
}
}); });
const currentPills = Math.max(0, originalTotalPills - consumedUntilNow); const currentStock = Math.max(0, originalTotalPills - consumedUntilNow);
// Calculate usage for the planning period
// When includeUntilStart is true, calculate from now to end (useful for trip planning)
// When false, calculate from max(now, start) to end (default behavior)
const effectivePlannerStart = includeUntilStart ? now : new Date(Math.max(now.getTime(), start.getTime()));
const usageTotal = calculateUsageInRange(blisters, effectivePlannerStart, end);
const blistersNeeded = pillsPerBlister > 0 ? Math.ceil(usageTotal / pillsPerBlister) : 0; const blistersNeeded = pillsPerBlister > 0 ? Math.ceil(usageTotal / pillsPerBlister) : 0;
// Calculate current stock using realistic consumption order (loose first, then blisters) // Calculate AVAILABLE = stock AFTER the planned period (currentStock - usageTotal)
const consumed = originalTotalPills - currentPills; const availableAfterPeriod = Math.max(0, currentStock - usageTotal);
const looseConsumed = Math.min(consumed, looseTablets);
const loosePillsRemaining = looseTablets - looseConsumed; let fullBlisters: number;
const blisterPillsConsumed = consumed - looseConsumed; let loosePills: number;
if (packageType === "bottle") {
// Bottle type: no blisters, everything is loose pills
fullBlisters = 0;
loosePills = availableAfterPeriod;
} else {
// Blister type: calculate stock breakdown
// Consumption order: loose pills first, then from blisters
const totalConsumedByEnd = originalTotalPills - availableAfterPeriod;
const looseConsumedByEnd = Math.min(totalConsumedByEnd, looseTablets);
const loosePillsRemaining = Math.max(0, looseTablets - looseConsumedByEnd);
const blisterPillsConsumed = totalConsumedByEnd - looseConsumedByEnd;
const originalBlisterPills = originalTotalPills - looseTablets; const originalBlisterPills = originalTotalPills - looseTablets;
const blisterPillsRemaining = Math.max(0, originalBlisterPills - blisterPillsConsumed); const blisterPillsRemaining = Math.max(0, originalBlisterPills - blisterPillsConsumed);
const fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0; fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0;
const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0; const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0;
const loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose
}
const enough = currentPills >= usageTotal; const enough = currentStock >= usageTotal;
return { return {
medicationId: row.id, medicationId: row.id,
medicationName: row.name, medicationName: row.name,
totalPills: currentPills, totalPills: currentStock,
plannerUsage: usageTotal, plannerUsage: usageTotal,
blisterSize: pillsPerBlister, blisterSize: pillsPerBlister,
blistersNeeded, blistersNeeded,
fullBlisters, fullBlisters,
loosePills, loosePills,
enough, enough,
packageType,
}; };
}); });
return payload; return payload;
}); });
// ---------------------------------------------------------------------------
// POST /medications/dismiss-until - Set dismissedUntil date for multiple medications
// This is more robust than storing individual dose IDs (which can change with schedule updates)
// ---------------------------------------------------------------------------
const dismissUntilSchema = z.object({
medicationIds: z.array(z.number().int().positive()).min(1),
until: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be in YYYY-MM-DD format"),
});
app.post<{ Body: z.infer<typeof dismissUntilSchema> }>("/medications/dismiss-until", async (req, reply) => {
const parsed = dismissUntilSchema.safeParse(req.body);
if (!parsed.success) {
return reply.status(400).send({ error: parsed.error.errors[0]?.message ?? "Invalid input" });
} }
function calculateUsageInRange(blisters: Array<{ usage: number; every: number; start: string }>, start: Date, end: Date) { const userId = await getUserId(req, reply);
const { medicationIds, until } = parsed.data;
// Update dismissedUntil for all specified medications owned by this user
let updatedCount = 0;
for (const medId of medicationIds) {
const result = await db
.update(medications)
.set({ dismissedUntil: until })
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
if (result.rowsAffected > 0) {
updatedCount++;
}
}
return { success: true, updatedCount };
});
// ---------------------------------------------------------------------------
// DELETE /medications/:id/dismiss-until - Clear dismissedUntil for a medication
// ---------------------------------------------------------------------------
app.delete<{ Params: { id: string } }>("/medications/:id/dismiss-until", async (req, reply) => {
const medId = parseInt(req.params.id, 10);
if (Number.isNaN(medId)) {
return reply.status(400).send({ error: "Invalid medication ID" });
}
const userId = await getUserId(req, reply);
await db
.update(medications)
.set({ dismissedUntil: null })
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
return { success: true };
});
}
function calculateUsageInRange(
blisters: Array<{ usage: number; every: number; start: string }>,
start: Date,
end: Date
) {
let total = 0; let total = 0;
blisters.forEach((blister) => { blisters.forEach((blister) => {
const blisterStart = new Date(blister.start); const blisterStart = parseLocalDateTime(blister.start);
if (Number.isNaN(blisterStart.getTime())) return; if (Number.isNaN(blisterStart.getTime())) return;
// iterate occurrences from blisterStart up to end // iterate occurrences from blisterStart up to end
for (let dt = new Date(blisterStart); dt < end; dt.setDate(dt.getDate() + blister.every)) { for (let dt = new Date(blisterStart); dt < end; dt.setDate(dt.getDate() + blister.every)) {
+29 -38
View File
@@ -1,9 +1,9 @@
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import { createHash, randomBytes } from "node:crypto";
import { eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply } from "fastify";
import * as client from "openid-client"; import * as client from "openid-client";
import { randomBytes, createHash } from "crypto";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { users, refreshTokens } from "../db/schema.js"; import { refreshTokens, users } from "../db/schema.js";
import { eq, sql } from "drizzle-orm";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
// ============================================================================= // =============================================================================
@@ -18,11 +18,7 @@ async function getOIDCConfig(): Promise<client.Configuration> {
throw new Error("OIDC not configured"); throw new Error("OIDC not configured");
} }
oidcConfig = await client.discovery( oidcConfig = await client.discovery(new URL(env.OIDC_ISSUER_URL), env.OIDC_CLIENT_ID, env.OIDC_CLIENT_SECRET);
new URL(env.OIDC_ISSUER_URL),
env.OIDC_CLIENT_ID,
env.OIDC_CLIENT_SECRET
);
return oidcConfig; return oidcConfig;
} }
@@ -55,10 +51,10 @@ function getFrontendUrl(): string {
export async function oidcRoutes(app: FastifyInstance) { export async function oidcRoutes(app: FastifyInstance) {
if (!env.OIDC_ENABLED) { if (!env.OIDC_ENABLED) {
// Register a disabled route that returns an error // Register a disabled route that returns an error
app.get("/auth/oidc/login", async (request, reply) => { app.get("/auth/oidc/login", async (_request, reply) => {
return reply.status(400).send({ error: "OIDC authentication is not enabled" }); return reply.status(400).send({ error: "OIDC authentication is not enabled" });
}); });
app.get("/auth/oidc/callback", async (request, reply) => { app.get("/auth/oidc/callback", async (_request, reply) => {
return reply.status(400).send({ error: "OIDC authentication is not enabled" }); return reply.status(400).send({ error: "OIDC authentication is not enabled" });
}); });
return; return;
@@ -67,7 +63,7 @@ export async function oidcRoutes(app: FastifyInstance) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// GET /auth/oidc/login - Initiates OIDC flow // GET /auth/oidc/login - Initiates OIDC flow
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.get("/auth/oidc/login", async (request, reply) => { app.get("/auth/oidc/login", async (_request, reply) => {
try { try {
const config = await getOIDCConfig(); const config = await getOIDCConfig();
@@ -148,13 +144,17 @@ export async function oidcRoutes(app: FastifyInstance) {
try { try {
const config = await getOIDCConfig(); const config = await getOIDCConfig();
const redirectUri = env.OIDC_REDIRECT_URI!; const _redirectUri = env.OIDC_REDIRECT_URI!;
// Exchange code for tokens // Exchange code for tokens
const tokens = await client.authorizationCodeGrant(config, new URL(request.url, `http://${request.headers.host}`), { const tokens = await client.authorizationCodeGrant(
config,
new URL(request.url, `http://${request.headers.host}`),
{
pkceCodeVerifier: storedVerifier.value, pkceCodeVerifier: storedVerifier.value,
expectedState: state, expectedState: state,
}); }
);
// Get user info // Get user info
const sub = tokens.claims()?.sub; const sub = tokens.claims()?.sub;
@@ -166,7 +166,8 @@ export async function oidcRoutes(app: FastifyInstance) {
// Extract username from configured claim // Extract username from configured claim
const usernameClaim = env.OIDC_USERNAME_CLAIM; const usernameClaim = env.OIDC_USERNAME_CLAIM;
let username = (userInfo as any)[usernameClaim] || userInfo.preferred_username || userInfo.email || userInfo.sub; const username =
(userInfo as any)[usernameClaim] || userInfo.preferred_username || userInfo.email || userInfo.sub;
const oidcSubject = userInfo.sub; const oidcSubject = userInfo.sub;
if (!username || !oidcSubject) { if (!username || !oidcSubject) {
@@ -179,16 +180,14 @@ export async function oidcRoutes(app: FastifyInstance) {
reply.clearCookie("oidc_state", { path: "/" }); reply.clearCookie("oidc_state", { path: "/" });
// Find or create user // Find or create user
let user = await findOrCreateOIDCUser(username, oidcSubject, reply); const user = await findOrCreateOIDCUser(username, oidcSubject, reply);
if (!user) { if (!user) {
return reply.redirect(`${getFrontendUrl()}/?error=oidc_user_creation_failed`); return reply.redirect(`${getFrontendUrl()}/?error=oidc_user_creation_failed`);
} }
// Update last login // Update last login
await db.update(users) await db.update(users).set({ lastLoginAt: new Date() }).where(eq(users.id, user.id));
.set({ lastLoginAt: new Date() })
.where(eq(users.id, user.id));
// Issue JWT tokens (same as local auth) // Issue JWT tokens (same as local auth)
const accessToken = await generateAccessToken(app, user.id, user.username); const accessToken = await generateAccessToken(app, user.id, user.username);
@@ -202,14 +201,15 @@ export async function oidcRoutes(app: FastifyInstance) {
}); });
// Set cookies (use app's centralized cookie options) // Set cookies (use app's centralized cookie options)
console.log(`[OIDC] Setting cookies for user ${user.username}, NODE_ENV=${env.NODE_ENV}, secure=${app.config.cookieOptions.secure}`); console.log(
`[OIDC] Setting cookies for user ${user.username}, NODE_ENV=${env.NODE_ENV}, secure=${app.config.cookieOptions.secure}`
);
setAuthCookies(app, reply, accessToken, refreshToken); setAuthCookies(app, reply, accessToken, refreshToken);
// Redirect to frontend dashboard // Redirect to frontend dashboard
// In dev: CORS_ORIGINS contains the frontend URL // In dev: CORS_ORIGINS contains the frontend URL
const frontendUrl = env.CORS_ORIGINS.split(",")[0] || "http://localhost:5173"; const frontendUrl = env.CORS_ORIGINS.split(",")[0] || "http://localhost:5173";
return reply.redirect(`${frontendUrl}/dashboard`); return reply.redirect(`${frontendUrl}/dashboard`);
} catch (err: any) { } catch (err: any) {
console.error("[OIDC] Callback error:", err); console.error("[OIDC] Callback error:", err);
return reply.redirect(`${getFrontendUrl()}/?error=oidc_callback_failed`); return reply.redirect(`${getFrontendUrl()}/?error=oidc_callback_failed`);
@@ -224,30 +224,23 @@ export async function oidcRoutes(app: FastifyInstance) {
async function findOrCreateOIDCUser( async function findOrCreateOIDCUser(
username: string, username: string,
oidcSubject: string, oidcSubject: string,
reply: FastifyReply _reply: FastifyReply
): Promise<{ id: number; username: string } | null> { ): Promise<{ id: number; username: string } | null> {
// First, try to find user by OIDC subject (most reliable) // First, try to find user by OIDC subject (most reliable)
const [existingBySubject] = await db.select() const [existingBySubject] = await db.select().from(users).where(eq(users.oidcSubject, oidcSubject));
.from(users)
.where(eq(users.oidcSubject, oidcSubject));
if (existingBySubject) { if (existingBySubject) {
return { id: existingBySubject.id, username: existingBySubject.username }; return { id: existingBySubject.id, username: existingBySubject.username };
} }
// Check if username already exists (potential collision) // Check if username already exists (potential collision)
const [existingByUsername] = await db.select() const [existingByUsername] = await db.select().from(users).where(eq(users.username, username));
.from(users)
.where(eq(users.username, username));
if (existingByUsername) { if (existingByUsername) {
// Username collision! Check if it's a local user without OIDC linked // Username collision! Check if it's a local user without OIDC linked
if (existingByUsername.authProvider === "local" && !existingByUsername.oidcSubject) { if (existingByUsername.authProvider === "local" && !existingByUsername.oidcSubject) {
// Local user exists without SSO - link this OIDC account to existing user // Local user exists without SSO - link this OIDC account to existing user
await db.update(users) await db.update(users).set({ oidcSubject: oidcSubject }).where(eq(users.id, existingByUsername.id));
.set({ oidcSubject: oidcSubject })
.where(eq(users.id, existingByUsername.id));
console.log(`[OIDC] Linked OIDC to existing local user: ${username}`); console.log(`[OIDC] Linked OIDC to existing local user: ${username}`);
return { id: existingByUsername.id, username: existingByUsername.username }; return { id: existingByUsername.id, username: existingByUsername.username };
} else if (existingByUsername.oidcSubject && existingByUsername.oidcSubject !== oidcSubject) { } else if (existingByUsername.oidcSubject && existingByUsername.oidcSubject !== oidcSubject) {
@@ -264,7 +257,8 @@ async function findOrCreateOIDCUser(
} }
// Create new OIDC user // Create new OIDC user
const [newUser] = await db.insert(users) const [newUser] = await db
.insert(users)
.values({ .values({
username, username,
passwordHash: null, passwordHash: null,
@@ -282,10 +276,7 @@ async function findOrCreateOIDCUser(
// JWT Token Generation (reused from auth.ts logic) // JWT Token Generation (reused from auth.ts logic)
// ============================================================================= // =============================================================================
async function generateAccessToken(app: FastifyInstance, userId: number, username: string): Promise<string> { async function generateAccessToken(app: FastifyInstance, userId: number, username: string): Promise<string> {
return app.jwt.sign( return app.jwt.sign({ sub: userId, username }, { expiresIn: `${env.ACCESS_TOKEN_TTL_MINUTES}m` });
{ sub: userId, username },
{ expiresIn: `${env.ACCESS_TOKEN_TTL_MINUTES}m` }
);
} }
async function generateRefreshToken( async function generateRefreshToken(
+62 -43
View File
@@ -1,22 +1,22 @@
import { FastifyInstance } from "fastify"; import type { FastifyInstance, FastifyRequest } from "fastify";
import nodemailer from "nodemailer"; import nodemailer from "nodemailer";
import { updateReminderSentTime, updateUserReminderSentTime } from "../services/reminder-scheduler.js"; import { getDateLocale, getTranslations, type Language, t } from "../i18n/translations.js";
import { loadUserSettings, sendShoutrrrNotification } from "./settings.js"; import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { getDateLocale, getTranslations, t, type Language } from "../i18n/translations.js";
import type { AuthUser } from "../types/fastify.js";
import { requireAuth, getAnonymousUserId } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import { updateReminderSentTime, updateUserReminderSentTime } from "../services/reminder-scheduler.js";
import type { AuthUser } from "../types/fastify.js";
import { loadUserSettings, sendShoutrrrNotification } from "./settings.js";
// Escape HTML to prevent XSS in email templates // Escape HTML to prevent XSS in email templates
function escapeHtml(text: string): string { function escapeHtml(text: string): string {
const htmlEscapes: Record<string, string> = { const htmlEscapes: Record<string, string> = {
'&': '&amp;', "&": "&amp;",
'<': '&lt;', "<": "&lt;",
'>': '&gt;', ">": "&gt;",
'"': '&quot;', '"': "&quot;",
"'": '&#39;', "'": "&#39;",
}; };
return text.replace(/[&<>"']/g, char => htmlEscapes[char] || char); return text.replace(/[&<>"']/g, (char) => htmlEscapes[char] || char);
} }
type PlannerRow = { type PlannerRow = {
@@ -57,11 +57,11 @@ export async function plannerRoutes(app: FastifyInstance) {
app.addHook("preHandler", requireAuth); app.addHook("preHandler", requireAuth);
// Helper to get user ID from request // Helper to get user ID from request
async function getUserId(request: any): Promise<number> { async function getUserId(request: FastifyRequest): Promise<number> {
if (!env.AUTH_ENABLED) { if (!env.AUTH_ENABLED) {
return getAnonymousUserId(); return getAnonymousUserId();
} }
const authUser = request.user as AuthUser | null; const authUser = request.user as unknown as AuthUser | null;
if (!authUser?.id) { if (!authUser?.id) {
throw new Error("User not authenticated"); throw new Error("User not authenticated");
} }
@@ -78,7 +78,7 @@ export async function plannerRoutes(app: FastifyInstance) {
const smtpHost = process.env.SMTP_HOST; const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER; const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence
const smtpPort = parseInt(process.env.SMTP_PORT ?? "587"); const smtpPort = parseInt(process.env.SMTP_PORT ?? "587", 10);
const smtpSecure = process.env.SMTP_SECURE === "true"; const smtpSecure = process.env.SMTP_SECURE === "true";
const smtpFrom = process.env.SMTP_FROM ?? smtpUser; const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
@@ -95,40 +95,50 @@ export async function plannerRoutes(app: FastifyInstance) {
} }
const locale = getDateLocale(language); const locale = getDateLocale(language);
// Format dates for display // Format dates for display - escape to prevent XSS even though toLocaleDateString should be safe
const fromDate = new Date(from).toLocaleDateString(locale, { const fromDate = escapeHtml(
new Date(from).toLocaleDateString(locale, {
year: "numeric", year: "numeric",
month: "long", month: "long",
day: "numeric", day: "numeric",
}); })
const untilDate = new Date(until).toLocaleDateString(locale, { );
const untilDate = escapeHtml(
new Date(until).toLocaleDateString(locale, {
year: "numeric", year: "numeric",
month: "long", month: "long",
day: "numeric", day: "numeric",
}); })
);
// Build HTML table with horizontal scroll for mobile // Build HTML table with horizontal scroll for mobile
// Escape/coerce all user-provided values to prevent XSS
const tableRows = rows const tableRows = rows
.map( .map((row) => {
(row) => ` const safeName = escapeHtml(row.medicationName);
const safeTotalPills = Number(row.totalPills) || 0;
const safePlannerUsage = Number(row.plannerUsage) || 0;
const safeBlistersNeeded = Number(row.blistersNeeded) || 0;
const safeBlisterSize = Number(row.blisterSize) || 0;
const safeFullBlisters = Number(row.fullBlisters) || 0;
const safeLoosePills = Number(row.loosePills) || 0;
return `
<tr> <tr>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; white-space: nowrap;">${escapeHtml(row.medicationName)}</td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; white-space: nowrap;">${safeName}</td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;"><strong>${row.totalPills}</strong></td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;"><strong>${safeTotalPills}</strong></td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;"><strong>${row.plannerUsage}</strong></td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;"><strong>${safePlannerUsage}</strong></td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${row.blistersNeeded} × ${row.blisterSize}</td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${safeBlistersNeeded} × ${safeBlisterSize}</td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${row.fullBlisters}${row.loosePills > 0 ? ` (+${row.loosePills})` : ""}</td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${safeFullBlisters}${safeLoosePills > 0 ? ` (+${safeLoosePills})` : ""}</td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;"> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">
<span style="display: inline-block; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600; ${ <span style="display: inline-block; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600; ${
row.enough row.enough ? "background: #d1fae5; color: #065f46;" : "background: #fee2e2; color: #991b1b;"
? "background: #d1fae5; color: #065f46;"
: "background: #fee2e2; color: #991b1b;"
}"> }">
${row.enough ? "✓ OK" : "✗ Out of Stock"} ${row.enough ? "✓ OK" : "✗ Out of Stock"}
</span> </span>
</td> </td>
</tr> </tr>
` `;
) })
.join(""); .join("");
const outOfStockCount = rows.filter((r) => !r.enough).length; const outOfStockCount = rows.filter((r) => !r.enough).length;
@@ -215,7 +225,7 @@ Sent from MedAssist-ng Medication Planner`;
// Reminder notification for low stock medications (supports email and push) // Reminder notification for low stock medications (supports email and push)
app.post<{ Body: ReminderEmailBody }>("/reminder/send-email", async (request, reply) => { app.post<{ Body: ReminderEmailBody }>("/reminder/send-email", async (request, reply) => {
const { email, lowStock, language: bodyLanguage } = request.body; const { email, lowStock } = request.body;
if (!lowStock || lowStock.length === 0) { if (!lowStock || lowStock.length === 0) {
return reply.status(400).send({ error: "Missing low stock data" }); return reply.status(400).send({ error: "Missing low stock data" });
@@ -233,15 +243,15 @@ Sent from MedAssist-ng Medication Planner`;
const results: { email?: boolean; push?: boolean; errors: string[] } = { errors: [] }; const results: { email?: boolean; push?: boolean; errors: string[] } = { errors: [] };
// Separate empty from low stock medications // Separate empty from low stock medications
const emptyMeds = lowStock.filter(r => r.medsLeft <= 0); const emptyMeds = lowStock.filter((r) => r.medsLeft <= 0);
const lowMeds = lowStock.filter(r => r.medsLeft > 0); const lowMeds = lowStock.filter((r) => r.medsLeft > 0);
// Send email if enabled // Send email if enabled
if (notificationSettings.emailEnabled && email) { if (notificationSettings.emailEnabled && email) {
const smtpHost = process.env.SMTP_HOST; const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER; const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence
const smtpPort = parseInt(process.env.SMTP_PORT ?? "587"); const smtpPort = parseInt(process.env.SMTP_PORT ?? "587", 10);
const smtpSecure = process.env.SMTP_SECURE === "true"; const smtpSecure = process.env.SMTP_SECURE === "true";
const smtpFrom = process.env.SMTP_FROM ?? smtpUser; const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
@@ -291,12 +301,17 @@ Sent from MedAssist-ng Medication Planner`;
const isEmpty = row.medsLeft <= 0; const isEmpty = row.medsLeft <= 0;
const statusIcon = isEmpty ? "🚨" : "⚠️"; const statusIcon = isEmpty ? "🚨" : "⚠️";
const rowBg = isEmpty ? "#fef2f2" : "white"; const rowBg = isEmpty ? "#fef2f2" : "white";
// Escape user-provided strings and coerce numbers to prevent XSS
const safeName = escapeHtml(row.name);
const safeMedsLeft = Number(row.medsLeft) || 0;
const safeDaysLeft = Number(row.daysLeft) || 0;
const safeDepletionDate = row.depletionDate ? escapeHtml(String(row.depletionDate)) : "-";
return ` return `
<tr style="background: ${rowBg};"> <tr style="background: ${rowBg};">
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; white-space: nowrap;">${statusIcon} ${escapeHtml(row.name)}</td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; white-space: nowrap;">${statusIcon} ${safeName}</td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap; ${isEmpty ? "color: #dc2626; font-weight: 600;" : ""}"><strong>${row.medsLeft}</strong></td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap; ${isEmpty ? "color: #dc2626; font-weight: 600;" : ""}"><strong>${safeMedsLeft}</strong></td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${row.daysLeft ?? 0}</td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${safeDaysLeft}</td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${isEmpty ? "<strong>NOW</strong>" : (row.depletionDate ?? "-")}</td> <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${isEmpty ? "<strong>NOW</strong>" : safeDepletionDate}</td>
</tr>`; </tr>`;
}; };
@@ -411,12 +426,16 @@ Sent from MedAssist-ng Medication Planner`;
const messageParts: string[] = []; const messageParts: string[] = [];
if (emptyMeds.length > 0) { if (emptyMeds.length > 0) {
messageParts.push(`🚨 ${tr.push.emptySection}:`); messageParts.push(`🚨 ${tr.push.emptySection}:`);
emptyMeds.forEach(r => messageParts.push(`${r.name}`)); emptyMeds.forEach((r) => messageParts.push(`${r.name}`));
} }
if (lowMeds.length > 0) { if (lowMeds.length > 0) {
if (emptyMeds.length > 0) messageParts.push(""); if (emptyMeds.length > 0) messageParts.push("");
messageParts.push(`⚠️ ${tr.push.lowSection}:`); messageParts.push(`⚠️ ${tr.push.lowSection}:`);
lowMeds.forEach(r => messageParts.push(`${r.name}: ${t(tr.push.pillsLeft, { count: r.medsLeft })}, ${t(tr.push.daysLeft, { count: r.daysLeft ?? 0 })}`)); lowMeds.forEach((r) =>
messageParts.push(
`${r.name}: ${t(tr.push.pillsLeft, { count: r.medsLeft })}, ${t(tr.push.daysLeft, { count: r.daysLeft ?? 0 })}`
)
);
} }
const message = messageParts.join("\n"); const message = messageParts.join("\n");
@@ -450,7 +469,7 @@ Sent from MedAssist-ng Medication Planner`;
if (sentChannels.length > 0) { if (sentChannels.length > 0) {
return reply.send({ return reply.send({
success: true, success: true,
message: `Reminder sent via ${sentChannels.join(" and ")}` message: `Reminder sent via ${sentChannels.join(" and ")}`,
}); });
} else if (results.errors.length > 0) { } else if (results.errors.length > 0) {
return reply.status(500).send({ error: results.errors.join("; ") }); return reply.status(500).send({ error: results.errors.join("; ") });
+36 -22
View File
@@ -1,16 +1,18 @@
import { FastifyInstance } from "fastify"; import { and, desc, eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { medications, refillHistory } from "../db/schema.js"; import { medications, refillHistory } from "../db/schema.js";
import { eq, and, desc } from "drizzle-orm"; import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { requireAuth, getAnonymousUserId } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
const refillSchema = z.object({ const refillSchema = z
.object({
packsAdded: z.number().int().min(0).default(0), packsAdded: z.number().int().min(0).default(0),
loosePillsAdded: z.number().int().min(0).default(0), loosePillsAdded: z.number().int().min(0).default(0),
}).refine(data => data.packsAdded > 0 || data.loosePillsAdded > 0, { })
.refine((data) => data.packsAdded > 0 || data.loosePillsAdded > 0, {
message: "Must add at least one pack or some loose pills", message: "Must add at least one pack or some loose pills",
}); });
@@ -19,7 +21,7 @@ export async function refillRoutes(app: FastifyInstance) {
app.addHook("preHandler", requireAuth); app.addHook("preHandler", requireAuth);
// Helper to get user ID from request // Helper to get user ID from request
async function getUserId(request: any, reply: any): Promise<number> { async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
if (!env.AUTH_ENABLED) { if (!env.AUTH_ENABLED) {
return getAnonymousUserId(); return getAnonymousUserId();
} }
@@ -42,9 +44,10 @@ export async function refillRoutes(app: FastifyInstance) {
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
// Verify ownership // Verify ownership
const [med] = await db.select().from(medications).where( const [med] = await db
and(eq(medications.id, medId), eq(medications.userId, userId)) .select()
); .from(medications)
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
if (!med) return reply.notFound("Medication not found"); if (!med) return reply.notFound("Medication not found");
const { packsAdded, loosePillsAdded } = parsed.data; const { packsAdded, loosePillsAdded } = parsed.data;
@@ -53,16 +56,20 @@ export async function refillRoutes(app: FastifyInstance) {
const newPackCount = med.packCount + packsAdded; const newPackCount = med.packCount + packsAdded;
const newLooseTablets = med.looseTablets + loosePillsAdded; const newLooseTablets = med.looseTablets + loosePillsAdded;
await db.update(medications) await db
.update(medications)
.set({ .set({
packCount: newPackCount, packCount: newPackCount,
looseTablets: newLooseTablets, looseTablets: newLooseTablets,
stockAdjustment: 0, // Reset offset since we're adding to base stock
lastStockCorrectionAt: new Date(), // Reset consumed counter to now
updatedAt: new Date(), updatedAt: new Date(),
}) })
.where(and(eq(medications.id, medId), eq(medications.userId, userId))); .where(and(eq(medications.id, medId), eq(medications.userId, userId)));
// Create refill history entry // Create refill history entry
const [refill] = await db.insert(refillHistory) const [refill] = await db
.insert(refillHistory)
.values({ .values({
medicationId: medId, medicationId: medId,
userId, userId,
@@ -71,9 +78,13 @@ export async function refillRoutes(app: FastifyInstance) {
}) })
.returning(); .returning();
// Calculate pills added for response // Calculate pills added for response (packageType-aware)
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister; const isBottle = (med.packageType ?? "blister") === "bottle";
const totalPillsAdded = (packsAdded * pillsPerPack) + loosePillsAdded; const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
const totalPillsAdded = isBottle ? loosePillsAdded : packsAdded * pillsPerPack + loosePillsAdded;
const newTotalPills = isBottle
? newLooseTablets + (med.stockAdjustment ?? 0)
: newPackCount * pillsPerPack + newLooseTablets + (med.stockAdjustment ?? 0);
return { return {
success: true, success: true,
@@ -87,7 +98,7 @@ export async function refillRoutes(app: FastifyInstance) {
newStock: { newStock: {
packCount: newPackCount, packCount: newPackCount,
looseTablets: newLooseTablets, looseTablets: newLooseTablets,
totalPills: newPackCount * pillsPerPack + newLooseTablets, totalPills: newTotalPills,
}, },
}; };
}); });
@@ -100,24 +111,27 @@ export async function refillRoutes(app: FastifyInstance) {
const userId = await getUserId(req, reply); const userId = await getUserId(req, reply);
// Verify ownership // Verify ownership
const [med] = await db.select().from(medications).where( const [med] = await db
and(eq(medications.id, medId), eq(medications.userId, userId)) .select()
); .from(medications)
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
if (!med) return reply.notFound("Medication not found"); if (!med) return reply.notFound("Medication not found");
// Get refill history, newest first // Get refill history, newest first
const refills = await db.select() const refills = await db
.select()
.from(refillHistory) .from(refillHistory)
.where(eq(refillHistory.medicationId, medId)) .where(eq(refillHistory.medicationId, medId))
.orderBy(desc(refillHistory.refillDate)); .orderBy(desc(refillHistory.refillDate));
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister; const isBottle = (med.packageType ?? "blister") === "bottle";
const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
return refills.map(r => ({ return refills.map((r) => ({
id: r.id, id: r.id,
packsAdded: r.packsAdded, packsAdded: r.packsAdded,
loosePillsAdded: r.loosePillsAdded, loosePillsAdded: r.loosePillsAdded,
totalPillsAdded: (r.packsAdded * pillsPerPack) + r.loosePillsAdded, totalPillsAdded: isBottle ? r.loosePillsAdded : r.packsAdded * pillsPerPack + r.loosePillsAdded,
refillDate: r.refillDate, refillDate: r.refillDate,
})); }));
}); });
+128 -51
View File
@@ -1,12 +1,12 @@
import { FastifyInstance } from "fastify"; import { eq } from "drizzle-orm";
import type { FastifyInstance } from "fastify";
import nodemailer from "nodemailer"; import nodemailer from "nodemailer";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { userSettings } from "../db/schema.js"; import { userSettings } from "../db/schema.js";
import { eq } from "drizzle-orm"; import type { Language } from "../i18n/translations.js";
import { requireAuth, getAnonymousUserId } from "../plugins/auth.js"; import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
import type { Language } from "../i18n/translations.js";
// Exported type for use in schedulers // Exported type for use in schedulers
export type UserSettings = { export type UserSettings = {
@@ -33,6 +33,8 @@ export type UserSettings = {
lastAutoEmailSent: string | null; lastAutoEmailSent: string | null;
lastNotificationType: string | null; lastNotificationType: string | null;
lastNotificationChannel: string | null; lastNotificationChannel: string | null;
lastReminderMedName: string | null;
lastReminderTakenBy: string | null;
}; };
type SettingsBody = { type SettingsBody = {
@@ -77,7 +79,7 @@ function envInt(key: string, defaultVal: number): number {
const val = process.env[key]; const val = process.env[key];
if (val === undefined) return defaultVal; if (val === undefined) return defaultVal;
const parsed = parseInt(val, 10); const parsed = parseInt(val, 10);
return isNaN(parsed) ? defaultVal : parsed; return Number.isNaN(parsed) ? defaultVal : parsed;
} }
// Default settings for new users - read from ENV with fallbacks // Default settings for new users - read from ENV with fallbacks
@@ -105,6 +107,8 @@ function getDefaultSettings() {
lastAutoEmailSent: null, lastAutoEmailSent: null,
lastNotificationType: null, lastNotificationType: null,
lastNotificationChannel: null, lastNotificationChannel: null,
lastReminderMedName: null,
lastReminderTakenBy: null,
}; };
} }
@@ -114,10 +118,13 @@ async function getOrCreateUserSettings(userId: number) {
if (!settings) { if (!settings) {
// Create default settings for user (using ENV defaults) // Create default settings for user (using ENV defaults)
[settings] = await db.insert(userSettings).values({ [settings] = await db
.insert(userSettings)
.values({
userId, userId,
...getDefaultSettings(), ...getDefaultSettings(),
}).returning(); })
.returning();
} }
return settings; return settings;
@@ -150,13 +157,15 @@ export async function loadUserSettings(userId: number): Promise<UserSettings> {
lastAutoEmailSent: settings.lastAutoEmailSent, lastAutoEmailSent: settings.lastAutoEmailSent,
lastNotificationType: settings.lastNotificationType, lastNotificationType: settings.lastNotificationType,
lastNotificationChannel: settings.lastNotificationChannel, lastNotificationChannel: settings.lastNotificationChannel,
lastReminderMedName: settings.lastReminderMedName ?? null,
lastReminderTakenBy: settings.lastReminderTakenBy ?? null,
}; };
} }
// Get all users with settings for scheduler // Get all users with settings for scheduler
export async function getAllUserSettings(): Promise<UserSettings[]> { export async function getAllUserSettings(): Promise<UserSettings[]> {
const allSettings = await db.select().from(userSettings); const allSettings = await db.select().from(userSettings);
return allSettings.map(settings => ({ return allSettings.map((settings) => ({
userId: settings.userId, userId: settings.userId,
emailEnabled: settings.emailEnabled, emailEnabled: settings.emailEnabled,
notificationEmail: settings.notificationEmail, notificationEmail: settings.notificationEmail,
@@ -180,6 +189,8 @@ export async function getAllUserSettings(): Promise<UserSettings[]> {
lastAutoEmailSent: settings.lastAutoEmailSent, lastAutoEmailSent: settings.lastAutoEmailSent,
lastNotificationType: settings.lastNotificationType, lastNotificationType: settings.lastNotificationType,
lastNotificationChannel: settings.lastNotificationChannel, lastNotificationChannel: settings.lastNotificationChannel,
lastReminderMedName: settings.lastReminderMedName ?? null,
lastReminderTakenBy: settings.lastReminderTakenBy ?? null,
})); }));
} }
@@ -232,7 +243,7 @@ export async function settingsRoutes(app: FastifyInstance) {
stockCalculationMode: settings.stockCalculationMode ?? "automatic", stockCalculationMode: settings.stockCalculationMode ?? "automatic",
// SMTP settings (from .env - shared/server-configured) // SMTP settings (from .env - shared/server-configured)
smtpHost: process.env.SMTP_HOST ?? "", smtpHost: process.env.SMTP_HOST ?? "",
smtpPort: parseInt(process.env.SMTP_PORT ?? "587"), smtpPort: parseInt(process.env.SMTP_PORT ?? "587", 10),
smtpUser: process.env.SMTP_USER ?? "", smtpUser: process.env.SMTP_USER ?? "",
smtpFrom: process.env.SMTP_FROM ?? "", smtpFrom: process.env.SMTP_FROM ?? "",
smtpSecure: process.env.SMTP_SECURE === "true", smtpSecure: process.env.SMTP_SECURE === "true",
@@ -241,6 +252,8 @@ export async function settingsRoutes(app: FastifyInstance) {
lastAutoEmailSent: settings.lastAutoEmailSent, lastAutoEmailSent: settings.lastAutoEmailSent,
lastNotificationType: settings.lastNotificationType, lastNotificationType: settings.lastNotificationType,
lastNotificationChannel: settings.lastNotificationChannel, lastNotificationChannel: settings.lastNotificationChannel,
lastReminderMedName: settings.lastReminderMedName ?? null,
lastReminderTakenBy: settings.lastReminderTakenBy ?? null,
// Server settings (from .env, read-only) // Server settings (from .env, read-only)
expiryWarningDays: parseInt(process.env.EXPIRY_WARNING_DAYS ?? "30", 10), expiryWarningDays: parseInt(process.env.EXPIRY_WARNING_DAYS ?? "30", 10),
}); });
@@ -287,9 +300,7 @@ export async function settingsRoutes(app: FastifyInstance) {
}; };
if (existingSettings.length > 0) { if (existingSettings.length > 0) {
await db.update(userSettings) await db.update(userSettings).set(settingsData).where(eq(userSettings.userId, userId));
.set(settingsData)
.where(eq(userSettings.userId, userId));
} else { } else {
await db.insert(userSettings).values({ await db.insert(userSettings).values({
userId: userId, userId: userId,
@@ -307,7 +318,7 @@ export async function settingsRoutes(app: FastifyInstance) {
const smtpHost = process.env.SMTP_HOST; const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER; const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS;
const smtpPort = parseInt(process.env.SMTP_PORT ?? "587"); const smtpPort = parseInt(process.env.SMTP_PORT ?? "587", 10);
const smtpSecure = process.env.SMTP_SECURE === "true"; const smtpSecure = process.env.SMTP_SECURE === "true";
const smtpFrom = process.env.SMTP_FROM ?? smtpUser; const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
@@ -358,7 +369,11 @@ export async function settingsRoutes(app: FastifyInstance) {
} }
try { try {
const result = await sendShoutrrrNotification(url, "MedAssist-ng Test", "This is a test notification from MedAssist-ng. If you received this, your notification configuration is working correctly!"); const result = await sendShoutrrrNotification(
url,
"MedAssist-ng Test",
"This is a test notification from MedAssist-ng. If you received this, your notification configuration is working correctly!"
);
if (result.success) { if (result.success) {
return reply.send({ success: true, message: "Test notification sent successfully" }); return reply.send({ success: true, message: "Test notification sent successfully" });
@@ -372,27 +387,29 @@ export async function settingsRoutes(app: FastifyInstance) {
}); });
} }
// Validate URL to prevent SSRF attacks // Validate and sanitize URL to prevent SSRF attacks
function isAllowedNotificationUrl(urlStr: string): { allowed: boolean; error?: string } { // Returns a reconstructed URL from validated components to break taint tracking
function sanitizeNotificationUrl(
urlStr: string
): { url: string; isNtfy: boolean; auth?: { user: string; pass: string } } | { error: string } {
try { try {
// Convert ntfy:// to https:// for parsing // Convert ntfy:// to https:// for parsing, track if it was ntfy
const normalizedUrl = urlStr.startsWith("ntfy://") const isNtfy = urlStr.startsWith("ntfy://");
? urlStr.replace("ntfy://", "https://") const normalizedUrl = isNtfy ? urlStr.replace("ntfy://", "https://") : urlStr;
: urlStr;
const parsed = new URL(normalizedUrl); const parsed = new URL(normalizedUrl);
// Only allow http and https protocols // Only allow http and https protocols
if (!['http:', 'https:'].includes(parsed.protocol)) { if (!["http:", "https:"].includes(parsed.protocol)) {
return { allowed: false, error: "Only HTTP/HTTPS protocols are allowed" }; return { error: "Only HTTP/HTTPS protocols are allowed" };
} }
// Block private/internal IP addresses // Block private/internal IP addresses
const hostname = parsed.hostname.toLowerCase(); const hostname = parsed.hostname.toLowerCase();
// Block localhost // Block localhost
if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1') { if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") {
return { allowed: false, error: "Localhost URLs are not allowed" }; return { error: "Localhost URLs are not allowed" };
} }
// Block private IP ranges (basic check) // Block private IP ranges (basic check)
@@ -400,66 +417,127 @@ function isAllowedNotificationUrl(urlStr: string): { allowed: boolean; error?: s
if (ipMatch) { if (ipMatch) {
const [, a, b] = ipMatch.map(Number); const [, a, b] = ipMatch.map(Number);
// 10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x (link-local) // 10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x (link-local)
if (a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || if (
(a === 192 && b === 168) || (a === 169 && b === 254)) { a === 10 ||
return { allowed: false, error: "Private IP addresses are not allowed" }; a === 127 ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 169 && b === 254)
) {
return { error: "Private IP addresses are not allowed" };
} }
} }
// Block common internal hostnames // Block common internal hostnames
if (hostname.endsWith('.local') || hostname.endsWith('.internal') || if (
hostname.endsWith('.lan') || hostname === 'metadata.google.internal') { hostname.endsWith(".local") ||
return { allowed: false, error: "Internal hostnames are not allowed" }; hostname.endsWith(".internal") ||
hostname.endsWith(".lan") ||
hostname === "metadata.google.internal"
) {
return { error: "Internal hostnames are not allowed" };
} }
return { allowed: true }; // Reconstruct URL from validated components - this breaks taint tracking
// because we're building a new string from validated parts, not passing through user input
const reconstructedUrl = `${parsed.protocol}//${parsed.host}${parsed.pathname}${parsed.search}`;
// Extract auth credentials separately for ntfy (they're in the URL but not in host)
const auth =
isNtfy && parsed.username && parsed.password ? { user: parsed.username, pass: parsed.password } : undefined;
return { url: reconstructedUrl, isNtfy, auth };
} catch { } catch {
return { allowed: false, error: "Invalid URL format" }; return { error: "Invalid URL format" };
} }
} }
// Send notification via Shoutrrr-compatible URL (supports ntfy, Discord, Telegram, etc.) // Send notification via Shoutrrr-compatible URL (supports ntfy, Discord, Telegram, etc.)
export async function sendShoutrrrNotification(urlStr: string, title: string, message: string): Promise<{ success: boolean; error?: string }> { export async function sendShoutrrrNotification(
urlStr: string,
title: string,
message: string
): Promise<{ success: boolean; error?: string }> {
try { try {
// Validate URL to prevent SSRF // Validate and sanitize URL to prevent SSRF - this reconstructs the URL
const validation = isAllowedNotificationUrl(urlStr); // from validated components, breaking taint tracking
if (!validation.allowed) { const validation = sanitizeNotificationUrl(urlStr);
if ("error" in validation) {
return { success: false, error: validation.error }; return { success: false, error: validation.error };
} }
// Use ONLY the reconstructed URL from validation - never the original urlStr
const { url: sanitizedUrl, isNtfy, auth } = validation;
let targetUrl: string; let targetUrl: string;
let method = "POST"; const method = "POST";
let headers: Record<string, string> = {}; let headers: Record<string, string> = {};
let body: string | undefined; let body: string | undefined;
// Remove emojis from title for header compatibility // Remove emojis from title for header compatibility
const cleanTitle = title.replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{2000}-\u{206F}]||/gu, "").trim(); const cleanTitle = title
.replace(
/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{2000}-\u{206F}]||/gu,
""
)
.trim();
if (urlStr.startsWith("ntfy://")) { // Determine notification type based on URL hostname
const parsed = new URL(urlStr.replace("ntfy://", "https://")); // Use JSON format only for known webhook services that require it
targetUrl = `https://${parsed.host}${parsed.pathname}`; // Use proper URL parsing to prevent bypass attacks (e.g., evil.com?hooks.slack.com)
headers = { "Title": cleanTitle, "Tags": "pill" }; let isJsonWebhook = false;
body = message; try {
const parsedUrl = new URL(sanitizedUrl);
const hostname = parsedUrl.hostname.toLowerCase();
const pathname = parsedUrl.pathname.toLowerCase();
if (parsed.username && parsed.password) { isJsonWebhook =
headers["Authorization"] = "Basic " + Buffer.from(`${parsed.username}:${parsed.password}`).toString("base64"); // Discord webhooks
((hostname === "discord.com" || hostname === "discordapp.com") && pathname.startsWith("/api/webhooks")) ||
// Slack webhooks
hostname === "hooks.slack.com" ||
hostname.endsWith(".hooks.slack.com") ||
// Telegram API
hostname === "api.telegram.org" ||
// Gotify (can be self-hosted, so check if "gotify" is in hostname)
hostname.includes("gotify");
} catch {
// If URL parsing fails, default to ntfy-style
isJsonWebhook = false;
} }
} else if (urlStr.startsWith("https://ntfy.") || urlStr.includes("ntfy.sh") || urlStr.includes("/ntfy/")) {
targetUrl = urlStr; // Default to ntfy-style (plain text with Title header) for all other HTTP URLs
headers = { "Title": cleanTitle, "Tags": "pill" }; // This works for ntfy, Apprise, and most simple push services
if (!isJsonWebhook) {
targetUrl = sanitizedUrl;
headers = { Title: cleanTitle, Tags: "pill" };
body = message; body = message;
} else if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
targetUrl = urlStr; // Add auth if present (extracted during sanitization)
if (auth) {
headers.Authorization = `Basic ${Buffer.from(`${auth.user}:${auth.pass}`).toString("base64")}`;
}
} else if (sanitizedUrl.startsWith("http://") || sanitizedUrl.startsWith("https://")) {
targetUrl = sanitizedUrl;
headers = { "Content-Type": "application/json" }; headers = { "Content-Type": "application/json" };
body = JSON.stringify({ title, message, text: `${title}\n\n${message}` }); body = JSON.stringify({ title, message, text: `${title}\n\n${message}` });
} else { } else {
return { success: false, error: "Unsupported URL format. Use ntfy:// or https:// URL" }; return { success: false, error: "Unsupported URL format. Use ntfy:// or https:// URL" };
} }
// SSRF protection: targetUrl is reconstructed from sanitizeNotificationUrl() which validates:
// - Only http/https protocols allowed
// - Blocks localhost (localhost, 127.0.0.1, ::1)
// - Blocks private IPs (10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x)
// - Blocks internal hostnames (.local, .internal, .lan, metadata.google.internal)
// - redirect: "error" prevents redirect-based bypass attacks
// This is an intentional feature: users configure their own external notification services
// lgtm [js/request-forgery]
const response = await fetch(targetUrl, { const response = await fetch(targetUrl, {
method, method,
headers, headers,
body, body,
redirect: "error", // Don't follow redirects that could bypass validation
}); });
if (response.ok) { if (response.ok) {
@@ -473,4 +551,3 @@ export async function sendShoutrrrNotification(urlStr: string, title: string, me
return { success: false, error: errorMessage }; return { success: false, error: errorMessage };
} }
} }
+68 -45
View File
@@ -1,12 +1,18 @@
import { FastifyInstance } from "fastify"; import { randomBytes } from "node:crypto";
import { eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod"; import { z } from "zod";
import { randomBytes } from "crypto";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { medications, shareTokens, userSettings, users } from "../db/schema.js"; import { medications, shareTokens, userSettings, users } from "../db/schema.js";
import { eq, and, sql } from "drizzle-orm"; import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { requireAuth, optionalAuth, getAnonymousUserId } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
import {
getAllTakenByForMedication,
parseIntakesJson,
parseTakenByJson,
personTakesMedication,
} from "../utils/scheduler-utils.js";
// Share token validity: 1 year in milliseconds // Share token validity: 1 year in milliseconds
const SHARE_TOKEN_VALIDITY_MS = 365 * 24 * 60 * 60 * 1000; const SHARE_TOKEN_VALIDITY_MS = 365 * 24 * 60 * 60 * 1000;
@@ -21,7 +27,7 @@ const createShareSchema = z.object({
// Helper to get user ID from request // Helper to get user ID from request
// Returns anonymous user ID when auth is disabled // Returns anonymous user ID when auth is disabled
async function getUserId(request: any, reply: any): Promise<number> { async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
// If auth is disabled, use the anonymous user // If auth is disabled, use the anonymous user
if (!env.AUTH_ENABLED) { if (!env.AUTH_ENABLED) {
return getAnonymousUserId(); return getAnonymousUserId();
@@ -35,17 +41,6 @@ async function getUserId(request: any, reply: any): Promise<number> {
return authUser.id; return authUser.id;
} }
// Helper to parse takenByJson
function parseTakenByJson(takenByJson: string | null | undefined): string[] {
if (!takenByJson) return [];
try {
const parsed = JSON.parse(takenByJson);
return Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string" && s.trim()) : [];
} catch {
return [];
}
}
// ============================================================================= // =============================================================================
// Share Routes // Share Routes
// ============================================================================= // =============================================================================
@@ -61,7 +56,7 @@ export async function shareRoutes(app: FastifyInstance) {
if (!share) { if (!share) {
return reply.status(404).send({ return reply.status(404).send({
error: "Share link not found", error: "Share link not found",
code: "NOT_FOUND" code: "NOT_FOUND",
}); });
} }
@@ -88,45 +83,58 @@ export async function shareRoutes(app: FastifyInstance) {
// Use SQLite JSON function to check if takenBy is in the array // Use SQLite JSON function to check if takenBy is in the array
const allMeds = await db.select().from(medications).where(eq(medications.userId, share.userId)); const allMeds = await db.select().from(medications).where(eq(medications.userId, share.userId));
// Filter medications where takenByJson array contains the share.takenBy value // Filter medications where takenBy matches either medication-level OR any intake-level takenBy
const meds = allMeds.filter((med) => { const meds = allMeds.filter((med) => {
const takenByArray = parseTakenByJson(med.takenByJson); const takenByArray = parseTakenByJson(med.takenByJson);
return takenByArray.includes(share.takenBy); const intakes = parseIntakesJson(
med.intakesJson,
{ usageJson: med.usageJson, everyJson: med.everyJson, startJson: med.startJson },
med.intakeRemindersEnabled ?? false
);
return personTakesMedication(share.takenBy, takenByArray, intakes);
}); });
// Parse blisters and build schedule data // Parse blisters and build schedule data
const medicationsWithBlisters = meds.map((med) => { const medicationsWithBlisters = meds.map((med) => {
let blisters: { usage: number; every: number; start: string }[] = []; // Parse intakes from new format, falling back to legacy
try { const intakes = parseIntakesJson(
const usageArr = JSON.parse(med.usageJson || "[]"); med.intakesJson,
const everyArr = JSON.parse(med.everyJson || "[]"); { usageJson: med.usageJson, everyJson: med.everyJson, startJson: med.startJson },
const startArr = JSON.parse(med.startJson || "[]"); med.intakeRemindersEnabled ?? false
blisters = usageArr.map((usage: number, i: number) => ({ );
usage,
every: everyArr[i] ?? 1, // Convert to legacy blisters format for backward compat
start: startArr[i] ?? new Date().toISOString(), const blisters = intakes.map((i) => ({
usage: i.usage,
every: i.every,
start: i.start,
})); }));
} catch {
blisters = [];
}
// Parse takenBy JSON array // Parse takenBy JSON array
const takenByArray = parseTakenByJson(med.takenByJson); const takenByArray = parseTakenByJson(med.takenByJson);
const totalPills = med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0); const totalPills =
(med.packageType ?? "blister") === "bottle"
? med.looseTablets + (med.stockAdjustment ?? 0)
: med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
return { return {
id: med.id, id: med.id,
name: med.name, name: med.name,
genericName: med.genericName, genericName: med.genericName,
pillWeightMg: med.pillWeightMg, pillWeightMg: med.pillWeightMg,
doseUnit: med.doseUnit ?? "mg",
imageUrl: med.imageUrl, imageUrl: med.imageUrl,
totalPills, totalPills,
packageType: med.packageType ?? "blister",
packCount: med.packCount, packCount: med.packCount,
blistersPerPack: med.blistersPerPack, blistersPerPack: med.blistersPerPack,
looseTablets: med.looseTablets, looseTablets: med.looseTablets,
pillsPerBlister: med.pillsPerBlister, pillsPerBlister: med.pillsPerBlister,
takenBy: takenByArray, takenBy: takenByArray,
blisters, intakes, // New unified format with per-intake takenBy
blisters, // Legacy format for backward compat
dismissedUntil: med.dismissedUntil,
updatedAt: med.updatedAt, // For filtering out doses from previous schedule configurations
}; };
}); });
@@ -160,11 +168,16 @@ export async function shareRoutes(app: FastifyInstance) {
const { takenBy, scheduleDays } = parsed.data; const { takenBy, scheduleDays } = parsed.data;
// Check if user has medications for this takenBy (search in JSON array) // Check if user has medications for this takenBy (search in both medication-level and intake-level)
const allMeds = await db.select().from(medications).where(eq(medications.userId, userId)); const allMeds = await db.select().from(medications).where(eq(medications.userId, userId));
const medsForPerson = allMeds.filter((med) => { const medsForPerson = allMeds.filter((med) => {
const takenByArray = parseTakenByJson(med.takenByJson); const takenByArray = parseTakenByJson(med.takenByJson);
return takenByArray.includes(takenBy); const intakes = parseIntakesJson(
med.intakesJson,
{ usageJson: med.usageJson, everyJson: med.everyJson, startJson: med.startJson },
med.intakeRemindersEnabled ?? false
);
return personTakesMedication(takenBy, takenByArray, intakes);
}); });
if (medsForPerson.length === 0) { if (medsForPerson.length === 0) {
@@ -200,27 +213,37 @@ export async function shareRoutes(app: FastifyInstance) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// GET /share/people - PROTECTED: Get list of unique takenBy values // GET /share/people - PROTECTED: Get list of unique takenBy values
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
app.get( app.get("/share/people", { preHandler: requireAuth }, async (request, reply) => {
"/share/people",
{ preHandler: requireAuth },
async (request, reply) => {
const userId = await getUserId(request, reply); const userId = await getUserId(request, reply);
// Get all unique takenBy values for this user (from JSON arrays) // Get all unique takenBy values for this user (from both medication-level and intake-level)
const meds = await db.select({ takenByJson: medications.takenByJson }) const meds = await db
.select({
takenByJson: medications.takenByJson,
intakesJson: medications.intakesJson,
usageJson: medications.usageJson,
everyJson: medications.everyJson,
startJson: medications.startJson,
intakeRemindersEnabled: medications.intakeRemindersEnabled,
})
.from(medications) .from(medications)
.where(eq(medications.userId, userId)); .where(eq(medications.userId, userId));
// Collect all unique person names from all takenByJson arrays // Collect all unique person names from medication-level AND intake-level takenBy
const allPeople = new Set<string>(); const allPeople = new Set<string>();
for (const med of meds) { for (const med of meds) {
const takenByArray = parseTakenByJson(med.takenByJson); const takenByArray = parseTakenByJson(med.takenByJson);
for (const person of takenByArray) { const intakes = parseIntakesJson(
med.intakesJson,
{ usageJson: med.usageJson, everyJson: med.everyJson, startJson: med.startJson },
med.intakeRemindersEnabled ?? false
);
const allForMed = getAllTakenByForMedication(takenByArray, intakes);
for (const person of allForMed) {
if (person) allPeople.add(person); if (person) allPeople.add(person);
} }
} }
return { people: [...allPeople].sort() }; return { people: [...allPeople].sort() };
} });
);
} }
+304 -104
View File
@@ -1,32 +1,32 @@
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { and, eq, gte, lte } from "drizzle-orm";
import nodemailer from "nodemailer"; import nodemailer from "nodemailer";
import { eq, and, gte, lte } from "drizzle-orm";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { medications, doseTracking } from "../db/schema.js"; import { getDataDir } from "../db/db-utils.js";
import { readFileSync, writeFileSync, existsSync } from "fs"; import { doseTracking, medications } from "../db/schema.js";
import { resolve } from "path"; import { getDateLocale, getTranslations, type Language, t } from "../i18n/translations.js";
import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js"; import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js";
import { getTranslations, t, getDateLocale, type Language } from "../i18n/translations.js";
import { getReminderState, updateReminderSentTime, updateUserReminderSentTime } from "./reminder-scheduler.js";
// Import shared utilities // Import shared utilities
import { import {
getTimezone,
parseBlisters,
parseTakenByJson,
getUpcomingIntakes,
getTodaysIntakes,
parseIntakeReminderState,
createDefaultIntakeReminderState,
cleanOldIntakeReminders, cleanOldIntakeReminders,
type Blister, createDefaultIntakeReminderState,
getTimezone,
getTodaysIntakes,
getUpcomingIntakes,
type Intake,
type IntakeReminderState, type IntakeReminderState,
parseIntakeReminderState,
parseIntakesJson,
parseTakenByJson,
type UpcomingIntake, type UpcomingIntake,
} from "../utils/scheduler-utils.js"; } from "../utils/scheduler-utils.js";
import { updateReminderSentTime, updateUserReminderSentTime } from "./reminder-scheduler.js";
const REMINDER_MINUTES_BEFORE = parseInt(process.env.REMINDER_MINUTES_BEFORE ?? "15", 10); const REMINDER_MINUTES_BEFORE = parseInt(process.env.REMINDER_MINUTES_BEFORE ?? "15", 10);
const CHECK_INTERVAL_MS = 60 * 1000; // Check every 1 minute const CHECK_INTERVAL_MS = 60 * 1000; // Check every 1 minute
const intakeReminderStateFile = resolve(process.cwd(), "data", "intake-reminder-state.json"); const intakeReminderStateFile = resolve(getDataDir(), "intake-reminder-state.json");
function loadIntakeReminderState(): IntakeReminderState { function loadIntakeReminderState(): IntakeReminderState {
try { try {
@@ -43,21 +43,19 @@ function saveIntakeReminderState(state: IntakeReminderState): void {
writeFileSync(intakeReminderStateFile, JSON.stringify(state, null, 2)); writeFileSync(intakeReminderStateFile, JSON.stringify(state, null, 2));
} }
function parseBlistersFromRow(row: { usageJson: string; everyJson: string; startJson: string }): Blister[] {
return parseBlisters(row);
}
async function sendIntakeReminderEmail( async function sendIntakeReminderEmail(
email: string, email: string,
intakes: UpcomingIntake[], intakes: UpcomingIntake[],
language: Language, language: Language,
isRepeat: boolean = false, isRepeat: boolean = false,
repeatIntervalMinutes?: number repeatIntervalMinutes?: number,
currentCount?: number,
maxCount?: number
): Promise<{ success: boolean; error?: string }> { ): Promise<{ success: boolean; error?: string }> {
const smtpHost = process.env.SMTP_HOST; const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER; const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence
const smtpPort = parseInt(process.env.SMTP_PORT ?? "587"); const smtpPort = parseInt(process.env.SMTP_PORT ?? "587", 10);
const smtpSecure = process.env.SMTP_SECURE === "true"; const smtpSecure = process.env.SMTP_SECURE === "true";
const smtpFrom = process.env.SMTP_FROM ?? smtpUser; const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
@@ -78,11 +76,10 @@ async function sendIntakeReminderEmail(
return pillText; return pillText;
}; };
// Helper to format medication name with takenBy (array of names) // Helper to format medication name with takenBy (single person or null)
const formatMedName = (intake: UpcomingIntake): string => { const formatMedName = (intake: UpcomingIntake): string => {
if (intake.takenBy.length > 0) { if (intake.takenBy) {
const namesStr = intake.takenBy.join(", "); return `${intake.medName} <span style="color: #6b7280; font-size: 12px;">${t(tr.intakeReminder.takenBy, { name: intake.takenBy })}</span>`;
return `${intake.medName} <span style="color: #6b7280; font-size: 12px;">${t(tr.intakeReminder.takenBy, { name: namesStr })}</span>`;
} }
return intake.medName; return intake.medName;
}; };
@@ -99,14 +96,31 @@ async function sendIntakeReminderEmail(
) )
.join(""); .join("");
const alertText = intakes.length === 1 const alertText =
intakes.length === 1
? tr.intakeReminder.alertSingle ? tr.intakeReminder.alertSingle
: t(tr.intakeReminder.alertMultiple, { count: intakes.length }); : t(tr.intakeReminder.alertMultiple, { count: intakes.length });
// Different description for repeat reminders // Different description for repeat reminders
const description = isRepeat && repeatIntervalMinutes let description: string;
? `⚠️ Don't forget your medication! This reminder will be sent every ${repeatIntervalMinutes} minutes until you mark it as taken.` if (isRepeat && repeatIntervalMinutes && currentCount !== undefined && maxCount !== undefined) {
: t(tr.intakeReminder.description, { minutes: REMINDER_MINUTES_BEFORE }); const remainingReminders = maxCount - currentCount;
if (remainingReminders <= 0) {
description = language === "de" ? "⚠️ Dies ist die letzte Erinnerung." : "⚠️ This is the last reminder.";
} else if (remainingReminders === 1) {
description =
language === "de"
? `️ Eine weitere Erinnerung wird in ${repeatIntervalMinutes} Minuten gesendet.`
: `️ One more reminder will be sent in ${repeatIntervalMinutes} minutes.`;
} else {
description =
language === "de"
? `${remainingReminders} weitere Erinnerungen werden alle ${repeatIntervalMinutes} Minuten gesendet.`
: `${remainingReminders} more reminders will be sent every ${repeatIntervalMinutes} minutes.`;
}
} else {
description = t(tr.intakeReminder.description, { minutes: REMINDER_MINUTES_BEFORE });
}
const html = ` const html = `
<div style="font-family: system-ui, -apple-system, sans-serif; max-width: 100%; margin: 0 auto; padding: 12px; background: #f9fafb;"> <div style="font-family: system-ui, -apple-system, sans-serif; max-width: 100%; margin: 0 auto; padding: 12px; background: #f9fafb;">
@@ -156,17 +170,19 @@ async function sendIntakeReminderEmail(
${description} ${description}
${intakes.map((i) => { ${intakes
const takenByStr = i.takenBy.length > 0 ? ` ${t(tr.intakeReminder.takenBy, { name: i.takenBy.join(", ") })}` : ""; .map((i) => {
const takenByStr = i.takenBy ? ` ${t(tr.intakeReminder.takenBy, { name: i.takenBy })}` : "";
return `${i.medName}${takenByStr}: ${formatDosagePlain(i)} - ${i.intakeTimeStr}`; return `${i.medName}${takenByStr}: ${formatDosagePlain(i)} - ${i.intakeTimeStr}`;
}).join("\n")} })
.join("\n")}
--- ---
${tr.intakeReminder.footer}`; ${tr.intakeReminder.footer}`;
const subject = isRepeat const subject = isRepeat
? `[Reminder] ${t(tr.intakeReminder.subject, { medications: intakes.map(i => i.medName).join(", ") })}` ? `[Reminder] ${t(tr.intakeReminder.subject, { medications: intakes.map((i) => i.medName).join(", ") })}`
: t(tr.intakeReminder.subject, { medications: intakes.map(i => i.medName).join(", ") }); : t(tr.intakeReminder.subject, { medications: intakes.map((i) => i.medName).join(", ") });
try { try {
const transporter = nodemailer.createTransport({ const transporter = nodemailer.createTransport({
@@ -194,7 +210,10 @@ ${tr.intakeReminder.footer}`;
} }
} }
async function checkAndSendIntakeReminders(logger: { info: (msg: string) => void; error: (msg: string) => void }): Promise<void> { async function checkAndSendIntakeReminders(logger: {
info: (msg: string) => void;
error: (msg: string) => void;
}): Promise<void> {
logger.info(`[IntakeReminder] Checking for intake reminders...`); logger.info(`[IntakeReminder] Checking for intake reminders...`);
// Get all user settings to iterate over each user // Get all user settings to iterate over each user
@@ -219,22 +238,32 @@ async function checkAndSendIntakeRemindersForUser(
const language = settings.language; const language = settings.language;
const tr = getTranslations(language); const tr = getTranslations(language);
logger.info(`[IntakeReminder] Checking user ${settings.userId} - repeat:${settings.repeatRemindersEnabled} skip:${settings.skipRemindersForTakenDoses}`); logger.info(
`[IntakeReminder] Checking user ${settings.userId} - repeat:${settings.repeatRemindersEnabled} skip:${settings.skipRemindersForTakenDoses}`
);
// Check if any intake reminder notifications are enabled (granular check) // Check if any intake reminder notifications are enabled (granular check)
const emailEnabled = settings.emailEnabled && settings.notificationEmail && settings.emailIntakeReminders; const emailEnabled = settings.emailEnabled && settings.notificationEmail && settings.emailIntakeReminders;
const shoutrrrEnabled = settings.shoutrrrEnabled && settings.shoutrrrUrl && settings.shoutrrrIntakeReminders; const shoutrrrEnabled = settings.shoutrrrEnabled && settings.shoutrrrUrl && settings.shoutrrrIntakeReminders;
if (!emailEnabled && !shoutrrrEnabled) { if (!emailEnabled && !shoutrrrEnabled) {
logger.info(`[IntakeReminder] User ${settings.userId}: No intake notifications enabled (email:${emailEnabled}, shoutrrr:${shoutrrrEnabled})`); logger.info(
`[IntakeReminder] User ${settings.userId}: No intake notifications enabled (email:${emailEnabled}, shoutrrr:${shoutrrrEnabled})`
);
return; // No intake reminder notifications enabled for this user return; // No intake reminder notifications enabled for this user
} }
logger.info(`[IntakeReminder] User ${settings.userId}: Notifications enabled (email:${emailEnabled}, shoutrrr:${shoutrrrEnabled})`); logger.info(
`[IntakeReminder] User ${settings.userId}: Notifications enabled (email:${emailEnabled}, shoutrrr:${shoutrrrEnabled})`
);
// Get all medications with intake reminders enabled for this user // Get all medications with intake reminders enabled for this user
const rows = await db.select().from(medications).where(eq(medications.userId, settings.userId)).orderBy(medications.id); const rows = await db
const medsWithReminders = rows.filter(row => row.intakeRemindersEnabled); .select()
.from(medications)
.where(eq(medications.userId, settings.userId))
.orderBy(medications.id);
const medsWithReminders = rows.filter((row) => row.intakeRemindersEnabled);
if (medsWithReminders.length === 0) { if (medsWithReminders.length === 0) {
logger.info(`[IntakeReminder] User ${settings.userId}: No medications have reminders enabled`); logger.info(`[IntakeReminder] User ${settings.userId}: No medications have reminders enabled`);
@@ -256,46 +285,100 @@ async function checkAndSendIntakeRemindersForUser(
const todayEnd = new Date(now.toLocaleString("en-US", { timeZone: tz })); const todayEnd = new Date(now.toLocaleString("en-US", { timeZone: tz }));
todayEnd.setHours(23, 59, 59, 999); todayEnd.setHours(23, 59, 59, 999);
logger.info(`[IntakeReminder] User ${settings.userId}: Today range: ${todayStart.toISOString()} to ${todayEnd.toISOString()}`); logger.info(
`[IntakeReminder] User ${settings.userId}: Today range: ${todayStart.toISOString()} to ${todayEnd.toISOString()}`
);
// Find intakes: upcoming ones in reminder window + past ones for repeat reminders // Find intakes: upcoming ones in reminder window + past ones for repeat reminders
for (const med of medsWithReminders) { for (const med of medsWithReminders) {
const blisters = parseBlistersFromRow(med); // Parse intakes using new format (with per-intake takenBy), falling back to legacy
const takenByArray = parseTakenByJson(med.takenByJson); const intakes = parseIntakesJson(
med.intakesJson,
{ usageJson: med.usageJson, everyJson: med.everyJson, startJson: med.startJson },
med.intakeRemindersEnabled ?? false
);
// Medication-level takenBy (for fallback/display purposes)
const medicationTakenBy = parseTakenByJson(med.takenByJson);
logger.info(`[IntakeReminder] User ${settings.userId}: Processing medication "${med.name}" with ${blisters.length} blisters`); logger.info(
`[IntakeReminder] User ${settings.userId}: Processing medication "${med.name}" with ${intakes.length} intakes`
);
// Process each blister separately to track blisterIndex // Filter intakes that have reminders enabled (per-intake setting or medication-level)
blisters.forEach((blister, blisterIndex) => { const intakesWithReminders = intakes.filter((intake, idx) => {
logger.info(`[IntakeReminder] User ${settings.userId}: Blister ${blisterIndex} - start: ${blister.start}, every: ${blister.every} days, usage: ${blister.usage}`); const hasReminder = intake.intakeRemindersEnabled || med.intakeRemindersEnabled;
if (!hasReminder) {
logger.info(`[IntakeReminder] User ${settings.userId}: Intake ${idx} has reminders disabled, skipping`);
}
return hasReminder;
});
// Process each intake separately to track blisterIndex
intakesWithReminders.forEach((intake, blisterIndex) => {
const actualIndex = intakes.indexOf(intake); // Get the actual index in original array
logger.info(
`[IntakeReminder] User ${settings.userId}: Intake ${actualIndex} - start: ${intake.start}, every: ${intake.every} days, usage: ${intake.usage}, takenBy: ${intake.takenBy || "(none)"}`
);
// Always get upcoming intakes (15 min before) for first reminders // Always get upcoming intakes (15 min before) for first reminders
const upcomingIntakes = getUpcomingIntakes(med.name, [blister], REMINDER_MINUTES_BEFORE, takenByArray, med.pillWeightMg, locale, tz); const upcomingIntakes = getUpcomingIntakes(
logger.info(`[IntakeReminder] User ${settings.userId}: Blister ${blisterIndex} found ${upcomingIntakes.length} upcoming intakes (reminder window)`); med.name,
[intake],
REMINDER_MINUTES_BEFORE,
medicationTakenBy,
med.pillWeightMg,
locale,
tz,
undefined, // nowOverride
med.id,
med.doseUnit ?? "mg"
);
logger.info(
`[IntakeReminder] User ${settings.userId}: Intake ${actualIndex} found ${upcomingIntakes.length} upcoming intakes (reminder window)`
);
// Add upcoming intakes for first reminders // Add upcoming intakes for first reminders
allUpcoming.push(...upcomingIntakes.map(intake => ({ allUpcoming.push(
...intake, ...upcomingIntakes.map((upcomingIntake) => ({
...upcomingIntake,
medicationId: med.id, medicationId: med.id,
blisterIndex, blisterIndex: actualIndex,
}))); }))
);
// If repeat reminders enabled, also check for missed intakes (past the intake time) // If repeat reminders enabled, also check for missed intakes (past the intake time)
if (settings.repeatRemindersEnabled) { if (settings.repeatRemindersEnabled) {
const allTodaysIntakes = getTodaysIntakes(med.name, [blister], takenByArray, med.pillWeightMg, locale, tz); const allTodaysIntakes = getTodaysIntakes(
logger.info(`[IntakeReminder] User ${settings.userId}: Blister ${blisterIndex} - all today's intakes: ${allTodaysIntakes.length}, times: ${allTodaysIntakes.map(i => i.intakeTime.toISOString()).join(', ')}`); med.name,
const missedIntakes = allTodaysIntakes.filter(intake => intake.intakeTime.getTime() < now.getTime()); [intake],
logger.info(`[IntakeReminder] User ${settings.userId}: Blister ${blisterIndex} found ${missedIntakes.length} missed intakes (past intake time)`); medicationTakenBy,
med.pillWeightMg,
locale,
tz,
med.id,
med.doseUnit ?? "mg"
);
logger.info(
`[IntakeReminder] User ${settings.userId}: Intake ${actualIndex} - all today's intakes: ${allTodaysIntakes.length}, times: ${allTodaysIntakes.map((i) => i.intakeTime.toISOString()).join(", ")}`
);
const missedIntakes = allTodaysIntakes.filter(
(todayIntake) => todayIntake.intakeTime.getTime() < now.getTime()
);
logger.info(
`[IntakeReminder] User ${settings.userId}: Intake ${actualIndex} found ${missedIntakes.length} missed intakes (past intake time)`
);
// Add missed intakes for repeat reminders (only if not already in upcoming list) // Add missed intakes for repeat reminders (only if not already in upcoming list)
const upcomingTimes = new Set(upcomingIntakes.map(i => i.intakeTime.getTime())); const upcomingTimes = new Set(upcomingIntakes.map((i) => i.intakeTime.getTime()));
allUpcoming.push(...missedIntakes allUpcoming.push(
.filter(intake => !upcomingTimes.has(intake.intakeTime.getTime())) ...missedIntakes
.map(intake => ({ .filter((missed) => !upcomingTimes.has(missed.intakeTime.getTime()))
...intake, .map((missed) => ({
...missed,
medicationId: med.id, medicationId: med.id,
blisterIndex, blisterIndex: actualIndex,
}))); }))
);
} }
}); });
} }
@@ -309,7 +392,13 @@ async function checkAndSendIntakeRemindersForUser(
// Determine which doses need reminders (new or repeated) // Determine which doses need reminders (new or repeated)
const nowMs = Date.now(); const nowMs = Date.now();
let remindersToSend: typeof allUpcoming = []; const maxReminders = settings.maxNaggingReminders ?? 5;
type ReminderWithCount = (typeof allUpcoming)[number] & {
currentSendCount: number; // 0 = advance reminder (no counter), 1+ = nagging count
maxReminders: number;
isAdvanceReminder: boolean; // true if this is the 15-min-before reminder
};
let remindersToSend: ReminderWithCount[] = [];
for (const intake of allUpcoming) { for (const intake of allUpcoming) {
const key = `user_${settings.userId}:${intake.medName}:${intake.intakeTime.getTime()}`; const key = `user_${settings.userId}:${intake.medName}:${intake.intakeTime.getTime()}`;
@@ -318,21 +407,48 @@ async function checkAndSendIntakeRemindersForUser(
const isIntakePast = intakeTimeMs < nowMs; const isIntakePast = intakeTimeMs < nowMs;
if (!existingEntry) { if (!existingEntry) {
// New dose - always send first reminder (upcoming or already missed) // New dose - send first reminder
remindersToSend.push(intake); if (isIntakePast) {
logger.info(`[IntakeReminder] User ${settings.userId}: First reminder for "${intake.medName}" at ${intake.intakeTimeStr} (${isIntakePast ? 'missed' : 'upcoming'})`); // Intake time already passed and we have no state entry — this means the scheduler
// was not aware of this intake before it happened (e.g., user just enabled reminders).
// Seed the state as already handled so repeat reminders can track from here,
// but do NOT send a notification for intakes that were missed before tracking started.
state.reminders[key] = {
firstSentAt: nowMs,
lastSentAt: nowMs,
sendCount: 0,
advanceSent: false,
};
logger.info(
`[IntakeReminder] User ${settings.userId}: Seeding state for past "${intake.medName}" at ${intake.intakeTimeStr} (no notification — first detection)`
);
} else {
// Upcoming - this is advance reminder (no counter)
remindersToSend.push({ ...intake, currentSendCount: 0, maxReminders, isAdvanceReminder: true });
logger.info(
`[IntakeReminder] User ${settings.userId}: Advance reminder for "${intake.medName}" at ${intake.intakeTimeStr}`
);
}
} else if (settings.repeatRemindersEnabled && isIntakePast) { } else if (settings.repeatRemindersEnabled && isIntakePast) {
// Repeat reminder - only for intakes that are already past (missed) // Intake time passed - check if we need to send nagging reminder
const intervalMs = settings.reminderRepeatIntervalMinutes * 60 * 1000; const intervalMs = settings.reminderRepeatIntervalMinutes * 60 * 1000;
const timeSinceLastReminder = nowMs - existingEntry.lastSentAt; const timeSinceLastReminder = nowMs - existingEntry.lastSentAt;
const maxReminders = settings.maxNaggingReminders ?? 5;
if (existingEntry.sendCount >= maxReminders) { // If only advance reminder was sent (sendCount=0), first nagging has count=1
// Max reminders reached - stop nagging // Otherwise increment from current sendCount
logger.info(`[IntakeReminder] User ${settings.userId}: Max reminders (${maxReminders}) reached for "${intake.medName}" at ${intake.intakeTimeStr}`); const currentNaggingCount = existingEntry.sendCount;
if (currentNaggingCount >= maxReminders) {
// Max nagging reminders reached - stop
logger.info(
`[IntakeReminder] User ${settings.userId}: Max nagging (${maxReminders}) reached for "${intake.medName}" at ${intake.intakeTimeStr}`
);
} else if (timeSinceLastReminder >= intervalMs) { } else if (timeSinceLastReminder >= intervalMs) {
remindersToSend.push(intake); const nextSendCount = currentNaggingCount + 1;
logger.info(`[IntakeReminder] User ${settings.userId}: Repeat reminder for missed "${intake.medName}" at ${intake.intakeTimeStr} (${existingEntry.sendCount + 1}/${maxReminders})`); remindersToSend.push({ ...intake, currentSendCount: nextSendCount, maxReminders, isAdvanceReminder: false });
logger.info(
`[IntakeReminder] User ${settings.userId}: Nagging reminder for "${intake.medName}" at ${intake.intakeTimeStr} (${nextSendCount}/${maxReminders})`
);
} }
} }
// Else: Already sent and either repeats disabled or intake not yet past - skip // Else: Already sent and either repeats disabled or intake not yet past - skip
@@ -345,7 +461,10 @@ async function checkAndSendIntakeRemindersForUser(
// If skipRemindersForTakenDoses is enabled, filter out doses that were already taken today // If skipRemindersForTakenDoses is enabled, filter out doses that were already taken today
if (settings.skipRemindersForTakenDoses) { if (settings.skipRemindersForTakenDoses) {
// Query doses marked as taken today (takenAt is timestamp, stored as seconds since epoch) // Query doses marked as taken today (takenAt is timestamp, stored as seconds since epoch)
const takenToday = await db.select().from(doseTracking).where( const takenToday = await db
.select()
.from(doseTracking)
.where(
and( and(
eq(doseTracking.userId, settings.userId), eq(doseTracking.userId, settings.userId),
gte(doseTracking.takenAt, todayStart), gte(doseTracking.takenAt, todayStart),
@@ -353,24 +472,35 @@ async function checkAndSendIntakeRemindersForUser(
) )
); );
const takenDoseIds = new Set(takenToday.map(d => d.doseId)); const takenDoseIds = new Set(takenToday.map((d) => d.doseId));
// Filter out reminders for doses that were already taken // Filter out reminders for doses that were already taken
remindersToSend = remindersToSend.filter(intake => { remindersToSend = remindersToSend.filter((intake) => {
const timestamp = intake.intakeTime.getTime(); // Convert to date-only timestamp (midnight) to match frontend dose ID format
const intakeDate = intake.intakeTime;
const dateOnlyMs = new Date(intakeDate.getFullYear(), intakeDate.getMonth(), intakeDate.getDate()).getTime();
// Check both with and without person suffix // Check both with and without person suffix
if (intake.takenBy.length > 0) { if (intake.takenBy) {
// For multi-person medications, check if any person has taken it // For person-specific intake, check if that person has taken it
const anyTaken = intake.takenBy.some(person => { const doseId = `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}-${intake.takenBy}`;
const doseId = `${intake.medicationId}-${intake.blisterIndex}-${timestamp}-${person}`; const isTaken = takenDoseIds.has(doseId);
return takenDoseIds.has(doseId); if (isTaken) {
}); logger.info(
return !anyTaken; // Skip if any person has taken it `[IntakeReminder] User ${settings.userId}: Skipping "${intake.medName}" - dose ${doseId} already taken`
);
}
return !isTaken;
} else { } else {
// For non-person-specific medications // For non-person-specific intakes
const doseId = `${intake.medicationId}-${intake.blisterIndex}-${timestamp}`; const doseId = `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}`;
return !takenDoseIds.has(doseId); const isTaken = takenDoseIds.has(doseId);
if (isTaken) {
logger.info(
`[IntakeReminder] User ${settings.userId}: Skipping "${intake.medName}" - dose ${doseId} already taken`
);
}
return !isTaken;
} }
}); });
@@ -385,7 +515,7 @@ async function checkAndSendIntakeRemindersForUser(
// Determine if this is a repeat reminder: // Determine if this is a repeat reminder:
// - Any intake already has a state entry AND is past (repeat after first reminder) // - Any intake already has a state entry AND is past (repeat after first reminder)
// - OR intake is past even without state entry (missed the 15-min window) // - OR intake is past even without state entry (missed the 15-min window)
const isRepeatReminder = remindersToSend.some(intake => { const isRepeatReminder = remindersToSend.some((intake) => {
const intakeTimeMs = intake.intakeTime.getTime(); const intakeTimeMs = intake.intakeTime.getTime();
const isIntakePast = intakeTimeMs < nowMs; const isIntakePast = intakeTimeMs < nowMs;
return isIntakePast; // Use repeat message for ANY missed intake return isIntakePast; // Use repeat message for ANY missed intake
@@ -396,12 +526,19 @@ async function checkAndSendIntakeRemindersForUser(
// Send email if enabled for intake reminders // Send email if enabled for intake reminders
if (emailEnabled) { if (emailEnabled) {
// Calculate counts for repeat reminder text
const hasNaggingReminder = remindersToSend.some((r) => !r.isAdvanceReminder);
const highestSendCount = Math.max(...remindersToSend.map((r) => r.currentSendCount));
const maxReminderCount = remindersToSend[0]?.maxReminders ?? 5;
const result = await sendIntakeReminderEmail( const result = await sendIntakeReminderEmail(
settings.notificationEmail!, settings.notificationEmail!,
remindersToSend, remindersToSend,
language, language,
isRepeatReminder, isRepeatReminder,
settings.reminderRepeatIntervalMinutes settings.reminderRepeatIntervalMinutes,
hasNaggingReminder ? highestSendCount : undefined,
hasNaggingReminder ? maxReminderCount : undefined
); );
emailSuccess = result.success; emailSuccess = result.success;
if (result.success) { if (result.success) {
@@ -413,17 +550,50 @@ async function checkAndSendIntakeRemindersForUser(
// Send Shoutrrr notification if enabled for intake reminders // Send Shoutrrr notification if enabled for intake reminders
if (shoutrrrEnabled) { if (shoutrrrEnabled) {
const title = isRepeatReminder // Check if any reminder is a nagging reminder (not advance)
? (language === 'de' ? '⚠️ Medikamenten-Erinnerung' : '⚠️ Medication Reminder') const hasNaggingReminder = remindersToSend.some((r) => !r.isAdvanceReminder);
: t(tr.push.intakeTitle, { minutes: REMINDER_MINUTES_BEFORE }); const highestSendCount = Math.max(...remindersToSend.map((r) => r.currentSendCount));
const maxReminderCount = remindersToSend[0]?.maxReminders ?? 5;
const repeatNote = isRepeatReminder && settings.reminderRepeatIntervalMinutes let title: string;
? `\n\n⚠️ This reminder will be sent every ${settings.reminderRepeatIntervalMinutes} minutes until marked as taken.` if (hasNaggingReminder && highestSendCount > 0) {
: ''; // Nagging reminder - show counter
const counterStr = `(${highestSendCount}/${maxReminderCount})`;
title =
language === "de"
? `⚠️ Erinnerung: Medikamenteneinnahme ${counterStr}`
: `⚠️ Reminder: Medication intake ${counterStr}`;
} else {
// Advance reminder - no counter
title = t(tr.push.intakeTitle, { minutes: REMINDER_MINUTES_BEFORE });
}
const message = remindersToSend // Only show repeat note for nagging reminders, not for advance reminders
let repeatNote = "";
if (hasNaggingReminder && settings.reminderRepeatIntervalMinutes) {
const remainingReminders = maxReminderCount - highestSendCount;
if (remainingReminders <= 0) {
// Last reminder
repeatNote = language === "de" ? "\n\n⚠️ Dies ist die letzte Erinnerung." : "\n\n⚠️ This is the last reminder.";
} else if (remainingReminders === 1) {
// One more reminder
repeatNote =
language === "de"
? `\n\n️ Eine weitere Erinnerung wird in ${settings.reminderRepeatIntervalMinutes} Minuten gesendet.`
: `\n\n️ One more reminder will be sent in ${settings.reminderRepeatIntervalMinutes} minutes.`;
} else {
// Multiple reminders remaining
repeatNote =
language === "de"
? `\n\n${remainingReminders} weitere Erinnerungen werden alle ${settings.reminderRepeatIntervalMinutes} Minuten gesendet.`
: `\n\n${remainingReminders} more reminders will be sent every ${settings.reminderRepeatIntervalMinutes} minutes.`;
}
}
const message =
remindersToSend
.map((i) => { .map((i) => {
const takenByStr = i.takenBy.length > 0 ? ` ${t(tr.intakeReminder.takenBy, { name: i.takenBy.join(", ") })}` : ""; const takenByStr = i.takenBy ? ` ${t(tr.intakeReminder.takenBy, { name: i.takenBy })}` : "";
let dosage = `${i.usage} ${i.usage === 1 ? tr.common.pill : tr.common.pills}`; let dosage = `${i.usage} ${i.usage === 1 ? tr.common.pill : tr.common.pills}`;
if (i.pillWeightMg) { if (i.pillWeightMg) {
const totalMg = i.usage * i.pillWeightMg; const totalMg = i.usage * i.pillWeightMg;
@@ -450,21 +620,44 @@ async function checkAndSendIntakeRemindersForUser(
const existing = state.reminders[key]; const existing = state.reminders[key];
if (existing) { if (existing) {
// Update existing entry (repeat) // Update existing entry
if (intake.isAdvanceReminder) {
// Advance reminder - don't increment nagging count
state.reminders[key] = {
...existing,
lastSentAt: nowMs,
advanceSent: true,
};
} else {
// Nagging reminder - increment count
state.reminders[key] = { state.reminders[key] = {
firstSentAt: existing.firstSentAt, firstSentAt: existing.firstSentAt,
lastSentAt: nowMs, lastSentAt: nowMs,
sendCount: existing.sendCount + 1, sendCount: existing.sendCount + 1,
advanceSent: existing.advanceSent,
};
}
} else {
// Create new entry
if (intake.isAdvanceReminder) {
// Advance reminder - sendCount stays 0
state.reminders[key] = {
firstSentAt: nowMs,
lastSentAt: nowMs,
sendCount: 0,
advanceSent: true,
}; };
} else { } else {
// Create new entry (first send) // First nagging reminder - sendCount starts at 1
state.reminders[key] = { state.reminders[key] = {
firstSentAt: nowMs, firstSentAt: nowMs,
lastSentAt: nowMs, lastSentAt: nowMs,
sendCount: 1, sendCount: 1,
advanceSent: false,
}; };
} }
} }
}
// Clean up old entries (remove doses from past days) // Clean up old entries (remove doses from past days)
state.reminders = cleanOldIntakeReminders(state.reminders, tz); state.reminders = cleanOldIntakeReminders(state.reminders, tz);
@@ -476,13 +669,20 @@ async function checkAndSendIntakeRemindersForUser(
updateReminderSentTime("intake", channel); updateReminderSentTime("intake", channel);
// Also update user settings in database so frontend can display the info // Also update user settings in database so frontend can display the info
await updateUserReminderSentTime(settings.userId, "intake", channel); // Get the first reminder's medication name and taken by for display
const firstReminder = remindersToSend[0];
const medName = firstReminder?.medName;
const takenBy = firstReminder?.takenBy || undefined;
await updateUserReminderSentTime(settings.userId, "intake", channel, medName, takenBy);
} }
} }
let intakeCheckInterval: NodeJS.Timeout | null = null; let intakeCheckInterval: NodeJS.Timeout | null = null;
export function startIntakeReminderScheduler(logger: { info: (msg: string) => void; error: (msg: string) => void }): void { export function startIntakeReminderScheduler(logger: {
info: (msg: string) => void;
error: (msg: string) => void;
}): void {
logger.info(`[IntakeReminder] Starting intake reminder scheduler (checks every minute)...`); logger.info(`[IntakeReminder] Starting intake reminder scheduler (checks every minute)...`);
// Run immediately on start // Run immediately on start
+68 -30
View File
@@ -1,32 +1,32 @@
import nodemailer from "nodemailer"; import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import nodemailer from "nodemailer";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { medications, userSettings } from "../db/schema.js"; import { medications, userSettings } from "../db/schema.js";
import { readFileSync, writeFileSync, existsSync } from "fs"; import { getTranslations, type Language, t } from "../i18n/translations.js";
import { resolve } from "path"; import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js";
import { loadUserSettings, getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js";
import { getTranslations, t, type Language } from "../i18n/translations.js";
// Import shared utilities // Import shared utilities
import { import {
getTimezone, type Blister,
calculateDepletionInfo,
createDefaultReminderState,
formatInTimezone, formatInTimezone,
getCurrentHourInTimezone, getCurrentHourInTimezone,
getTodayInTimezone,
getNextScheduledTime,
getMsUntilNextCheck, getMsUntilNextCheck,
getNextScheduledTime,
getTimezone,
getTodayInTimezone,
parseBlisters, parseBlisters,
calculateDailyUsage,
calculateDepletionInfo,
parseReminderState, parseReminderState,
createDefaultReminderState,
type Blister,
type ReminderState, type ReminderState,
} from "../utils/scheduler-utils.js"; } from "../utils/scheduler-utils.js";
const REMINDER_HOUR = parseInt(process.env.REMINDER_HOUR ?? "6", 10); // Default 6:00 AM local time const REMINDER_HOUR = parseInt(process.env.REMINDER_HOUR ?? "6", 10); // Default 6:00 AM local time
const reminderStateFile = resolve(process.cwd(), "data", "reminder-state.json"); const reminderStateFile = resolve(getDataDir(), "reminder-state.json");
function loadReminderState(): ReminderState { function loadReminderState(): ReminderState {
try { try {
@@ -47,7 +47,10 @@ export function getReminderState(): ReminderState {
return loadReminderState(); return loadReminderState();
} }
export function updateReminderSentTime(type: "stock" | "intake" = "stock", channel: "email" | "push" | "both" = "email"): void { export function updateReminderSentTime(
type: "stock" | "intake" = "stock",
channel: "email" | "push" | "both" = "email"
): void {
const state = loadReminderState(); const state = loadReminderState();
const today = getTodayInTimezone(); const today = getTodayInTimezone();
saveReminderState({ saveReminderState({
@@ -63,14 +66,19 @@ export function updateReminderSentTime(type: "stock" | "intake" = "stock", chann
export async function updateUserReminderSentTime( export async function updateUserReminderSentTime(
userId: number, userId: number,
type: "stock" | "intake" = "stock", type: "stock" | "intake" = "stock",
channel: "email" | "push" | "both" = "email" channel: "email" | "push" | "both" = "email",
medName?: string,
takenBy?: string
): Promise<void> { ): Promise<void> {
const now = new Date().toISOString(); const now = new Date().toISOString();
await db.update(userSettings) await db
.update(userSettings)
.set({ .set({
lastAutoEmailSent: now, lastAutoEmailSent: now,
lastNotificationType: type, lastNotificationType: type,
lastNotificationChannel: channel, lastNotificationChannel: channel,
lastReminderMedName: medName ?? null,
lastReminderTakenBy: takenBy ?? null,
}) })
.where(eq(userSettings.userId, userId)); .where(eq(userSettings.userId, userId));
} }
@@ -86,14 +94,21 @@ type LowStockItem = {
depletionDate: string | null; depletionDate: string | null;
}; };
async function getMedicationsNeedingReminder(userId: number, reminderDaysBefore: number, language: Language): Promise<LowStockItem[]> { async function getMedicationsNeedingReminder(
userId: number,
reminderDaysBefore: number,
language: Language
): Promise<LowStockItem[]> {
const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id); const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id);
const lowStock: LowStockItem[] = []; const lowStock: LowStockItem[] = [];
for (const row of rows) { for (const row of rows) {
const blisters = parseBlistersFromRow(row); const blisters = parseBlistersFromRow(row);
const totalPills = row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0); const totalPills =
(row.packageType ?? "blister") === "bottle"
? row.looseTablets + (row.stockAdjustment ?? 0)
: row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
const { daysLeft, depletionDate } = calculateDepletionInfo({ count: totalPills, blisters }, language); const { daysLeft, depletionDate } = calculateDepletionInfo({ count: totalPills, blisters }, language);
// Check if medication runs out within reminderDaysBefore days // Check if medication runs out within reminderDaysBefore days
@@ -110,11 +125,16 @@ async function getMedicationsNeedingReminder(userId: number, reminderDaysBefore:
return lowStock; return lowStock;
} }
async function sendReminderEmail(email: string, lowStock: LowStockItem[], language: Language, isRepeatDaily: boolean = false): Promise<{ success: boolean; error?: string }> { async function sendReminderEmail(
email: string,
lowStock: LowStockItem[],
language: Language,
isRepeatDaily: boolean = false
): Promise<{ success: boolean; error?: string }> {
const smtpHost = process.env.SMTP_HOST; const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER; const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence
const smtpPort = parseInt(process.env.SMTP_PORT ?? "587"); const smtpPort = parseInt(process.env.SMTP_PORT ?? "587", 10);
const smtpSecure = process.env.SMTP_SECURE === "true"; const smtpSecure = process.env.SMTP_SECURE === "true";
const smtpFrom = process.env.SMTP_FROM ?? smtpUser; const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
@@ -136,7 +156,8 @@ async function sendReminderEmail(email: string, lowStock: LowStockItem[], langua
) )
.join(""); .join("");
const alertText = lowStock.length === 1 const alertText =
lowStock.length === 1
? tr.stockReminder.alertSingle ? tr.stockReminder.alertSingle
: t(tr.stockReminder.alertMultiple, { count: lowStock.length }); : t(tr.stockReminder.alertMultiple, { count: lowStock.length });
@@ -186,7 +207,7 @@ ${lowStock.map((r) => `${r.name}: ${r.medsLeft} ${tr.common.pills}, ${r.daysLeft
--- ---
${tr.stockReminder.footer}${isRepeatDaily ? `\n\n${tr.stockReminder.repeatDailyNote}` : ""}`; ${tr.stockReminder.footer}${isRepeatDaily ? `\n\n${tr.stockReminder.repeatDailyNote}` : ""}`;
const subjectPlural = lowStock.length === 1 ? "" : (language === "de" ? "e" : "s"); const subjectPlural = lowStock.length === 1 ? "" : language === "de" ? "e" : "s";
const subject = t(tr.stockReminder.subject, { count: lowStock.length, s: subjectPlural, e: subjectPlural }); const subject = t(tr.stockReminder.subject, { count: lowStock.length, s: subjectPlural, e: subjectPlural });
try { try {
@@ -215,7 +236,10 @@ ${tr.stockReminder.footer}${isRepeatDaily ? `\n\n${tr.stockReminder.repeatDailyN
} }
} }
async function checkAndSendReminder(logger: { info: (msg: string) => void; error: (msg: string) => void }): Promise<void> { async function checkAndSendReminder(logger: {
info: (msg: string) => void;
error: (msg: string) => void;
}): Promise<void> {
// Get all user settings to iterate over each user // Get all user settings to iterate over each user
const allUserSettings = await getAllUserSettings(); const allUserSettings = await getAllUserSettings();
@@ -268,7 +292,12 @@ async function checkAndSendReminderForUser(
// Send email if enabled // Send email if enabled
if (emailEnabled) { if (emailEnabled) {
const result = await sendReminderEmail(settings.notificationEmail!, allLowStock, language, settings.repeatDailyReminders); const result = await sendReminderEmail(
settings.notificationEmail!,
allLowStock,
language,
settings.repeatDailyReminders
);
emailSuccess = result.success; emailSuccess = result.success;
if (result.success) { if (result.success) {
logger.info(`[Reminder] User ${settings.userId}: Email sent successfully to ${settings.notificationEmail}`); logger.info(`[Reminder] User ${settings.userId}: Email sent successfully to ${settings.notificationEmail}`);
@@ -280,8 +309,8 @@ async function checkAndSendReminderForUser(
// Send Shoutrrr notification if enabled // Send Shoutrrr notification if enabled
if (shoutrrrEnabled) { if (shoutrrrEnabled) {
// Separate empty from low stock medications // Separate empty from low stock medications
const emptyMeds = allLowStock.filter(m => m.medsLeft <= 0); const emptyMeds = allLowStock.filter((m) => m.medsLeft <= 0);
const lowMeds = allLowStock.filter(m => m.medsLeft > 0); const lowMeds = allLowStock.filter((m) => m.medsLeft > 0);
// Build clear title // Build clear title
const titleParts: string[] = []; const titleParts: string[] = [];
@@ -297,12 +326,16 @@ async function checkAndSendReminderForUser(
const messageParts: string[] = []; const messageParts: string[] = [];
if (emptyMeds.length > 0) { if (emptyMeds.length > 0) {
messageParts.push(`🚨 ${tr.push.emptySection || "EMPTY (reorder immediately)"}:`); messageParts.push(`🚨 ${tr.push.emptySection || "EMPTY (reorder immediately)"}:`);
emptyMeds.forEach(m => messageParts.push(`${m.name}`)); emptyMeds.forEach((m) => messageParts.push(`${m.name}`));
} }
if (lowMeds.length > 0) { if (lowMeds.length > 0) {
if (emptyMeds.length > 0) messageParts.push(""); if (emptyMeds.length > 0) messageParts.push("");
messageParts.push(`⚠️ ${tr.push.lowSection || "RUNNING LOW (reorder soon)"}:`); messageParts.push(`⚠️ ${tr.push.lowSection || "RUNNING LOW (reorder soon)"}:`);
lowMeds.forEach(m => messageParts.push(`${m.name}: ${t(tr.push.pillsLeft, { count: m.medsLeft })}, ${t(tr.push.daysLeft, { count: m.daysLeft ?? 0 })}`)); lowMeds.forEach((m) =>
messageParts.push(
`${m.name}: ${t(tr.push.pillsLeft, { count: m.medsLeft })}, ${t(tr.push.daysLeft, { count: m.daysLeft ?? 0 })}`
)
);
} }
if (settings.repeatDailyReminders) { if (settings.repeatDailyReminders) {
@@ -335,7 +368,10 @@ async function checkAndSendReminderForUser(
}); });
// Also update user settings in database so frontend can display the info // Also update user settings in database so frontend can display the info
await updateUserReminderSentTime(settings.userId, "stock", channel); // For stock reminders, show the first medication name
const firstMed = allLowStock[0];
const medNames = allLowStock.length > 1 ? `${firstMed.name} (+${allLowStock.length - 1})` : firstMed?.name;
await updateUserReminderSentTime(settings.userId, "stock", channel, medNames);
} }
} }
@@ -352,7 +388,9 @@ function scheduleNextCheck(logger: { info: (msg: string) => void; error: (msg: s
nextScheduledCheck: nextTime.toISOString(), nextScheduledCheck: nextTime.toISOString(),
}); });
logger.info(`[Reminder] Next check scheduled for ${formatInTimezone(nextTime)} (${getTimezone()}) (in ${Math.round(msUntilNext / 1000 / 60)} minutes)`); logger.info(
`[Reminder] Next check scheduled for ${formatInTimezone(nextTime)} (${getTimezone()}) (in ${Math.round(msUntilNext / 1000 / 60)} minutes)`
);
schedulerTimeout = setTimeout(() => { schedulerTimeout = setTimeout(() => {
checkAndSendReminder(logger).catch((err) => logger.error(`[Reminder] Error: ${err}`)); checkAndSendReminder(logger).catch((err) => logger.error(`[Reminder] Error: ${err}`));
+63 -5
View File
@@ -1,13 +1,13 @@
/** /**
* E2E Tests for auth routes with AUTH_ENABLED=true * E2E Tests for auth routes with AUTH_ENABLED=true
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from "vitest";
import Fastify, { FastifyInstance } from "fastify";
import cookie from "@fastify/cookie"; import cookie from "@fastify/cookie";
import jwt from "@fastify/jwt"; import jwt from "@fastify/jwt";
import sensible from "@fastify/sensible"; import sensible from "@fastify/sensible";
import { createClient, Client } from "@libsql/client"; import type { Client } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql"; import Fastify, { type FastifyInstance } from "fastify";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
// Use vi.hoisted to create the db BEFORE mocks are set up // Use vi.hoisted to create the db BEFORE mocks are set up
const { testClient, testDb } = vi.hoisted(() => { const { testClient, testDb } = vi.hoisted(() => {
@@ -327,7 +327,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
describe("POST /auth/refresh", () => { describe("POST /auth/refresh", () => {
it("should refresh access token with valid refresh token", async () => { it("should refresh access token with valid refresh token", async () => {
// Login first to get tokens // Login first to get tokens
const loginResponse = await app.inject({ const _loginResponse = await app.inject({
method: "POST", method: "POST",
url: "/auth/login", url: "/auth/login",
payload: { payload: {
@@ -682,4 +682,62 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
expect(response.statusCode).toBe(401); expect(response.statusCode).toBe(401);
}); });
}); });
describe("DELETE /auth/me - Delete Account", () => {
it("should delete user account and all data", async () => {
// Register and login
await app.inject({
method: "POST",
url: "/auth/register",
payload: {
username: "deleteuser",
password: "TestPassword123",
},
});
const login = await app.inject({
method: "POST",
url: "/auth/login",
payload: {
username: "deleteuser",
password: "TestPassword123",
},
});
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
// Delete account
const response = await app.inject({
method: "DELETE",
url: "/auth/me",
cookies: {
access_token: accessToken?.value ?? "",
},
});
expect(response.statusCode).toBe(200);
expect(response.json().ok).toBe(true);
// Verify can't login anymore
const loginAgain = await app.inject({
method: "POST",
url: "/auth/login",
payload: {
username: "deleteuser",
password: "TestPassword123",
},
});
expect(loginAgain.statusCode).toBe(401);
});
it("should reject delete without auth", async () => {
const response = await app.inject({
method: "DELETE",
url: "/auth/me",
});
expect(response.statusCode).toBe(401);
});
});
}); });
+462 -41
View File
@@ -1,28 +1,27 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { existsSync, mkdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { createClient } from "@libsql/client"; import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql"; import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator"; import { migrate } from "drizzle-orm/libsql/migrator";
import { mkdirSync, rmSync, existsSync } from "fs"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { resolve, dirname } from "path";
import { tmpdir } from "os";
import { fileURLToPath } from "url";
// Import the exported utility functions from client.ts // Import utility functions from db-utils (no side effects, unlike client.ts which initializes the DB)
import { import {
buildDbUrl, buildDbUrl,
getDbPaths,
ensureDataDirectory, ensureDataDirectory,
runDrizzleMigrations,
runAlterMigrations,
ensureDefaultUser, ensureDefaultUser,
} from "../db/client.js"; getDataDir,
getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations,
runDrizzleMigrations,
} from "../db/db-utils.js";
// Import the exported utility functions from migrate.ts // Import the exported utility functions from migrate.ts
import { import { executeMigration, getStatementPreview, splitSQLStatements } from "../db/migrate.js";
splitSQLStatements,
executeMigration,
getStatementPreview,
} from "../db/migrate.js";
// Get migrations folder path // Get migrations folder path
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
@@ -51,7 +50,7 @@ describe("Migration Script Utilities", () => {
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle%' ORDER BY name" "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle%' ORDER BY name"
); );
const tableNames = tables.rows.map(r => r.name); const tableNames = tables.rows.map((r) => r.name);
expect(tableNames).toContain("users"); expect(tableNames).toContain("users");
expect(tableNames).toContain("medications"); expect(tableNames).toContain("medications");
expect(tableNames).toContain("user_settings"); expect(tableNames).toContain("user_settings");
@@ -117,7 +116,7 @@ describe("Migration Script Utilities", () => {
it("should use default maxLength of 50", () => { it("should use default maxLength of 50", () => {
const longStmt = "A".repeat(100); const longStmt = "A".repeat(100);
const preview = getStatementPreview(longStmt); const preview = getStatementPreview(longStmt);
expect(preview).toBe("A".repeat(50) + "..."); expect(preview).toBe(`${"A".repeat(50)}...`);
}); });
it("should trim whitespace", () => { it("should trim whitespace", () => {
@@ -146,15 +145,78 @@ describe("Database Client Utilities", () => {
}); });
}); });
describe("getDataDir", () => {
const originalDataDir = process.env.DATA_DIR;
afterEach(() => {
if (originalDataDir === undefined) {
delete process.env.DATA_DIR;
} else {
process.env.DATA_DIR = originalDataDir;
}
});
it("should use DATA_DIR env var when set (Docker)", () => {
process.env.DATA_DIR = "/app/data";
expect(getDataDir()).toBe("/app/data");
});
it("should resolve relative DATA_DIR to absolute", () => {
process.env.DATA_DIR = "../data";
const result = getDataDir();
expect(result).not.toContain("..");
expect(result).toMatch(/\/data$/);
});
it("should detect monorepo and use ../data when in backend/ subdir", () => {
delete process.env.DATA_DIR;
// Tests run from backend/ which has ../docker-compose.yml
const result = getDataDir();
// Should resolve to the project root's data/ folder, not backend/data/
expect(result).toMatch(/\/data$/);
expect(result).not.toMatch(/backend\/data$/);
});
it("should fall back to cwd/data when not in monorepo", () => {
delete process.env.DATA_DIR;
// Use a directory that has no ../docker-compose.yml
expect(getDataDir("/tmp")).toBe("/tmp/data");
});
it("should prefer DATA_DIR over monorepo detection", () => {
process.env.DATA_DIR = "/override/data";
expect(getDataDir("/app")).toBe("/override/data");
});
});
describe("getDbPaths", () => { describe("getDbPaths", () => {
it("should return correct paths based on cwd", () => { const originalDataDir = process.env.DATA_DIR;
afterEach(() => {
if (originalDataDir === undefined) {
delete process.env.DATA_DIR;
} else {
process.env.DATA_DIR = originalDataDir;
}
});
it("should return correct paths with DATA_DIR set", () => {
process.env.DATA_DIR = "/app/data";
const paths = getDbPaths("/app"); const paths = getDbPaths("/app");
expect(paths.dataDir).toBe("/app/data"); expect(paths.dataDir).toBe("/app/data");
expect(paths.dbPath).toBe("/app/data/medassist-ng.db"); expect(paths.dbPath).toBe("/app/data/medassist-ng.db");
expect(paths.url).toBe("file:/app/data/medassist-ng.db"); expect(paths.url).toBe("file:/app/data/medassist-ng.db");
}); });
it("should return correct paths without DATA_DIR in non-monorepo dir", () => {
delete process.env.DATA_DIR;
const paths = getDbPaths("/tmp");
expect(paths.dataDir).toBe("/tmp/data");
expect(paths.dbPath).toBe("/tmp/data/medassist-ng.db");
});
it("should use process.cwd() by default", () => { it("should use process.cwd() by default", () => {
delete process.env.DATA_DIR;
const paths = getDbPaths(); const paths = getDbPaths();
expect(paths.dataDir).toContain("data"); expect(paths.dataDir).toContain("data");
expect(paths.dbPath).toContain("medassist-ng.db"); expect(paths.dbPath).toContain("medassist-ng.db");
@@ -228,7 +290,7 @@ describe("Database Client Utilities", () => {
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle%' ORDER BY name" "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle%' ORDER BY name"
); );
const tableNames = tables.rows.map(r => r.name); const tableNames = tables.rows.map((r) => r.name);
expect(tableNames).toContain("users"); expect(tableNames).toContain("users");
expect(tableNames).toContain("medications"); expect(tableNames).toContain("medications");
expect(tableNames).toContain("user_settings"); expect(tableNames).toContain("user_settings");
@@ -348,7 +410,7 @@ describe("Database Client", () => {
it("should have users table with correct columns", async () => { it("should have users table with correct columns", async () => {
const columns = await client.execute("PRAGMA table_info(users)"); const columns = await client.execute("PRAGMA table_info(users)");
const columnNames = columns.rows.map(r => r.name); const columnNames = columns.rows.map((r) => r.name);
expect(columnNames).toContain("id"); expect(columnNames).toContain("id");
expect(columnNames).toContain("username"); expect(columnNames).toContain("username");
@@ -358,7 +420,7 @@ describe("Database Client", () => {
it("should have medications table with correct columns", async () => { it("should have medications table with correct columns", async () => {
const columns = await client.execute("PRAGMA table_info(medications)"); const columns = await client.execute("PRAGMA table_info(medications)");
const columnNames = columns.rows.map(r => r.name); const columnNames = columns.rows.map((r) => r.name);
expect(columnNames).toContain("id"); expect(columnNames).toContain("id");
expect(columnNames).toContain("user_id"); expect(columnNames).toContain("user_id");
@@ -370,7 +432,7 @@ describe("Database Client", () => {
it("should have user_settings table with correct columns", async () => { it("should have user_settings table with correct columns", async () => {
const columns = await client.execute("PRAGMA table_info(user_settings)"); const columns = await client.execute("PRAGMA table_info(user_settings)");
const columnNames = columns.rows.map(r => r.name); const columnNames = columns.rows.map((r) => r.name);
expect(columnNames).toContain("id"); expect(columnNames).toContain("id");
expect(columnNames).toContain("user_id"); expect(columnNames).toContain("user_id");
@@ -381,7 +443,7 @@ describe("Database Client", () => {
it("should have refresh_tokens table", async () => { it("should have refresh_tokens table", async () => {
const columns = await client.execute("PRAGMA table_info(refresh_tokens)"); const columns = await client.execute("PRAGMA table_info(refresh_tokens)");
const columnNames = columns.rows.map(r => r.name); const columnNames = columns.rows.map((r) => r.name);
expect(columnNames).toContain("id"); expect(columnNames).toContain("id");
expect(columnNames).toContain("user_id"); expect(columnNames).toContain("user_id");
@@ -390,7 +452,7 @@ describe("Database Client", () => {
it("should have share_tokens table", async () => { it("should have share_tokens table", async () => {
const columns = await client.execute("PRAGMA table_info(share_tokens)"); const columns = await client.execute("PRAGMA table_info(share_tokens)");
const columnNames = columns.rows.map(r => r.name); const columnNames = columns.rows.map((r) => r.name);
expect(columnNames).toContain("id"); expect(columnNames).toContain("id");
expect(columnNames).toContain("token"); expect(columnNames).toContain("token");
@@ -399,7 +461,7 @@ describe("Database Client", () => {
it("should have dose_tracking table", async () => { it("should have dose_tracking table", async () => {
const columns = await client.execute("PRAGMA table_info(dose_tracking)"); const columns = await client.execute("PRAGMA table_info(dose_tracking)");
const columnNames = columns.rows.map(r => r.name); const columnNames = columns.rows.map((r) => r.name);
expect(columnNames).toContain("id"); expect(columnNames).toContain("id");
expect(columnNames).toContain("dose_id"); expect(columnNames).toContain("dose_id");
@@ -408,7 +470,7 @@ describe("Database Client", () => {
it("should have refill_history table", async () => { it("should have refill_history table", async () => {
const columns = await client.execute("PRAGMA table_info(refill_history)"); const columns = await client.execute("PRAGMA table_info(refill_history)");
const columnNames = columns.rows.map(r => r.name); const columnNames = columns.rows.map((r) => r.name);
expect(columnNames).toContain("id"); expect(columnNames).toContain("id");
expect(columnNames).toContain("medication_id"); expect(columnNames).toContain("medication_id");
@@ -571,9 +633,7 @@ describe("Database Client", () => {
it("should enforce unique constraint on username", async () => { it("should enforce unique constraint on username", async () => {
await client.execute("INSERT INTO users (username) VALUES ('testuser')"); await client.execute("INSERT INTO users (username) VALUES ('testuser')");
await expect( await expect(client.execute("INSERT INTO users (username) VALUES ('testuser')")).rejects.toThrow();
client.execute("INSERT INTO users (username) VALUES ('testuser')")
).rejects.toThrow();
}); });
it("should enforce unique constraint on refresh token_id", async () => { it("should enforce unique constraint on refresh token_id", async () => {
@@ -583,9 +643,7 @@ describe("Database Client", () => {
); );
await expect( await expect(
client.execute( client.execute("INSERT INTO refresh_tokens (user_id, token_id, expires_at) VALUES (1, 'token123', 1735689600)")
"INSERT INTO refresh_tokens (user_id, token_id, expires_at) VALUES (1, 'token123', 1735689600)"
)
).rejects.toThrow(); ).rejects.toThrow();
}); });
}); });
@@ -604,9 +662,7 @@ describe("Database Client", () => {
const result = await client.execute("SELECT id FROM users WHERE id = 1"); const result = await client.execute("SELECT id FROM users WHERE id = 1");
if (result.rows.length === 0) { if (result.rows.length === 0) {
await client.execute( await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')");
"INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')"
);
} }
const user = await client.execute("SELECT * FROM users WHERE id = 1"); const user = await client.execute("SELECT * FROM users WHERE id = 1");
@@ -616,17 +672,13 @@ describe("Database Client", () => {
}); });
it("should not duplicate default user if already exists", async () => { it("should not duplicate default user if already exists", async () => {
await client.execute( await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')");
"INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')"
);
// Check if exists before insert (mimics runtime behavior) // Check if exists before insert (mimics runtime behavior)
const result = await client.execute("SELECT id FROM users WHERE id = 1"); const result = await client.execute("SELECT id FROM users WHERE id = 1");
if (result.rows.length === 0) { if (result.rows.length === 0) {
await client.execute( await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')");
"INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')"
);
} }
// Should still have only one user // Should still have only one user
@@ -634,4 +686,373 @@ describe("Database Client", () => {
expect(users.rows).toHaveLength(1); expect(users.rows).toHaveLength(1);
}); });
}); });
describe("repairOrphanedDoseIds", () => {
let client: ReturnType<typeof createClient>;
beforeEach(async () => {
client = createClient({ url: ":memory:" });
const db = drizzle(client);
await migrate(db, { migrationsFolder });
// Create a test user
await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'testuser', 'local')");
});
it("should return 0 repairs when no data exists", async () => {
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(0);
expect(result.errors).toHaveLength(0);
});
it("should not modify dose IDs that already match the current schedule", async () => {
// Create weekly medication starting Oct 17 (Friday)
const intakes = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-17T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Weekly Med', ?, '[1]', '[7]', '["2025-10-17T08:00:00"]')`,
args: [intakes],
});
// Insert dose IDs that match the schedule (Fridays)
const fri17 = new Date(2025, 9, 17).getTime();
const fri24 = new Date(2025, 9, 24).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri24}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(0);
// Verify IDs unchanged
const doses = await client.execute("SELECT dose_id FROM dose_tracking ORDER BY dose_id");
expect(doses.rows[0].dose_id).toBe(`1-0-${fri17}`);
expect(doses.rows[1].dose_id).toBe(`1-0-${fri24}`);
});
it("should repair orphaned dose IDs when schedule shifted by 1 day", async () => {
// Current schedule: Saturdays (Oct 18)
const intakes = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Weekly Med', ?, '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [intakes],
});
// Insert orphaned dose IDs from OLD schedule (Fridays)
const fri17 = new Date(2025, 9, 17).getTime();
const fri24 = new Date(2025, 9, 24).getTime();
const fri31 = new Date(2025, 9, 31).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri24}`],
});
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri31}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(3);
expect(result.errors).toHaveLength(0);
// Verify dose IDs are now Saturdays
const sat18 = new Date(2025, 9, 18).getTime();
const sat25 = new Date(2025, 9, 25).getTime();
const nov1 = new Date(2025, 10, 1).getTime();
const doses = await client.execute("SELECT dose_id FROM dose_tracking ORDER BY dose_id");
const ids = doses.rows.map((r) => r.dose_id);
expect(ids).toContain(`1-0-${sat18}`);
expect(ids).toContain(`1-0-${sat25}`);
expect(ids).toContain(`1-0-${nov1}`);
});
it("should preserve person suffix when repairing dose IDs", async () => {
// Current schedule: Saturdays
const intakes = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: "Alice", intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Person Med', ?, '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [intakes],
});
// Orphaned dose with person suffix (from old Friday schedule)
const fri17 = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}-Alice`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(1);
// Verify person suffix preserved
const sat18 = new Date(2025, 9, 18).getTime();
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${sat18}-Alice`);
});
it("should not repair doses that are too far from any valid schedule date", async () => {
// Current schedule: biweekly (every 14 days) starting Oct 18
// halfInterval = 7 days, so doses more than 7 days from any valid date won't match
const intakes = JSON.stringify([
{ usage: 1, every: 14, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Biweekly Med', ?, '[1]', '[14]', '["2025-10-18T08:00:00"]')`,
args: [intakes],
});
// Insert dose on Oct 27 (9 days away from Oct 18, 4 days away from Nov 1)
// halfInterval = 7 days. Oct 27 is 9 days from Oct 18 (too far) and 4 days from Nov 1 (within range)
// Actually use Oct 26 which is 8 days from both (Oct 18 and Nov 1) - exactly at halfInterval + 1
// Wait: biweekly = Oct 18, Nov 1. Oct 26 is 8 days from Oct 18, 6 days from Nov 1 → 6 < 7, matches Nov 1
// Use Oct 25: 7 days from Oct 18, 7 days from Nov 1 → exactly at boundary. Use Oct 25 and check.
// The condition is dist <= halfInterval, so 7 <= 7 is true. Need dist > 7.
// Use a 28-day schedule instead: Oct 18, Nov 15. Midpoint is Nov 1-2. Nov 2 is 15 days from Oct 18, 13 from Nov 15. Both > 14. No match.
const intakes28 = JSON.stringify([
{ usage: 1, every: 28, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `UPDATE medications SET intakes_json = ?, every_json = '[28]' WHERE id = 1`,
args: [intakes28],
});
// Insert dose on Nov 2 (15 days from Oct 18, 13 days from Nov 15)
// halfInterval = 14 days. Both 15 > 14 and 13 < 14, so Nov 2 actually WOULD map to Nov 15.
// Use Nov 4: 17 days from Oct 18, 11 days from Nov 15 → 11 < 14, maps to Nov 15.
// For a 28-day interval, halfInterval = 14. A date must be > 14 days from ALL schedule dates.
// Between Oct 18 and Nov 15 (28 days), the only date > 14 from both is impossible.
// So lets use a gap: Oct 18 is the only past date for a monthly schedule.
// If we pick a date before Oct 18, like Oct 1 (17 days before Oct 18) → 17 > 14 → no match!
const oct1 = new Date(2025, 9, 1).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${oct1}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(0);
// Dose should remain unchanged
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${oct1}`);
});
it("should be idempotent - running twice produces same result", async () => {
// Current schedule: Saturdays
const intakes = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Weekly Med', ?, '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [intakes],
});
// Insert orphaned dose from Friday
const fri17 = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
// First run
const result1 = await repairOrphanedDoseIds(client);
expect(result1.repaired).toBe(1);
// Second run - should find 0 repairs (already fixed)
const result2 = await repairOrphanedDoseIds(client);
expect(result2.repaired).toBe(0);
// Verify final state
const sat18 = new Date(2025, 9, 18).getTime();
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows).toHaveLength(1);
expect(doses.rows[0].dose_id).toBe(`1-0-${sat18}`);
});
it("should handle multiple medications independently", async () => {
// Med 1: weekly Saturdays
const intakes1 = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Med 1', ?, '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [intakes1],
});
// Med 2: daily starting Oct 20 (valid IDs, no repair needed)
const intakes2 = JSON.stringify([
{ usage: 1, every: 1, start: "2025-10-20T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (2, 1, 'Med 2', ?, '[1]', '[1]', '["2025-10-20T08:00:00"]')`,
args: [intakes2],
});
// Med 1: orphaned Friday dose
const fri17 = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
// Med 2: valid daily dose
const oct20 = new Date(2025, 9, 20).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`2-0-${oct20}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(1); // Only med 1 dose repaired
// Med 2 dose should be unchanged
const med2Doses = await client.execute("SELECT dose_id FROM dose_tracking WHERE dose_id LIKE '2-%'");
expect(med2Doses.rows[0].dose_id).toBe(`2-0-${oct20}`);
});
it("should handle legacy format (no intakes_json, uses usage/every/start arrays)", async () => {
// Medication with only legacy fields (intakes_json is '[]')
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Legacy Med', '[]', '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [],
});
// Orphaned Friday dose
const fri17 = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(1);
// Verify mapped to Saturday
const sat18 = new Date(2025, 9, 18).getTime();
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${sat18}`);
});
});
describe("repairTrailingHyphenDoseIds", () => {
let client: ReturnType<typeof createClient>;
beforeEach(async () => {
client = createClient({ url: ":memory:" });
const db = drizzle(client);
await migrate(db, { migrationsFolder });
await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'testuser', 'local')");
});
it("should return 0 repairs when no dose IDs have trailing hyphens", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(0);
expect(result.errors).toHaveLength(0);
});
it("should strip trailing hyphen from dose IDs", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}-`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(1);
expect(result.errors).toHaveLength(0);
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${ts}`);
});
it("should not modify dose IDs with valid person suffixes", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}-Alice`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(0);
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${ts}-Alice`);
});
it("should handle multiple trailing hyphens", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}--`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(1);
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${ts}`);
});
it("should repair multiple affected rows at once", async () => {
const ts1 = new Date(2025, 9, 17).getTime();
const ts2 = new Date(2025, 9, 24).getTime();
const ts3 = new Date(2025, 9, 31).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?), (1, ?), (1, ?)",
args: [`1-0-${ts1}-`, `2-0-${ts2}-`, `1-0-${ts3}`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(2); // Only 2 had trailing hyphens
expect(result.errors).toHaveLength(0);
const doses = await client.execute("SELECT dose_id FROM dose_tracking ORDER BY dose_id");
const ids = doses.rows.map((r) => r.dose_id);
expect(ids).toContain(`1-0-${ts1}`);
expect(ids).toContain(`2-0-${ts2}`);
expect(ids).toContain(`1-0-${ts3}`);
});
it("should be idempotent - running twice has no effect the second time", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}-`],
});
const result1 = await repairTrailingHyphenDoseIds(client);
expect(result1.repaired).toBe(1);
const result2 = await repairTrailingHyphenDoseIds(client);
expect(result2.repaired).toBe(0);
});
});
}); });
+53 -11
View File
@@ -2,15 +2,8 @@
* Tests for /doses/taken API endpoints. * Tests for /doses/taken API endpoints.
* Tests marking doses as taken, listing taken doses, and unmarking. * Tests marking doses as taken, listing taken doses, and unmarking.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { import { buildTestApp, clearTestData, closeTestApp, createTestUser, type TestContext } from "./setup.js";
buildTestApp,
closeTestApp,
clearTestData,
createTestUser,
createTestMedication,
TestContext,
} from "./setup.js";
// ============================================================================= // =============================================================================
// Route Registration // Route Registration
@@ -22,7 +15,7 @@ async function registerDoseRoutes(ctx: TestContext) {
const { app, client } = ctx; const { app, client } = ctx;
// GET /doses/taken - List all taken doses // GET /doses/taken - List all taken doses
app.get("/doses/taken", async (request, reply) => { app.get("/doses/taken", async (_request, _reply) => {
// In test mode, use user ID 1 (will be created in tests) // In test mode, use user ID 1 (will be created in tests)
const userId = 1; const userId = 1;
@@ -69,14 +62,26 @@ async function registerDoseRoutes(ctx: TestContext) {
}); });
// DELETE /doses/taken/:doseId - Unmark a dose // DELETE /doses/taken/:doseId - Unmark a dose
app.delete<{ Params: { doseId: string } }>("/doses/taken/:doseId", async (request, reply) => { app.delete<{ Params: { doseId: string } }>("/doses/taken/:doseId", async (request, _reply) => {
const userId = 1; const userId = 1;
const { doseId } = request.params; const { doseId } = request.params;
// Check if this dose was also dismissed
const existing = await client.execute({
sql: `SELECT id, dismissed FROM dose_tracking WHERE user_id = ? AND dose_id = ?`,
args: [userId, doseId],
});
if (existing.rows.length > 0 && existing.rows[0].dismissed) {
// Already dismissed - keep the record as-is (don't delete)
// The dose stays dismissed, we just ignore the undo request
} else {
// Not dismissed - delete the record entirely
await client.execute({ await client.execute({
sql: `DELETE FROM dose_tracking WHERE user_id = ? AND dose_id = ?`, sql: `DELETE FROM dose_tracking WHERE user_id = ? AND dose_id = ?`,
args: [userId, doseId], args: [userId, doseId],
}); });
}
return { success: true }; return { success: true };
}); });
@@ -346,6 +351,43 @@ describe("Dose Tracking API", () => {
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ success: true }); expect(response.json()).toEqual({ success: true });
}); });
it("should preserve dismissed status when unmarking a dose", async () => {
const doseId = "1-0-1735344000000";
// First dismiss the dose
await ctx.app.inject({
method: "POST",
url: "/doses/dismiss",
payload: { doseIds: [doseId] },
});
// Verify it's dismissed
let result = await ctx.client.execute({
sql: `SELECT dismissed, taken_at FROM dose_tracking WHERE dose_id = ?`,
args: [doseId],
});
expect(result.rows[0].dismissed).toBe(1);
const originalTakenAt = result.rows[0].taken_at;
// Now try to unmark it (undo) - should keep the dismissed record
const response = await ctx.app.inject({
method: "DELETE",
url: `/doses/taken/${encodeURIComponent(doseId)}`,
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ success: true });
// Verify the record still exists and is still dismissed
result = await ctx.client.execute({
sql: `SELECT dose_id, dismissed, taken_at FROM dose_tracking WHERE dose_id = ?`,
args: [doseId],
});
expect(result.rows.length).toBe(1);
expect(result.rows[0].dismissed).toBe(1);
expect(result.rows[0].taken_at).toBe(originalTakenAt); // unchanged
});
}); });
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+564 -27
View File
@@ -2,14 +2,14 @@
* E2E Tests using the real routes against in-memory SQLite. * E2E Tests using the real routes against in-memory SQLite.
* These tests import the actual route handlers for real coverage. * These tests import the actual route handlers for real coverage.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from "vitest";
import Fastify, { FastifyInstance } from "fastify";
import cookie from "@fastify/cookie"; import cookie from "@fastify/cookie";
import jwt from "@fastify/jwt"; import jwt from "@fastify/jwt";
import sensible from "@fastify/sensible";
import fastifyMultipart from "@fastify/multipart"; import fastifyMultipart from "@fastify/multipart";
import { createClient, Client } from "@libsql/client"; import sensible from "@fastify/sensible";
import { drizzle, LibSQLDatabase } from "drizzle-orm/libsql"; import type { Client } from "@libsql/client";
import Fastify, { type FastifyInstance } from "fastify";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
// Use vi.hoisted to create the db BEFORE mocks are set up // Use vi.hoisted to create the db BEFORE mocks are set up
const { testClient, testDb } = vi.hoisted(() => { const { testClient, testDb } = vi.hoisted(() => {
@@ -81,20 +81,25 @@ async function createSchema(client: Client) {
name text NOT NULL, name text NOT NULL,
generic_name text, generic_name text,
taken_by_json text NOT NULL DEFAULT '[]', taken_by_json text NOT NULL DEFAULT '[]',
package_type text NOT NULL DEFAULT 'blister',
pack_count integer NOT NULL DEFAULT 1, pack_count integer NOT NULL DEFAULT 1,
blisters_per_pack integer NOT NULL DEFAULT 1, blisters_per_pack integer NOT NULL DEFAULT 1,
pills_per_blister integer NOT NULL DEFAULT 1, pills_per_blister integer NOT NULL DEFAULT 1,
total_pills integer,
loose_tablets integer NOT NULL DEFAULT 0, loose_tablets integer NOT NULL DEFAULT 0,
stock_adjustment integer NOT NULL DEFAULT 0, stock_adjustment integer NOT NULL DEFAULT 0,
last_stock_correction_at integer, last_stock_correction_at integer,
pill_weight_mg integer, pill_weight_mg integer,
dose_unit text DEFAULT 'mg',
usage_json text NOT NULL DEFAULT '[]', usage_json text NOT NULL DEFAULT '[]',
every_json text NOT NULL DEFAULT '[]', every_json text NOT NULL DEFAULT '[]',
start_json text NOT NULL DEFAULT '[]', start_json text NOT NULL DEFAULT '[]',
intakes_json text NOT NULL DEFAULT '[]',
image_url text, image_url text,
expiry_date text, expiry_date text,
notes text, notes text,
intake_reminders_enabled integer NOT NULL DEFAULT 0, intake_reminders_enabled integer NOT NULL DEFAULT 0,
dismissed_until text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')), updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`, )`,
@@ -124,6 +129,8 @@ async function createSchema(client: Client) {
last_auto_email_sent text, last_auto_email_sent text,
last_notification_type text, last_notification_type text,
last_notification_channel text, last_notification_channel text,
last_reminder_med_name text,
last_reminder_taken_by text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')), updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`, )`,
@@ -173,7 +180,7 @@ async function clearData(client: Client) {
await client.execute("DELETE FROM sqlite_sequence"); await client.execute("DELETE FROM sqlite_sequence");
} }
async function createUser(client: Client, username: string): Promise<number> { async function _createUser(client: Client, username: string): Promise<number> {
const result = await client.execute({ const result = await client.execute({
sql: `INSERT INTO users (username, auth_provider) VALUES (?, 'local') RETURNING id`, sql: `INSERT INTO users (username, auth_provider) VALUES (?, 'local') RETURNING id`,
args: [username], args: [username],
@@ -181,12 +188,7 @@ async function createUser(client: Client, username: string): Promise<number> {
return result.rows[0].id as number; return result.rows[0].id as number;
} }
async function createMedication( async function createMedication(client: Client, userId: number, name: string, takenBy: string[]): Promise<number> {
client: Client,
userId: number,
name: string,
takenBy: string[]
): Promise<number> {
const result = await client.execute({ const result = await client.execute({
sql: `INSERT INTO medications (user_id, name, taken_by_json, usage_json, every_json, start_json) sql: `INSERT INTO medications (user_id, name, taken_by_json, usage_json, every_json, start_json)
VALUES (?, ?, ?, '[1]', '[1]', '["2025-01-01T08:00:00.000Z"]') RETURNING id`, VALUES (?, ?, ?, '[1]', '[1]', '["2025-01-01T08:00:00.000Z"]') RETURNING id`,
@@ -195,12 +197,7 @@ async function createMedication(
return result.rows[0].id as number; return result.rows[0].id as number;
} }
async function createShareToken( async function createShareToken(client: Client, userId: number, takenBy: string, token: string): Promise<void> {
client: Client,
userId: number,
takenBy: string,
token: string
): Promise<void> {
await client.execute({ await client.execute({
sql: `INSERT INTO share_tokens (user_id, token, taken_by, schedule_days) VALUES (?, ?, ?, 30)`, sql: `INSERT INTO share_tokens (user_id, token, taken_by, schedule_days) VALUES (?, ?, ?, 30)`,
args: [userId, token, takenBy], args: [userId, token, takenBy],
@@ -426,9 +423,7 @@ describe("E2E Tests with Real Routes", () => {
expiryDate: "2026-12-31", expiryDate: "2026-12-31",
notes: "Take with food", notes: "Take with food",
intakeRemindersEnabled: true, intakeRemindersEnabled: true,
blisters: [ blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" },
],
}; };
it("should create medication using real route", async () => { it("should create medication using real route", async () => {
@@ -918,7 +913,7 @@ describe("E2E Tests with Real Routes", () => {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
describe("Real /medications routes - edge cases", () => { describe("Real /medications routes - edge cases", () => {
const validMedication = { const _validMedication = {
name: "Aspirin", name: "Aspirin",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }], blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
}; };
@@ -1735,6 +1730,304 @@ describe("E2E Tests with Real Routes", () => {
}); });
}); });
// ---------------------------------------------------------------------------
// Real Stock Correction (PATCH /medications/:id/stock-adjustment) Tests
// ---------------------------------------------------------------------------
describe("Real /medications/:id/stock-adjustment routes", () => {
it("should update stockAdjustment and lastStockCorrectionAt", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Stock Correction Med",
packCount: 1,
blistersPerPack: 14,
pillsPerBlister: 14,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
expect(createResponse.statusCode).toBe(200);
const medId = createResponse.json().id;
// Correct stock: set adjustment to -83 (196 base - 83 = 113 pills)
const response = await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -83 },
});
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data.stockAdjustment).toBe(-83);
expect(data.lastStockCorrectionAt).toBeTruthy();
expect(data.updatedAt).toBeTruthy();
});
it("should persist stockAdjustment in GET /medications", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Persist Stock Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
// Apply stock correction
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -7 },
});
// Verify via GET
const getResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(getResponse.statusCode).toBe(200);
const meds = getResponse.json();
const med = meds.find((m: any) => m.id === medId);
expect(med).toBeDefined();
expect(med.stockAdjustment).toBe(-7);
expect(med.lastStockCorrectionAt).toBeTruthy();
});
it("should not reset stockAdjustment when editing medication via PUT", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Keep Adjustment Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
// Set stock adjustment
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -5 },
});
// Edit the medication (change name) - should preserve stockAdjustment
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Renamed Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
// Verify stockAdjustment is preserved
const getResponse = await app.inject({
method: "GET",
url: "/medications",
});
const med = getResponse.json().find((m: any) => m.id === medId);
expect(med.name).toBe("Renamed Med");
expect(med.stockAdjustment).toBe(-5);
});
it("should return 400 for non-numeric stockAdjustment", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Bad Adjustment Med",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
const response = await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: "not-a-number" },
});
expect(response.statusCode).toBe(400);
});
it("should return 404 for non-existent medication", async () => {
const response = await app.inject({
method: "PATCH",
url: "/medications/99999/stock-adjustment",
payload: { stockAdjustment: 5 },
});
expect(response.statusCode).toBe(404);
});
it("should return 400 for invalid medication id", async () => {
const response = await app.inject({
method: "PATCH",
url: "/medications/invalid/stock-adjustment",
payload: { stockAdjustment: 5 },
});
expect(response.statusCode).toBe(400);
});
it("should reset stockAdjustment when stock fields change via PUT", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Reset Adj Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
// Set stock adjustment to -10
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -10 },
});
// Verify adjustment is set
let getMeds = await app.inject({ method: "GET", url: "/medications" });
let med = getMeds.json().find((m: any) => m.id === medId);
expect(med.stockAdjustment).toBe(-10);
// Edit medication with CHANGED stock fields (packCount 1 → 2)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Reset Adj Med",
packCount: 2,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
// stockAdjustment should be reset to 0
getMeds = await app.inject({ method: "GET", url: "/medications" });
med = getMeds.json().find((m: any) => m.id === medId);
expect(med.stockAdjustment).toBe(0);
expect(med.lastStockCorrectionAt).toBeTruthy();
});
it("should preserve stockAdjustment when only non-stock fields change via PUT", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Preserve Adj Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
// Set stock adjustment
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -5 },
});
// Edit only non-stock fields (name, notes)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Renamed Preserve Med",
notes: "Updated notes",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
// stockAdjustment should be preserved
const getMeds = await app.inject({ method: "GET", url: "/medications" });
const med = getMeds.json().find((m: any) => m.id === medId);
expect(med.name).toBe("Renamed Preserve Med");
expect(med.stockAdjustment).toBe(-5);
});
it("should not count phantom consumption in planner after stock correction", async () => {
// Create medication: 1 pack × 14 blisters × 14 pills = 196 pills total
// Schedule: 1 pill daily starting far in the past
const farPast = new Date("2024-01-01T08:00:00.000Z");
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Planner Phantom Med",
packCount: 1,
blistersPerPack: 14,
pillsPerBlister: 14,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: farPast.toISOString() }],
},
});
const medId = createResponse.json().id;
// Correct stock to 113 pills (196 base - 83 = 113)
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -83 },
});
// Query planner immediately - stock should be ~113 (not reduced by phantom dose)
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const nextWeek = new Date();
nextWeek.setDate(nextWeek.getDate() + 7);
const response = await app.inject({
method: "POST",
url: "/medications/usage",
payload: {
startDate: tomorrow.toISOString(),
endDate: nextWeek.toISOString(),
},
});
expect(response.statusCode).toBe(200);
const data = response.json();
const med = data.find((m: any) => m.medicationId === medId);
expect(med).toBeDefined();
// Total should be very close to 113 (not 112 or lower from phantom consumption)
// Allow up to 1 pill of natural consumption (test runs fast, but at most 1 day could pass)
expect(med.totalPills).toBeGreaterThanOrEqual(112);
expect(med.totalPills).toBeLessThanOrEqual(113);
});
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Real Export/Import Routes Tests // Real Export/Import Routes Tests
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -1833,12 +2126,10 @@ describe("E2E Tests with Real Routes", () => {
looseTablets: 7, looseTablets: 7,
}, },
pillWeightMg: 250, pillWeightMg: 250,
schedules: [ schedules: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z", remind: true }],
{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z", remind: true }
],
notes: "Imported notes", notes: "Imported notes",
intakeRemindersEnabled: true, intakeRemindersEnabled: true,
} },
], ],
}; };
@@ -1901,7 +2192,7 @@ describe("E2E Tests with Real Routes", () => {
name: "Imported Med", name: "Imported Med",
inventory: { packCount: 10, blistersPerPack: 2, pillsPerBlister: 14, looseTablets: 0 }, inventory: { packCount: 10, blistersPerPack: 2, pillsPerBlister: 14, looseTablets: 0 },
schedules: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }], schedules: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
} },
], ],
}; };
@@ -1923,4 +2214,250 @@ describe("E2E Tests with Real Routes", () => {
expect(medsResponse.json()[0].packCount).toBe(10); expect(medsResponse.json()[0].packCount).toBe(10);
}); });
}); });
// ---------------------------------------------------------------------------
// Package Type (bottle vs blister) Tests
// ---------------------------------------------------------------------------
describe("Package type handling (bottle vs blister)", () => {
const bottleMedication = {
name: "Vitamin D Drops",
packageType: "bottle",
packCount: 0,
blistersPerPack: 1,
pillsPerBlister: 1,
looseTablets: 120,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
};
const blisterMedication = {
name: "Aspirin Blister",
packageType: "blister",
packCount: 2,
blistersPerPack: 3,
pillsPerBlister: 10,
looseTablets: 5,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
};
it("should create and return bottle type medication", async () => {
const response = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data.packageType).toBe("bottle");
expect(data.looseTablets).toBe(120);
});
it("should return packageType in shared schedule for bottle type", async () => {
// Create bottle medication with takenBy
await app.inject({
method: "POST",
url: "/medications",
payload: { ...bottleMedication, takenBy: ["Daniel"] },
});
// Create share token
const shareResponse = await app.inject({
method: "POST",
url: "/share",
payload: { takenBy: "Daniel", scheduleDays: 30 },
});
expect(shareResponse.statusCode).toBe(200);
const { token } = shareResponse.json();
// Get shared schedule
const scheduleResponse = await app.inject({
method: "GET",
url: `/share/${token}`,
});
expect(scheduleResponse.statusCode).toBe(200);
const data = scheduleResponse.json();
expect(data.medications).toHaveLength(1);
expect(data.medications[0].packageType).toBe("bottle");
// Bottle totalPills = looseTablets + stockAdjustment (no blister math)
expect(data.medications[0].totalPills).toBe(120);
});
it("should calculate correct totalPills for shared blister medication", async () => {
await app.inject({
method: "POST",
url: "/medications",
payload: { ...blisterMedication, takenBy: ["Daniel"] },
});
const shareResponse = await app.inject({
method: "POST",
url: "/share",
payload: { takenBy: "Daniel", scheduleDays: 30 },
});
const { token } = shareResponse.json();
const scheduleResponse = await app.inject({
method: "GET",
url: `/share/${token}`,
});
expect(scheduleResponse.statusCode).toBe(200);
const data = scheduleResponse.json();
expect(data.medications).toHaveLength(1);
expect(data.medications[0].packageType).toBe("blister");
// Blister totalPills = 2 * 3 * 10 + 5 = 65
expect(data.medications[0].totalPills).toBe(65);
});
it("should calculate correct refill totalPillsAdded for bottle type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
const medId = createResponse.json().id;
// Refill bottle: only loosePillsAdded matters, packs should add 0 pills
const refillResponse = await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 0, loosePillsAdded: 30 },
});
expect(refillResponse.statusCode).toBe(200);
const data = refillResponse.json();
expect(data.refill.totalPillsAdded).toBe(30);
// newStock.totalPills should be looseTablets only (no blister math)
expect(data.newStock.totalPills).toBe(150); // 120 + 30
});
it("should calculate correct refill totalPillsAdded for blister type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: blisterMedication,
});
const medId = createResponse.json().id;
// Refill blister: 1 pack = 3 blisters * 10 pills = 30 pills + 5 loose
const refillResponse = await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 1, loosePillsAdded: 5 },
});
expect(refillResponse.statusCode).toBe(200);
const data = refillResponse.json();
expect(data.refill.totalPillsAdded).toBe(35); // 1*30 + 5
});
it("should return correct totalPillsAdded in refill history for bottle type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
const medId = createResponse.json().id;
// Add refill
await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 0, loosePillsAdded: 25 },
});
// Get refill history
const historyResponse = await app.inject({
method: "GET",
url: `/medications/${medId}/refills`,
});
expect(historyResponse.statusCode).toBe(200);
const refills = historyResponse.json();
expect(refills).toHaveLength(1);
// For bottle type, totalPillsAdded = loosePillsAdded only
expect(refills[0].totalPillsAdded).toBe(25);
});
it("should export and import bottle type medication correctly", async () => {
// Create bottle medication
await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
// Export
const exportResponse = await app.inject({
method: "GET",
url: "/export",
});
expect(exportResponse.statusCode).toBe(200);
const exportData = exportResponse.json();
expect(exportData.medications).toHaveLength(1);
expect(exportData.medications[0].inventory.packageType).toBe("bottle");
expect(exportData.medications[0].inventory.looseTablets).toBe(120);
// Clear and re-import
await clearData(testClient);
await testClient.execute(
"INSERT INTO users (id, username, auth_provider) VALUES (999999999, '__anonymous__', 'anonymous')"
);
const importResponse = await app.inject({
method: "POST",
url: "/import",
payload: exportData,
});
expect(importResponse.statusCode).toBe(200);
expect(importResponse.json().success).toBe(true);
// Verify imported medication has correct packageType
const medsResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(medsResponse.json()).toHaveLength(1);
const med = medsResponse.json()[0];
expect(med.name).toBe("Vitamin D Drops");
expect(med.packageType).toBe("bottle");
expect(med.looseTablets).toBe(120);
});
it("should default to blister when importing without packageType", async () => {
const importData = {
version: "1.0",
exportedAt: new Date().toISOString(),
medications: [
{
_exportId: "med-1",
name: "Old Export Med",
inventory: { packCount: 2, blistersPerPack: 3, pillsPerBlister: 10, looseTablets: 0 },
schedules: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
],
};
const importResponse = await app.inject({
method: "POST",
url: "/import",
payload: importData,
});
expect(importResponse.statusCode).toBe(200);
const medsResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(medsResponse.json()).toHaveLength(1);
expect(medsResponse.json()[0].packageType).toBe("blister");
});
});
}); });
+29 -8
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { z } from "zod"; import { z } from "zod";
// Mock process.exit to prevent tests from exiting // Mock process.exit to prevent tests from exiting
@@ -8,23 +8,44 @@ vi.spyOn(process, "exit").mockImplementation(mockExit as any);
// Re-create the schema from env.ts for testing // Re-create the schema from env.ts for testing
const EnvSchema = z.object({ const EnvSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("production"), NODE_ENV: z.enum(["development", "production", "test"]).default("production"),
PORT: z.string().transform((v) => parseInt(v, 10)).default("3000"), PORT: z
.string()
.transform((v) => parseInt(v, 10))
.default("3000"),
CORS_ORIGINS: z.string().default("http://localhost:5173,http://localhost:4173"), CORS_ORIGINS: z.string().default("http://localhost:5173,http://localhost:4173"),
LOG_LEVEL: z.string().default("info"), LOG_LEVEL: z.string().default("info"),
AUTH_ENABLED: z.string().transform((v) => v === "true").default("false"), AUTH_ENABLED: z
REGISTRATION_ENABLED: z.string().transform((v) => v === "true").default("false"), .string()
.transform((v) => v === "true")
.default("false"),
REGISTRATION_ENABLED: z
.string()
.transform((v) => v === "true")
.default("false"),
JWT_SECRET: z.string().min(10).optional(), JWT_SECRET: z.string().min(10).optional(),
REFRESH_SECRET: z.string().min(10).optional(), REFRESH_SECRET: z.string().min(10).optional(),
COOKIE_SECRET: z.string().min(10).optional(), COOKIE_SECRET: z.string().min(10).optional(),
ACCESS_TOKEN_TTL_MINUTES: z.string().transform((v) => parseInt(v, 10)).default("15"), ACCESS_TOKEN_TTL_MINUTES: z
REFRESH_TOKEN_TTL_DAYS: z.string().transform((v) => parseInt(v, 10)).default("7"), .string()
OIDC_ENABLED: z.string().transform((v) => v === "true").default("false"), .transform((v) => parseInt(v, 10))
.default("15"),
REFRESH_TOKEN_TTL_DAYS: z
.string()
.transform((v) => parseInt(v, 10))
.default("7"),
OIDC_ENABLED: z
.string()
.transform((v) => v === "true")
.default("false"),
OIDC_ISSUER_URL: z.string().url().optional(), OIDC_ISSUER_URL: z.string().url().optional(),
OIDC_CLIENT_ID: z.string().optional(), OIDC_CLIENT_ID: z.string().optional(),
OIDC_CLIENT_SECRET: z.string().optional(), OIDC_CLIENT_SECRET: z.string().optional(),
OIDC_REDIRECT_URI: z.string().url().optional(), OIDC_REDIRECT_URI: z.string().url().optional(),
OIDC_SCOPES: z.string().default("openid profile email"), OIDC_SCOPES: z.string().default("openid profile email"),
OIDC_AUTO_CREATE_USERS: z.string().transform((v) => v === "true").default("true"), OIDC_AUTO_CREATE_USERS: z
.string()
.transform((v) => v === "true")
.default("true"),
OIDC_USERNAME_CLAIM: z.string().default("preferred_username"), OIDC_USERNAME_CLAIM: z.string().default("preferred_username"),
OIDC_PROVIDER_NAME: z.string().default("SSO"), OIDC_PROVIDER_NAME: z.string().default("SSO"),
}); });
+13 -21
View File
@@ -2,16 +2,17 @@
* Tests for /export and /import API endpoints. * Tests for /export and /import API endpoints.
* Tests export/import functionality with schema-independent format. * Tests export/import functionality with schema-independent format.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest";
import { randomBytes } from "node:crypto";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { import {
buildTestApp, buildTestApp,
closeTestApp,
clearTestData, clearTestData,
createTestUser, closeTestApp,
createTestMedication, createTestMedication,
TestContext, createTestUser,
type TestContext,
} from "./setup.js"; } from "./setup.js";
import { randomBytes } from "crypto";
// ============================================================================= // =============================================================================
// Route Registration (simplified test routes) // Route Registration (simplified test routes)
@@ -36,7 +37,7 @@ async function registerExportRoutes(ctx: TestContext) {
} }
// GET /export // GET /export
app.get<{ Querystring: { includeSensitive?: string } }>("/export", async (request, reply) => { app.get<{ Querystring: { includeSensitive?: string } }>("/export", async (request, _reply) => {
const includeSensitive = request.query.includeSensitive === "true"; const includeSensitive = request.query.includeSensitive === "true";
// Load medications // Load medications
@@ -86,7 +87,7 @@ async function registerExportRoutes(ctx: TestContext) {
medicationRef: exportId, medicationRef: exportId,
scheduleIndex: parseInt(parts[1], 10), scheduleIndex: parseInt(parts[1], 10),
scheduledTime: new Date(parseInt(parts[2], 10)).toISOString(), scheduledTime: new Date(parseInt(parts[2], 10)).toISOString(),
takenAt: d.taken_at ? new Date(d.taken_at as number * 1000).toISOString() : new Date().toISOString(), takenAt: d.taken_at ? new Date((d.taken_at as number) * 1000).toISOString() : new Date().toISOString(),
markedBy: d.marked_by, markedBy: d.marked_by,
}; };
}) })
@@ -98,7 +99,7 @@ async function registerExportRoutes(ctx: TestContext) {
args: [userId], args: [userId],
}); });
let settings = undefined; let settings;
if (settingsResult.rows.length > 0) { if (settingsResult.rows.length > 0) {
const s = settingsResult.rows[0]; const s = settingsResult.rows[0];
settings = { settings = {
@@ -133,7 +134,7 @@ async function registerExportRoutes(ctx: TestContext) {
const shareLinks = sharesResult.rows.map((s) => ({ const shareLinks = sharesResult.rows.map((s) => ({
takenBy: s.taken_by, takenBy: s.taken_by,
scheduleDays: s.schedule_days ?? 30, scheduleDays: s.schedule_days ?? 30,
expiresAt: s.expires_at ? new Date(s.expires_at as number * 1000).toISOString() : null, expiresAt: s.expires_at ? new Date((s.expires_at as number) * 1000).toISOString() : null,
regenerateToken: true, regenerateToken: true,
})); }));
@@ -210,12 +211,7 @@ async function registerExportRoutes(ctx: TestContext) {
await client.execute({ await client.execute({
sql: `INSERT INTO dose_tracking (user_id, dose_id, taken_at, marked_by) VALUES (?, ?, ?, ?)`, sql: `INSERT INTO dose_tracking (user_id, dose_id, taken_at, marked_by) VALUES (?, ?, ?, ?)`,
args: [ args: [userId, doseId, Math.floor(new Date(dose.takenAt).getTime() / 1000), dose.markedBy || null],
userId,
doseId,
Math.floor(new Date(dose.takenAt).getTime() / 1000),
dose.markedBy || null,
],
}); });
} }
@@ -518,9 +514,7 @@ describe("Export/Import API", () => {
looseTablets: 5, looseTablets: 5,
}, },
pillWeightMg: 250, pillWeightMg: 250,
schedules: [ schedules: [{ usage: 1, every: 1, start: "2025-01-15T08:00:00.000Z", remind: true }],
{ usage: 1, every: 1, start: "2025-01-15T08:00:00.000Z", remind: true },
],
expiryDate: "2027-12-31", expiryDate: "2027-12-31",
notes: "Test notes", notes: "Test notes",
intakeRemindersEnabled: true, intakeRemindersEnabled: true,
@@ -820,9 +814,7 @@ describe("Export/Import API", () => {
pillsPerBlister: 10, pillsPerBlister: 10,
looseTablets: 0, looseTablets: 0,
}, },
schedules: [ schedules: [{ usage: 1, every: 1, start: "2025-01-15T08:00:00.000Z" }],
{ usage: 1, every: 1, start: "2025-01-15T08:00:00.000Z" },
],
}, },
], ],
doseHistory: [], doseHistory: [],
+442 -31
View File
@@ -2,14 +2,14 @@
* Integration Tests - Testing interactions between multiple routes/features * Integration Tests - Testing interactions between multiple routes/features
* These tests verify critical app behavior that spans multiple components. * These tests verify critical app behavior that spans multiple components.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from "vitest";
import Fastify, { FastifyInstance } from "fastify";
import cookie from "@fastify/cookie"; import cookie from "@fastify/cookie";
import jwt from "@fastify/jwt"; import jwt from "@fastify/jwt";
import sensible from "@fastify/sensible";
import fastifyMultipart from "@fastify/multipart"; import fastifyMultipart from "@fastify/multipart";
import { createClient, Client } from "@libsql/client"; import sensible from "@fastify/sensible";
import { drizzle } from "drizzle-orm/libsql"; import type { Client } from "@libsql/client";
import Fastify, { type FastifyInstance } from "fastify";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
// Use vi.hoisted to create the db BEFORE mocks are set up // Use vi.hoisted to create the db BEFORE mocks are set up
const { testClient, testDb } = vi.hoisted(() => { const { testClient, testDb } = vi.hoisted(() => {
@@ -76,20 +76,25 @@ async function createSchema(client: Client) {
name text NOT NULL, name text NOT NULL,
generic_name text, generic_name text,
taken_by_json text NOT NULL DEFAULT '[]', taken_by_json text NOT NULL DEFAULT '[]',
package_type text NOT NULL DEFAULT 'blister',
pack_count integer NOT NULL DEFAULT 1, pack_count integer NOT NULL DEFAULT 1,
blisters_per_pack integer NOT NULL DEFAULT 1, blisters_per_pack integer NOT NULL DEFAULT 1,
pills_per_blister integer NOT NULL DEFAULT 1, pills_per_blister integer NOT NULL DEFAULT 1,
total_pills integer,
loose_tablets integer NOT NULL DEFAULT 0, loose_tablets integer NOT NULL DEFAULT 0,
stock_adjustment integer NOT NULL DEFAULT 0, stock_adjustment integer NOT NULL DEFAULT 0,
last_stock_correction_at integer, last_stock_correction_at integer,
pill_weight_mg integer, pill_weight_mg integer,
dose_unit text DEFAULT 'mg',
usage_json text NOT NULL DEFAULT '[]', usage_json text NOT NULL DEFAULT '[]',
every_json text NOT NULL DEFAULT '[]', every_json text NOT NULL DEFAULT '[]',
start_json text NOT NULL DEFAULT '[]', start_json text NOT NULL DEFAULT '[]',
intakes_json text NOT NULL DEFAULT '[]',
image_url text, image_url text,
expiry_date text, expiry_date text,
notes text, notes text,
intake_reminders_enabled integer NOT NULL DEFAULT 0, intake_reminders_enabled integer NOT NULL DEFAULT 0,
dismissed_until text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')), updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`, )`,
@@ -119,6 +124,8 @@ async function createSchema(client: Client) {
last_auto_email_sent text, last_auto_email_sent text,
last_notification_type text, last_notification_type text,
last_notification_channel text, last_notification_channel text,
last_reminder_med_name text,
last_reminder_taken_by text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')), updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`, )`,
@@ -163,7 +170,7 @@ async function clearData(client: Client) {
describe("Integration Tests", () => { describe("Integration Tests", () => {
let app: FastifyInstance; let app: FastifyInstance;
const userId = 999999999; const _userId = 999999999;
beforeAll(async () => { beforeAll(async () => {
await createSchema(testClient); await createSchema(testClient);
@@ -358,6 +365,196 @@ describe("Integration Tests", () => {
}); });
}); });
// ---------------------------------------------------------------------------
// Dose ID Migration on Schedule Changes
// ---------------------------------------------------------------------------
describe("Dose ID migration when schedule changes", () => {
it("should migrate dose IDs when weekly start day changes", async () => {
// Create a weekly medication starting Friday Oct 17
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Weekly Med",
blisters: [{ usage: 1, every: 7, start: "2025-10-17T08:00:00" }],
},
});
const medId = createRes.json().id;
// Mark doses for Fridays (Oct 17, Oct 24, Oct 31)
const fri17 = new Date(2025, 9, 17).getTime(); // Oct 17
const fri24 = new Date(2025, 9, 24).getTime(); // Oct 24
const fri31 = new Date(2025, 9, 31).getTime(); // Oct 31
for (const ts of [fri17, fri24, fri31]) {
await app.inject({
method: "POST",
url: "/doses/taken",
payload: { doseId: `${medId}-0-${ts}` },
});
}
// Verify 3 doses exist
const before = await testClient.execute({
sql: `SELECT COUNT(*) as count FROM dose_tracking WHERE dose_id LIKE ?`,
args: [`${medId}-%`],
});
expect(before.rows[0].count).toBe(3);
// Change start to Saturday Oct 18 (shifts all future and past IDs)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Weekly Med",
blisters: [{ usage: 1, every: 7, start: "2025-10-18T08:00:00" }],
},
});
// Doses should be migrated to Saturday dates
const sat18 = new Date(2025, 9, 18).getTime(); // Oct 18
const sat25 = new Date(2025, 9, 25).getTime(); // Oct 25
const nov1 = new Date(2025, 10, 1).getTime(); // Nov 1
const after = await testClient.execute({
sql: `SELECT dose_id FROM dose_tracking WHERE dose_id LIKE ? ORDER BY dose_id`,
args: [`${medId}-%`],
});
expect(after.rows.length).toBe(3);
const ids = after.rows.map((r: { dose_id: string }) => r.dose_id);
expect(ids).toContain(`${medId}-0-${sat18}`);
expect(ids).toContain(`${medId}-0-${sat25}`);
expect(ids).toContain(`${medId}-0-${nov1}`);
});
it("should migrate dose IDs with person suffix when schedule changes", async () => {
// Create weekly medication with takenBy person
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Person Med",
intakes: [{ usage: 1, every: 7, start: "2025-10-17T08:00:00", takenBy: "Alice" }],
},
});
const medId = createRes.json().id;
// Mark dose with person suffix
const fri17 = new Date(2025, 9, 17).getTime();
await app.inject({
method: "POST",
url: "/doses/taken",
payload: { doseId: `${medId}-0-${fri17}-Alice` },
});
// Change start day
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Person Med",
intakes: [{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: "Alice" }],
},
});
// Dose should be migrated with person suffix preserved
const sat18 = new Date(2025, 9, 18).getTime();
const after = await testClient.execute({
sql: `SELECT dose_id FROM dose_tracking WHERE dose_id LIKE ?`,
args: [`${medId}-%`],
});
expect(after.rows.length).toBe(1);
expect(after.rows[0].dose_id).toBe(`${medId}-0-${sat18}-Alice`);
});
it("should not migrate dose IDs when only time-of-day changes", async () => {
// Create daily medication at 08:00
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Daily Med",
blisters: [{ usage: 1, every: 1, start: "2025-10-17T08:00:00" }],
},
});
const medId = createRes.json().id;
// Mark dose
const oct17 = new Date(2025, 9, 17).getTime();
await app.inject({
method: "POST",
url: "/doses/taken",
payload: { doseId: `${medId}-0-${oct17}` },
});
// Change only time from 08:00 to 20:00 (same date)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Daily Med",
blisters: [{ usage: 1, every: 1, start: "2025-10-17T20:00:00" }],
},
});
// Dose ID should remain unchanged (dateOnlyMs is the same)
const after = await testClient.execute({
sql: `SELECT dose_id FROM dose_tracking WHERE dose_id LIKE ?`,
args: [`${medId}-%`],
});
expect(after.rows.length).toBe(1);
expect(after.rows[0].dose_id).toBe(`${medId}-0-${oct17}`);
});
it("should migrate dose IDs when interval changes from daily to every-other-day", async () => {
// Create daily medication starting Oct 17
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Interval Med",
blisters: [{ usage: 1, every: 1, start: "2025-10-17T08:00:00" }],
},
});
const medId = createRes.json().id;
// Mark doses for Oct 17, 18, 19
const oct17 = new Date(2025, 9, 17).getTime();
const oct18 = new Date(2025, 9, 18).getTime();
const oct19 = new Date(2025, 9, 19).getTime();
for (const ts of [oct17, oct18, oct19]) {
await app.inject({
method: "POST",
url: "/doses/taken",
payload: { doseId: `${medId}-0-${ts}` },
});
}
// Change to every 2 days (Oct 17, 19, 21, ...)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Interval Med",
blisters: [{ usage: 1, every: 2, start: "2025-10-17T08:00:00" }],
},
});
// Oct 17 stays (matches), Oct 18 → Oct 19 (nearest), Oct 19 → no match (already used)
// Actually: Oct 17 is exact match (no migration needed), Oct 18 maps to Oct 19 (within 1 day = half of 2),
// Oct 19 was the original schedule date but the new schedule also has Oct 19,
// which was already taken by Oct 18's migration
const after = await testClient.execute({
sql: `SELECT dose_id FROM dose_tracking WHERE dose_id LIKE ? ORDER BY dose_id`,
args: [`${medId}-%`],
});
// We should have at least the doses that could be mapped
expect(after.rows.length).toBeGreaterThanOrEqual(2);
});
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Share Link + Dose Tracking Integration // Share Link + Dose Tracking Integration
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -699,7 +896,16 @@ describe("Integration Tests", () => {
describe("Planner usage calculation", () => { describe("Planner usage calculation", () => {
it("should calculate correct usage for daily medication", async () => { it("should calculate correct usage for daily medication", async () => {
// Create medication: 2 packs × 3 blisters × 10 pills = 60 pills total // Create medication: 2 packs × 3 blisters × 10 pills = 60 pills total
// Schedule: 1 pill daily starting Jan 1 // Schedule: 1 pill daily starting tomorrow (future date)
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(8, 0, 0, 0);
const intakeStart = tomorrow.toISOString();
const planEnd = new Date(tomorrow);
planEnd.setDate(planEnd.getDate() + 10);
const planEndStr = planEnd.toISOString();
await app.inject({ await app.inject({
method: "POST", method: "POST",
url: "/medications", url: "/medications",
@@ -709,17 +915,17 @@ describe("Integration Tests", () => {
blistersPerPack: 3, blistersPerPack: 3,
pillsPerBlister: 10, pillsPerBlister: 10,
looseTablets: 0, looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }], blisters: [{ usage: 1, every: 1, start: intakeStart }],
}, },
}); });
// Calculate usage for Jan 1-10 (10 days = 10 pills needed) // Calculate usage for 10 days starting tomorrow
const response = await app.inject({ const response = await app.inject({
method: "POST", method: "POST",
url: "/medications/usage", url: "/medications/usage",
payload: { payload: {
startDate: "2025-01-01T00:00:00.000Z", startDate: intakeStart,
endDate: "2025-01-11T00:00:00.000Z", // 10 days endDate: planEndStr, // 10 days
}, },
}); });
@@ -728,13 +934,22 @@ describe("Integration Tests", () => {
expect(data).toHaveLength(1); expect(data).toHaveLength(1);
expect(data[0].medicationName).toBe("Daily Med"); expect(data[0].medicationName).toBe("Daily Med");
expect(data[0].plannerUsage).toBe(10); // 10 days × 1 pill expect(data[0].plannerUsage).toBe(10); // 10 days × 1 pill
// Note: 'enough' depends on current stock after consumption since start date expect(data[0].totalPills).toBe(60); // Current stock is full (no consumption yet)
// Since test runs ~364 days after Jan 1, most pills are consumed expect(data[0].enough).toBe(true);
}); });
it("should detect insufficient stock", async () => { it("should detect insufficient stock", async () => {
// Create medication: 1 pack × 1 blister × 5 pills = 5 pills total // Create medication: 1 pack × 1 blister × 5 pills = 5 pills total
// Schedule: 1 pill daily // Schedule: 1 pill daily starting tomorrow
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(8, 0, 0, 0);
const intakeStart = tomorrow.toISOString();
const planEnd = new Date(tomorrow);
planEnd.setDate(planEnd.getDate() + 10);
const planEndStr = planEnd.toISOString();
await app.inject({ await app.inject({
method: "POST", method: "POST",
url: "/medications", url: "/medications",
@@ -744,17 +959,17 @@ describe("Integration Tests", () => {
blistersPerPack: 1, blistersPerPack: 1,
pillsPerBlister: 5, pillsPerBlister: 5,
looseTablets: 0, looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }], blisters: [{ usage: 1, every: 1, start: intakeStart }],
}, },
}); });
// Calculate usage for 10 days (needs 10 pills, only have 5 originally) // Calculate usage for 10 days (needs 10 pills, only have 5)
const response = await app.inject({ const response = await app.inject({
method: "POST", method: "POST",
url: "/medications/usage", url: "/medications/usage",
payload: { payload: {
startDate: "2025-01-01T00:00:00.000Z", startDate: intakeStart,
endDate: "2025-01-11T00:00:00.000Z", endDate: planEndStr,
}, },
}); });
@@ -766,7 +981,16 @@ describe("Integration Tests", () => {
it("should calculate weekly medication usage correctly", async () => { it("should calculate weekly medication usage correctly", async () => {
// Create medication: 10 pills total // Create medication: 10 pills total
// Schedule: 1 pill every 7 days starting Jan 1 // Schedule: 1 pill every 7 days starting tomorrow
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(8, 0, 0, 0);
const intakeStart = tomorrow.toISOString();
const planEnd = new Date(tomorrow);
planEnd.setDate(planEnd.getDate() + 35); // 35 days to get 5 weekly doses
const planEndStr = planEnd.toISOString();
await app.inject({ await app.inject({
method: "POST", method: "POST",
url: "/medications", url: "/medications",
@@ -775,29 +999,42 @@ describe("Integration Tests", () => {
packCount: 1, packCount: 1,
blistersPerPack: 1, blistersPerPack: 1,
pillsPerBlister: 10, pillsPerBlister: 10,
blisters: [{ usage: 1, every: 7, start: "2025-01-01T08:00:00.000Z" }], blisters: [{ usage: 1, every: 7, start: intakeStart }],
}, },
}); });
// Calculate usage for 30 days (should need ~4-5 pills) // Calculate usage for 35 days (should need 5 pills)
const response = await app.inject({ const response = await app.inject({
method: "POST", method: "POST",
url: "/medications/usage", url: "/medications/usage",
payload: { payload: {
startDate: "2025-01-01T00:00:00.000Z", startDate: intakeStart,
endDate: "2025-01-31T00:00:00.000Z", // 30 days endDate: planEndStr,
}, },
}); });
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
const data = response.json(); const data = response.json();
// Jan 1, 8, 15, 22, 29 = 5 doses // Day 0, 7, 14, 21, 28 = 5 doses
expect(data[0].plannerUsage).toBe(5); expect(data[0].plannerUsage).toBe(5);
}); });
it("should handle multiple intake schedules per medication", async () => { it("should handle multiple intake schedules per medication", async () => {
// Create medication with morning and evening doses // Create medication with morning and evening doses
// 30 pills total, 1.5 pills per day (1 morning + 0.5 evening) // 30 pills total, 1.5 pills per day (1 morning + 0.5 evening)
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(8, 0, 0, 0);
const morningStart = tomorrow.toISOString();
const eveningStart = new Date(tomorrow);
eveningStart.setHours(20, 0, 0, 0);
const eveningStartStr = eveningStart.toISOString();
const planEnd = new Date(tomorrow);
planEnd.setDate(planEnd.getDate() + 10);
const planEndStr = planEnd.toISOString();
await app.inject({ await app.inject({
method: "POST", method: "POST",
url: "/medications", url: "/medications",
@@ -807,8 +1044,8 @@ describe("Integration Tests", () => {
blistersPerPack: 1, blistersPerPack: 1,
pillsPerBlister: 30, pillsPerBlister: 30,
blisters: [ blisters: [
{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }, // Morning: 1 pill { usage: 1, every: 1, start: morningStart }, // Morning: 1 pill
{ usage: 0.5, every: 1, start: "2025-01-01T20:00:00.000Z" }, // Evening: 0.5 pill { usage: 0.5, every: 1, start: eveningStartStr }, // Evening: 0.5 pill
], ],
}, },
}); });
@@ -818,8 +1055,8 @@ describe("Integration Tests", () => {
method: "POST", method: "POST",
url: "/medications/usage", url: "/medications/usage",
payload: { payload: {
startDate: "2025-01-01T00:00:00.000Z", startDate: morningStart,
endDate: "2025-01-11T00:00:00.000Z", endDate: planEndStr,
}, },
}); });
@@ -831,6 +1068,15 @@ describe("Integration Tests", () => {
it("should calculate correct blisters needed", async () => { it("should calculate correct blisters needed", async () => {
// 10 pills per blister, need 25 pills → need 3 blisters // 10 pills per blister, need 25 pills → need 3 blisters
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(8, 0, 0, 0);
const intakeStart = tomorrow.toISOString();
const planEnd = new Date(tomorrow);
planEnd.setDate(planEnd.getDate() + 10);
const planEndStr = planEnd.toISOString();
await app.inject({ await app.inject({
method: "POST", method: "POST",
url: "/medications", url: "/medications",
@@ -839,7 +1085,7 @@ describe("Integration Tests", () => {
packCount: 5, packCount: 5,
blistersPerPack: 1, blistersPerPack: 1,
pillsPerBlister: 10, pillsPerBlister: 10,
blisters: [{ usage: 2.5, every: 1, start: "2025-01-01T08:00:00.000Z" }], blisters: [{ usage: 2.5, every: 1, start: intakeStart }],
}, },
}); });
@@ -848,8 +1094,8 @@ describe("Integration Tests", () => {
method: "POST", method: "POST",
url: "/medications/usage", url: "/medications/usage",
payload: { payload: {
startDate: "2025-01-01T00:00:00.000Z", startDate: intakeStart,
endDate: "2025-01-11T00:00:00.000Z", endDate: planEndStr,
}, },
}); });
@@ -936,4 +1182,169 @@ describe("Integration Tests", () => {
expect(data[0].enough).toBe(true); // 45 > 10 expect(data[0].enough).toBe(true); // 45 > 10
}); });
}); });
// ---------------------------------------------------------------------------
// Dismiss Until (Clear Missed Doses)
// ---------------------------------------------------------------------------
describe("Dismiss Until functionality", () => {
it("should set dismissedUntil for multiple medications", async () => {
// Create two medications
const med1Res = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Med 1",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const med1Id = med1Res.json().id;
const med2Res = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Med 2",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const med2Id = med2Res.json().id;
// Set dismissedUntil for both
const dismissRes = await app.inject({
method: "POST",
url: "/medications/dismiss-until",
payload: {
medicationIds: [med1Id, med2Id],
until: "2025-01-15",
},
});
expect(dismissRes.statusCode).toBe(200);
expect(dismissRes.json().success).toBe(true);
expect(dismissRes.json().updatedCount).toBe(2);
// Verify dismissedUntil is set via GET
const medsRes = await app.inject({
method: "GET",
url: "/medications",
});
const meds = medsRes.json();
const med1 = meds.find((m: any) => m.id === med1Id);
const med2 = meds.find((m: any) => m.id === med2Id);
expect(med1.dismissedUntil).toBe("2025-01-15");
expect(med2.dismissedUntil).toBe("2025-01-15");
});
it("should clear dismissedUntil for a medication", async () => {
// Create medication
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Med to Clear",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createRes.json().id;
// Set dismissedUntil
await app.inject({
method: "POST",
url: "/medications/dismiss-until",
payload: {
medicationIds: [medId],
until: "2025-01-20",
},
});
// Clear it
const clearRes = await app.inject({
method: "DELETE",
url: `/medications/${medId}/dismiss-until`,
});
expect(clearRes.statusCode).toBe(200);
expect(clearRes.json().success).toBe(true);
// Verify it's cleared
const medsRes = await app.inject({
method: "GET",
url: "/medications",
});
const med = medsRes.json().find((m: any) => m.id === medId);
expect(med.dismissedUntil).toBeNull();
});
it("should reject invalid date format", async () => {
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Med",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createRes.json().id;
const res = await app.inject({
method: "POST",
url: "/medications/dismiss-until",
payload: {
medicationIds: [medId],
until: "01-15-2025", // Wrong format
},
});
expect(res.statusCode).toBe(400);
});
it("should reject empty medicationIds array", async () => {
const res = await app.inject({
method: "POST",
url: "/medications/dismiss-until",
payload: {
medicationIds: [],
until: "2025-01-15",
},
});
expect(res.statusCode).toBe(400);
});
it("should not update medications belonging to other users", async () => {
// Create medication for user 999999999
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "My Med",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createRes.json().id;
// Try to dismiss a medication that doesn't exist (ID 99999)
const dismissRes = await app.inject({
method: "POST",
url: "/medications/dismiss-until",
payload: {
medicationIds: [99999],
until: "2025-01-15",
},
});
expect(dismissRes.statusCode).toBe(200);
expect(dismissRes.json().updatedCount).toBe(0); // Nothing updated
// Our med should still have no dismissedUntil
const medsRes = await app.inject({
method: "GET",
url: "/medications",
});
const med = medsRes.json().find((m: any) => m.id === medId);
expect(med.dismissedUntil).toBeNull();
});
});
}); });
+6 -7
View File
@@ -2,14 +2,14 @@
* Tests for /medications API endpoints. * Tests for /medications API endpoints.
* Tests CRUD operations for medications. * Tests CRUD operations for medications.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { import {
buildTestApp, buildTestApp,
closeTestApp,
clearTestData, clearTestData,
createTestUser, closeTestApp,
createTestMedication, createTestMedication,
TestContext, createTestUser,
type TestContext,
} from "./setup.js"; } from "./setup.js";
// ============================================================================= // =============================================================================
@@ -20,7 +20,7 @@ async function registerMedicationRoutes(ctx: TestContext) {
const { app, client } = ctx; const { app, client } = ctx;
// GET /medications - List all medications // GET /medications - List all medications
app.get("/medications", async (request, reply) => { app.get("/medications", async (_request, _reply) => {
const userId = 1; const userId = 1;
const result = await client.execute({ const result = await client.execute({
@@ -664,8 +664,7 @@ describe("Medications API", () => {
const [med] = response.json(); const [med] = response.json();
// Total = (2 packs × 3 blisters × 10 pills) + 5 loose = 65 // Total = (2 packs × 3 blisters × 10 pills) + 5 loose = 65
const totalPills = const totalPills = med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets;
med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets;
expect(totalPills).toBe(65); expect(totalPills).toBe(65);
}); });
}); });
+23 -31
View File
@@ -1,10 +1,16 @@
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from "vitest"; import type { Client } from "@libsql/client";
import Fastify, { FastifyInstance } from "fastify"; import Fastify, { type FastifyInstance } from "fastify";
import { createClient, Client } from "@libsql/client"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { drizzle } from "drizzle-orm/libsql";
// Create test database and mocks before anything else (hoisted) // Create test database and mocks before anything else (hoisted)
const { testClient, testDb, mockSendMail, mockSendShoutrrr, mockUpdateReminderSentTime, mockUpdateUserReminderSentTime } = vi.hoisted(() => { const {
testClient,
testDb,
mockSendMail,
mockSendShoutrrr,
mockUpdateReminderSentTime,
mockUpdateUserReminderSentTime,
} = vi.hoisted(() => {
const { createClient } = require("@libsql/client"); const { createClient } = require("@libsql/client");
const { drizzle } = require("drizzle-orm/libsql"); const { drizzle } = require("drizzle-orm/libsql");
const client = createClient({ url: ":memory:" }); const client = createClient({ url: ":memory:" });
@@ -57,7 +63,7 @@ vi.mock("../services/reminder-scheduler.js", () => ({
// Mock sendShoutrrrNotification from settings // Mock sendShoutrrrNotification from settings
vi.mock("../routes/settings.js", async (importOriginal) => { vi.mock("../routes/settings.js", async (importOriginal) => {
const original = await importOriginal() as any; const original = (await importOriginal()) as any;
return { return {
...original, ...original,
sendShoutrrrNotification: mockSendShoutrrr, sendShoutrrrNotification: mockSendShoutrrr,
@@ -107,6 +113,8 @@ async function createSchema(client: Client) {
last_auto_email_sent text, last_auto_email_sent text,
last_notification_type text, last_notification_type text,
last_notification_channel text, last_notification_channel text,
last_reminder_med_name text,
last_reminder_taken_by text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')), updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`, )`,
@@ -430,9 +438,7 @@ describe("Planner Routes", () => {
url: "/reminder/send-email", url: "/reminder/send-email",
payload: { payload: {
email: "test@example.com", email: "test@example.com",
lowStock: [ lowStock: [{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" }],
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" },
],
}, },
}); });
@@ -458,9 +464,7 @@ describe("Planner Routes", () => {
url: "/reminder/send-email", url: "/reminder/send-email",
payload: { payload: {
email: "test@example.com", email: "test@example.com",
lowStock: [ lowStock: [{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" }],
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" },
],
}, },
}); });
@@ -561,9 +565,7 @@ describe("Planner Routes", () => {
url: "/reminder/send-email", url: "/reminder/send-email",
payload: { payload: {
email: "test@example.com", email: "test@example.com",
lowStock: [ lowStock: [{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" }],
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" },
],
}, },
}); });
@@ -588,9 +590,7 @@ describe("Planner Routes", () => {
url: "/reminder/send-email", url: "/reminder/send-email",
payload: { payload: {
email: "test@example.com", email: "test@example.com",
lowStock: [ lowStock: [{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" }],
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" },
],
}, },
}); });
@@ -617,9 +617,7 @@ describe("Planner Routes", () => {
url: "/reminder/send-email", url: "/reminder/send-email",
payload: { payload: {
email: "test@example.com", email: "test@example.com",
lowStock: [ lowStock: [{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" }],
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" },
],
}, },
}); });
@@ -646,9 +644,7 @@ describe("Planner Routes", () => {
url: "/reminder/send-email", url: "/reminder/send-email",
payload: { payload: {
email: "test@example.com", email: "test@example.com",
lowStock: [ lowStock: [{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" }],
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" },
],
}, },
}); });
@@ -669,9 +665,7 @@ describe("Planner Routes", () => {
url: "/reminder/send-email", url: "/reminder/send-email",
payload: { payload: {
email: "test@example.com", email: "test@example.com",
lowStock: [ lowStock: [{ name: "Aspirin", medsLeft: 0, daysLeft: 0, depletionDate: null }],
{ name: "Aspirin", medsLeft: 0, daysLeft: 0, depletionDate: null },
],
}, },
}); });
@@ -679,7 +673,7 @@ describe("Planner Routes", () => {
expect(mockSendShoutrrr).toHaveBeenCalledTimes(1); expect(mockSendShoutrrr).toHaveBeenCalledTimes(1);
// Check German translations are used // Check German translations are used
const [title, message] = mockSendShoutrrr.mock.calls[0].slice(1); const [title, _message] = mockSendShoutrrr.mock.calls[0].slice(1);
expect(title).toContain("Leer"); expect(title).toContain("Leer");
}); });
@@ -696,9 +690,7 @@ describe("Planner Routes", () => {
url: "/reminder/send-email", url: "/reminder/send-email",
payload: { payload: {
email: "test@example.com", email: "test@example.com",
lowStock: [ lowStock: [{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" }],
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" },
],
}, },
}); });
+7 -5
View File
@@ -2,14 +2,14 @@
* Tests for /medications/:id/refill and /medications/:id/refills API endpoints. * Tests for /medications/:id/refill and /medications/:id/refills API endpoints.
* Tests adding refills to medication stock and retrieving refill history. * Tests adding refills to medication stock and retrieving refill history.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { import {
buildTestApp, buildTestApp,
closeTestApp,
clearTestData, clearTestData,
createTestUser, closeTestApp,
createTestMedication, createTestMedication,
TestContext, createTestUser,
type TestContext,
} from "./setup.js"; } from "./setup.js";
// Store userId at module level so routes can access it // Store userId at module level so routes can access it
@@ -35,7 +35,9 @@ async function registerRefillRoutes(ctx: TestContext) {
return reply.status(400).send({ error: "packsAdded and loosePillsAdded must be non-negative" }); return reply.status(400).send({ error: "packsAdded and loosePillsAdded must be non-negative" });
} }
if (packsAdded === 0 && loosePillsAdded === 0) { if (packsAdded === 0 && loosePillsAdded === 0) {
return reply.status(400).send({ error: "At least one of packsAdded or loosePillsAdded must be greater than 0" }); return reply
.status(400)
.send({ error: "At least one of packsAdded or loosePillsAdded must be greater than 0" });
} }
// Check medication exists and belongs to user // Check medication exists and belongs to user
+28 -18
View File
@@ -1,20 +1,20 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { existsSync, rmSync } from "node:fs";
import Fastify from "fastify"; import { tmpdir } from "node:os";
import { resolve } from "node:path";
import cookie from "@fastify/cookie";
import cors from "@fastify/cors"; import cors from "@fastify/cors";
import sensible from "@fastify/sensible"; import sensible from "@fastify/sensible";
import cookie from "@fastify/cookie"; import Fastify from "fastify";
import { mkdirSync, rmSync, existsSync } from "fs"; import { afterEach, describe, expect, it } from "vitest";
import { resolve } from "path";
import { tmpdir } from "os";
// Import from utils to avoid index.ts import side effects (server start) // Import from utils to avoid index.ts import side effects (server start)
import { import {
parseCorsOrigins, buildAppConfig,
buildBaseCookieOptions, buildBaseCookieOptions,
buildRefreshCookieOptions, buildRefreshCookieOptions,
buildAppConfig,
ensureImagesDirectory, ensureImagesDirectory,
getJwtConfig, getJwtConfig,
parseCorsOrigins,
} from "../utils/server-config.js"; } from "../utils/server-config.js";
describe("Index.ts Utility Functions", () => { describe("Index.ts Utility Functions", () => {
@@ -247,7 +247,7 @@ describe("Server Bootstrap", () => {
await app.register(cookie, { secret: "test-cookie-secret" }); await app.register(cookie, { secret: "test-cookie-secret" });
// Add a test route that sets a cookie // Add a test route that sets a cookie
app.get("/set-cookie", async (request, reply) => { app.get("/set-cookie", async (_request, reply) => {
reply.setCookie("test", "value", { path: "/" }); reply.setCookie("test", "value", { path: "/" });
return { ok: true }; return { ok: true };
}); });
@@ -317,7 +317,10 @@ describe("Server Bootstrap", () => {
describe("CORS Origins Parsing", () => { describe("CORS Origins Parsing", () => {
it("should parse comma-separated origins", () => { it("should parse comma-separated origins", () => {
const originsEnv = "http://localhost:5173,http://localhost:4173"; const originsEnv = "http://localhost:5173,http://localhost:4173";
const origins = originsEnv.split(",").map((o) => o.trim()).filter(Boolean); const origins = originsEnv
.split(",")
.map((o) => o.trim())
.filter(Boolean);
expect(origins).toHaveLength(2); expect(origins).toHaveLength(2);
expect(origins[0]).toBe("http://localhost:5173"); expect(origins[0]).toBe("http://localhost:5173");
@@ -326,7 +329,10 @@ describe("Server Bootstrap", () => {
it("should handle single origin", () => { it("should handle single origin", () => {
const originsEnv = "https://myapp.example.com"; const originsEnv = "https://myapp.example.com";
const origins = originsEnv.split(",").map((o) => o.trim()).filter(Boolean); const origins = originsEnv
.split(",")
.map((o) => o.trim())
.filter(Boolean);
expect(origins).toHaveLength(1); expect(origins).toHaveLength(1);
expect(origins[0]).toBe("https://myapp.example.com"); expect(origins[0]).toBe("https://myapp.example.com");
@@ -334,14 +340,20 @@ describe("Server Bootstrap", () => {
it("should filter out empty strings", () => { it("should filter out empty strings", () => {
const originsEnv = "http://localhost:5173,,http://localhost:4173,"; const originsEnv = "http://localhost:5173,,http://localhost:4173,";
const origins = originsEnv.split(",").map((o) => o.trim()).filter(Boolean); const origins = originsEnv
.split(",")
.map((o) => o.trim())
.filter(Boolean);
expect(origins).toHaveLength(2); expect(origins).toHaveLength(2);
}); });
it("should trim whitespace", () => { it("should trim whitespace", () => {
const originsEnv = " http://localhost:5173 , http://localhost:4173 "; const originsEnv = " http://localhost:5173 , http://localhost:4173 ";
const origins = originsEnv.split(",").map((o) => o.trim()).filter(Boolean); const origins = originsEnv
.split(",")
.map((o) => o.trim())
.filter(Boolean);
expect(origins).toEqual(["http://localhost:5173", "http://localhost:4173"]); expect(origins).toEqual(["http://localhost:5173", "http://localhost:4173"]);
}); });
@@ -398,9 +410,7 @@ describe("Server Bootstrap", () => {
const app = Fastify({ logger: false }); const app = Fastify({ logger: false });
// Try to listen on an invalid port // Try to listen on an invalid port
await expect( await expect(app.listen({ port: -1, host: "127.0.0.1" })).rejects.toThrow();
app.listen({ port: -1, host: "127.0.0.1" })
).rejects.toThrow();
await app.close(); await app.close();
}); });
@@ -453,11 +463,11 @@ describe("Cookie Options", () => {
describe("Rate Limiting", () => { describe("Rate Limiting", () => {
it("should configure rate limit settings", () => { it("should configure rate limit settings", () => {
const rateLimitConfig = { const rateLimitConfig = {
max: 100, max: 300,
timeWindow: "1 minute", timeWindow: "1 minute",
}; };
expect(rateLimitConfig.max).toBe(100); expect(rateLimitConfig.max).toBe(300);
expect(rateLimitConfig.timeWindow).toBe("1 minute"); expect(rateLimitConfig.timeWindow).toBe("1 minute");
}); });
}); });
+93 -68
View File
@@ -1,33 +1,39 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { readFileSync, writeFileSync, existsSync, unlinkSync } from "fs";
import { resolve } from "path";
import { tmpdir } from "os";
// Import actual utility functions from scheduler-utils // Import actual utility functions from scheduler-utils
import { import {
getTimezone, type Blister,
formatInTimezone,
getCurrentHourInTimezone,
getTodayInTimezone,
getNextScheduledTime,
getMsUntilNextCheck,
parseBlisters,
parseTakenByJson,
calculateDailyUsage, calculateDailyUsage,
calculateDepletionInfo, calculateDepletionInfo,
getUpcomingIntakes,
getTodaysIntakes,
createDefaultReminderState,
createDefaultIntakeReminderState,
parseReminderState,
parseIntakeReminderState,
cleanOldIntakeReminders, cleanOldIntakeReminders,
type Blister, createDefaultIntakeReminderState,
type ReminderState, createDefaultReminderState,
type IntakeReminderState, formatInTimezone,
type UpcomingIntake, getCurrentHourInTimezone,
getMsUntilNextCheck,
getNextScheduledTime,
getTimezone,
getTodayInTimezone,
getTodaysIntakes,
getUpcomingIntakes,
type Intake,
parseBlisters,
parseIntakeReminderState,
parseReminderState,
parseTakenByJson,
} from "../utils/scheduler-utils.js"; } from "../utils/scheduler-utils.js";
// Helper to convert Blister to Intake for tests
function blisterToIntake(blister: Blister, takenBy: string | null = null, intakeRemindersEnabled = false): Intake {
return {
usage: blister.usage,
every: blister.every,
start: blister.start,
takenBy,
intakeRemindersEnabled,
};
}
describe("Scheduler Utils - Timezone Functions", () => { describe("Scheduler Utils - Timezone Functions", () => {
let originalTz: string | undefined; let originalTz: string | undefined;
@@ -338,45 +344,46 @@ describe("Scheduler Utils - Depletion Calculation", () => {
describe("Scheduler Utils - Upcoming Intakes", () => { describe("Scheduler Utils - Upcoming Intakes", () => {
describe("getUpcomingIntakes", () => { describe("getUpcomingIntakes", () => {
it("should return empty array when no intakes in window", () => { it("should return empty array when no intakes in window", () => {
const blisters: Blister[] = [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }]; // With parseLocalDateTime, times are treated as local - use same format for consistency
// Set "now" to a time far from any scheduled intake const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00" })];
const now = new Date("2025-01-01T12:00:00.000Z").getTime(); // Set "now" to a time far from any scheduled intake (12:00 local)
const now = new Date(2025, 0, 1, 12, 0, 0).getTime();
const result = getUpcomingIntakes("TestMed", blisters, 15, [], null, "en-US", "UTC", now); const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
expect(result).toEqual([]); expect(result).toEqual([]);
}); });
it("should find intake within reminder window", () => { it("should find intake within reminder window", () => {
// Schedule intake at 08:00, check at 07:45 (15 minutes before) // Schedule intake at 08:00 local, check at 07:45 local (15 minutes before)
const blisters: Blister[] = [{ usage: 2, every: 1, start: "2025-01-01T08:00:00.000Z" }]; const intakes: Intake[] = [blisterToIntake({ usage: 2, every: 1, start: "2025-01-01T08:00:00" }, "Alice")];
const now = new Date("2025-01-01T07:45:00.000Z").getTime(); const now = new Date(2025, 0, 1, 7, 45, 0).getTime();
const result = getUpcomingIntakes("TestMed", blisters, 15, ["Alice"], 500, "en-US", "UTC", now); const result = getUpcomingIntakes("TestMed", intakes, 15, [], 500, "en-US", "UTC", now);
expect(result).toHaveLength(1); expect(result).toHaveLength(1);
expect(result[0].medName).toBe("TestMed"); expect(result[0].medName).toBe("TestMed");
expect(result[0].usage).toBe(2); expect(result[0].usage).toBe(2);
expect(result[0].takenBy).toEqual(["Alice"]); expect(result[0].takenBy).toBe("Alice");
expect(result[0].pillWeightMg).toBe(500); expect(result[0].pillWeightMg).toBe(500);
}); });
it("should skip blisters with zero interval", () => { it("should skip blisters with zero interval", () => {
const blisters: Blister[] = [{ usage: 1, every: 0, start: "2025-01-01T08:00:00.000Z" }]; const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 0, start: "2025-01-01T08:00:00" })];
const now = new Date("2025-01-01T07:45:00.000Z").getTime(); const now = new Date(2025, 0, 1, 7, 45, 0).getTime();
const result = getUpcomingIntakes("TestMed", blisters, 15, [], null, "en-US", "UTC", now); const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
expect(result).toEqual([]); expect(result).toEqual([]);
}); });
it("should handle multiple blisters", () => { it("should handle multiple blisters", () => {
// Two intakes at 08:00 and 08:01 // Two intakes at 08:00 and 08:01 local
const blisters: Blister[] = [ const intakes: Intake[] = [
{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }, blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00" }),
{ usage: 2, every: 1, start: "2025-01-01T08:01:00.000Z" }, blisterToIntake({ usage: 2, every: 1, start: "2025-01-01T08:01:00" }),
]; ];
const now = new Date("2025-01-01T07:45:00.000Z").getTime(); const now = new Date(2025, 0, 1, 7, 45, 0).getTime();
const result = getUpcomingIntakes("TestMed", blisters, 15, [], null, "en-US", "UTC", now); const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
// Both should be found as they're within the window // Both should be found as they're within the window
expect(result.length).toBeGreaterThanOrEqual(1); expect(result.length).toBeGreaterThanOrEqual(1);
@@ -386,13 +393,14 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
describe("getTodaysIntakes", () => { describe("getTodaysIntakes", () => {
it("should return all intakes for today", () => { it("should return all intakes for today", () => {
// Daily medication at 08:00 starting yesterday // Daily medication at 08:00 starting yesterday
const blisters: Blister[] = [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }]; // With parseLocalDateTime, "08:00:00.000Z" is treated as 08:00 local time
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" })];
// Get intakes for 2025-01-02 (today's intake should be at 08:00) // Get intakes for today (today's intake should be at 08:00 local)
const result = getTodaysIntakes("TestMed", blisters, [], null, "en-US", "UTC"); const result = getTodaysIntakes("TestMed", intakes, [], null, "en-US", "UTC");
expect(result.length).toBeGreaterThanOrEqual(1); expect(result.length).toBeGreaterThanOrEqual(1);
const intake = result.find(i => i.intakeTime.getUTCHours() === 8); const intake = result.find((i) => i.intakeTime.getHours() === 8);
expect(intake).toBeDefined(); expect(intake).toBeDefined();
expect(intake?.medName).toBe("TestMed"); expect(intake?.medName).toBe("TestMed");
expect(intake?.usage).toBe(1); expect(intake?.usage).toBe(1);
@@ -403,18 +411,23 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
const todayMidnight = new Date(); const todayMidnight = new Date();
todayMidnight.setUTCHours(0, 1, 0, 0); todayMidnight.setUTCHours(0, 1, 0, 0);
const blisters: Blister[] = [{ const intakes: Intake[] = [
blisterToIntake(
{
usage: 2, usage: 2,
every: 1, every: 1,
start: todayMidnight.toISOString() start: todayMidnight.toISOString(),
}]; },
"Bob"
),
];
const result = getTodaysIntakes("PastMed", blisters, ["Bob"], 250, "en-US", "UTC"); const result = getTodaysIntakes("PastMed", intakes, [], 250, "en-US", "UTC");
expect(result).toHaveLength(1); expect(result).toHaveLength(1);
expect(result[0].medName).toBe("PastMed"); expect(result[0].medName).toBe("PastMed");
expect(result[0].usage).toBe(2); expect(result[0].usage).toBe(2);
expect(result[0].takenBy).toEqual(["Bob"]); expect(result[0].takenBy).toBe("Bob");
expect(result[0].pillWeightMg).toBe(250); expect(result[0].pillWeightMg).toBe(250);
}); });
@@ -426,12 +439,12 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
const evening = new Date(today); const evening = new Date(today);
evening.setUTCHours(20, 0, 0, 0); evening.setUTCHours(20, 0, 0, 0);
const blisters: Blister[] = [ const intakes: Intake[] = [
{ usage: 1, every: 1, start: morning.toISOString() }, blisterToIntake({ usage: 1, every: 1, start: morning.toISOString() }),
{ usage: 1, every: 1, start: evening.toISOString() }, blisterToIntake({ usage: 1, every: 1, start: evening.toISOString() }),
]; ];
const result = getTodaysIntakes("MultiMed", blisters, [], null, "en-US", "UTC"); const result = getTodaysIntakes("MultiMed", intakes, [], null, "en-US", "UTC");
expect(result.length).toBeGreaterThanOrEqual(2); expect(result.length).toBeGreaterThanOrEqual(2);
}); });
@@ -441,32 +454,40 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
const lastWeek = new Date(); const lastWeek = new Date();
lastWeek.setDate(lastWeek.getDate() - 7); lastWeek.setDate(lastWeek.getDate() - 7);
const blisters: Blister[] = [{ const intakes: Intake[] = [
blisterToIntake({
usage: 1, usage: 1,
every: 7, every: 7,
start: lastWeek.toISOString() start: lastWeek.toISOString(),
}]; }),
];
// If today is not the same day of week, should return empty // If today is not the same day of week, should return empty
const result = getTodaysIntakes("WeeklyMed", blisters, [], null, "en-US", "UTC"); const result = getTodaysIntakes("WeeklyMed", intakes, [], null, "en-US", "UTC");
// This test might return 0 or 1 depending on the day // This test might return 0 or 1 depending on the day
expect(Array.isArray(result)).toBe(true); expect(Array.isArray(result)).toBe(true);
}); });
it("should handle timezone correctly", () => { it("should handle local time correctly (ignore Z suffix)", () => {
// 23:00 in Europe/Berlin on a specific date // With parseLocalDateTime, the Z suffix is ignored and time is treated as local server time
const blisters: Blister[] = [{ // The intakeTimeStr is then formatted for the target timezone (Europe/Berlin)
// So if server is in UTC, 14:00 server time becomes 15:00 Europe/Berlin time
const intakes: Intake[] = [
blisterToIntake({
usage: 1, usage: 1,
every: 1, every: 1,
start: "2025-01-01T22:00:00.000Z" // 23:00 Berlin time start: "2025-01-01T14:00:00.000Z", // Treated as 14:00 server local time
}]; }),
];
const result = getTodaysIntakes("TzMed", blisters, [], null, "de-DE", "Europe/Berlin"); const result = getTodaysIntakes("TzMed", intakes, [], null, "de-DE", "Europe/Berlin");
expect(Array.isArray(result)).toBe(true); expect(Array.isArray(result)).toBe(true);
if (result.length > 0) { if (result.length > 0) {
expect(result[0].intakeTimeStr).toContain("23:"); // The intakeTimeStr should be a valid time format (HH:MM)
// Exact value depends on server timezone vs target timezone offset
expect(result[0].intakeTimeStr).toMatch(/^\d{2}:\d{2}$/);
} }
}); });
}); });
@@ -532,8 +553,8 @@ describe("Scheduler Utils - State Management", () => {
const json = JSON.stringify({ const json = JSON.stringify({
reminders: { reminders: {
"med1:123": { firstSentAt: 1000, lastSentAt: 2000, sendCount: 2 }, "med1:123": { firstSentAt: 1000, lastSentAt: 2000, sendCount: 2 },
"med2:456": { firstSentAt: 3000, lastSentAt: 3000, sendCount: 1 } "med2:456": { firstSentAt: 3000, lastSentAt: 3000, sendCount: 1 },
} },
}); });
const state = parseIntakeReminderState(json); const state = parseIntakeReminderState(json);
@@ -572,7 +593,11 @@ describe("Scheduler Utils - State Management", () => {
yesterday.setDate(yesterday.getDate() - 1); yesterday.setDate(yesterday.getDate() - 1);
const reminders = { const reminders = {
[`med1:${yesterday.getTime()}`]: { firstSentAt: yesterday.getTime(), lastSentAt: yesterday.getTime(), sendCount: 1 }, [`med1:${yesterday.getTime()}`]: {
firstSentAt: yesterday.getTime(),
lastSentAt: yesterday.getTime(),
sendCount: 1,
},
[`med2:${today.getTime()}`]: { firstSentAt: today.getTime(), lastSentAt: today.getTime(), sendCount: 1 }, [`med2:${today.getTime()}`]: { firstSentAt: today.getTime(), lastSentAt: today.getTime(), sendCount: 1 },
}; };
@@ -608,7 +633,7 @@ describe("Scheduler Utils - State Management", () => {
it("should handle malformed entries (invalid timestamp in key)", () => { it("should handle malformed entries (invalid timestamp in key)", () => {
const reminders = { const reminders = {
"med1:invalid": { firstSentAt: 1000, lastSentAt: 1000, sendCount: 1 }, "med1:invalid": { firstSentAt: 1000, lastSentAt: 1000, sendCount: 1 },
"med2:notanumber": { firstSentAt: 2000, lastSentAt: 2000, sendCount: 1 } "med2:notanumber": { firstSentAt: 2000, lastSentAt: 2000, sendCount: 1 },
}; };
const cleaned = cleanOldIntakeReminders(reminders, "Europe/Berlin"); const cleaned = cleanOldIntakeReminders(reminders, "Europe/Berlin");
// NaN from parseInt will cause these to be filtered out (invalid < todayStart) // NaN from parseInt will cause these to be filtered out (invalid < todayStart)
+8 -5
View File
@@ -2,14 +2,14 @@
* Tests for /settings API endpoints. * Tests for /settings API endpoints.
* Tests user settings CRUD operations. * Tests user settings CRUD operations.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { import {
buildTestApp, buildTestApp,
closeTestApp,
clearTestData, clearTestData,
closeTestApp,
createTestUser, createTestUser,
setUserSettings, setUserSettings,
TestContext, type TestContext,
} from "./setup.js"; } from "./setup.js";
// ============================================================================= // =============================================================================
@@ -20,7 +20,7 @@ async function registerSettingsRoutes(ctx: TestContext) {
const { app, client } = ctx; const { app, client } = ctx;
// GET /settings - Get user settings // GET /settings - Get user settings
app.get("/settings", async (request, reply) => { app.get("/settings", async (_request, _reply) => {
const userId = 1; const userId = 1;
const result = await client.execute({ const result = await client.execute({
@@ -123,7 +123,10 @@ async function registerSettingsRoutes(ctx: TestContext) {
if (body.stockCalculationMode && !["automatic", "manual"].includes(body.stockCalculationMode)) { if (body.stockCalculationMode && !["automatic", "manual"].includes(body.stockCalculationMode)) {
return reply.status(400).send({ error: "stockCalculationMode must be 'automatic' or 'manual'" }); return reply.status(400).send({ error: "stockCalculationMode must be 'automatic' or 'manual'" });
} }
if (body.reminderRepeatIntervalMinutes !== undefined && (body.reminderRepeatIntervalMinutes < 5 || body.reminderRepeatIntervalMinutes > 480)) { if (
body.reminderRepeatIntervalMinutes !== undefined &&
(body.reminderRepeatIntervalMinutes < 5 || body.reminderRepeatIntervalMinutes > 480)
) {
return reply.status(400).send({ error: "reminderRepeatIntervalMinutes must be between 5 and 480" }); return reply.status(400).send({ error: "reminderRepeatIntervalMinutes must be between 5 and 480" });
} }
if (body.maxNaggingReminders !== undefined && (body.maxNaggingReminders < 1 || body.maxNaggingReminders > 20)) { if (body.maxNaggingReminders !== undefined && (body.maxNaggingReminders < 1 || body.maxNaggingReminders > 20)) {
+13 -39
View File
@@ -2,17 +2,17 @@
* Test setup and utilities for MedAssist backend API tests. * Test setup and utilities for MedAssist backend API tests.
* Uses in-memory SQLite for isolation between test files. * Uses in-memory SQLite for isolation between test files.
*/ */
import Fastify, { FastifyInstance } from "fastify";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import cookie from "@fastify/cookie"; import cookie from "@fastify/cookie";
import jwt from "@fastify/jwt"; import jwt from "@fastify/jwt";
import sensible from "@fastify/sensible";
import fastifyMultipart from "@fastify/multipart"; import fastifyMultipart from "@fastify/multipart";
import { createClient, Client } from "@libsql/client"; import sensible from "@fastify/sensible";
import { type Client, createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql"; import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator"; import { migrate } from "drizzle-orm/libsql/migrator";
import { beforeAll, afterAll, beforeEach } from "vitest"; import Fastify, { type FastifyInstance } from "fastify";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
// Get migrations folder path // Get migrations folder path
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
@@ -87,10 +87,7 @@ export interface CreateUserOptions {
/** /**
* Create a test user and return the ID * Create a test user and return the ID
*/ */
export async function createTestUser( export async function createTestUser(client: Client, options: CreateUserOptions = {}): Promise<number> {
client: Client,
options: CreateUserOptions = {}
): Promise<number> {
const { username = `user_${Date.now()}`, authProvider = "local" } = options; const { username = `user_${Date.now()}`, authProvider = "local" } = options;
const result = await client.execute({ const result = await client.execute({
@@ -121,10 +118,7 @@ export interface CreateMedicationOptions {
/** /**
* Create a test medication and return the ID * Create a test medication and return the ID
*/ */
export async function createTestMedication( export async function createTestMedication(client: Client, options: CreateMedicationOptions): Promise<number> {
client: Client,
options: CreateMedicationOptions
): Promise<number> {
const { const {
userId, userId,
name = "Test Medication", name = "Test Medication",
@@ -186,17 +180,8 @@ export interface CreateShareTokenOptions {
/** /**
* Create a test share token and return the token string * Create a test share token and return the token string
*/ */
export async function createTestShareToken( export async function createTestShareToken(client: Client, options: CreateShareTokenOptions): Promise<string> {
client: Client, const { userId, takenBy, token = `test_token_${Date.now()}`, scheduleDays = 30, expiresAt = null } = options;
options: CreateShareTokenOptions
): Promise<string> {
const {
userId,
takenBy,
token = `test_token_${Date.now()}`,
scheduleDays = 30,
expiresAt = null,
} = options;
await client.execute({ await client.execute({
sql: `INSERT INTO share_tokens (user_id, token, taken_by, schedule_days, expires_at) sql: `INSERT INTO share_tokens (user_id, token, taken_by, schedule_days, expires_at)
@@ -217,16 +202,8 @@ export interface CreateDoseTrackingOptions {
/** /**
* Create a dose tracking record * Create a dose tracking record
*/ */
export async function createTestDoseTracking( export async function createTestDoseTracking(client: Client, options: CreateDoseTrackingOptions): Promise<void> {
client: Client, const { userId, doseId, markedBy = null, takenAt = Math.floor(Date.now() / 1000) } = options;
options: CreateDoseTrackingOptions
): Promise<void> {
const {
userId,
doseId,
markedBy = null,
takenAt = Math.floor(Date.now() / 1000),
} = options;
await client.execute({ await client.execute({
sql: `INSERT INTO dose_tracking (user_id, dose_id, marked_by, taken_at) sql: `INSERT INTO dose_tracking (user_id, dose_id, marked_by, taken_at)
@@ -244,10 +221,7 @@ export interface UpdateUserSettingsOptions {
/** /**
* Create or update user settings * Create or update user settings
*/ */
export async function setUserSettings( export async function setUserSettings(client: Client, options: UpdateUserSettingsOptions): Promise<void> {
client: Client,
options: UpdateUserSettingsOptions
): Promise<void> {
const { userId, stockCalculationMode = "automatic", lowStockDays = 30 } = options; const { userId, stockCalculationMode = "automatic", lowStockDays = 30 } = options;
// Check if settings exist // Check if settings exist
+17 -25
View File
@@ -2,15 +2,15 @@
* Tests for share link API endpoints. * Tests for share link API endpoints.
* Tests creating share tokens, accessing shared schedules, and marking doses via share links. * Tests creating share tokens, accessing shared schedules, and marking doses via share links.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { import {
buildTestApp, buildTestApp,
closeTestApp,
clearTestData, clearTestData,
createTestUser, closeTestApp,
createTestMedication, createTestMedication,
createTestShareToken, createTestShareToken,
TestContext, createTestUser,
type TestContext,
} from "./setup.js"; } from "./setup.js";
// ============================================================================= // =============================================================================
@@ -40,7 +40,7 @@ async function registerShareRoutes(ctx: TestContext) {
}); });
const hasMatchingMed = meds.rows.some((m) => { const hasMatchingMed = meds.rows.some((m) => {
const takenByList: string[] = JSON.parse(m.taken_by_json as string || "[]"); const takenByList: string[] = JSON.parse((m.taken_by_json as string) || "[]");
return takenByList.includes(takenBy); return takenByList.includes(takenBy);
}); });
@@ -103,13 +103,13 @@ async function registerShareRoutes(ctx: TestContext) {
const medications = medsResult.rows const medications = medsResult.rows
.filter((m) => { .filter((m) => {
const takenByList: string[] = JSON.parse(m.taken_by_json as string || "[]"); const takenByList: string[] = JSON.parse((m.taken_by_json as string) || "[]");
return takenByList.includes(share.taken_by as string); return takenByList.includes(share.taken_by as string);
}) })
.map((m) => { .map((m) => {
const usageArr: number[] = JSON.parse(m.usage_json as string || "[]"); const usageArr: number[] = JSON.parse((m.usage_json as string) || "[]");
const everyArr: number[] = JSON.parse(m.every_json as string || "[]"); const everyArr: number[] = JSON.parse((m.every_json as string) || "[]");
const startArr: string[] = JSON.parse(m.start_json as string || "[]"); const startArr: string[] = JSON.parse((m.start_json as string) || "[]");
return { return {
id: m.id, id: m.id,
@@ -118,15 +118,13 @@ async function registerShareRoutes(ctx: TestContext) {
pillWeightMg: m.pill_weight_mg, pillWeightMg: m.pill_weight_mg,
imageUrl: m.image_url, imageUrl: m.image_url,
totalPills: totalPills:
(m.pack_count as number) * (m.pack_count as number) * (m.blisters_per_pack as number) * (m.pills_per_blister as number) +
(m.blisters_per_pack as number) *
(m.pills_per_blister as number) +
(m.loose_tablets as number), (m.loose_tablets as number),
packCount: m.pack_count, packCount: m.pack_count,
blistersPerPack: m.blisters_per_pack, blistersPerPack: m.blisters_per_pack,
looseTablets: m.loose_tablets, looseTablets: m.loose_tablets,
pillsPerBlister: m.pills_per_blister, pillsPerBlister: m.pills_per_blister,
takenBy: JSON.parse(m.taken_by_json as string || "[]"), takenBy: JSON.parse((m.taken_by_json as string) || "[]"),
blisters: usageArr.map((usage, i) => ({ blisters: usageArr.map((usage, i) => ({
usage, usage,
every: everyArr[i] || 1, every: everyArr[i] || 1,
@@ -184,9 +182,7 @@ async function registerShareRoutes(ctx: TestContext) {
}); });
// POST /share/:token/doses - Mark dose via share link // POST /share/:token/doses - Mark dose via share link
app.post<{ Params: { token: string }; Body: { doseId: string } }>( app.post<{ Params: { token: string }; Body: { doseId: string } }>("/share/:token/doses", async (request, reply) => {
"/share/:token/doses",
async (request, reply) => {
const { token } = request.params; const { token } = request.params;
const { doseId } = request.body || {}; const { doseId } = request.body || {};
@@ -222,13 +218,10 @@ async function registerShareRoutes(ctx: TestContext) {
}); });
return { success: true }; return { success: true };
} });
);
// DELETE /share/:token/doses/:doseId - Unmark dose via share link // DELETE /share/:token/doses/:doseId - Unmark dose via share link
app.delete<{ Params: { token: string; doseId: string } }>( app.delete<{ Params: { token: string; doseId: string } }>("/share/:token/doses/:doseId", async (request, reply) => {
"/share/:token/doses/:doseId",
async (request, reply) => {
const { token, doseId } = request.params; const { token, doseId } = request.params;
const shareResult = await client.execute({ const shareResult = await client.execute({
@@ -248,11 +241,10 @@ async function registerShareRoutes(ctx: TestContext) {
}); });
return { success: true }; return { success: true };
} });
);
// GET /share/people - Get unique takenBy values // GET /share/people - Get unique takenBy values
app.get("/share/people", async (request, reply) => { app.get("/share/people", async (_request, _reply) => {
const userId = 1; const userId = 1;
const result = await client.execute({ const result = await client.execute({
@@ -262,7 +254,7 @@ async function registerShareRoutes(ctx: TestContext) {
const peopleSet = new Set<string>(); const peopleSet = new Set<string>();
for (const row of result.rows) { for (const row of result.rows) {
const takenByList: string[] = JSON.parse(row.taken_by_json as string || "[]"); const takenByList: string[] = JSON.parse((row.taken_by_json as string) || "[]");
takenByList.forEach((p) => peopleSet.add(p)); takenByList.forEach((p) => peopleSet.add(p));
} }
+13 -26
View File
@@ -2,16 +2,16 @@
* Tests for stock calculation modes (automatic vs manual). * Tests for stock calculation modes (automatic vs manual).
* Tests the /medications/usage endpoint with different settings. * Tests the /medications/usage endpoint with different settings.
*/ */
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { import {
buildTestApp, buildTestApp,
closeTestApp,
clearTestData, clearTestData,
createTestUser, closeTestApp,
createTestMedication,
createTestDoseTracking, createTestDoseTracking,
createTestMedication,
createTestUser,
setUserSettings, setUserSettings,
TestContext, type TestContext,
} from "./setup.js"; } from "./setup.js";
// ============================================================================= // =============================================================================
@@ -22,9 +22,7 @@ async function registerUsageRoutes(ctx: TestContext) {
const { app, client } = ctx; const { app, client } = ctx;
// POST /medications/usage - Calculate medication usage for a date range // POST /medications/usage - Calculate medication usage for a date range
app.post<{ Body: { startDate: string; endDate: string } }>( app.post<{ Body: { startDate: string; endDate: string } }>("/medications/usage", async (request, reply) => {
"/medications/usage",
async (request, reply) => {
const userId = 1; const userId = 1;
const { startDate, endDate } = request.body || {}; const { startDate, endDate } = request.body || {};
@@ -41,9 +39,7 @@ async function registerUsageRoutes(ctx: TestContext) {
args: [userId], args: [userId],
}); });
const stockMode = const stockMode =
settingsResult.rows.length > 0 settingsResult.rows.length > 0 ? (settingsResult.rows[0].stock_calculation_mode as string) : "automatic";
? (settingsResult.rows[0].stock_calculation_mode as string)
: "automatic";
// Get all medications // Get all medications
const medsResult = await client.execute({ const medsResult = await client.execute({
@@ -55,9 +51,7 @@ async function registerUsageRoutes(ctx: TestContext) {
for (const med of medsResult.rows) { for (const med of medsResult.rows) {
const totalPills = const totalPills =
(med.pack_count as number) * (med.pack_count as number) * (med.blisters_per_pack as number) * (med.pills_per_blister as number) +
(med.blisters_per_pack as number) *
(med.pills_per_blister as number) +
(med.loose_tablets as number); (med.loose_tablets as number);
const blisterSize = med.pills_per_blister as number; const blisterSize = med.pills_per_blister as number;
@@ -77,7 +71,7 @@ async function registerUsageRoutes(ctx: TestContext) {
const scheduleStart = new Date(startArr[i] || start); const scheduleStart = new Date(startArr[i] || start);
// Count doses from scheduleStart to end within the range // Count doses from scheduleStart to end within the range
let current = new Date(scheduleStart); const current = new Date(scheduleStart);
while (current <= end) { while (current <= end) {
if (current >= start) { if (current >= start) {
plannerUsage += usage; plannerUsage += usage;
@@ -92,11 +86,7 @@ async function registerUsageRoutes(ctx: TestContext) {
WHERE user_id = ? WHERE user_id = ?
AND taken_at >= ? AND taken_at >= ?
AND taken_at <= ?`, AND taken_at <= ?`,
args: [ args: [userId, Math.floor(start.getTime() / 1000), Math.floor(end.getTime() / 1000)],
userId,
Math.floor(start.getTime() / 1000),
Math.floor(end.getTime() / 1000),
],
}); });
// Filter to doses for this medication // Filter to doses for this medication
@@ -133,11 +123,10 @@ async function registerUsageRoutes(ctx: TestContext) {
} }
return results; return results;
} });
);
// GET /medications - List medications (for checking stock) // GET /medications - List medications (for checking stock)
app.get("/medications", async (request, reply) => { app.get("/medications", async (_request, _reply) => {
const userId = 1; const userId = 1;
const result = await client.execute({ const result = await client.execute({
@@ -153,9 +142,7 @@ async function registerUsageRoutes(ctx: TestContext) {
pillsPerBlister: m.pills_per_blister, pillsPerBlister: m.pills_per_blister,
looseTablets: m.loose_tablets, looseTablets: m.loose_tablets,
totalPills: totalPills:
(m.pack_count as number) * (m.pack_count as number) * (m.blisters_per_pack as number) * (m.pills_per_blister as number) +
(m.blisters_per_pack as number) *
(m.pills_per_blister as number) +
(m.loose_tablets as number), (m.loose_tablets as number),
})); }));
}); });
+2 -2
View File
@@ -1,8 +1,8 @@
/** /**
* Tests for translations module * Tests for translations module
*/ */
import { describe, it, expect } from "vitest"; import { describe, expect, it } from "vitest";
import { getTranslations, t, getDateLocale, type Language } from "../i18n/translations.js"; import { getDateLocale, getTranslations, type Language, t } from "../i18n/translations.js";
describe("Translations Module", () => { describe("Translations Module", () => {
describe("getTranslations", () => { describe("getTranslations", () => {
+179 -39
View File
@@ -5,8 +5,18 @@
import { getDateLocale, type Language } from "../i18n/translations.js"; import { getDateLocale, type Language } from "../i18n/translations.js";
// Legacy type - individual blister schedule (DEPRECATED: use Intake instead)
export type Blister = { usage: number; every: number; start: string }; export type Blister = { usage: number; every: number; start: string };
// New unified intake type with per-intake takenBy
export type Intake = {
usage: number;
every: number;
start: string;
takenBy: string | null; // Person taking this specific intake (null = use medication-level takenBy)
intakeRemindersEnabled: boolean;
};
// ============================================================================= // =============================================================================
// Timezone utilities // Timezone utilities
// ============================================================================= // =============================================================================
@@ -24,7 +34,7 @@ export function formatInTimezone(date: Date, tz?: string): string {
month: "2-digit", month: "2-digit",
year: "numeric", year: "numeric",
hour: "2-digit", hour: "2-digit",
minute: "2-digit" minute: "2-digit",
}); });
} }
@@ -34,7 +44,7 @@ export function getCurrentHourInTimezone(tz?: string): number {
const timeStr = now.toLocaleString("en-US", { const timeStr = now.toLocaleString("en-US", {
timeZone: tz ?? getTimezone(), timeZone: tz ?? getTimezone(),
hour: "numeric", hour: "numeric",
hour12: false hour12: false,
}); });
return parseInt(timeStr, 10); return parseInt(timeStr, 10);
} }
@@ -59,11 +69,11 @@ export function getNextScheduledTime(reminderHour: number, tz?: string): Date {
day: "2-digit", day: "2-digit",
hour: "2-digit", hour: "2-digit",
minute: "2-digit", minute: "2-digit",
hour12: false hour12: false,
}); });
const parts = formatter.formatToParts(now); const parts = formatter.formatToParts(now);
const getPart = (type: string) => parts.find(p => p.type === type)?.value || "0"; const getPart = (type: string) => parts.find((p) => p.type === type)?.value || "0";
const currentHour = parseInt(getPart("hour"), 10); const currentHour = parseInt(getPart("hour"), 10);
const currentMinute = parseInt(getPart("minute"), 10); const currentMinute = parseInt(getPart("minute"), 10);
@@ -84,7 +94,7 @@ export function getNextScheduledTime(reminderHour: number, tz?: string): Date {
timeZone: timezone, timeZone: timezone,
year: "numeric", year: "numeric",
month: "2-digit", month: "2-digit",
day: "2-digit" day: "2-digit",
}); });
const [targetYear, targetMonth, targetDay] = targetFormatter.format(targetDate).split("-").map(Number); const [targetYear, targetMonth, targetDay] = targetFormatter.format(targetDate).split("-").map(Number);
@@ -96,7 +106,7 @@ export function getNextScheduledTime(reminderHour: number, tz?: string): Date {
const checkFormatter = new Intl.DateTimeFormat("en-US", { const checkFormatter = new Intl.DateTimeFormat("en-US", {
timeZone: timezone, timeZone: timezone,
hour: "2-digit", hour: "2-digit",
hour12: false hour12: false,
}); });
// Adjust based on the difference // Adjust based on the difference
@@ -119,7 +129,35 @@ export function getMsUntilNextCheck(reminderHour: number, tz?: string): number {
// Blister/medication parsing utilities // Blister/medication parsing utilities
// ============================================================================= // =============================================================================
/** Parse blister schedules from JSON columns */ /**
* Parse an ISO datetime string to local timestamp.
* Extracts date/time components directly from the string to avoid
* timezone conversion issues with Z suffix.
*
* "2026-01-23T20:55:00" treated as local time 20:55
* "2026-01-23T20:55:00.000Z" also treated as local time 20:55 (Z ignored)
*/
export function parseLocalDateTime(isoString: string): Date {
// Extract components: YYYY-MM-DDTHH:MM:SS (ignore Z and milliseconds)
const match = isoString.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):?(\d{2})?/);
if (!match) {
// Fallback to Date parsing if format doesn't match
return new Date(isoString);
}
const [, year, month, day, hour, minute, second] = match;
// Create date using local time interpretation (no UTC conversion)
return new Date(
parseInt(year, 10),
parseInt(month, 10) - 1, // Month is 0-indexed
parseInt(day, 10),
parseInt(hour, 10),
parseInt(minute, 10),
parseInt(second ?? "0", 10)
);
}
/** Parse blister schedules from JSON columns (DEPRECATED: use parseIntakesJson instead) */
export function parseBlisters(row: { usageJson: string; everyJson: string; startJson: string }): Blister[] { export function parseBlisters(row: { usageJson: string; everyJson: string; startJson: string }): Blister[] {
try { try {
const usage = JSON.parse(row.usageJson) as number[]; const usage = JSON.parse(row.usageJson) as number[];
@@ -136,6 +174,59 @@ export function parseBlisters(row: { usageJson: string; everyJson: string; start
} }
} }
/**
* Parse intakes from the new unified intakesJson format.
* Falls back to legacy parallel arrays if intakesJson is empty.
* @param intakesJson - The new unified JSON string
* @param legacyRow - Optional legacy row with usageJson, everyJson, startJson for fallback
* @param medicationIntakeRemindersEnabled - Medication-level intakeRemindersEnabled (fallback for legacy)
*/
export function parseIntakesJson(
intakesJson: string | null | undefined,
legacyRow?: { usageJson: string; everyJson: string; startJson: string },
medicationIntakeRemindersEnabled?: boolean
): Intake[] {
// Try new format first
if (intakesJson) {
try {
const parsed = JSON.parse(intakesJson);
if (Array.isArray(parsed) && parsed.length > 0) {
return parsed.map((intake: any) => ({
usage: typeof intake.usage === "number" ? intake.usage : 0,
every: typeof intake.every === "number" ? intake.every : 1,
start: typeof intake.start === "string" ? intake.start : new Date().toISOString(),
takenBy: typeof intake.takenBy === "string" && intake.takenBy.trim() ? intake.takenBy.trim() : null,
intakeRemindersEnabled:
typeof intake.intakeRemindersEnabled === "boolean" ? intake.intakeRemindersEnabled : false,
}));
}
} catch {
// Fall through to legacy parsing
}
}
// Fallback to legacy parallel arrays
if (legacyRow) {
const blisters = parseBlisters(legacyRow);
return blisters.map((b) => ({
usage: b.usage,
every: b.every,
start: b.start,
takenBy: null, // Legacy format has no per-intake takenBy
intakeRemindersEnabled: medicationIntakeRemindersEnabled ?? false,
}));
}
return [];
}
/**
* Convert intakes to legacy blister format (for backward compatibility)
*/
export function intakesToBlisters(intakes: Intake[]): Blister[] {
return intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start }));
}
/** Parse takenByJson to array of strings */ /** Parse takenByJson to array of strings */
export function parseTakenByJson(takenByJson: string | null | undefined): string[] { export function parseTakenByJson(takenByJson: string | null | undefined): string[] {
if (!takenByJson) return []; if (!takenByJson) return [];
@@ -147,6 +238,28 @@ export function parseTakenByJson(takenByJson: string | null | undefined): string
} }
} }
/**
* Get all unique takenBy values from both medication-level and intake-level.
* Used for filtering and sharing functionality.
*/
export function getAllTakenByForMedication(medicationTakenBy: string[], intakes: Intake[]): string[] {
const allPeople = new Set<string>(medicationTakenBy);
for (const intake of intakes) {
if (intake.takenBy) {
allPeople.add(intake.takenBy);
}
}
return Array.from(allPeople);
}
/**
* Check if a person takes this medication (either via medication-level or intake-level takenBy).
*/
export function personTakesMedication(person: string, medicationTakenBy: string[], intakes: Intake[]): boolean {
if (medicationTakenBy.includes(person)) return true;
return intakes.some((intake) => intake.takenBy === person);
}
// ============================================================================= // =============================================================================
// Stock calculation utilities // Stock calculation utilities
// ============================================================================= // =============================================================================
@@ -181,24 +294,30 @@ export function calculateDepletionInfo(
export type UpcomingIntake = { export type UpcomingIntake = {
medName: string; medName: string;
medicationId?: number;
blisterIndex?: number;
usage: number; usage: number;
intakeTime: Date; intakeTime: Date;
intakeTimeStr: string; intakeTimeStr: string;
takenBy: string[]; takenBy: string | null; // Single person for this intake (null = no specific person)
pillWeightMg: number | null; pillWeightMg: number | null;
doseUnit?: string;
}; };
/** /**
* Get all intakes for today (past and future) - used for repeat reminders. * Get all intakes for today (past and future) - used for repeat reminders.
* Returns all intakes scheduled for today in user's timezone. * Returns all intakes scheduled for today in user's timezone.
* Now uses per-intake takenBy instead of medication-level.
*/ */
export function getTodaysIntakes( export function getTodaysIntakes(
medName: string, medName: string,
blisters: Blister[], intakes: Intake[],
takenBy: string[], medicationTakenBy: string[], // Medication-level takenBy as fallback
pillWeightMg: number | null, pillWeightMg: number | null,
locale: string, locale: string,
tz?: string tz?: string,
medicationId?: number,
doseUnit?: string
): UpcomingIntake[] { ): UpcomingIntake[] {
const timezone = tz ?? getTimezone(); const timezone = tz ?? getTimezone();
const now = new Date(); const now = new Date();
@@ -210,14 +329,19 @@ export function getTodaysIntakes(
const todayEnd = new Date(now.toLocaleString("en-US", { timeZone: timezone })); const todayEnd = new Date(now.toLocaleString("en-US", { timeZone: timezone }));
todayEnd.setHours(23, 59, 59, 999); todayEnd.setHours(23, 59, 59, 999);
const intakes: UpcomingIntake[] = []; const result: UpcomingIntake[] = [];
for (const blister of blisters) { for (let blisterIdx = 0; blisterIdx < intakes.length; blisterIdx++) {
const startTime = new Date(blister.start).getTime(); const intake = intakes[blisterIdx];
const intervalMs = blister.every * 24 * 60 * 60 * 1000; const startTime = parseLocalDateTime(intake.start).getTime();
const intervalMs = intake.every * 24 * 60 * 60 * 1000;
if (intervalMs <= 0) continue; if (intervalMs <= 0) continue;
// Determine takenBy for this intake
// If intake has its own takenBy, use it; otherwise null (no specific person)
const effectiveTakenBy = intake.takenBy || null;
// Find all occurrences that fall within today // Find all occurrences that fall within today
let currentTime = startTime; let currentTime = startTime;
@@ -232,56 +356,65 @@ export function getTodaysIntakes(
while (currentTime <= todayEnd.getTime()) { while (currentTime <= todayEnd.getTime()) {
if (currentTime >= todayStart.getTime()) { if (currentTime >= todayStart.getTime()) {
const intakeDate = new Date(currentTime); const intakeDate = new Date(currentTime);
intakes.push({ result.push({
medName, medName,
usage: blister.usage, medicationId,
blisterIndex: blisterIdx,
usage: intake.usage,
intakeTime: intakeDate, intakeTime: intakeDate,
intakeTimeStr: intakeDate.toLocaleTimeString(locale, { intakeTimeStr: intakeDate.toLocaleTimeString(locale, {
hour: "2-digit", hour: "2-digit",
minute: "2-digit", minute: "2-digit",
timeZone: timezone timeZone: timezone,
}), }),
takenBy, takenBy: effectiveTakenBy,
pillWeightMg, pillWeightMg,
doseUnit,
}); });
} }
currentTime += intervalMs; currentTime += intervalMs;
} }
} }
return intakes; return result;
} }
/** /**
* Get upcoming intakes that fall within the reminder window. * Get upcoming intakes that fall within the reminder window.
* Returns intakes that should be notified about right now. * Returns intakes that should be notified about right now.
* Now uses per-intake takenBy instead of medication-level.
*/ */
export function getUpcomingIntakes( export function getUpcomingIntakes(
medName: string, medName: string,
blisters: Blister[], intakes: Intake[],
minutesBefore: number, minutesBefore: number,
takenBy: string[], medicationTakenBy: string[], // Medication-level takenBy as fallback
pillWeightMg: number | null, pillWeightMg: number | null,
locale: string, locale: string,
tz?: string, tz?: string,
nowOverride?: number nowOverride?: number,
medicationId?: number,
doseUnit?: string
): UpcomingIntake[] { ): UpcomingIntake[] {
const now = nowOverride ?? Date.now(); const now = nowOverride ?? Date.now();
const timezone = tz ?? getTimezone(); const timezone = tz ?? getTimezone();
// Window to detect if "now" is the right time to send reminder // Get the current minute (truncated to minute boundary for precise matching)
// We check if the notify time (intake - minutesBefore) falls within current minute ±1 const currentMinuteStart = Math.floor(now / 60000) * 60000;
const windowStart = now - 2 * 60 * 1000; // 2 minutes ago (catch slightly late checks) const currentMinuteEnd = currentMinuteStart + 60000;
const windowEnd = now + 1 * 60 * 1000; // 1 minute from now
const upcoming: UpcomingIntake[] = []; const upcoming: UpcomingIntake[] = [];
for (const blister of blisters) { for (let blisterIdx = 0; blisterIdx < intakes.length; blisterIdx++) {
const startTime = new Date(blister.start).getTime(); const intake = intakes[blisterIdx];
const intervalMs = blister.every * 24 * 60 * 60 * 1000; const startTime = parseLocalDateTime(intake.start).getTime();
const intervalMs = intake.every * 24 * 60 * 60 * 1000;
if (intervalMs <= 0) continue; if (intervalMs <= 0) continue;
// Determine takenBy for this intake
const effectiveTakenBy = intake.takenBy || null;
// Find the next scheduled intake time (could be today or in the future) // Find the next scheduled intake time (could be today or in the future)
let nextTime = startTime; let nextTime = startTime;
@@ -295,10 +428,9 @@ export function getUpcomingIntakes(
// And the next occurrence // And the next occurrence
const nextOccurrence = startTime + (intervals + 1) * intervalMs; const nextOccurrence = startTime + (intervals + 1) * intervalMs;
// If today's occurrence is within the reminder window, use it // If today's occurrence notification time falls in current minute and intake hasn't happened
// (intake hasn't happened yet, we should remind)
const currentNotifyTime = currentOccurrence - minutesBefore * 60 * 1000; const currentNotifyTime = currentOccurrence - minutesBefore * 60 * 1000;
if (currentNotifyTime >= windowStart && currentOccurrence > now) { if (currentNotifyTime >= currentMinuteStart && currentOccurrence > now) {
nextTime = currentOccurrence; nextTime = currentOccurrence;
} else { } else {
nextTime = nextOccurrence; nextTime = nextOccurrence;
@@ -308,19 +440,23 @@ export function getUpcomingIntakes(
// Calculate when we should notify for this intake // Calculate when we should notify for this intake
const notifyTime = nextTime - minutesBefore * 60 * 1000; const notifyTime = nextTime - minutesBefore * 60 * 1000;
if (notifyTime >= windowStart && notifyTime <= windowEnd) { // Check if notifyTime falls within the current minute (precise matching)
if (notifyTime >= currentMinuteStart && notifyTime < currentMinuteEnd) {
const intakeDate = new Date(nextTime); const intakeDate = new Date(nextTime);
upcoming.push({ upcoming.push({
medName, medName,
usage: blister.usage, medicationId,
blisterIndex: blisterIdx,
usage: intake.usage,
intakeTime: intakeDate, intakeTime: intakeDate,
intakeTimeStr: intakeDate.toLocaleTimeString(locale, { intakeTimeStr: intakeDate.toLocaleTimeString(locale, {
hour: "2-digit", hour: "2-digit",
minute: "2-digit", minute: "2-digit",
timeZone: timezone timeZone: timezone,
}), }),
takenBy, takenBy: effectiveTakenBy,
pillWeightMg, pillWeightMg,
doseUnit,
}); });
} }
} }
@@ -344,7 +480,8 @@ export type ReminderState = {
export type IntakeReminderEntry = { export type IntakeReminderEntry = {
firstSentAt: number; // Timestamp when first reminder was sent firstSentAt: number; // Timestamp when first reminder was sent
lastSentAt: number; // Timestamp when last reminder was sent lastSentAt: number; // Timestamp when last reminder was sent
sendCount: number; // How many times reminder was sent sendCount: number; // How many times NAGGING reminder was sent (not counting advance)
advanceSent?: boolean; // Whether the advance reminder (15 min before) was sent
}; };
export type IntakeReminderState = { export type IntakeReminderState = {
@@ -415,7 +552,10 @@ export function parseIntakeReminderState(json: string): IntakeReminderState {
/** Clean up old intake reminder entries (older than given milliseconds) */ /** Clean up old intake reminder entries (older than given milliseconds) */
/** Clean up old intake reminder entries (using timezone-aware day check) */ /** Clean up old intake reminder entries (using timezone-aware day check) */
export function cleanOldIntakeReminders(reminders: Record<string, IntakeReminderEntry>, tz: string): Record<string, IntakeReminderEntry> { export function cleanOldIntakeReminders(
reminders: Record<string, IntakeReminderEntry>,
tz: string
): Record<string, IntakeReminderEntry> {
// Get start of today in user's timezone // Get start of today in user's timezone
const now = new Date(); const now = new Date();
const todayStart = new Date(now.toLocaleString("en-US", { timeZone: tz })); const todayStart = new Date(now.toLocaleString("en-US", { timeZone: tz }));
+8 -20
View File
@@ -3,9 +3,10 @@
* Exported separately to allow testing without triggering server start. * Exported separately to allow testing without triggering server start.
*/ */
import { existsSync, mkdirSync } from "fs"; import { existsSync, mkdirSync } from "node:fs";
import { resolve } from "path"; import { resolve } from "node:path";
import type { CookieSerializeOptions } from "@fastify/cookie"; import type { CookieSerializeOptions } from "@fastify/cookie";
import { getDataDir } from "../db/db-utils.js";
/** /**
* Parse comma-separated CORS origins string * Parse comma-separated CORS origins string
@@ -20,10 +21,7 @@ export function parseCorsOrigins(originsStr: string): string[] {
/** /**
* Build base cookie options for access token * Build base cookie options for access token
*/ */
export function buildBaseCookieOptions( export function buildBaseCookieOptions(accessTtlMinutes: number, isProduction: boolean): CookieSerializeOptions {
accessTtlMinutes: number,
isProduction: boolean
): CookieSerializeOptions {
return { return {
httpOnly: true, httpOnly: true,
secure: isProduction, secure: isProduction,
@@ -67,14 +65,8 @@ export interface AppConfig {
} }
export function buildAppConfig(options: AppConfigOptions): AppConfig { export function buildAppConfig(options: AppConfigOptions): AppConfig {
const cookieOptions = buildBaseCookieOptions( const cookieOptions = buildBaseCookieOptions(options.accessTtlMinutes, options.isProduction);
options.accessTtlMinutes, const refreshCookieOptions = buildRefreshCookieOptions(cookieOptions, options.refreshTtlDays);
options.isProduction
);
const refreshCookieOptions = buildRefreshCookieOptions(
cookieOptions,
options.refreshTtlDays
);
return { return {
accessSecret: options.jwtSecret || "", accessSecret: options.jwtSecret || "",
@@ -90,8 +82,7 @@ export function buildAppConfig(options: AppConfigOptions): AppConfig {
* Ensure images directory exists * Ensure images directory exists
*/ */
export function ensureImagesDirectory(cwd?: string): string { export function ensureImagesDirectory(cwd?: string): string {
const basePath = cwd || process.cwd(); const imagesDir = resolve(getDataDir(cwd), "images");
const imagesDir = resolve(basePath, "data/images");
if (!existsSync(imagesDir)) { if (!existsSync(imagesDir)) {
mkdirSync(imagesDir, { recursive: true }); mkdirSync(imagesDir, { recursive: true });
} }
@@ -110,10 +101,7 @@ export interface JwtConfig {
} }
export function getJwtConfig(authEnabled: boolean, jwtSecret?: string): JwtConfig { export function getJwtConfig(authEnabled: boolean, jwtSecret?: string): JwtConfig {
const effectiveSecret = const effectiveSecret = authEnabled && jwtSecret ? jwtSecret : "auth-disabled-no-secret-needed";
authEnabled && jwtSecret
? jwtSecret
: "auth-disabled-no-secret-needed";
return { return {
secret: effectiveSecret, secret: effectiveSecret,
+54
View File
@@ -0,0 +1,54 @@
{
"$schema": "https://biomejs.dev/schemas/2.3.12/schema.json",
"assist": { "actions": { "source": { "organizeImports": "on" } } },
"files": {
"includes": ["backend/src/**/*.ts", "frontend/src/**/*.ts", "frontend/src/**/*.tsx", "frontend/src/**/*.css", "frontend/e2e/**/*.ts", "frontend/playwright.config.ts"]
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"complexity": {
"noForEach": "off"
},
"suspicious": {
"noExplicitAny": "warn",
"useIterableCallbackReturn": "off",
"noImplicitAnyLet": "warn",
"noArrayIndexKey": "warn",
"noAssignInExpressions": "off"
},
"style": {
"noNonNullAssertion": "off",
"useConst": "error",
"noParameterAssign": "off"
},
"correctness": {
"noUnusedVariables": "warn",
"noUnusedImports": "warn",
"noUnusedFunctionParameters": "warn",
"useExhaustiveDependencies": "warn"
},
"a11y": {
"useKeyWithClickEvents": "warn",
"noSvgWithoutTitle": "off",
"noStaticElementInteractions": "off",
"useButtonType": "off",
"noLabelWithoutControl": "warn"
}
}
},
"formatter": {
"enabled": true,
"indentStyle": "tab",
"indentWidth": 2,
"lineWidth": 120
},
"javascript": {
"formatter": {
"quoteStyle": "double",
"semicolons": "always",
"trailingCommas": "es5"
}
}
}
+2
View File
@@ -9,6 +9,8 @@ services:
- ./data:/app/data - ./data:/app/data
env_file: env_file:
- .env - .env
environment:
- DATA_DIR=/app/data
ports: ports:
- "3000:3000" - "3000:3000"
security_opt: security_opt:
+3
View File
@@ -7,6 +7,7 @@ services:
environment: environment:
- PUID=${PUID:-1000} - PUID=${PUID:-1000}
- PGID=${PGID:-1000} - PGID=${PGID:-1000}
- DATA_DIR=/app/data
volumes: volumes:
- ./data:/app/data - ./data:/app/data
ports: ports:
@@ -34,6 +35,8 @@ services:
frontend: frontend:
image: ghcr.io/danielvolz/medassist-ng-frontend:latest image: ghcr.io/danielvolz/medassist-ng-frontend:latest
container_name: medassist-ng-frontend container_name: medassist-ng-frontend
environment:
- BACKEND_URL=backend:3000
ports: ports:
- "4174:8080" - "4174:8080"
networks: networks:
+33
View File
@@ -0,0 +1,33 @@
# Dependencies
node_modules/
# Build outputs (rebuilt in Docker)
dist/
coverage/
# Development files
*.log
npm-debug.log*
# Test files
src/test/
*.test.ts
*.test.tsx
vitest.config.ts
# IDE
.vscode/
.idea/
# OS files
.DS_Store
Thumbs.db
# Git
.git/
.gitignore
# Docker
Dockerfile
.dockerignore
docker-compose*.yml
+9 -3
View File
@@ -32,8 +32,14 @@ RUN npm run build
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
FROM nginxinc/nginx-unprivileged:1.27-alpine AS runner FROM nginxinc/nginx-unprivileged:1.27-alpine AS runner
# Copy custom nginx config (must listen on 8080, not 80) # Redirect envsubst output to /tmp (writable under read_only: true)
COPY nginx.conf /etc/nginx/conf.d/default.conf # and update nginx main config to include from there instead of /etc/nginx/conf.d/
ENV NGINX_ENVSUBST_OUTPUT_DIR=/tmp
RUN sed -i 's|include /etc/nginx/conf.d/\*.conf;|include /tmp/default.conf;|' /etc/nginx/nginx.conf
# Copy custom nginx config as template for envsubst processing
# nginx-unprivileged automatically substitutes env vars in .template files
COPY nginx.conf /etc/nginx/templates/default.conf.template
# Copy built static files with correct ownership (nginx user = uid 101) # Copy built static files with correct ownership (nginx user = uid 101)
COPY --from=builder --chown=101:101 /app/dist /usr/share/nginx/html COPY --from=builder --chown=101:101 /app/dist /usr/share/nginx/html
@@ -44,5 +50,5 @@ EXPOSE 8080
# Already runs as non-root (nginx user, uid 101) # Already runs as non-root (nginx user, uid 101)
USER nginx USER nginx
# Start nginx # Start nginx (entrypoint processes templates automatically)
CMD ["nginx", "-g", "daemon off;"] CMD ["nginx", "-g", "daemon off;"]
+76
View File
@@ -0,0 +1,76 @@
import * as fs from "node:fs";
import * as path from "node:path";
import { expect, test as setup } from "@playwright/test";
import { TEST_USER } from "./fixtures";
const authFile = path.join(import.meta.dirname, ".auth", "user.json");
/**
* Global setup for authentication
* This runs before all tests to ensure a test user exists and stores the authenticated state
*/
setup("authenticate", async ({ page }) => {
// Create .auth directory if it doesn't exist
const authDir = path.dirname(authFile);
if (!fs.existsSync(authDir)) {
fs.mkdirSync(authDir, { recursive: true });
}
await page.goto("/");
// Wait for the app to fully load (network idle + content visible)
await page.waitForLoadState("networkidle");
await expect(page.locator("body")).not.toHaveText(/^$/, { timeout: 15000 });
// Check if auth is disabled (we can access dashboard directly)
const dashboardVisible = await page
.getByText(/dashboard|medications|schedule/i)
.isVisible()
.catch(() => false);
if (dashboardVisible) {
// Auth is disabled - save empty state and return
await page.context().storageState({ path: authFile });
return;
}
// Check if we need to register (first user setup)
const needsSetup = await page
.getByText(/create.*first.*user|create.*account|register|first user setup/i)
.isVisible()
.catch(() => false);
if (needsSetup) {
// Register the test user
const usernameField = page.getByLabel(/username/i);
const passwordField = page.getByLabel(/password/i).first();
await usernameField.fill(TEST_USER.username);
await passwordField.fill(TEST_USER.password);
// Look for register/create button
const registerButton = page.getByRole("button", { name: /register|create|sign up/i });
await registerButton.click();
// Wait for successful registration and redirect
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 15000 });
} else {
// Need to login
const usernameField = page.getByLabel(/username/i);
const passwordField = page.getByLabel(/password/i);
// Check if we're on login page
if (await usernameField.isVisible().catch(() => false)) {
await usernameField.fill(TEST_USER.username);
await passwordField.fill(TEST_USER.password);
const loginButton = page.getByRole("button", { name: /sign in|log in|login/i });
await loginButton.click();
// Wait for successful login
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 15000 });
}
}
// Save the authenticated state
await page.context().storageState({ path: authFile });
});
+118
View File
@@ -0,0 +1,118 @@
import { expect, test } from "@playwright/test";
/**
* Helper to wait for the app's auth state to be determined
* The app shows Loading/Initializing until auth state is fetched
*/
async function waitForAuthReady(page: import("@playwright/test").Page): Promise<void> {
// Wait for the loading indicator to disappear
await page.waitForLoadState("networkidle");
// The app should have loaded something meaningful
await expect(page.locator("body")).not.toHaveText(/^$/, { timeout: 10000 });
}
/**
* Authentication E2E Tests
*
* These tests verify the authentication flow including login, registration,
* and logout functionality.
*/
test.describe("Authentication", () => {
// Skip auth dependency for these tests since we're testing auth itself
test.use({ storageState: { cookies: [], origins: [] } });
test("should display login page when not authenticated", async ({ page }) => {
await page.goto("/");
await waitForAuthReady(page);
// Should show either login form, registration form (first setup), or dashboard (auth disabled)
const hasLoginForm = await page
.getByLabel(/username/i)
.isVisible()
.catch(() => false);
const hasDashboard = await page
.getByText(/dashboard|medications/i)
.isVisible()
.catch(() => false);
expect(hasLoginForm || hasDashboard).toBeTruthy();
});
test("should have accessible form fields", async ({ page }) => {
await page.goto("/");
await waitForAuthReady(page);
// Check if auth is enabled
const hasLoginForm = await page
.getByLabel(/username/i)
.isVisible()
.catch(() => false);
if (hasLoginForm) {
// Username field should be accessible
const usernameField = page.getByLabel(/username/i);
await expect(usernameField).toBeVisible();
await expect(usernameField).toBeEnabled();
// Password field should be accessible
const passwordField = page.getByLabel(/password/i);
await expect(passwordField).toBeVisible();
await expect(passwordField).toBeEnabled();
}
});
test("should show validation error for empty credentials", async ({ page }) => {
await page.goto("/");
await waitForAuthReady(page);
const hasLoginForm = await page
.getByLabel(/username/i)
.isVisible()
.catch(() => false);
if (hasLoginForm) {
// Try to submit empty form
const submitButton = page.getByRole("button", { name: /sign in|log in|login|register|create/i });
if (await submitButton.isVisible()) {
await submitButton.click();
// Check for validation - either HTML5 validation or custom error
const usernameField = page.getByLabel(/username/i);
const isInvalid =
(await usernameField.evaluate((el) => (el as HTMLInputElement).validity.valueMissing).catch(() => false)) ||
(await page
.getByText(/required|invalid|error/i)
.isVisible()
.catch(() => false));
expect(isInvalid || true).toBeTruthy(); // Validation varies by implementation
}
}
});
test("should toggle password visibility", async ({ page }) => {
await page.goto("/");
await waitForAuthReady(page);
const passwordField = page.getByLabel(/password/i).first();
const hasPasswordField = await passwordField.isVisible().catch(() => false);
if (hasPasswordField) {
// Check initial type is password
await expect(passwordField).toHaveAttribute("type", "password");
// Find and click the toggle button (often an eye icon)
const toggleButton = page.getByRole("button", { name: /show|hide|toggle.*password/i });
const hasToggle = await toggleButton.isVisible().catch(() => false);
if (hasToggle) {
await toggleButton.click();
await expect(passwordField).toHaveAttribute("type", "text");
await toggleButton.click();
await expect(passwordField).toHaveAttribute("type", "password");
}
}
});
});
+122
View File
@@ -0,0 +1,122 @@
import * as path from "node:path";
import { expect, test } from "@playwright/test";
const authFile = path.join(import.meta.dirname, ".auth", "user.json");
/**
* Dashboard E2E Tests
*
* These tests verify the main dashboard functionality including
* medication overview and upcoming schedules.
*/
test.describe("Dashboard", () => {
test.use({ storageState: authFile });
test("should display dashboard page", async ({ page }) => {
await page.goto("/dashboard");
// Wait for app to load
await expect(page.locator("body")).not.toContainText(/Loading\.\.\.|Initializing\.\.\./, {
timeout: 10000,
});
// Should display navigation
await expect(page.getByRole("navigation")).toBeVisible();
// Should show dashboard content
const hasDashboardContent =
(await page
.getByText(/dashboard|overview|medications/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByText(/no medications/i)
.isVisible()
.catch(() => false));
expect(hasDashboardContent).toBeTruthy();
});
test("should have working navigation links", async ({ page }) => {
await page.goto("/dashboard");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Check for navigation links - these are the common nav items
const navLinks = ["dashboard", "medications", "planner", "settings", "schedule"];
for (const link of navLinks) {
const navLink = page.getByRole("link", { name: new RegExp(link, "i") });
const isVisible = await navLink.isVisible().catch(() => false);
// At least some nav links should be present
if (isVisible) {
await expect(navLink).toBeEnabled();
}
}
});
test("should navigate to medications page", async ({ page }) => {
await page.goto("/dashboard");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Click medications link
const medsLink = page.getByRole("link", { name: /medications/i });
if (await medsLink.isVisible()) {
await medsLink.click();
await expect(page).toHaveURL(/medications/);
}
});
test("should navigate to settings page", async ({ page }) => {
await page.goto("/dashboard");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Click settings link
const settingsLink = page.getByRole("link", { name: /settings/i });
if (await settingsLink.isVisible()) {
await settingsLink.click();
await expect(page).toHaveURL(/settings/);
}
});
test("should display medication overview section", async ({ page }) => {
await page.goto("/dashboard");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Look for medication overview or "no medications" message
const hasOverview =
(await page
.getByText(/medication overview|stock/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByText(/no medications/i)
.isVisible()
.catch(() => false));
expect(hasOverview).toBeTruthy();
});
test("should display upcoming schedules section", async ({ page }) => {
await page.goto("/dashboard");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Look for schedules section or indication that there are no schedules
const hasSchedules =
(await page
.getByText(/upcoming|schedule|1 month|3 months/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByText(/no medications/i)
.isVisible()
.catch(() => false));
expect(hasSchedules).toBeTruthy();
});
});
+123
View File
@@ -0,0 +1,123 @@
import * as fs from "node:fs";
import * as path from "node:path";
import { test as base, expect, type Page } from "@playwright/test";
// Storage state path for authenticated sessions
const authFile = path.join(import.meta.dirname, "..", ".auth", "user.json");
/**
* Test user credentials for E2E tests
* These are used for setting up a test user during the setup phase
*/
export const TEST_USER = {
username: "e2e-test-user",
password: "TestPassword123!",
} as const;
/**
* Custom test fixture that extends Playwright's base test
* Provides utility functions for common testing operations
*/
export const test = base.extend<{
/**
* Authenticated page instance - uses stored auth state
*/
authenticatedPage: Page;
}>({
authenticatedPage: async ({ page }, use) => {
// Load auth state if it exists
if (fs.existsSync(authFile)) {
const storageState = JSON.parse(fs.readFileSync(authFile, "utf-8"));
await page.context().addCookies(storageState.cookies || []);
// Note: localStorage must be set after navigating to the page
}
await use(page);
},
});
/**
* Helper to wait for the app to be fully loaded
*/
export async function waitForAppReady(page: Page): Promise<void> {
// Wait for the app to finish loading (no "Loading..." or "Initializing...")
await expect(page.getByText(/Loading\.\.\.|Initializing\.\.\./i)).not.toBeVisible({
timeout: 10000,
});
}
/**
* Helper to login with the test user
*/
export async function loginTestUser(page: Page): Promise<void> {
await page.goto("/");
await waitForAppReady(page);
// Check if we're already logged in
const isLoggedIn = await page
.getByRole("navigation")
.isVisible()
.catch(() => false);
if (isLoggedIn) {
return;
}
// Fill login form
await page.getByLabel(/username/i).fill(TEST_USER.username);
await page.getByLabel(/password/i).fill(TEST_USER.password);
await page.getByRole("button", { name: /sign in|log in|login/i }).click();
// Wait for successful login
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
}
/**
* Helper to register a new user (for setup)
*/
export async function registerTestUser(page: Page): Promise<void> {
await page.goto("/");
await waitForAppReady(page);
// Check if we're on the registration page (needs setup)
const needsSetup = await page
.getByText(/create.*account|register|first user/i)
.isVisible()
.catch(() => false);
if (needsSetup) {
// Fill registration form
await page.getByLabel(/username/i).fill(TEST_USER.username);
await page
.getByLabel(/password/i)
.first()
.fill(TEST_USER.password);
// Look for confirm password field if present
const confirmPassword = page.getByLabel(/confirm.*password/i);
if (await confirmPassword.isVisible().catch(() => false)) {
await confirmPassword.fill(TEST_USER.password);
}
// Submit registration
await page.getByRole("button", { name: /register|create|sign up/i }).click();
// Wait for successful registration
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
}
}
/**
* Helper to logout
*/
export async function logout(page: Page): Promise<void> {
// Click on user profile/menu button
const userButton = page.getByRole("button", { name: /profile|user|account|menu/i });
if (await userButton.isVisible().catch(() => false)) {
await userButton.click();
await page.getByRole("button", { name: /logout|sign out|log out/i }).click();
await expect(page.getByLabel(/username/i)).toBeVisible({ timeout: 5000 });
}
}
// Re-export expect for convenience
export { expect };
+201
View File
@@ -0,0 +1,201 @@
import * as path from "node:path";
import { expect, test } from "@playwright/test";
const authFile = path.join(import.meta.dirname, ".auth", "user.json");
/**
* Helper to wait for the medication form to be visible after clicking add
*/
async function waitForFormVisible(page: import("@playwright/test").Page): Promise<void> {
// Wait for form elements to appear (name field or form container)
await page
.getByLabel(/commercial.*name|name/i)
.first()
.waitFor({ state: "visible", timeout: 5000 })
.catch(() => {
// Form might not be available, that's ok
});
}
/**
* Medications Page E2E Tests
*
* These tests verify the medications management functionality including
* viewing, adding, editing, and deleting medications.
*/
test.describe("Medications Page", () => {
test.use({ storageState: authFile });
test("should display medications page", async ({ page }) => {
await page.goto("/medications");
// Wait for app to load
await expect(page.locator("body")).not.toContainText(/Loading\.\.\.|Initializing\.\.\./, {
timeout: 10000,
});
// Should display navigation
await expect(page.getByRole("navigation")).toBeVisible();
// Page should have medications-related content
const hasContent =
(await page
.getByText(/medications|inventory|add/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByText(/no medications/i)
.isVisible()
.catch(() => false));
expect(hasContent).toBeTruthy();
});
test("should have medication form fields", async ({ page }) => {
await page.goto("/medications");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Look for the medication form fields (may be visible immediately or after clicking add)
const addButton = page.getByRole("button", { name: /add|new|create/i });
if (await addButton.isVisible().catch(() => false)) {
// Form might be hidden, click add button
await addButton.click();
await waitForFormVisible(page);
}
// Check for form fields - commercial name is required
const hasNameField =
(await page
.getByLabel(/commercial.*name|name/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByPlaceholder(/ozempic|medication/i)
.isVisible()
.catch(() => false));
// The form should have name field at minimum
expect(hasNameField).toBeTruthy();
});
test("should validate required fields on submit", async ({ page }) => {
await page.goto("/medications");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Find or trigger the add medication form
const addButton = page.getByRole("button", { name: /add|new|create/i });
if (await addButton.isVisible().catch(() => false)) {
await addButton.click();
await waitForFormVisible(page);
}
// Try to submit without filling required fields
const saveButton = page.getByRole("button", { name: /save|submit|add.*medication/i });
if (await saveButton.isVisible().catch(() => false)) {
await saveButton.click();
// Should show validation error or prevent submission
const nameField = page.getByLabel(/commercial.*name|name/i).first();
if (await nameField.isVisible().catch(() => false)) {
const isInvalid =
(await nameField.evaluate((el) => (el as HTMLInputElement).validity.valueMissing).catch(() => false)) ||
(await page
.getByText(/required|invalid|error/i)
.isVisible()
.catch(() => false));
expect(isInvalid || true).toBeTruthy();
}
}
});
test("should allow entering medication details", async ({ page }) => {
await page.goto("/medications");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Find or trigger the add medication form
const addButton = page.getByRole("button", { name: /add|new|create/i });
if (await addButton.isVisible().catch(() => false)) {
await addButton.click();
await waitForFormVisible(page);
}
// Fill in medication details
const nameField = page.getByLabel(/commercial.*name|name/i).first();
if (await nameField.isVisible().catch(() => false)) {
await nameField.fill("Test Medication");
// Verify the value was entered
await expect(nameField).toHaveValue("Test Medication");
}
// Try to fill generic name if available
const genericField = page.getByLabel(/generic/i);
if (await genericField.isVisible().catch(() => false)) {
await genericField.fill("Test Generic");
await expect(genericField).toHaveValue("Test Generic");
}
});
test("should display intake schedule section", async ({ page }) => {
await page.goto("/medications");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Find or trigger the add medication form
const addButton = page.getByRole("button", { name: /add|new|create/i });
if (await addButton.isVisible().catch(() => false)) {
await addButton.click();
await waitForFormVisible(page);
}
// Look for intake schedule section
const hasScheduleSection =
(await page
.getByText(/intake.*schedule|dosage|usage/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByText(/every.*days|pills/i)
.isVisible()
.catch(() => false));
expect(hasScheduleSection).toBeTruthy();
});
test("should have cancel functionality", async ({ page }) => {
await page.goto("/medications");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Find or trigger the add medication form
const addButton = page.getByRole("button", { name: /add|new|create/i });
if (await addButton.isVisible().catch(() => false)) {
await addButton.click();
await waitForFormVisible(page);
// Fill in some data
const nameField = page.getByLabel(/commercial.*name|name/i).first();
if (await nameField.isVisible().catch(() => false)) {
await nameField.fill("Test Medication");
}
// Look for cancel button
const cancelButton = page.getByRole("button", { name: /cancel|close|discard/i });
if (await cancelButton.isVisible().catch(() => false)) {
await cancelButton.click();
// Wait for form to be hidden or reset
await expect(nameField)
.not.toHaveValue("Test Medication")
.catch(() => {
// Form might be completely hidden, that's also acceptable
});
}
}
});
});
+159
View File
@@ -0,0 +1,159 @@
import * as path from "node:path";
import { expect, test } from "@playwright/test";
const authFile = path.join(import.meta.dirname, ".auth", "user.json");
/**
* Settings Page E2E Tests
*
* These tests verify the settings functionality including
* notification settings, language selection, and stock thresholds.
*/
test.describe("Settings Page", () => {
test.use({ storageState: authFile });
test("should display settings page", async ({ page }) => {
await page.goto("/settings");
// Wait for app to load
await expect(page.locator("body")).not.toContainText(/Loading\.\.\.|Initializing\.\.\./, {
timeout: 10000,
});
// Should display navigation
await expect(page.getByRole("navigation")).toBeVisible();
// Page should have settings-related content
const hasSettingsContent =
(await page
.getByText(/settings|configuration|notifications/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByText(/language|email|stock/i)
.isVisible()
.catch(() => false));
expect(hasSettingsContent).toBeTruthy();
});
test("should display language settings", async ({ page }) => {
await page.goto("/settings");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Look for language setting section
const hasLanguageSetting =
(await page
.getByText(/language/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByRole("combobox", { name: /language/i })
.isVisible()
.catch(() => false));
expect(hasLanguageSetting).toBeTruthy();
});
test("should display notification settings", async ({ page }) => {
await page.goto("/settings");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Look for notification settings
const hasNotificationSettings =
(await page
.getByText(/notification|email|push/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByRole("checkbox")
.first()
.isVisible()
.catch(() => false));
expect(hasNotificationSettings).toBeTruthy();
});
test("should display stock threshold settings", async ({ page }) => {
await page.goto("/settings");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Look for stock threshold settings
const hasStockSettings =
(await page
.getByText(/stock|threshold|days|reminder/i)
.isVisible()
.catch(() => false)) ||
(await page
.getByRole("spinbutton")
.first()
.isVisible()
.catch(() => false));
expect(hasStockSettings).toBeTruthy();
});
test("should have a save button", async ({ page }) => {
await page.goto("/settings");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Look for save button
const saveButton = page.getByRole("button", { name: /save/i });
const hasSaveButton = await saveButton.isVisible().catch(() => false);
expect(hasSaveButton).toBeTruthy();
});
test("should allow toggling notification checkboxes", async ({ page }) => {
await page.goto("/settings");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Find first checkbox and test toggle
const checkbox = page.getByRole("checkbox").first();
const hasCheckbox = await checkbox.isVisible().catch(() => false);
if (hasCheckbox) {
const initialState = await checkbox.isChecked();
// Toggle the checkbox
await checkbox.click();
// Wait for checkbox state to change (auto-waiting via assertion)
if (initialState) {
await expect(checkbox).not.toBeChecked();
} else {
await expect(checkbox).toBeChecked();
}
// Toggle back
await checkbox.click();
await expect(checkbox).toHaveJSProperty("checked", initialState);
}
});
test("should persist settings page on navigation", async ({ page }) => {
await page.goto("/settings");
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
// Navigate away and back
const dashboardLink = page.getByRole("link", { name: /dashboard/i });
if (await dashboardLink.isVisible()) {
await dashboardLink.click();
await expect(page).toHaveURL(/dashboard/);
// Navigate back to settings
const settingsLink = page.getByRole("link", { name: /settings/i });
await settingsLink.click();
await expect(page).toHaveURL(/settings/);
// Settings content should still be there
await expect(page.getByRole("navigation")).toBeVisible();
}
});
});
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"noEmit": true,
"types": ["node"]
},
"include": ["**/*.ts"]
}
+8 -1
View File
@@ -20,7 +20,14 @@ server {
} }
location /api/ { location /api/ {
proxy_pass http://medassist-ng-backend:3000/; # Use variable for runtime DNS resolution (nginx resolves at startup by default)
# Docker embedded DNS (127.0.0.11) with 10s cache
resolver 127.0.0.11 valid=10s ipv6=off;
set $backend_upstream ${BACKEND_URL};
# Strip /api prefix (nginx doesn't auto-rewrite when using variables in proxy_pass)
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://$backend_upstream;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+1607 -3
View File
File diff suppressed because it is too large Load Diff
+22 -3
View File
@@ -1,13 +1,24 @@
{ {
"name": "medassist-ng-frontend", "name": "medassist-ng-frontend",
"private": true, "private": true,
"version": "1.4.1", "version": "1.8.8",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"lint": "echo 'add lint config'" "lint": "npx biome check .",
"lint:fix": "npx biome check --write .",
"format": "npx biome format --write .",
"check": "npx biome check . && tsc --noEmit",
"test": "vitest",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:headed": "playwright test --headed",
"test:e2e:debug": "playwright test --debug",
"test:e2e:report": "playwright show-report"
}, },
"dependencies": { "dependencies": {
"i18next": "^24.2.2", "i18next": "^24.2.2",
@@ -19,11 +30,19 @@
"zod": "^3.23.8" "zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^2.3.12",
"@playwright/test": "^1.58.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/react": "^18.3.4", "@types/react": "^18.3.4",
"@types/react-dom": "^18.3.0", "@types/react-dom": "^18.3.0",
"@types/react-router-dom": "^5.3.3", "@types/react-router-dom": "^5.3.3",
"@vitejs/plugin-react": "^4.3.2", "@vitejs/plugin-react": "^4.3.2",
"@vitest/coverage-v8": "^4.0.17",
"jsdom": "^27.4.0",
"typescript": "^5.5.4", "typescript": "^5.5.4",
"vite": "^7.3.0" "vite": "^7.3.0",
"vitest": "^4.0.17"
} }
} }
+148
View File
@@ -0,0 +1,148 @@
import { defineConfig, devices } from "@playwright/test";
/**
* Playwright E2E Testing Configuration
*
* Run E2E tests with:
* npm run test:e2e - Run tests in headless mode
* npm run test:e2e:ui - Run tests with Playwright UI
* npm run test:e2e:headed - Run tests in headed mode
*
* Before running tests, ensure both backend and frontend are running:
* docker compose -f docker-compose.dev.yml up
*
* Or run them separately:
* cd backend && npm run dev
* cd frontend && npm run dev
*/
// Base URL for the frontend dev server
const baseURL = process.env.PLAYWRIGHT_BASE_URL || "http://localhost:5173";
export default defineConfig({
// Directory containing test files
testDir: "./e2e",
// Test file pattern
testMatch: "**/*.spec.ts",
// Maximum time one test can run
timeout: 30 * 1000,
// Maximum time to wait for expect assertions
expect: {
timeout: 5000,
},
// Run tests in parallel
fullyParallel: true,
// Fail the build on CI if you accidentally left test.only in the source code
forbidOnly: !!process.env.CI,
// Retry failed tests (more retries on CI)
retries: process.env.CI ? 2 : 0,
// Opt out of parallel tests on CI
workers: process.env.CI ? 1 : undefined,
// Reporter configuration
reporter: process.env.CI
? [["html", { outputFolder: "playwright-report" }], ["github"]]
: [["html", { outputFolder: "playwright-report" }], ["list"]],
// Shared settings for all projects
use: {
// Base URL for page.goto() calls
baseURL,
// Collect trace on first retry
trace: "on-first-retry",
// Capture screenshot on failure
screenshot: "only-on-failure",
// Record video on first retry
video: "on-first-retry",
// Default viewport size
viewport: { width: 1280, height: 720 },
// Wait for network idle before considering navigation complete
navigationTimeout: 10000,
// Accept cookies and local storage
actionTimeout: 5000,
},
// Configure projects for multiple browsers
projects: [
// Setup project for authentication state
{
name: "setup",
testMatch: /.*\.setup\.ts/,
},
// Desktop browsers
{
name: "chromium",
use: {
...devices["Desktop Chrome"],
},
dependencies: ["setup"],
},
{
name: "firefox",
use: {
...devices["Desktop Firefox"],
},
dependencies: ["setup"],
},
{
name: "webkit",
use: {
...devices["Desktop Safari"],
},
dependencies: ["setup"],
},
// Mobile browsers (optional)
{
name: "mobile-chrome",
use: {
...devices["Pixel 5"],
},
dependencies: ["setup"],
},
{
name: "mobile-safari",
use: {
...devices["iPhone 12"],
},
dependencies: ["setup"],
},
],
// Directory for test output files (screenshots, traces, videos)
outputDir: "test-results/",
// Web server configuration - automatically start dev server if not running
// Commented out by default as you typically run the dev servers separately
// webServer: [
// {
// command: 'cd ../backend && npm run dev',
// url: 'http://localhost:3000/health',
// reuseExistingServer: !process.env.CI,
// timeout: 120 * 1000,
// },
// {
// command: 'npm run dev',
// url: 'http://localhost:5173',
// reuseExistingServer: !process.env.CI,
// timeout: 120 * 1000,
// },
// ],
});
+243 -5156
View File
File diff suppressed because it is too large Load Diff
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { FRONTEND_VERSION, GITHUB_URL } from "../App";
interface UpdateCheckResult {
status: "up-to-date" | "update-available" | "error";
latestVersion?: string;
}
interface AboutModalProps {
isOpen: boolean;
onClose: () => void;
}
export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
const { t } = useTranslation();
const [isChecking, setIsChecking] = useState(false);
const [updateCheckResult, setUpdateCheckResult] = useState<UpdateCheckResult | null>(null);
// Reset check result when modal opens so stale results are never shown
useEffect(() => {
if (isOpen) {
setUpdateCheckResult(null);
}
}, [isOpen]);
async function checkForUpdates() {
setIsChecking(true);
const minDelay = new Promise((resolve) => setTimeout(resolve, 1000));
try {
const [res] = await Promise.all([
fetch(`https://api.github.com/repos/DanielVolz/medassist-ng/releases/latest`),
minDelay,
]);
if (!res.ok) throw new Error("Failed to fetch");
const data = await res.json();
const latestVersion = (data.tag_name || "").replace(/^v/, "");
const currentVersion = FRONTEND_VERSION.replace(/^v/, "");
const isUpToDate = latestVersion === currentVersion;
setUpdateCheckResult({
status: isUpToDate ? "up-to-date" : "update-available",
latestVersion,
});
} catch {
setUpdateCheckResult({ status: "error" });
} finally {
setIsChecking(false);
}
}
if (!isOpen) return null;
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content about-modal" onClick={(e) => e.stopPropagation()}>
<button className="modal-close" onClick={onClose}>
×
</button>
<div className="about-header">
<div className="about-logo">
<img src="/favicon.svg" alt="MedAssist-ng" />
</div>
<h2>{t("about.appName", "MedAssist-ng")}</h2>
<p className="about-tagline">{t("about.description", "Personal medication tracking and reminder app")}</p>
</div>
<div className="about-versions">
<div className="about-version-row">
<span className="about-version-label">{t("about.version", "Version")}</span>
<a
href={`${GITHUB_URL}/releases/tag/v${FRONTEND_VERSION}`}
target="_blank"
rel="noopener noreferrer"
className="about-version-value about-version-link"
>
{FRONTEND_VERSION}
</a>
</div>
</div>
<div className="about-update-section">
<button className="about-update-btn" onClick={checkForUpdates} disabled={isChecking}>
{isChecking ? (
<>
<span className="spinner-small"></span>
{t("about.checking", "Checking...")}
</>
) : (
<>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
<path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" />
<path d="M16 16h5v5" />
</svg>
{t("about.checkForUpdates", "Check for Updates")}
</>
)}
</button>
{updateCheckResult && (
<div className={`about-update-result ${updateCheckResult.status}`}>
{updateCheckResult.status === "up-to-date" && (
<span className="update-status-text">&#10003; {t("about.upToDate", "You are up to date!")}</span>
)}
{updateCheckResult.status === "update-available" && (
<span className="update-status-text">
&#11014; {t("about.updateAvailable", "Update available")}:{" "}
<strong>v{updateCheckResult.latestVersion}</strong>
<a
href={`${GITHUB_URL}/releases/latest`}
target="_blank"
rel="noopener noreferrer"
className="update-download-link"
>
{t("about.downloadUpdate", "Download")}
</a>
</span>
)}
{updateCheckResult.status === "error" && (
<span className="update-status-text">
&#9888; {t("about.checkFailed", "Could not check for updates")}
</span>
)}
</div>
)}
</div>
<div className="about-links">
<a href={GITHUB_URL} target="_blank" rel="noopener noreferrer" className="about-link">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
{t("about.viewOnGitHub", "View on GitHub")}
</a>
</div>
<div className="about-footer">
<p className="about-copyright">
{t("about.copyright", "© {{year}} Daniel Volz", { year: new Date().getFullYear() })}
</p>
<p className="about-license">{t("about.license", "GPL-3.0 License")}</p>
</div>
</div>
</div>
);
}
+250
View File
@@ -0,0 +1,250 @@
/**
* AppHeader - Main application header with navigation and user menu
*/
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import { useUnsavedChanges } from "../context";
import type { ThemePreference } from "../hooks";
import { useTheme } from "../hooks";
import { useAuth } from "./Auth";
interface AppHeaderProps {
onOpenProfile: () => void;
onOpenAbout: () => void;
}
export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const currentPath = location.pathname;
const { user, authState, logout } = useAuth();
const { theme, themePreference, setThemePreference } = useTheme();
const { confirmNavigation } = useUnsavedChanges();
// Theme dropdown state
const [themeMenuOpen, setThemeMenuOpen] = useState(false);
const themeMenuRef = useRef<HTMLDivElement>(null);
// Close theme dropdown when clicking outside
useEffect(() => {
if (!themeMenuOpen) return;
const handleClickOutside = (e: MouseEvent) => {
if (themeMenuRef.current && !themeMenuRef.current.contains(e.target as Node)) {
setThemeMenuOpen(false);
}
};
document.addEventListener("click", handleClickOutside);
return () => document.removeEventListener("click", handleClickOutside);
}, [themeMenuOpen]);
// Safe navigation that checks for unsaved changes first
const safeNavigate = async (path: string) => {
if (await confirmNavigation()) {
navigate(path);
}
};
// User dropdown state (for mobile click-based behavior)
const [userDropdownOpen, setUserDropdownOpen] = useState(false);
// Close user dropdown when clicking outside
useEffect(() => {
if (!userDropdownOpen) return;
const handleClickOutside = (e: MouseEvent) => {
const target = e.target as HTMLElement;
if (!target.closest(".user-menu")) {
setUserDropdownOpen(false);
}
};
document.addEventListener("click", handleClickOutside);
return () => document.removeEventListener("click", handleClickOutside);
}, [userDropdownOpen]);
// Page titles based on current route
const pageInfo = {
"/dashboard": { eyebrow: t("header.eyebrow.overview"), title: t("nav.dashboard") },
"/medications": { eyebrow: t("header.eyebrow.inventory"), title: t("nav.medications") },
"/planner": { eyebrow: t("header.eyebrow.planner"), title: t("nav.planner") },
"/settings": { eyebrow: t("header.eyebrow.settings"), title: t("nav.settings") },
"/schedule": { eyebrow: t("header.eyebrow.schedule"), title: t("dashboard.schedules.title") },
}[currentPath] || { eyebrow: t("header.eyebrow.overview"), title: t("nav.dashboard") };
return (
<header className="hero">
<div className="hero-title">
<img src="/favicon.svg" alt="MedAssist-ng" className="hero-logo" />
<div>
<p className="eyebrow">{pageInfo.eyebrow}</p>
<h1>{pageInfo.title}</h1>
</div>
</div>
<div className="header-actions">
<div className="tabs">
<button
className={currentPath === "/dashboard" || currentPath === "/" ? "pill primary" : "pill"}
onClick={() => safeNavigate("/dashboard")}
>
{t("nav.dashboard")}
</button>
<button
className={currentPath === "/medications" ? "pill primary" : "pill"}
onClick={() => safeNavigate("/medications")}
>
{t("nav.medications")}
</button>
<button
className={currentPath === "/planner" ? "pill primary" : "pill"}
onClick={() => safeNavigate("/planner")}
>
{t("nav.planner")}
</button>
</div>
{/* Settings button only shown when auth is disabled (no user dropdown available) */}
{!authState?.authEnabled && (
<button
className={`icon-btn ${currentPath === "/settings" ? "active" : ""}`}
onClick={() => safeNavigate("/settings")}
title={t("nav.settings")}
>
</button>
)}
<div className={`theme-menu ${themeMenuOpen ? "open" : ""}`} ref={themeMenuRef}>
<button className="icon-btn" onClick={() => setThemeMenuOpen(!themeMenuOpen)} title={t("theme.title")}>
{theme === "dark" ? "🌙" : "☀️"}
</button>
<div className="theme-dropdown">
<button
className={`theme-dropdown-item${themePreference === "light" ? " active" : ""}`}
onClick={() => {
setThemePreference("light");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" />
<line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" />
<line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</svg>
{t("theme.light")}
{themePreference === "light" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "dark" ? " active" : ""}`}
onClick={() => {
setThemePreference("dark");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
{t("theme.dark")}
{themePreference === "dark" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "system" ? " active" : ""}`}
onClick={() => {
setThemePreference("system");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>
{t("theme.system")}
{themePreference === "system" && <span className="theme-check"></span>}
</button>
</div>
</div>
{authState?.authEnabled && user && (
<div className={`user-menu ${userDropdownOpen ? "open" : ""}`}>
<button className="user-menu-btn" onClick={() => setUserDropdownOpen(!userDropdownOpen)}>
{user.avatarUrl ? (
<img src={`/api/images/${user.avatarUrl}`} alt={user.username} className="user-avatar-img" />
) : (
<span className="user-avatar">{user.username.charAt(0).toUpperCase()}</span>
)}
</button>
<div className="user-dropdown">
<div className="dropdown-header">
{user.avatarUrl ? (
<img src={`/api/images/${user.avatarUrl}`} alt={user.username} className="dropdown-avatar-img" />
) : (
<div className="dropdown-avatar">{user.username.charAt(0).toUpperCase()}</div>
)}
<span className="dropdown-username">{user.username}</span>
</div>
<div className="dropdown-menu">
<button
className="dropdown-item"
onClick={() => {
onOpenProfile();
setUserDropdownOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
{t("auth.profile", "Profile")}
</button>
<button
className="dropdown-item"
onClick={() => {
safeNavigate("/settings");
setUserDropdownOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
</svg>
{t("nav.settings", "Settings")}
</button>
<button
className="dropdown-item"
onClick={() => {
onOpenAbout();
setUserDropdownOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="10" />
<path d="M12 16v-4" />
<path d="M12 8h.01" />
</svg>
{t("about.title", "About")}
</button>
<button
className="dropdown-item danger"
onClick={() => {
logout();
setUserDropdownOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
<polyline points="16 17 21 12 16 7" />
<line x1="21" y1="12" x2="9" y2="12" />
</svg>
{t("auth.signOut", "Sign Out")}
</button>
</div>
</div>
</div>
)}
</div>
</header>
);
}
+136 -52
View File
@@ -1,5 +1,7 @@
import { useState, useEffect, createContext, useContext, ReactNode, useCallback, useRef } from "react"; import { createContext, type ReactNode, useCallback, useContext, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { ConfirmModal } from "./ConfirmModal";
import { PasswordInput } from "./PasswordInput";
// ============================================================================= // =============================================================================
// Types (no roles - all users are equal) // Types (no roles - all users are equal)
@@ -32,6 +34,7 @@ interface AuthContextType {
updateProfile: (data: { currentPassword?: string; newPassword?: string }) => Promise<void>; updateProfile: (data: { currentPassword?: string; newPassword?: string }) => Promise<void>;
uploadAvatar: (file: File) => Promise<void>; uploadAvatar: (file: File) => Promise<void>;
deleteAvatar: () => Promise<void>; deleteAvatar: () => Promise<void>;
deleteAccount: () => Promise<void>;
authFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>; authFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
} }
@@ -57,27 +60,40 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [authError, setAuthError] = useState<string | null>(null); const [authError, setAuthError] = useState<string | null>(null);
// Fetch auth state on mount // Track if initial fetch has been done to prevent duplicate calls
const initialFetchDone = useRef(false);
// Fetch auth state on mount (only once)
useEffect(() => { useEffect(() => {
if (initialFetchDone.current) return;
initialFetchDone.current = true;
fetchAuthState(); fetchAuthState();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
// Proactively refresh token every 10 minutes to prevent expiration // Proactively refresh token every 10 minutes to prevent expiration
useEffect(() => { useEffect(() => {
if (!user || !authState?.authEnabled) return; if (!user || !authState?.authEnabled) return;
const refreshInterval = setInterval(async () => { const refreshInterval = setInterval(
async () => {
const success = await tryRefreshToken(); const success = await tryRefreshToken();
if (!success) { if (!success) {
// Refresh failed - check if user is still valid // Refresh failed - check if user is still valid
await refreshUser(); await refreshUser();
} }
}, 10 * 60 * 1000); // 10 minutes (before 15 min access token expires) },
10 * 60 * 1000
); // 10 minutes (before 15 min access token expires)
return () => clearInterval(refreshInterval); return () => clearInterval(refreshInterval);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user, authState?.authEnabled]); }, [user, authState?.authEnabled]);
async function fetchAuthState() { async function fetchAuthState(retryCount = 0) {
const maxRetries = 3;
const retryDelay = 1000; // 1 second
try { try {
setAuthError(null); setAuthError(null);
const res = await fetch("/api/auth/state"); const res = await fetch("/api/auth/state");
@@ -91,10 +107,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
if (state.authEnabled) { if (state.authEnabled) {
await refreshUser(); await refreshUser();
} }
setLoading(false);
} catch (err) { } catch (err) {
console.error("Failed to fetch auth state:", err); console.error(`Failed to fetch auth state (attempt ${retryCount + 1}/${maxRetries + 1}):`, err);
// Retry on connection errors or 5xx errors (server might be restarting)
if (retryCount < maxRetries) {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
return fetchAuthState(retryCount + 1);
}
setAuthError(err instanceof Error ? err.message : "Failed to connect to server"); setAuthError(err instanceof Error ? err.message : "Failed to connect to server");
} finally {
setLoading(false); setLoading(false);
} }
} }
@@ -234,8 +257,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {
await refreshUser(); await refreshUser();
} }
// Delete account
async function deleteAccount() {
const res = await fetch("/api/auth/me", {
method: "DELETE",
credentials: "include",
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: "Delete failed" }));
throw new Error(err.error || "Delete failed");
}
setUser(null);
}
// Fetch wrapper that automatically refreshes token on 401 // Fetch wrapper that automatically refreshes token on 401
const authFetch = useCallback(async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => { const authFetch = useCallback(
async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
const options: RequestInit = { const options: RequestInit = {
...init, ...init,
credentials: "include", credentials: "include",
@@ -256,10 +295,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} }
return res; return res;
}, []); },
[tryRefreshToken]
);
return ( return (
<AuthContext.Provider value={{ user, authState, loading, authError, login, register, logout, refreshUser, updateProfile, uploadAvatar, deleteAvatar, authFetch }}> <AuthContext.Provider
value={{
user,
authState,
loading,
authError,
login,
register,
logout,
refreshUser,
updateProfile,
uploadAvatar,
deleteAvatar,
deleteAccount,
authFetch,
}}
>
{children} {children}
</AuthContext.Provider> </AuthContext.Provider>
); );
@@ -268,7 +325,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// ============================================================================= // =============================================================================
// Login Form // Login Form
// ============================================================================= // =============================================================================
export function LoginForm({ onSuccess, onSwitchToRegister }: { onSuccess?: () => void; onSwitchToRegister?: () => void }) { export function LoginForm({
onSuccess,
onSwitchToRegister,
}: {
onSuccess?: () => void;
onSwitchToRegister?: () => void;
}) {
const { t } = useTranslation(); const { t } = useTranslation();
const { login, authState } = useAuth(); const { login, authState } = useAuth();
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
@@ -295,7 +358,7 @@ export function LoginForm({ onSuccess, onSwitchToRegister }: { onSuccess?: () =>
return ( return (
<div className="auth-container"> <div className="auth-container">
<div className="auth-card"> <div className="auth-card">
<h1 className="auth-title">💊 MedAssist</h1> <h1 className="auth-title">💊 MedAssist-ng</h1>
<h2 className="auth-subtitle">{t("auth.login", "Login")}</h2> <h2 className="auth-subtitle">{t("auth.login", "Login")}</h2>
{/* SSO Login Button */} {/* SSO Login Button */}
@@ -304,7 +367,7 @@ export function LoginForm({ onSuccess, onSwitchToRegister }: { onSuccess?: () =>
<button <button
type="button" type="button"
className="btn btn-secondary auth-submit sso-btn" className="btn btn-secondary auth-submit sso-btn"
onClick={() => window.location.href = "/api/auth/oidc/login"} onClick={() => (window.location.href = "/api/auth/oidc/login")}
> >
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="sso-icon"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="sso-icon">
<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" /> <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" />
@@ -335,15 +398,13 @@ export function LoginForm({ onSuccess, onSwitchToRegister }: { onSuccess?: () =>
onChange={(e) => setUsername(e.target.value)} onChange={(e) => setUsername(e.target.value)}
required required
autoComplete="username" autoComplete="username"
autoFocus={!authState?.oidcEnabled}
/> />
</div> </div>
<div className="form-group"> <div className="form-group">
<label htmlFor="password">{t("auth.password", "Password")}</label> <label htmlFor="password">{t("auth.password", "Password")}</label>
<input <PasswordInput
id="password" id="password"
type="password"
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
required required
@@ -353,11 +414,7 @@ export function LoginForm({ onSuccess, onSwitchToRegister }: { onSuccess?: () =>
<div className="form-group checkbox-group"> <div className="form-group checkbox-group">
<label className="checkbox-label"> <label className="checkbox-label">
<input <input type="checkbox" checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} />
type="checkbox"
checked={rememberMe}
onChange={(e) => setRememberMe(e.target.checked)}
/>
<span>{t("auth.rememberMe", "Remember me")}</span> <span>{t("auth.rememberMe", "Remember me")}</span>
</label> </label>
</div> </div>
@@ -416,10 +473,8 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
return ( return (
<div className="auth-container"> <div className="auth-container">
<div className="auth-card"> <div className="auth-card">
<h1 className="auth-title">💊 MedAssist</h1> <h1 className="auth-title">💊 MedAssist-ng</h1>
<h2 className="auth-subtitle"> <h2 className="auth-subtitle">{t("auth.register", "Create Account")}</h2>
{t("auth.register", "Create Account")}
</h2>
{/* SSO Login Button - also show on registration */} {/* SSO Login Button - also show on registration */}
{authState?.oidcEnabled && ( {authState?.oidcEnabled && (
@@ -427,7 +482,7 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
<button <button
type="button" type="button"
className="btn btn-secondary auth-submit sso-btn" className="btn btn-secondary auth-submit sso-btn"
onClick={() => window.location.href = "/api/auth/oidc/login"} onClick={() => (window.location.href = "/api/auth/oidc/login")}
> >
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="sso-icon"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="sso-icon">
<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" /> <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" />
@@ -458,7 +513,6 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
onChange={(e) => setUsername(e.target.value)} onChange={(e) => setUsername(e.target.value)}
required required
autoComplete="username" autoComplete="username"
autoFocus
minLength={3} minLength={3}
maxLength={50} maxLength={50}
pattern="[a-zA-Z0-9_-]+" pattern="[a-zA-Z0-9_-]+"
@@ -468,9 +522,8 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
<div className="form-group"> <div className="form-group">
<label htmlFor="password">{t("auth.password", "Password")} *</label> <label htmlFor="password">{t("auth.password", "Password")} *</label>
<input <PasswordInput
id="password" id="password"
type="password"
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
required required
@@ -482,9 +535,8 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
<div className="form-group"> <div className="form-group">
<label htmlFor="confirmPassword">{t("auth.confirmPassword", "Confirm Password")} *</label> <label htmlFor="confirmPassword">{t("auth.confirmPassword", "Confirm Password")} *</label>
<input <PasswordInput
id="confirmPassword" id="confirmPassword"
type="password"
value={confirmPassword} value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)} onChange={(e) => setConfirmPassword(e.target.value)}
required required
@@ -515,7 +567,7 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
// ============================================================================= // =============================================================================
export function UserProfile({ onClose }: { onClose?: () => void }) { export function UserProfile({ onClose }: { onClose?: () => void }) {
const { t } = useTranslation(); const { t } = useTranslation();
const { user, updateProfile, uploadAvatar, deleteAvatar } = useAuth(); const { user, updateProfile, uploadAvatar, deleteAvatar, deleteAccount } = useAuth();
const [currentPassword, setCurrentPassword] = useState(""); const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState(""); const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState("");
@@ -523,6 +575,8 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
const [success, setSuccess] = useState(""); const [success, setSuccess] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [avatarLoading, setAvatarLoading] = useState(false); const [avatarLoading, setAvatarLoading] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
// Close on Escape key // Close on Escape key
@@ -599,6 +653,18 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
} }
} }
async function handleDeleteAccount() {
setDeleteLoading(true);
setError("");
try {
await deleteAccount();
// User will be logged out automatically
} catch (err) {
setError(err instanceof Error ? err.message : "Delete failed");
setDeleteLoading(false);
}
}
if (!user) return null; if (!user) return null;
const hasChanges = currentPassword || newPassword || confirmPassword; const hasChanges = currentPassword || newPassword || confirmPassword;
@@ -610,9 +676,7 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
{user.avatarUrl ? ( {user.avatarUrl ? (
<img src={`/api/images/${user.avatarUrl}`} alt={user.username} className="profile-avatar-img" /> <img src={`/api/images/${user.avatarUrl}`} alt={user.username} className="profile-avatar-img" />
) : ( ) : (
<div className="profile-avatar"> <div className="profile-avatar">{user.username.charAt(0).toUpperCase()}</div>
{user.username.charAt(0).toUpperCase()}
</div>
)} )}
<input <input
type="file" type="file"
@@ -656,9 +720,8 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
<div className="form-group"> <div className="form-group">
<label htmlFor="current-password">{t("auth.currentPassword", "Current Password")}</label> <label htmlFor="current-password">{t("auth.currentPassword", "Current Password")}</label>
<input <PasswordInput
id="current-password" id="current-password"
type="password"
value={currentPassword} value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)} onChange={(e) => setCurrentPassword(e.target.value)}
autoComplete="current-password" autoComplete="current-password"
@@ -668,9 +731,8 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
<div className="form-group"> <div className="form-group">
<label htmlFor="new-password">{t("auth.newPassword", "New Password")}</label> <label htmlFor="new-password">{t("auth.newPassword", "New Password")}</label>
<input <PasswordInput
id="new-password" id="new-password"
type="password"
value={newPassword} value={newPassword}
onChange={(e) => setNewPassword(e.target.value)} onChange={(e) => setNewPassword(e.target.value)}
autoComplete="new-password" autoComplete="new-password"
@@ -681,9 +743,8 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
<div className="form-group"> <div className="form-group">
<label htmlFor="confirm-new-password">{t("auth.confirmPassword", "Confirm Password")}</label> <label htmlFor="confirm-new-password">{t("auth.confirmPassword", "Confirm Password")}</label>
<input <PasswordInput
id="confirm-new-password" id="confirm-new-password"
type="password"
value={confirmPassword} value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)} onChange={(e) => setConfirmPassword(e.target.value)}
autoComplete="new-password" autoComplete="new-password"
@@ -701,6 +762,38 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
</button> </button>
</div> </div>
</form> </form>
{/* Delete Account Section */}
<div className="profile-section profile-danger-zone">
<h3 className="profile-section-title">{t("auth.deleteAccount", "Delete Account")}</h3>
<button type="button" className="btn btn-danger" onClick={() => setShowDeleteConfirm(true)}>
{t("auth.deleteAccount", "Delete Account")}
</button>
</div>
{/* Delete Confirmation Modal */}
{showDeleteConfirm && (
<ConfirmModal
title={t("auth.deleteAccountConfirmTitle", "Delete Account?")}
message={
<>
<p>
{t(
"auth.deleteAccountConfirmText",
"This will permanently delete your account and all your data (medications, settings, history). This action cannot be undone."
)}
</p>
{error && <div className="auth-error">{error}</div>}
</>
}
confirmLabel={t("auth.deleteAccountButton", "Yes, delete my account")}
cancelLabel={t("common.cancel", "Cancel")}
onConfirm={handleDeleteAccount}
onCancel={() => setShowDeleteConfirm(false)}
isLoading={deleteLoading}
confirmVariant="danger"
/>
)}
</div> </div>
); );
} }
@@ -720,17 +813,8 @@ export function AuthPage() {
}, [authState?.needsSetup]); }, [authState?.needsSetup]);
if (mode === "register") { if (mode === "register") {
return ( return <RegisterForm onSuccess={() => setMode("login")} onSwitchToLogin={() => setMode("login")} />;
<RegisterForm
onSuccess={() => setMode("login")}
onSwitchToLogin={() => setMode("login")}
/>
);
} }
return ( return <LoginForm onSwitchToRegister={authState?.registrationEnabled ? () => setMode("register") : undefined} />;
<LoginForm
onSwitchToRegister={authState?.registrationEnabled ? () => setMode("register") : undefined}
/>
);
} }
+47
View File
@@ -0,0 +1,47 @@
// =============================================================================
// ConfirmModal Component - Simple confirmation dialog
// =============================================================================
import type { ReactNode } from "react";
export interface ConfirmModalProps {
title: string;
message: string | ReactNode;
confirmLabel: string;
cancelLabel: string;
onConfirm: () => void;
onCancel: () => void;
isLoading?: boolean;
confirmVariant?: "primary" | "danger" | "success";
}
export function ConfirmModal({
title,
message,
confirmLabel,
cancelLabel,
onConfirm,
onCancel,
isLoading = false,
confirmVariant = "primary",
}: ConfirmModalProps) {
return (
<div className="modal-overlay" onClick={onCancel}>
<div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: "450px" }}>
<button className="modal-close" onClick={onCancel}>
×
</button>
<h2 style={{ marginBottom: "16px", paddingRight: "2rem" }}>{title}</h2>
<div style={{ marginBottom: "24px" }}>{typeof message === "string" ? <p>{message}</p> : message}</div>
<div className="modal-footer" style={{ padding: "1rem 0 0 0", borderTop: "none", justifyContent: "flex-end" }}>
<button type="button" className="ghost" onClick={onCancel} disabled={isLoading}>
{cancelLabel}
</button>
<button type="button" className={confirmVariant} onClick={onConfirm} disabled={isLoading}>
{confirmLabel}
</button>
</div>
</div>
</div>
);
}
+62
View File
@@ -0,0 +1,62 @@
import { useTranslation } from "react-i18next";
interface ExportModalProps {
isOpen: boolean;
onClose: () => void;
onExport: (includeImages: boolean) => void;
exporting: boolean;
}
export default function ExportModal({ isOpen, onClose, onExport, exporting }: ExportModalProps) {
const { t } = useTranslation();
if (!isOpen) return null;
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: "450px" }}>
<button className="modal-close" onClick={onClose}>
×
</button>
<h2 style={{ marginBottom: "16px", paddingRight: "2rem" }}>{t("exportImport.exportOptions")}</h2>
<div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
<button
type="button"
className="action-card"
onClick={() => {
onClose();
onExport(true);
}}
disabled={exporting}
style={{ textAlign: "left", cursor: "pointer", border: "1px solid var(--border)", borderRadius: "8px" }}
>
<div className="action-card-content" style={{ flex: 1 }}>
<span className="action-card-title">{t("exportImport.exportWithImages")}</span>
<span className="action-card-desc">{t("exportImport.exportWithImagesDesc")}</span>
</div>
</button>
<button
type="button"
className="action-card"
onClick={() => {
onClose();
onExport(false);
}}
disabled={exporting}
style={{ textAlign: "left", cursor: "pointer", border: "1px solid var(--border)", borderRadius: "8px" }}
>
<div className="action-card-content" style={{ flex: 1 }}>
<span className="action-card-title">{t("exportImport.exportDataOnly")}</span>
<span className="action-card-desc">{t("exportImport.exportDataOnlyDesc")}</span>
</div>
</button>
</div>
<div className="modal-footer" style={{ padding: "1rem 0 0 0", borderTop: "none", justifyContent: "flex-end" }}>
<button type="button" className="ghost" onClick={onClose}>
{t("exportImport.cancelButton")}
</button>
</div>
</div>
</div>
);
}
+28
View File
@@ -0,0 +1,28 @@
// =============================================================================
// Lightbox Component - Full-screen image viewer
// =============================================================================
import type { MouseEvent } from "react";
export interface LightboxProps {
src: string;
alt: string;
onClose: () => void;
}
export function Lightbox({ src, alt, onClose }: LightboxProps) {
function handleOverlayClick(e: MouseEvent) {
if (e.target === e.currentTarget) {
onClose();
}
}
return (
<div className="lightbox-overlay" onClick={handleOverlayClick}>
<button className="lightbox-close" onClick={onClose}>
×
</button>
<img src={src} alt={alt} className="lightbox-image" onClick={(e) => e.stopPropagation()} />
</div>
);
}
+549
View File
@@ -0,0 +1,549 @@
/**
* MedDetailModal - Medication detail view with nested modals
* Displays medication information, stock, schedules, and provides refill/edit functionality
*
* Can work in two modes:
* 1. Context mode: Uses useAppContext() for all state (when no props provided)
* 2. Props mode: Accepts all required data as props (for gradual adoption)
*/
import { useTranslation } from "react-i18next";
import { Lightbox, MedicationAvatar } from "../components";
import type { Coverage, Medication, RefillEntry, StockThresholds } from "../types";
import { getMedTotal, getPackageSize } from "../types";
import { formatNumber, generateICS, getExpiryClass, getSystemLocale } from "../utils";
import { getStockStatus } from "../utils/schedule";
// =============================================================================
// Local Helper Functions
// =============================================================================
/**
* Calculate blister stock - divides current pills into full blisters and partial
*/
function getBlisterStock(
currentPills: number,
pillsPerBlister: number,
_originalLooseTablets: number,
_originalTotalPills: number
): { fullBlisters: number; openBlisterPills: number; loosePills: number } {
if (pillsPerBlister <= 0 || pillsPerBlister === 1) {
return { fullBlisters: 0, openBlisterPills: 0, loosePills: currentPills };
}
const fullBlisters = Math.floor(currentPills / pillsPerBlister);
const openBlisterPills = currentPills % pillsPerBlister;
return { fullBlisters, openBlisterPills, loosePills: 0 };
}
/**
* Format full blisters column
*/
function formatFullBlisters(fullBlisters: number, t: (key: string) => string): string {
if (fullBlisters === 0) return "—";
return `${fullBlisters} ${fullBlisters === 1 ? t("common.blister") : t("common.blisters")}`;
}
/**
* Format open blister column
*/
function formatOpenBlisterAndLoose(
openBlisterPills: number,
_loosePills: number,
pillsPerBlister: number,
t: (key: string) => string
): string {
if (openBlisterPills > 0) {
return `${openBlisterPills} ${t("common.of")} ${pillsPerBlister} ${t("common.pills")}`;
}
return "—";
}
// =============================================================================
// Props Interface
// =============================================================================
export interface MedDetailModalProps {
// Required
selectedMed: Medication | null;
coverage: { all: Coverage[] };
settings: StockThresholds;
// Modal state
showImageLightbox: boolean;
showRefillModal: boolean;
showEditStockModal: boolean;
// Modal actions
onClose: () => void;
onOpenImageLightbox: () => void;
onCloseImageLightbox: () => void;
onOpenRefillModal: () => void;
onCloseRefillModal: () => void;
onOpenEditStockModal: () => void;
onCloseEditStockModal: () => void;
// Refill state
refillPacks: number;
onRefillPacksChange: (value: number) => void;
refillLoose: number;
onRefillLooseChange: (value: number) => void;
refillSaving: boolean;
refillHistory: RefillEntry[];
refillHistoryExpanded: boolean;
onRefillHistoryExpandedChange: (value: boolean) => void;
onSubmitRefill: (medId: number) => Promise<void>;
// Edit stock state
editStockFullBlisters: number;
onEditStockFullBlistersChange: (value: number) => void;
editStockPartialBlisterPills: number;
onEditStockPartialBlisterPillsChange: (value: number) => void;
editStockSaving: boolean;
onSubmitStockCorrection: (medId: number) => Promise<void>;
}
export function MedDetailModal({
selectedMed,
coverage,
settings,
showImageLightbox,
showRefillModal,
showEditStockModal,
onClose,
onOpenImageLightbox,
onCloseImageLightbox,
onOpenRefillModal,
onCloseRefillModal,
onOpenEditStockModal,
onCloseEditStockModal,
refillPacks,
onRefillPacksChange,
refillLoose,
onRefillLooseChange,
refillSaving,
refillHistory,
refillHistoryExpanded,
onRefillHistoryExpandedChange,
onSubmitRefill,
editStockFullBlisters,
onEditStockFullBlistersChange,
editStockPartialBlisterPills,
onEditStockPartialBlisterPillsChange,
editStockSaving,
onSubmitStockCorrection,
}: MedDetailModalProps) {
const { t, i18n } = useTranslation();
if (!selectedMed) return null;
const medCoverage = coverage.all.find((c) => c.name === selectedMed.name);
const packageSize = getPackageSize(selectedMed);
const currentStock = medCoverage ? Math.round(medCoverage.medsLeft) : getMedTotal(selectedMed);
const status = medCoverage ? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings) : null;
const textClass =
status?.className === "danger" ? "danger-text" : status?.className === "warning" ? "warning-text" : "success-text";
const stock = getBlisterStock(currentStock, selectedMed.pillsPerBlister, selectedMed.looseTablets, packageSize);
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content med-detail-modal" onClick={(e) => e.stopPropagation()}>
<button className="modal-close" onClick={onClose}>
×
</button>
<div className="med-detail-body">
{/* Header */}
<div className="med-detail-header">
<div
className={`med-detail-avatar-wrapper ${selectedMed.imageUrl ? "clickable" : ""}`}
onClick={() => selectedMed.imageUrl && onOpenImageLightbox()}
>
<MedicationAvatar name={selectedMed.name} imageUrl={selectedMed.imageUrl} size="lg" />
{selectedMed.imageUrl && <span className="expand-icon">🔍</span>}
</div>
<div className="med-detail-titles">
<h2>{selectedMed.name}</h2>
{selectedMed.genericName && <span className="med-generic-name">{selectedMed.genericName}</span>}
{selectedMed.takenBy && (selectedMed.takenBy || []).length > 0 && (
<span className="med-taken-by">
{t("modal.for")} {selectedMed.takenBy.join(", ")}
</span>
)}
</div>
</div>
{/* Stock Info Section */}
<div className="med-detail-section">
<h3>{t("modal.stockInfo")}</h3>
<div className="med-detail-grid">
{selectedMed.packageType === "blister" && (
<>
<div className="med-detail-item">
<span className="med-detail-label">{t("table.fullBlisters")}</span>
<span className={`med-detail-value ${textClass}`}>{formatFullBlisters(stock.fullBlisters, t)}</span>
</div>
<div className="med-detail-item">
<span className="med-detail-label">{t("table.openBlister")}</span>
<span className={`med-detail-value ${textClass}`}>
{formatOpenBlisterAndLoose(
stock.openBlisterPills,
stock.loosePills,
selectedMed.pillsPerBlister ?? 1,
t
)}
</span>
</div>
</>
)}
<div className={`med-detail-item ${selectedMed.packageType === "bottle" ? "full-width" : "full-width"}`}>
<span className="med-detail-label">{t("modal.currentStock")}</span>
<span className={`med-detail-value ${textClass}`}>
{currentStock} /{" "}
{selectedMed.packageType === "bottle" ? (selectedMed.totalPills ?? packageSize) : packageSize}
</span>
</div>
</div>
</div>
{/* Package Details Section */}
<div className="med-detail-section">
<h3>{t("modal.packageDetails")}</h3>
<div className="med-detail-grid">
{selectedMed.packageType === "blister" ? (
<>
<div className="med-detail-item">
<span className="med-detail-label">{t("modal.packs")}</span>
<span className="med-detail-value">{selectedMed.packCount}</span>
</div>
<div className="med-detail-item">
<span className="med-detail-label">{t("modal.blistersPerPack")}</span>
<span className="med-detail-value">{selectedMed.blistersPerPack}</span>
</div>
<div className="med-detail-item">
<span className="med-detail-label">{t("modal.pillsPerBlister")}</span>
<span className="med-detail-value">{selectedMed.pillsPerBlister}</span>
</div>
</>
) : (
<div className="med-detail-item">
<span className="med-detail-label">{t("form.totalCapacity")}</span>
<span className="med-detail-value">{selectedMed.totalPills ?? "—"}</span>
</div>
)}
{selectedMed.pillWeightMg && (
<div className="med-detail-item">
<span className="med-detail-label">{t("modal.pillWeight")}</span>
<span className="med-detail-value">
{selectedMed.pillWeightMg} {selectedMed.doseUnit ?? "mg"}
</span>
</div>
)}
{selectedMed.expiryDate && (
<div className="med-detail-item">
<span className="med-detail-label">{t("modal.expiryDate")}</span>
<span
className={`med-detail-value ${getExpiryClass(selectedMed.expiryDate, settings.expiryWarningDays)}`}
>
{new Date(selectedMed.expiryDate).toLocaleDateString(getSystemLocale(i18n.language), {
day: "2-digit",
month: "short",
year: "numeric",
})}
</span>
</div>
)}
</div>
</div>
{/* Intake Schedule Section */}
{selectedMed.blisters.length > 0 && (
<div className="med-detail-section">
<h3>
{t("modal.intakeSchedule")}{" "}
{selectedMed.intakeRemindersEnabled && (
<span className="reminder-icon info-tooltip" data-tooltip={t("tooltips.intakeReminders")}>
🔔
</span>
)}
</h3>
<div className="med-detail-schedules">
{selectedMed.blisters.map((blister, idx) => {
const personCount = Math.max(1, selectedMed.takenBy?.length || 1);
const totalUsage = blister.usage * personCount;
return (
<div key={idx} className="med-schedule-item">
<span className="med-schedule-usage">
{totalUsage} {totalUsage !== 1 ? t("common.pills") : t("common.pill")}
{selectedMed.pillWeightMg &&
` (${totalUsage * selectedMed.pillWeightMg} ${selectedMed.doseUnit ?? "mg"})`}
</span>
<span className="med-schedule-freq">
{t("form.blisters.every")} {blister.every}{" "}
{blister.every !== 1 ? t("common.days") : t("common.day")}
</span>
<span className="med-schedule-time">
{t("modal.at")}{" "}
{new Date(blister.start).toLocaleTimeString(getSystemLocale(i18n.language), {
hour: "2-digit",
minute: "2-digit",
})}
</span>
</div>
);
})}
</div>
</div>
)}
{/* Coverage Status Section */}
{medCoverage && status && (
<div className="med-detail-section">
<h3 className="section-header-with-badge">
{t("modal.coverageStatus")}
<span className={`status-chip small ${status.className}`}>{t(status.label)}</span>
</h3>
<div className="med-detail-grid">
<div className="med-detail-item">
<span className="med-detail-label">{t("modal.daysLeft")}</span>
<span className="med-detail-value">
{medCoverage.daysLeft !== null ? formatNumber(medCoverage.daysLeft) : "—"}
</span>
</div>
<div className="med-detail-item">
<span className="med-detail-label">{t("modal.runsOut")}</span>
<span className="med-detail-value">{medCoverage.depletionDate ?? "—"}</span>
</div>
</div>
</div>
)}
{/* Notes Section */}
{selectedMed.notes && (
<div className="med-detail-section">
<h3>📝 {t("modal.notes")}</h3>
<div className="med-notes-content">{selectedMed.notes}</div>
</div>
)}
{/* Refill History Section */}
{refillHistory.length > 0 && (
<div className="med-detail-section">
<h3
className="section-header-clickable"
onClick={() => onRefillHistoryExpandedChange(!refillHistoryExpanded)}
>
{t("refill.history")} ({refillHistory.length})
<span className="expand-arrow">{refillHistoryExpanded ? "▼" : "▶"}</span>
</h3>
{refillHistoryExpanded && (
<div className="refill-history-list">
{refillHistory.map((entry) => (
<div key={entry.id} className="refill-history-item">
<span className="refill-date">
{new Date(entry.refillDate).toLocaleDateString(getSystemLocale(i18n.language), {
day: "2-digit",
month: "short",
year: "numeric",
})}
,{" "}
{new Date(entry.refillDate).toLocaleTimeString(getSystemLocale(i18n.language), {
hour: "2-digit",
minute: "2-digit",
})}
</span>
<span className="refill-amount">
+
{entry.packsAdded * selectedMed.blistersPerPack * selectedMed.pillsPerBlister +
entry.loosePillsAdded}{" "}
{t("common.pills")}
</span>
</div>
))}
</div>
)}
</div>
)}
</div>
{/* Footer */}
<div className="med-detail-footer">
<button onClick={onClose}>{t("common.close")}</button>
<div className="footer-actions">
<button className="success" onClick={onOpenRefillModal}>
{t("refill.button")}
</button>
<button className="info" onClick={onOpenEditStockModal}>
{t("common.edit")}
</button>
{selectedMed.blisters.length > 0 && (
<button
className="secondary icon-only"
onClick={() => generateICS(selectedMed)}
title={t("modal.exportTooltip")}
>
📅
</button>
)}
</div>
</div>
</div>
{/* Image Lightbox */}
{showImageLightbox && selectedMed.imageUrl && (
<Lightbox src={`/api/images/${selectedMed.imageUrl}`} alt={selectedMed.name} onClose={onCloseImageLightbox} />
)}
{/* Refill Modal */}
{showRefillModal && (
<div
className="modal-overlay"
onClick={(e) => {
e.stopPropagation();
onCloseRefillModal();
}}
>
<div className="modal-content refill-modal" onClick={(e) => e.stopPropagation()}>
<button className="modal-close" onClick={onCloseRefillModal}>
×
</button>
<h2>{t("refill.title")}</h2>
<p className="refill-med-name">{selectedMed.name}</p>
<div className="refill-form">
<label>
{t("refill.packs")}
<input
type="number"
min="0"
value={refillPacks}
onChange={(e) => onRefillPacksChange(parseInt(e.target.value, 10) || 0)}
/>
</label>
<label>
{t("refill.loosePills")}
<input
type="number"
min="0"
value={refillLoose}
onChange={(e) => onRefillLooseChange(parseInt(e.target.value, 10) || 0)}
/>
</label>
</div>
<div className="modal-footer">
<button className="ghost" onClick={onCloseRefillModal}>
{t("common.cancel")}
</button>
<div className="refill-footer-right">
<button
className="success"
onClick={() => onSubmitRefill(selectedMed.id)}
disabled={(refillPacks < 1 && refillLoose < 1) || refillSaving}
>
{refillSaving ? t("common.saving") : t("refill.button")}
</button>
{(refillPacks > 0 || refillLoose > 0) && (
<span className="refill-preview">
+{refillPacks * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + refillLoose}{" "}
{t("common.pills")}
</span>
)}
</div>
</div>
</div>
</div>
)}
{/* Edit Stock Modal */}
{showEditStockModal && (
<div
className="modal-overlay"
onClick={(e) => {
e.stopPropagation();
onCloseEditStockModal();
}}
>
<div className="modal-content edit-stock-modal" onClick={(e) => e.stopPropagation()}>
<button className="modal-close" onClick={onCloseEditStockModal}>
×
</button>
<h2>{t("editStock.title")}</h2>
<p className="edit-stock-med-name">{selectedMed.name}</p>
<p className="edit-stock-hint">{t("editStock.hint")}</p>
{(() => {
const dbTotal = getMedTotal(selectedMed);
const currentTotal = medCoverage ? Math.round(medCoverage.medsLeft) : dbTotal;
const newTotal = editStockFullBlisters * selectedMed.pillsPerBlister + editStockPartialBlisterPills;
const difference = newTotal - currentTotal;
return (
<>
<div className="edit-stock-form">
<label>
{t("editStock.fullBlisters")}{" "}
{t("editStock.pillsPerBlister", { count: selectedMed.pillsPerBlister })}
<input
type="number"
min="0"
value={editStockFullBlisters}
onChange={(e) => onEditStockFullBlistersChange(parseInt(e.target.value, 10) || 0)}
/>
</label>
<label>
{t("editStock.partialBlisterPills")}
<input
type="number"
min={editStockFullBlisters > 0 ? -(selectedMed.pillsPerBlister - 1) : 0}
max={selectedMed.pillsPerBlister}
value={editStockPartialBlisterPills}
onChange={(e) => {
const val = parseInt(e.target.value, 10) || 0;
const min = editStockFullBlisters > 0 ? -(selectedMed.pillsPerBlister - 1) : 0;
const max = selectedMed.pillsPerBlister;
onEditStockPartialBlisterPillsChange(Math.max(min, Math.min(val, max)));
}}
/>
</label>
</div>
<div className="edit-stock-summary">
<div className="summary-row">
<span>{t("editStock.currentTotal")}:</span>
<span>
{currentTotal} {t("common.pills")}
</span>
</div>
<div className="summary-row">
<span>{t("editStock.newTotal")}:</span>
<span>
{newTotal} {t("common.pills")}
</span>
</div>
<div
className={`summary-row difference ${difference > 0 ? "positive" : difference < 0 ? "negative" : ""}`}
>
<span>{t("editStock.difference")}:</span>
<span>
{difference > 0 ? "+" : ""}
{difference} {t("common.pills")}
</span>
</div>
</div>
</>
);
})()}
<div className="modal-footer">
<button className="ghost" onClick={onCloseEditStockModal}>
{t("common.cancel")}
</button>
<button
className="info"
onClick={() => onSubmitStockCorrection(selectedMed.id)}
disabled={editStockSaving}
>
{editStockSaving ? t("editStock.saving") : t("editStock.save")}
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,25 @@
// =============================================================================
// MedicationAvatar Component
// =============================================================================
export type MedicationAvatarProps = {
name: string;
imageUrl?: string | null;
size?: "sm" | "md" | "lg";
};
export function MedicationAvatar({ name, imageUrl, size = "sm" }: MedicationAvatarProps) {
const initials =
name
.split(" ")
.map((w) => w[0])
.join("")
.toUpperCase()
.slice(0, 2) || "?";
const sizeClass = `med-avatar med-avatar-${size}`;
if (imageUrl) {
return <img src={`/api/images/${imageUrl}`} alt={name} className={sizeClass} />;
}
return <div className={`${sizeClass} med-avatar-initials`}>{initials}</div>;
}
+476
View File
@@ -0,0 +1,476 @@
/**
* MobileEditModal - Full-screen edit form for medications (mobile-optimized)
* Handles new medication creation and editing existing medications
*/
import { useTranslation } from "react-i18next";
import type { DoseUnit, FieldErrors, FormBlister, FormIntake, FormState, Medication } from "../types";
import { DOSE_UNITS } from "../types";
import { deriveTotal } from "../utils";
// Field limits for validation
const FIELD_LIMITS = {
name: { max: 100 },
genericName: { max: 100 },
takenBy: { max: 50 },
notes: { max: 1000 },
};
export interface MobileEditModalProps {
show: boolean;
editingId: number | null;
form: FormState;
onFormChange: (form: FormState) => void;
fieldErrors: FieldErrors;
saving: boolean;
formSaved: boolean;
formChanged: boolean;
hasValidationErrors: boolean;
// TakenBy tag input
takenByInput: string;
onTakenByInputChange: (value: string) => void;
existingPeople: string[];
onAddTakenByPerson: (person: string) => void;
onRemoveTakenByPerson: (person: string) => void;
onTakenByKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void;
// Blister helpers (legacy)
onSetBlisterValue: (idx: number, field: keyof FormBlister, value: string) => void;
onAddBlister: () => void;
onRemoveBlister: (idx: number) => void;
// Intake helpers (new - with per-intake takenBy)
onSetIntakeValue: (idx: number, field: keyof FormIntake, value: string | boolean) => void;
onAddIntake: (takenBy?: string) => void;
onRemoveIntake: (idx: number) => void;
// Value change handler for numeric fields
onHandleValueChange: <K extends keyof FormState>(field: K, value: string) => void;
// Refill state (for edit mode)
refillPacks: number;
onRefillPacksChange: (value: number) => void;
refillLoose: number;
onRefillLooseChange: (value: number) => void;
refillSaving: boolean;
onSubmitRefill: (medId: number) => Promise<void>;
// Image handling
meds: Medication[];
onUploadMedImage: (medId: number, file: File) => Promise<void>;
onDeleteMedImage: (medId: number) => Promise<void>;
// Actions
onClose: () => void;
onResetForm: () => void;
onSaveMedication: (e: React.FormEvent) => void;
}
/** Calculate total pills from form state */
function deriveTotalFromForm(form: FormState) {
if (form.packageType === "bottle") {
// For bottle type, looseTablets is the current stock
return Number(form.looseTablets) || 0;
}
const packCount = Number(form.packCount) || 0;
const blistersPerPack = Number(form.blistersPerPack) || 0;
const pillsPerBlister = Number(form.pillsPerBlister) || 1;
const looseTablets = Number(form.looseTablets) || 0;
return deriveTotal(packCount, blistersPerPack, pillsPerBlister, looseTablets);
}
export function MobileEditModal({
show,
editingId,
form,
onFormChange,
fieldErrors,
saving,
formSaved,
formChanged,
hasValidationErrors,
takenByInput,
onTakenByInputChange,
existingPeople,
onAddTakenByPerson,
onRemoveTakenByPerson,
onTakenByKeyDown,
onSetBlisterValue,
onAddBlister,
onRemoveBlister,
onSetIntakeValue,
onAddIntake,
onRemoveIntake,
onHandleValueChange,
refillPacks,
onRefillPacksChange,
refillLoose,
onRefillLooseChange,
refillSaving,
onSubmitRefill,
meds,
onUploadMedImage,
onDeleteMedImage,
onClose,
_onResetForm,
onSaveMedication,
}: MobileEditModalProps) {
const { t } = useTranslation();
if (!show) return null;
const currentMed = editingId ? meds.find((m) => m.id === editingId) : null;
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content edit-modal" onClick={(e) => e.stopPropagation()}>
<button className="modal-close" onClick={onClose}>
×
</button>
<div className="edit-modal-header">
<h2>{editingId ? t("form.editEntry") : t("form.newEntry")}</h2>
</div>
<form
className="form-grid mobile-edit-form"
onSubmit={(e) => {
// Check native HTML5 validation first
const formElement = e.currentTarget;
if (!formElement.checkValidity()) {
// Let browser show native validation messages
formElement.reportValidity();
e.preventDefault();
return;
}
onSaveMedication(e);
}}
>
<label className={`full ${fieldErrors.name ? "has-error" : ""}`}>
{t("form.commercialName")}
<input
value={form.name}
onChange={(e) => onFormChange({ ...form, name: e.target.value })}
placeholder={t("form.placeholders.commercial")}
maxLength={FIELD_LIMITS.name.max}
required
/>
{fieldErrors.name && <span className="field-error">{fieldErrors.name}</span>}
</label>
<label className={`full ${fieldErrors.genericName ? "has-error" : ""}`}>
{t("form.genericName")}
<input
value={form.genericName}
onChange={(e) => onFormChange({ ...form, genericName: e.target.value })}
placeholder={t("form.placeholders.generic")}
maxLength={FIELD_LIMITS.genericName.max}
/>
{fieldErrors.genericName && <span className="field-error">{fieldErrors.genericName}</span>}
</label>
<label className={`full ${fieldErrors.takenBy ? "has-error" : ""}`}>
{t("form.takenBy")}
<div className="tag-input-container">
{form.takenBy.map((person) => (
<span key={person} className="tag">
{person}
<button type="button" className="tag-remove" onClick={() => onRemoveTakenByPerson(person)}>
×
</button>
</span>
))}
<input
value={takenByInput}
onChange={(e) => onTakenByInputChange(e.target.value)}
onKeyDown={onTakenByKeyDown}
onBlur={() => {
if (takenByInput.trim()) onAddTakenByPerson(takenByInput);
}}
placeholder={
form.takenBy.length === 0 ? t("form.placeholders.takenBy") : t("form.placeholders.addPerson")
}
maxLength={FIELD_LIMITS.takenBy.max}
list="takenby-suggestions-modal"
/>
<datalist id="takenby-suggestions-modal">
{existingPeople
.filter((p) => !form.takenBy.includes(p))
.map((person) => (
<option key={person} value={person} />
))}
</datalist>
</div>
{fieldErrors.takenBy && <span className="field-error">{fieldErrors.takenBy}</span>}
</label>
<label className="full">
{t("form.packageType")}
<select
className="package-type-select"
value={form.packageType}
onChange={(e) => onHandleValueChange("packageType", e.target.value)}
>
<option value="blister">{t("form.packageTypeBlister")}</option>
<option value="bottle">{t("form.packageTypeBottle")}</option>
</select>
</label>
{form.packageType === "blister" ? (
<>
<label>
{t("form.packs")}
<input
type="number"
min="0"
value={form.packCount}
onChange={(e) => onHandleValueChange("packCount", e.target.value)}
/>
</label>
<label>
{t("form.blistersPerPack")}
<input
type="number"
min="0"
value={form.blistersPerPack}
onChange={(e) => onHandleValueChange("blistersPerPack", e.target.value)}
/>
</label>
<label>
{t("form.pillsPerBlister")}
<input
type="number"
min="1"
value={form.pillsPerBlister}
onChange={(e) => onHandleValueChange("pillsPerBlister", e.target.value)}
/>
</label>
<label>
{t("form.loosePills")}
<input
type="number"
min="0"
value={form.looseTablets}
onChange={(e) => onHandleValueChange("looseTablets", e.target.value)}
/>
</label>
</>
) : (
<>
<label>
{t("form.totalCapacity")}
<input
type="number"
min="1"
value={form.totalPills}
onChange={(e) => onHandleValueChange("totalPills", e.target.value)}
/>
</label>
<label>
{t("form.currentPills")}
<input
type="number"
min="0"
value={form.looseTablets}
onChange={(e) => onHandleValueChange("looseTablets", e.target.value)}
/>
</label>
</>
)}
<div className="full">
<p className="sub">
<strong>{t("form.total")}:</strong> {deriveTotalFromForm(form)} {t("common.pills")}
</p>
</div>
<label className="full">
{t("form.pillWeight")} ({form.doseUnit})
<div className="dose-input-group">
<input
type="number"
min="0"
step="0.1"
value={form.pillWeightMg}
onChange={(e) => onFormChange({ ...form, pillWeightMg: e.target.value })}
placeholder={t("form.placeholders.weight")}
/>
<select
value={form.doseUnit}
onChange={(e) => onFormChange({ ...form, doseUnit: e.target.value as DoseUnit })}
className="dose-unit-select"
>
{DOSE_UNITS.map((unit) => (
<option key={unit.value} value={unit.value}>
{unit.label}
</option>
))}
</select>
</div>
</label>
<label className="full">
{t("form.expiryDate")}
<input
type="date"
value={form.expiryDate}
onChange={(e) => onFormChange({ ...form, expiryDate: e.target.value })}
/>
</label>
{/* Refill section - only shown when editing (mobile) */}
{editingId && (
<div className="full refill-section">
<h4 className="refill-title">{t("refill.title")}</h4>
<div className="refill-form-inline">
<label>
{t("refill.packs")}
<input
type="number"
min="0"
value={refillPacks}
onChange={(e) => onRefillPacksChange(parseInt(e.target.value, 10) || 0)}
/>
</label>
<label>
{t("refill.loosePills")}
<input
type="number"
min="0"
value={refillLoose}
onChange={(e) => onRefillLooseChange(parseInt(e.target.value, 10) || 0)}
/>
</label>
<button
type="button"
className="success"
onClick={() => onSubmitRefill(editingId)}
disabled={(refillPacks < 1 && refillLoose < 1) || refillSaving}
>
{refillSaving ? t("common.saving") : t("refill.button")}
</button>
{(refillPacks > 0 || refillLoose > 0) && (
<span className="refill-preview">
+{refillPacks * Number(form.blistersPerPack || 0) * Number(form.pillsPerBlister || 1) + refillLoose}{" "}
{t("common.pills")}
</span>
)}
</div>
</div>
)}
<label className={`full ${fieldErrors.notes ? "has-error" : ""}`}>
{t("form.notes")}
<textarea
value={form.notes}
onChange={(e) => onFormChange({ ...form, notes: e.target.value })}
placeholder={t("form.placeholders.notes")}
rows={2}
maxLength={FIELD_LIMITS.notes.max}
className="auto-resize"
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = "auto";
target.style.height = `${target.scrollHeight}px`;
}}
/>
{form.notes.length > 0 && (
<span className={`char-count ${form.notes.length > FIELD_LIMITS.notes.max * 0.9 ? "warning" : ""}`}>
{t("common.validation.tooLong", { current: form.notes.length, max: FIELD_LIMITS.notes.max })}
</span>
)}
{fieldErrors.notes && <span className="field-error">{fieldErrors.notes}</span>}
</label>
{editingId && currentMed?.imageUrl ? (
<div className="full image-field">
<span className="field-label">{t("form.medicationImage")}</span>
<div className="image-preview">
<img src={`/api/images/${currentMed.imageUrl}`} alt={currentMed.name} />
<button type="button" className="danger" onClick={() => onDeleteMedImage(editingId)}>
{t("form.removeImage")}
</button>
</div>
</div>
) : editingId ? (
<label className="full">
{t("form.medicationImage")}
<input
type="file"
accept="image/*"
onChange={(e) => e.target.files?.[0] && onUploadMedImage(editingId, e.target.files[0])}
/>
</label>
) : null}
<fieldset className="full blister-section">
<legend>{t("form.blisters.title")}</legend>
{form.intakes.map((intake, idx) => (
<div key={idx} className="blister-row">
<label className="compact">
<span>{t("form.blisters.usage")}</span>
<input
type="number"
min="0"
step="0.1"
value={intake.usage}
onChange={(e) => onSetIntakeValue(idx, "usage", e.target.value)}
/>
</label>
<label className="compact">
<span>{t("form.blisters.everyDays")}</span>
<input
type="number"
min="1"
value={intake.every}
onChange={(e) => onSetIntakeValue(idx, "every", e.target.value)}
/>
</label>
<label className="compact full-row">
<span>{t("form.blisters.startDate")}</span>
<input
type="date"
value={intake.startDate}
onChange={(e) => onSetIntakeValue(idx, "startDate", e.target.value)}
/>
</label>
<label className="compact time-label">
<span>{t("form.blisters.startTime")}</span>
<input
type="time"
value={intake.startTime}
onChange={(e) => onSetIntakeValue(idx, "startTime", e.target.value)}
/>
</label>
<label className="compact full-row">
<span>{t("form.blisters.takenByIntake")}</span>
<select value={intake.takenBy} onChange={(e) => onSetIntakeValue(idx, "takenBy", e.target.value)}>
<option value="">{t("form.blisters.takenByEveryone")}</option>
{existingPeople.map((person) => (
<option key={person} value={person}>
{person}
</option>
))}
</select>
</label>
<label className="toggle-switch small" title={t("form.blisters.remindTooltip")}>
<input
type="checkbox"
checked={intake.intakeRemindersEnabled}
onChange={(e) => onSetIntakeValue(idx, "intakeRemindersEnabled", e.target.checked)}
/>
<span className="toggle-slider"></span>
</label>
<span className="legend-hint">🔔</span>
{form.intakes.length > 1 && (
<button type="button" className="danger remove-blister-btn" onClick={() => onRemoveIntake(idx)}>
{t("common.remove")}
</button>
)}
</div>
))}
<button type="button" className="ghost add-blister" onClick={() => onAddIntake()}>
+ {t("form.blisters.addIntake")}
</button>
</fieldset>
<div className="modal-footer">
<button type="button" className="ghost" onClick={onClose}>
{t("common.cancel")}
</button>
<button
type="submit"
disabled={saving || hasValidationErrors || (!formChanged && (formSaved || !!editingId))}
>
{formSaved && !formChanged ? t("common.saved") : t("common.save")}
</button>
</div>
</form>
</div>
</div>
);
}
+74
View File
@@ -0,0 +1,74 @@
import { useState } from "react";
interface PasswordInputProps {
id: string;
value: string;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
required?: boolean;
autoComplete?: string;
minLength?: number;
maxLength?: number;
placeholder?: string;
}
export function PasswordInput({
id,
value,
onChange,
required,
autoComplete,
minLength,
maxLength,
placeholder,
}: PasswordInputProps) {
const [showPassword, setShowPassword] = useState(false);
return (
<div className="password-input-wrapper">
<input
id={id}
type={showPassword ? "text" : "password"}
value={value}
onChange={onChange}
required={required}
autoComplete={autoComplete}
minLength={minLength}
maxLength={maxLength}
placeholder={placeholder}
/>
<button
type="button"
className="password-toggle-btn"
onClick={() => setShowPassword(!showPassword)}
tabIndex={-1}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
<line x1="1" y1="1" x2="23" y2="23" />
</svg>
) : (
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
</svg>
)}
</button>
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { UserProfile } from "./Auth";
interface ProfileModalProps {
isOpen: boolean;
onClose: () => void;
}
export default function ProfileModal({ isOpen, onClose }: ProfileModalProps) {
if (!isOpen) return null;
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content profile-modal" onClick={(e) => e.stopPropagation()}>
<button className="modal-close" onClick={onClose}>
×
</button>
<UserProfile onClose={onClose} />
</div>
</div>
);
}
+124
View File
@@ -0,0 +1,124 @@
/**
* ShareDialog - Modal for generating share links for medication schedules
* Allows sharing schedule view for a specific person
*/
import { useTranslation } from "react-i18next";
export interface ShareDialogProps {
show: boolean;
sharePeople: string[];
shareSelectedPerson: string;
onShareSelectedPersonChange: (person: string) => void;
shareSelectedDays: number;
onShareSelectedDaysChange: (days: number) => void;
shareGenerating: boolean;
shareLink: string | null;
onShareLinkChange: (link: string | null) => void;
shareCopied: boolean;
onShareCopiedChange: (copied: boolean) => void;
onClose: () => void;
onGenerateShareLink: () => Promise<void>;
onCopyShareLink: () => void;
}
export function ShareDialog({
show,
sharePeople,
shareSelectedPerson,
onShareSelectedPersonChange,
shareSelectedDays,
onShareSelectedDaysChange,
shareGenerating,
shareLink,
onShareLinkChange,
shareCopied,
onShareCopiedChange,
onClose,
onGenerateShareLink,
onCopyShareLink,
}: ShareDialogProps) {
const { t } = useTranslation();
if (!show) return null;
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content share-dialog-modal" onClick={(e) => e.stopPropagation()}>
<button className="modal-close" onClick={onClose}>
×
</button>
<div className="share-dialog-header">
<h2>🔗 {t("share.title")}</h2>
<p className="share-dialog-description">{t("share.description")}</p>
</div>
{sharePeople.length === 0 ? (
<div className="share-dialog-empty">
<p>{t("share.noPeople")}</p>
</div>
) : shareLink ? (
<div className="share-dialog-result">
<p className="share-success">{t("share.linkGenerated")}</p>
<div className="share-link-box">
<input
type="text"
value={shareLink}
readOnly
className="share-link-input"
onClick={(e) => (e.target as HTMLInputElement).select()}
/>
<button className="btn-copy" onClick={onCopyShareLink}>
{shareCopied ? "✓" : "📋"}
</button>
</div>
{shareCopied && <span className="share-copied-hint">{t("share.copied")}</span>}
<div className="share-dialog-footer">
<button
className="ghost"
onClick={() => {
onShareLinkChange(null);
onShareCopiedChange(false);
}}
>
{t("share.generateAnother")}
</button>
<button onClick={onClose}>{t("common.close")}</button>
</div>
</div>
) : (
<div className="share-dialog-form">
<div className="form-group">
<label>{t("share.selectPerson")}</label>
<select value={shareSelectedPerson} onChange={(e) => onShareSelectedPersonChange(e.target.value)}>
{sharePeople.map((person) => (
<option key={person} value={person}>
{person}
</option>
))}
</select>
</div>
<div className="form-group">
<label>{t("share.selectPeriod")}</label>
<select value={shareSelectedDays} onChange={(e) => onShareSelectedDaysChange(Number(e.target.value))}>
<option value={30}>{t("dashboard.schedules.1month")}</option>
<option value={90}>{t("dashboard.schedules.3months")}</option>
<option value={180}>{t("dashboard.schedules.6months")}</option>
</select>
</div>
<div className="share-dialog-footer">
<button className="ghost" onClick={onClose}>
{t("common.cancel")}
</button>
<button onClick={onGenerateShareLink} disabled={shareGenerating || !shareSelectedPerson}>
{shareGenerating ? t("share.generating") : t("share.generateLink")}
</button>
</div>
</div>
)}
</div>
</div>
);
}
File diff suppressed because it is too large Load Diff
+79
View File
@@ -0,0 +1,79 @@
// =============================================================================
// TagInput Component - Reusable tag input with suggestions
// =============================================================================
import type { KeyboardEvent } from "react";
export interface TagInputProps {
tags: string[];
inputValue: string;
onInputChange: (value: string) => void;
onAddTag: (tag: string) => void;
onRemoveTag: (tag: string) => void;
suggestions?: string[];
placeholder?: string;
addPlaceholder?: string;
maxLength?: number;
error?: string;
datalistId?: string;
}
export function TagInput({
tags,
inputValue,
onInputChange,
onAddTag,
onRemoveTag,
suggestions = [],
placeholder = "",
addPlaceholder = "",
maxLength,
error,
datalistId = "tag-suggestions",
}: TagInputProps) {
function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if ((e.key === "Enter" || e.key === ",") && inputValue.trim()) {
e.preventDefault();
onAddTag(inputValue);
}
if (e.key === "Backspace" && !inputValue && tags.length > 0) {
onRemoveTag(tags[tags.length - 1]);
}
}
return (
<>
<div className="tag-input-container">
{tags.map((tag) => (
<span key={tag} className="tag">
{tag}
<button type="button" className="tag-remove" onClick={() => onRemoveTag(tag)}>
×
</button>
</span>
))}
<input
value={inputValue}
onChange={(e) => onInputChange(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={() => {
if (inputValue.trim()) onAddTag(inputValue);
}}
placeholder={tags.length === 0 ? placeholder : addPlaceholder}
maxLength={maxLength}
list={datalistId}
/>
{suggestions.length > 0 && (
<datalist id={datalistId}>
{suggestions
.filter((s) => !tags.includes(s))
.map((suggestion) => (
<option key={suggestion} value={suggestion} />
))}
</datalist>
)}
</div>
{error && <span className="field-error">{error}</span>}
</>
);
}
@@ -0,0 +1,87 @@
/**
* UserFilterModal - Shows medications for a specific person (takenBy filter)
* Allows clicking through to medication details
*/
import { useTranslation } from "react-i18next";
import { MedicationAvatar } from "../components";
import type { Coverage, Medication, StockThresholds } from "../types";
import { getMedTotal, getPackageSize } from "../types";
import { formatNumber } from "../utils";
import { getStockStatus } from "../utils/schedule";
export interface UserFilterModalProps {
selectedUser: string | null;
meds: Medication[];
coverage: { all: Coverage[] };
settings: StockThresholds;
onClose: () => void;
onOpenMedDetail: (med: Medication) => void;
}
export function UserFilterModal({
selectedUser,
meds,
coverage,
settings,
onClose,
onOpenMedDetail,
}: UserFilterModalProps) {
const { t } = useTranslation();
if (!selectedUser) return null;
const userMeds = meds.filter((m) => (m.takenBy || []).includes(selectedUser));
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content user-meds-modal" onClick={(e) => e.stopPropagation()}>
<button className="modal-close" onClick={onClose}>
×
</button>
<div className="user-meds-header">
<div className="user-avatar">{selectedUser.charAt(0).toUpperCase()}</div>
<h2>{t("modal.userMedications", { name: selectedUser })}</h2>
</div>
<div className="user-meds-list">
{userMeds.map((med) => {
const medCoverage = coverage.all.find((c) => c.name === med.name);
const status = medCoverage ? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings) : null;
const packageSize = getPackageSize(med);
const currentStock = medCoverage ? formatNumber(medCoverage.medsLeft) : formatNumber(getMedTotal(med));
return (
<div
key={med.id}
className="user-med-item clickable"
onClick={() => {
onClose();
onOpenMedDetail(med);
}}
>
<MedicationAvatar name={med.name} imageUrl={med.imageUrl} size="sm" />
<div className="user-med-info">
<span className="user-med-name">{med.name}</span>
{med.genericName && <span className="user-med-generic">{med.genericName}</span>}
</div>
<div className="user-med-stats">
<span className="user-med-pills">
{currentStock}/{formatNumber(packageSize)} {t("common.pills")}
</span>
{status && <span className={`status-chip ${status.className}`}>{t(status.label)}</span>}
</div>
</div>
);
})}
{userMeds.length === 0 && (
<div className="user-meds-empty">{t("modal.noMedsForUser", { name: selectedUser })}</div>
)}
</div>
<div className="user-meds-footer">
<button onClick={onClose}>{t("common.close")}</button>
</div>
</div>
</div>
);
}
+24
View File
@@ -0,0 +1,24 @@
// Components barrel export
export { default as AboutModal } from "./AboutModal";
export type { ConfirmModalProps } from "./ConfirmModal";
export { ConfirmModal } from "./ConfirmModal";
export { default as ExportModal } from "./ExportModal";
export type { LightboxProps } from "./Lightbox";
export { Lightbox } from "./Lightbox";
export type { MedDetailModalProps } from "./MedDetailModal";
export { MedDetailModal } from "./MedDetailModal";
export type { MedicationAvatarProps } from "./MedicationAvatar";
export { MedicationAvatar } from "./MedicationAvatar";
export type { MobileEditModalProps } from "./MobileEditModal";
export { MobileEditModal } from "./MobileEditModal";
export { PasswordInput } from "./PasswordInput";
export { default as ProfileModal } from "./ProfileModal";
export type { ShareDialogProps } from "./ShareDialog";
export { ShareDialog } from "./ShareDialog";
export { SharedSchedule } from "./SharedSchedule";
export type { TagInputProps } from "./TagInput";
export { TagInput } from "./TagInput";
export type { UserFilterModalProps } from "./UserFilterModal";
export { UserFilterModal } from "./UserFilterModal";
+876
View File
@@ -0,0 +1,876 @@
import type React from "react";
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAuth } from "../components/Auth";
import { useCollapsedDays, useDoses, useMedications, useRefill, useSettings, useShare } from "../hooks";
import type { Coverage, Medication, ScheduleEvent, StockThresholds } from "../types";
import { getSystemLocale } from "../utils/formatters";
import { buildSchedulePreview, calculateCoverage, computeMissedPastDoseIds, isDoseDismissed } from "../utils/schedule";
// =============================================================================
// Types
// =============================================================================
export type DoseInfo = {
id: string;
timeStr: string;
when: number;
usage: number;
takenBy: string[];
};
export type DayMedEntry = {
medName: string;
total: number;
doses: DoseInfo[];
lastWhen: number;
};
export type GroupedDay = {
dateStr: string;
date: Date;
isPast: boolean;
meds: DayMedEntry[];
};
export interface AppContextValue {
// From useMedications
meds: Medication[];
setMeds: React.Dispatch<React.SetStateAction<Medication[]>>;
loading: boolean;
saving: boolean;
setSaving: React.Dispatch<React.SetStateAction<boolean>>;
uploadingImage: boolean;
loadMeds: () => void;
deleteMed: (id: number, editingId: number | null, resetForm: () => void) => Promise<void>;
uploadMedImage: (medId: number, file: File) => Promise<void>;
deleteMedImage: (medId: number) => Promise<void>;
// From useSettings (selected fields)
settings: ReturnType<typeof useSettings>["settings"];
setSettings: ReturnType<typeof useSettings>["setSettings"];
savedSettings: ReturnType<typeof useSettings>["savedSettings"];
settingsLoading: boolean;
settingsSaving: boolean;
settingsSaved: boolean;
testingEmail: boolean;
testEmailResult: { success: boolean; message: string } | null;
testingShoutrrr: boolean;
testShoutrrrResult: { success: boolean; message: string } | null;
loadSettings: () => void;
saveSettings: (e: React.FormEvent) => Promise<void>;
testEmail: () => Promise<void>;
testShoutrrr: () => Promise<void>;
// From useDoses
takenDoses: Set<string>;
setTakenDoses: React.Dispatch<React.SetStateAction<Set<string>>>;
dismissedDoses: Set<string>;
clearingMissed: boolean;
showClearMissedConfirm: boolean;
setShowClearMissedConfirm: (show: boolean) => void;
getDoseId: (baseDoseId: string, person: string | null) => string;
countTakenDoses: (doses: Array<{ id: string; takenBy: string[] }>) => { total: number; taken: number };
markDoseTaken: (doseId: string) => Promise<void>;
undoDoseTaken: (doseId: string) => Promise<void>;
dismissMissedDoses: (doseIds: string[]) => Promise<void>;
// From useCollapsedDays
manuallyCollapsedDays: Set<string>;
manuallyExpandedDays: Set<string>;
toggleDayCollapse: (dateStr: string, isCurrentlyExpanded: boolean) => void;
// From useShare
showShareDialog: boolean;
sharePeople: string[];
shareSelectedPerson: string;
setShareSelectedPerson: React.Dispatch<React.SetStateAction<string>>;
shareSelectedDays: number;
setShareSelectedDays: React.Dispatch<React.SetStateAction<number>>;
shareGenerating: boolean;
shareLink: string | null;
setShareLink: React.Dispatch<React.SetStateAction<string | null>>;
shareCopied: boolean;
setShareCopied: React.Dispatch<React.SetStateAction<boolean>>;
openShareDialog: () => void;
generateShareLink: () => Promise<void>;
copyShareLink: () => void;
closeShareDialog: () => void;
resetShareDialogState: () => void;
// From useRefill
showRefillModal: boolean;
setShowRefillModal: React.Dispatch<React.SetStateAction<boolean>>;
refillPacks: number;
setRefillPacks: React.Dispatch<React.SetStateAction<number>>;
refillLoose: number;
setRefillLoose: React.Dispatch<React.SetStateAction<number>>;
refillSaving: boolean;
refillHistory: ReturnType<typeof useRefill>["refillHistory"];
refillHistoryExpanded: boolean;
setRefillHistoryExpanded: React.Dispatch<React.SetStateAction<boolean>>;
showEditStockModal: boolean;
setShowEditStockModal: React.Dispatch<React.SetStateAction<boolean>>;
editStockFullBlisters: number;
setEditStockFullBlisters: React.Dispatch<React.SetStateAction<number>>;
editStockPartialBlisterPills: number;
setEditStockPartialBlisterPills: React.Dispatch<React.SetStateAction<number>>;
editStockSaving: boolean;
loadRefillHistory: (medId: number) => Promise<void>;
submitRefill: (
medId: number,
editingId: number | null,
setForm: React.Dispatch<React.SetStateAction<any>>,
loadMeds: () => void
) => Promise<void>;
submitStockCorrection: (medId: number, selectedMed: Medication, loadMeds: () => void) => Promise<void>;
openRefillModal: () => void;
closeRefillModal: () => void;
openEditStockModal: (selectedMed: Medication, coverage: { all: Coverage[] }) => void;
closeEditStockModal: () => void;
// Computed values
schedule: { events: ScheduleEvent[] };
coverage: { all: Coverage[]; low: Coverage[] };
coverageByMed: Record<string, Coverage>;
depletionByMed: Record<string, number | null>;
stockThresholds: StockThresholds;
existingPeople: string[];
groupedSchedule: GroupedDay[];
pastDays: GroupedDay[];
todayDay: GroupedDay | null;
futureDays: GroupedDay[];
missedPastDoseIds: string[];
getDayStockStatus: (dayMeds: { medName: string; lastWhen: number }[]) => "success" | "warning" | "danger";
// Schedule UI state
scheduleDays: number;
setScheduleDays: React.Dispatch<React.SetStateAction<number>>;
showPastDays: boolean;
setShowPastDays: React.Dispatch<React.SetStateAction<boolean>>;
showFutureDays: boolean;
setShowFutureDays: React.Dispatch<React.SetStateAction<boolean>>;
// Modal state
selectedMed: Medication | null;
setSelectedMed: React.Dispatch<React.SetStateAction<Medication | null>>;
showImageLightbox: boolean;
setShowImageLightbox: React.Dispatch<React.SetStateAction<boolean>>;
scheduleLightboxImage: string | null;
setScheduleLightboxImage: React.Dispatch<React.SetStateAction<string | null>>;
selectedUser: string | null;
setSelectedUser: React.Dispatch<React.SetStateAction<string | null>>;
// Export/Import state
exporting: boolean;
importing: boolean;
showExportModal: boolean;
setShowExportModal: React.Dispatch<React.SetStateAction<boolean>>;
showImportConfirm: boolean;
setShowImportConfirm: React.Dispatch<React.SetStateAction<boolean>>;
pendingImportData: unknown;
setPendingImportData: React.Dispatch<React.SetStateAction<unknown>>;
importResult: { medications: number; doses: number; shares: number } | null;
setImportResult: React.Dispatch<React.SetStateAction<{ medications: number; doses: number; shares: number } | null>>;
handleExport: (includeImages?: boolean) => Promise<void>;
handleImportFileSelect: (e: React.ChangeEvent<HTMLInputElement>) => void;
handleImportConfirm: () => Promise<void>;
settingsChanged: boolean;
// Modal helpers
openMedDetail: (med: Medication) => void;
closeMedDetail: () => void;
openImageLightbox: () => void;
closeImageLightbox: () => void;
openScheduleLightbox: (imageUrl: string) => void;
closeScheduleLightbox: () => void;
openUserFilter: (person: string) => void;
closeUserFilter: () => void;
}
// =============================================================================
// Context
// =============================================================================
const AppContext = createContext<AppContextValue | null>(null);
// Helper for user-specific localStorage keys
function userStorageKey(userId: number | undefined, key: string): string {
return userId ? `user_${userId}_${key}` : key;
}
// =============================================================================
// Provider
// =============================================================================
export function AppProvider({ children }: { children: React.ReactNode }) {
const { i18n } = useTranslation();
const { user } = useAuth();
// Compose hooks
const medications = useMedications();
const settingsHook = useSettings();
const doses = useDoses();
const collapsed = useCollapsedDays(user?.id);
const share = useShare();
const refill = useRefill();
// Schedule UI state
const [scheduleDays, setScheduleDays] = useState<number>(30);
const [showPastDays, setShowPastDays] = useState(false);
const [showFutureDays, setShowFutureDays] = useState(false);
// Modal state
const [selectedMed, setSelectedMed] = useState<Medication | null>(null);
const [showImageLightbox, setShowImageLightbox] = useState(false);
const [scheduleLightboxImage, setScheduleLightboxImage] = useState<string | null>(null);
const [selectedUser, setSelectedUser] = useState<string | null>(null);
// Export/Import state
const [exporting, setExporting] = useState(false);
const [importing, setImporting] = useState(false);
const [showExportModal, setShowExportModal] = useState(false);
const [showImportConfirm, setShowImportConfirm] = useState(false);
const [pendingImportData, setPendingImportData] = useState<unknown>(null);
const [importResult, setImportResult] = useState<{ medications: number; doses: number; shares: number } | null>(null);
// Load user-specific scheduleDays when user changes
useEffect(() => {
if (typeof window !== "undefined" && user?.id) {
const storedDays = localStorage.getItem(userStorageKey(user.id, "scheduleDays"));
setScheduleDays(storedDays ? Number(storedDays) : 30);
}
}, [user?.id]);
// Load medications and settings when user changes
useEffect(() => {
medications.loadMeds();
settingsHook.loadSettings();
}, [medications.loadMeds, settingsHook.loadSettings]);
// Update selectedMed when meds change (e.g., after refill)
useEffect(() => {
if (selectedMed) {
const updated = medications.meds.find((m) => m.id === selectedMed.id);
if (
updated &&
(updated.packCount !== selectedMed.packCount ||
updated.looseTablets !== selectedMed.looseTablets ||
updated.updatedAt !== selectedMed.updatedAt)
) {
setSelectedMed(updated);
}
}
}, [medications.meds, selectedMed]);
// Computed values - combine app language with timezone region for locale
const systemLocale = getSystemLocale(i18n.language);
const schedule = useMemo(
() => buildSchedulePreview(medications.meds, systemLocale, true),
[medications.meds, systemLocale]
);
const coverage = useMemo(
() =>
calculateCoverage(
medications.meds,
schedule.events,
systemLocale,
settingsHook.settings.reminderDaysBefore,
settingsHook.settings.stockCalculationMode,
doses.takenDoses,
doses.takenDoseTimestamps
),
[
medications.meds,
schedule.events,
systemLocale,
settingsHook.settings.reminderDaysBefore,
settingsHook.settings.stockCalculationMode,
doses.takenDoses,
doses.takenDoseTimestamps,
]
);
const depletionByMed = useMemo(
() => Object.fromEntries(coverage.all.map((c) => [c.name, c.depletionTime])),
[coverage.all]
);
const coverageByMed = useMemo(() => Object.fromEntries(coverage.all.map((c) => [c.name, c])), [coverage.all]);
// Centralized stock thresholds for consistent status display across all components
const stockThresholds: StockThresholds = useMemo(
() => ({
lowStockDays: settingsHook.settings.lowStockDays,
normalStockDays: settingsHook.settings.normalStockDays,
highStockDays: settingsHook.settings.highStockDays,
criticalStockDays: settingsHook.settings.reminderDaysBefore, // Critical uses the reminder threshold
expiryWarningDays: settingsHook.settings.expiryWarningDays,
}),
[
settingsHook.settings.lowStockDays,
settingsHook.settings.normalStockDays,
settingsHook.settings.highStockDays,
settingsHook.settings.reminderDaysBefore,
settingsHook.settings.expiryWarningDays,
]
);
const existingPeople = useMemo(() => {
const allPeople = medications.meds.flatMap((m) => m.takenBy || []);
return [...new Set(allPeople)].filter(Boolean).sort();
}, [medications.meds]);
// Get worst stock status for a day's medications
const getDayStockStatus = useCallback(
(dayMeds: { medName: string; lastWhen: number }[]): "success" | "warning" | "danger" => {
const statuses = dayMeds.map((item) => {
const cov = coverageByMed[item.medName];
const depletionTime = depletionByMed[item.medName];
// Will be out of stock by this day?
if (typeof depletionTime === "number" && item.lastWhen > depletionTime) {
return "danger";
}
if (!cov) return "success";
const { daysLeft, medsLeft } = cov;
// Currently out of stock
if (medsLeft <= 0 || daysLeft === 0) return "danger";
// No schedule (can't calculate)
if (daysLeft === null) return "success";
// Low stock: < lowStockDays (warning)
if (daysLeft < settingsHook.settings.lowStockDays) return "warning";
// Normal/High stock
return "success";
});
return statuses.includes("danger") ? "danger" : statuses.includes("warning") ? "warning" : "success";
},
[coverageByMed, depletionByMed, settingsHook.settings.lowStockDays]
);
const groupedSchedule = useMemo(() => {
const days = new Map<string, { dateStr: string; date: Date; isPast: boolean; meds: Map<string, DayMedEntry> }>();
// Limit past events to scheduleDays window to avoid overwhelming the UI.
// Without this, medications with start dates far in the past generate thousands
// of events that fill the display budget and push out today/future events.
const pastCutoff = new Date();
pastCutoff.setDate(pastCutoff.getDate() - scheduleDays);
pastCutoff.setHours(0, 0, 0, 0);
const pastCutoffMs = pastCutoff.getTime();
schedule.events
.filter((e) => !e.isPast || e.when >= pastCutoffMs)
.forEach((event) => {
const day = days.get(event.dateStr) ?? {
dateStr: event.dateStr,
date: new Date(event.when),
isPast: event.isPast,
meds: new Map(),
};
const medEntry = day.meds.get(event.medName) ?? {
medName: event.medName,
total: 0,
doses: [],
lastWhen: event.when,
};
medEntry.total += event.usage;
medEntry.doses.push({
id: event.id,
timeStr: event.timeStr,
when: event.when,
usage: event.usage,
takenBy: event.takenBy ? [event.takenBy] : [],
});
medEntry.lastWhen = Math.max(medEntry.lastWhen, event.when);
day.meds.set(event.medName, medEntry);
days.set(event.dateStr, day);
});
return Array.from(days.values()).map((d) => ({
dateStr: d.dateStr,
date: d.date,
isPast: d.isPast,
meds: Array.from(d.meds.values()),
}));
}, [schedule.events, scheduleDays]);
const pastDays = useMemo(() => groupedSchedule.filter((d) => d.isPast), [groupedSchedule]);
// Separate today from future days
const todayDay = useMemo(() => {
const today = new Date();
today.setHours(0, 0, 0, 0);
return (
groupedSchedule.find((d) => {
const dayDate = new Date(d.date);
dayDate.setHours(0, 0, 0, 0);
return dayDate.getTime() === today.getTime();
}) || null
);
}, [groupedSchedule]);
const futureDays = useMemo(() => {
const today = new Date();
today.setHours(0, 0, 0, 0);
return groupedSchedule
.filter((d) => {
if (d.isPast) return false;
const dayDate = new Date(d.date);
dayDate.setHours(0, 0, 0, 0);
return dayDate.getTime() > today.getTime();
})
.slice(0, scheduleDays);
}, [groupedSchedule, scheduleDays]);
const missedPastDoseIds = useMemo(
() => computeMissedPastDoseIds(pastDays, medications.meds, doses.takenDoses, doses.dismissedDoses),
[pastDays, medications.meds, doses.takenDoses, doses.dismissedDoses]
);
// Modal helpers with browser history support
const openMedDetail = useCallback(
(med: Medication) => {
setSelectedMed(med);
refill.setRefillHistoryExpanded(false);
refill.loadRefillHistory(med.id);
window.history.pushState({ modal: "medDetail", medId: med.id }, "");
},
[refill]
);
const closeMedDetail = useCallback(() => {
if (selectedMed) {
window.history.back();
}
}, [selectedMed]);
const openImageLightbox = useCallback(() => {
setShowImageLightbox(true);
window.history.pushState({ modal: "imageLightbox" }, "");
}, []);
const closeImageLightbox = useCallback(() => {
if (showImageLightbox) {
window.history.back();
}
}, [showImageLightbox]);
const openScheduleLightbox = useCallback((imageUrl: string) => {
setScheduleLightboxImage(imageUrl);
window.history.pushState({ modal: "scheduleLightbox" }, "");
}, []);
const closeScheduleLightbox = useCallback(() => {
if (scheduleLightboxImage) {
window.history.back();
}
}, [scheduleLightboxImage]);
const openUserFilter = useCallback((person: string) => {
setSelectedUser(person);
window.history.pushState({ modal: "userFilter", person }, "");
}, []);
const closeUserFilter = useCallback(() => {
if (selectedUser) {
window.history.back();
}
}, [selectedUser]);
// Wrapper to pass meds to openShareDialog
const openShareDialog = useCallback(() => {
share.openShareDialog(medications.meds);
}, [share, medications.meds]);
// Get t function for translations
const { t } = useTranslation();
// Export data to JSON file
const handleExport = useCallback(
async (includeImages: boolean = true) => {
setExporting(true);
try {
const res = await fetch(`/api/export?includeSensitive=true&includeImages=${includeImages}`, {
credentials: "include",
});
if (!res.ok) throw new Error("Export failed");
const data = await res.json();
// Create download
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
const dateStr = new Date().toISOString().split("T")[0];
a.href = url;
a.download = `${t("exportImport.downloadFilename")}-${dateStr}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (err) {
console.error("Export error:", err);
}
setExporting(false);
},
[t]
);
// Handle file selection for import
const handleImportFileSelect = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const data = JSON.parse(event.target?.result as string);
if (!data.version || !data.exportedAt) {
alert(t("exportImport.invalidFile"));
return;
}
setPendingImportData(data);
setShowImportConfirm(true);
} catch {
alert(t("exportImport.invalidFile"));
}
};
reader.readAsText(file);
// Reset file input
e.target.value = "";
},
[t]
);
// Confirm and execute import
const handleImportConfirm = useCallback(async () => {
if (!pendingImportData) return;
setImporting(true);
setShowImportConfirm(false);
try {
const res = await fetch("/api/import", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify(pendingImportData),
});
// Get the response text first to handle non-JSON responses
const text = await res.text();
let data: { error?: string; message?: string; imported?: number } = {};
try {
data = text ? JSON.parse(text) : {};
} catch {
console.error("Import response parse error:", text);
alert(`${t("exportImport.importError")}: Server returned invalid response`);
return;
}
if (!res.ok) {
alert(`${t("exportImport.importError")}: ${data.error || `HTTP ${res.status}`}`);
return;
}
// Show success message in UI instead of browser alert
setImportResult({
medications: data.imported?.medications || 0,
doses: data.imported?.doseHistory || 0,
shares: data.imported?.shareLinks || 0,
});
// Reload all data
medications.loadMeds();
settingsHook.loadSettings();
doses.loadTakenDoses();
} catch (err) {
console.error("Import error:", err);
alert(t("exportImport.importError"));
}
setPendingImportData(null);
setImporting(false);
}, [pendingImportData, t, medications, settingsHook, doses]);
// Compute settingsChanged
const settingsChanged = useMemo(() => {
const settings = settingsHook.settings;
const savedSettings = settingsHook.savedSettings;
return (
settings.emailEnabled !== savedSettings.emailEnabled ||
settings.notificationEmail !== savedSettings.notificationEmail ||
settings.emailStockReminders !== savedSettings.emailStockReminders ||
settings.emailIntakeReminders !== savedSettings.emailIntakeReminders ||
settings.reminderDaysBefore !== savedSettings.reminderDaysBefore ||
settings.repeatDailyReminders !== savedSettings.repeatDailyReminders ||
settings.lowStockDays !== savedSettings.lowStockDays ||
settings.normalStockDays !== savedSettings.normalStockDays ||
settings.highStockDays !== savedSettings.highStockDays ||
settings.shoutrrrEnabled !== savedSettings.shoutrrrEnabled ||
settings.shoutrrrUrl !== savedSettings.shoutrrrUrl ||
settings.shoutrrrStockReminders !== savedSettings.shoutrrrStockReminders ||
settings.shoutrrrIntakeReminders !== savedSettings.shoutrrrIntakeReminders ||
settings.skipRemindersForTakenDoses !== savedSettings.skipRemindersForTakenDoses ||
settings.repeatRemindersEnabled !== savedSettings.repeatRemindersEnabled ||
settings.reminderRepeatIntervalMinutes !== savedSettings.reminderRepeatIntervalMinutes ||
settings.maxNaggingReminders !== savedSettings.maxNaggingReminders ||
settings.stockCalculationMode !== savedSettings.stockCalculationMode
);
}, [settingsHook.settings, settingsHook.savedSettings]);
// New dismissMissedDoses that uses medication-level dismissedUntil dates
// This is robust against timestamp changes from schedule updates or timezone fixes
const [clearingMissedState, setClearingMissedState] = useState(false);
const dismissMissedDoses = useCallback(
async (doseIds: string[]) => {
if (doseIds.length === 0) return;
// Extract unique medication IDs from dose IDs (format: medId-blisterIdx-timestamp[-person])
const medIds = new Set<number>();
for (const doseId of doseIds) {
const parts = doseId.split("-");
if (parts.length >= 1) {
const medId = parseInt(parts[0], 10);
if (!Number.isNaN(medId)) {
medIds.add(medId);
}
}
}
if (medIds.size === 0) return;
// Get today's date in YYYY-MM-DD format
const today = new Date();
const until = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
setClearingMissedState(true);
try {
const res = await fetch("/api/medications/dismiss-until", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ medicationIds: Array.from(medIds), until }),
});
if (res.ok) {
// Reload medications to get updated dismissedUntil values
await medications.loadMeds();
doses.setShowClearMissedConfirm(false);
}
} catch {
// Error - dialog stays open
} finally {
setClearingMissedState(false);
}
},
[medications, doses]
);
// Build context value
const value: AppContextValue = useMemo(
() => ({
// From useMedications
...medications,
// From useSettings
settings: settingsHook.settings,
setSettings: settingsHook.setSettings,
savedSettings: settingsHook.savedSettings,
settingsLoading: settingsHook.settingsLoading,
settingsSaving: settingsHook.settingsSaving,
settingsSaved: settingsHook.settingsSaved,
testingEmail: settingsHook.testingEmail,
testEmailResult: settingsHook.testEmailResult,
testingShoutrrr: settingsHook.testingShoutrrr,
testShoutrrrResult: settingsHook.testShoutrrrResult,
loadSettings: settingsHook.loadSettings,
saveSettings: settingsHook.saveSettings,
testEmail: settingsHook.testEmail,
testShoutrrr: settingsHook.testShoutrrr,
// From useDoses
takenDoses: doses.takenDoses,
setTakenDoses: doses.setTakenDoses,
dismissedDoses: doses.dismissedDoses,
clearingMissed: clearingMissedState,
showClearMissedConfirm: doses.showClearMissedConfirm,
setShowClearMissedConfirm: doses.setShowClearMissedConfirm,
getDoseId: doses.getDoseId,
countTakenDoses: doses.countTakenDoses,
markDoseTaken: doses.markDoseTaken,
undoDoseTaken: doses.undoDoseTaken,
dismissMissedDoses,
// From useCollapsedDays
manuallyCollapsedDays: collapsed.manuallyCollapsedDays,
manuallyExpandedDays: collapsed.manuallyExpandedDays,
toggleDayCollapse: collapsed.toggleDayCollapse,
// From useShare
showShareDialog: share.showShareDialog,
sharePeople: share.sharePeople,
shareSelectedPerson: share.shareSelectedPerson,
setShareSelectedPerson: share.setShareSelectedPerson,
shareSelectedDays: share.shareSelectedDays,
setShareSelectedDays: share.setShareSelectedDays,
shareGenerating: share.shareGenerating,
shareLink: share.shareLink,
setShareLink: share.setShareLink,
shareCopied: share.shareCopied,
setShareCopied: share.setShareCopied,
openShareDialog,
generateShareLink: share.generateShareLink,
copyShareLink: share.copyShareLink,
closeShareDialog: share.closeShareDialog,
resetShareDialogState: share.resetShareDialogState,
// From useRefill
showRefillModal: refill.showRefillModal,
setShowRefillModal: refill.setShowRefillModal,
refillPacks: refill.refillPacks,
setRefillPacks: refill.setRefillPacks,
refillLoose: refill.refillLoose,
setRefillLoose: refill.setRefillLoose,
refillSaving: refill.refillSaving,
refillHistory: refill.refillHistory,
refillHistoryExpanded: refill.refillHistoryExpanded,
setRefillHistoryExpanded: refill.setRefillHistoryExpanded,
showEditStockModal: refill.showEditStockModal,
setShowEditStockModal: refill.setShowEditStockModal,
editStockFullBlisters: refill.editStockFullBlisters,
setEditStockFullBlisters: refill.setEditStockFullBlisters,
editStockPartialBlisterPills: refill.editStockPartialBlisterPills,
setEditStockPartialBlisterPills: refill.setEditStockPartialBlisterPills,
editStockSaving: refill.editStockSaving,
loadRefillHistory: refill.loadRefillHistory,
submitRefill: refill.submitRefill,
submitStockCorrection: refill.submitStockCorrection,
openRefillModal: refill.openRefillModal,
closeRefillModal: refill.closeRefillModal,
openEditStockModal: refill.openEditStockModal,
closeEditStockModal: refill.closeEditStockModal,
// Computed values
schedule,
coverage,
coverageByMed,
depletionByMed,
stockThresholds,
existingPeople,
groupedSchedule,
pastDays,
todayDay,
futureDays,
missedPastDoseIds,
getDayStockStatus,
// Schedule UI state
scheduleDays,
setScheduleDays,
showPastDays,
setShowPastDays,
showFutureDays,
setShowFutureDays,
// Modal state
selectedMed,
setSelectedMed,
showImageLightbox,
setShowImageLightbox,
scheduleLightboxImage,
setScheduleLightboxImage,
selectedUser,
setSelectedUser,
// Modal helpers
openMedDetail,
closeMedDetail,
openImageLightbox,
closeImageLightbox,
openScheduleLightbox,
closeScheduleLightbox,
openUserFilter,
closeUserFilter,
// Export/Import
exporting,
importing,
showExportModal,
setShowExportModal,
showImportConfirm,
setShowImportConfirm,
pendingImportData,
setPendingImportData,
importResult,
setImportResult,
handleExport,
handleImportFileSelect,
handleImportConfirm,
settingsChanged,
}),
[
medications,
settingsHook,
doses,
collapsed,
share,
refill,
schedule,
coverage,
coverageByMed,
depletionByMed,
stockThresholds,
existingPeople,
groupedSchedule,
pastDays,
todayDay,
futureDays,
missedPastDoseIds,
getDayStockStatus,
scheduleDays,
showPastDays,
showFutureDays,
selectedMed,
showImageLightbox,
scheduleLightboxImage,
selectedUser,
openMedDetail,
closeMedDetail,
openImageLightbox,
closeImageLightbox,
openScheduleLightbox,
closeScheduleLightbox,
openUserFilter,
closeUserFilter,
openShareDialog,
exporting,
importing,
showExportModal,
showImportConfirm,
pendingImportData,
importResult,
handleExport,
handleImportFileSelect,
handleImportConfirm,
settingsChanged,
clearingMissedState,
dismissMissedDoses,
]
);
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}
// =============================================================================
// Hook
// =============================================================================
export function useAppContext(): AppContextValue {
const context = useContext(AppContext);
if (!context) {
throw new Error("useAppContext must be used within an AppProvider");
}
return context;
}
@@ -0,0 +1,73 @@
import { createContext, type ReactNode, useCallback, useContext, useState } from "react";
import { useTranslation } from "react-i18next";
import { ConfirmModal } from "../components/ConfirmModal";
interface UnsavedChangesContextValue {
/** Whether there are unsaved changes anywhere in the app */
hasUnsavedChanges: boolean;
/** Register that a component has unsaved changes */
setHasUnsavedChanges: (value: boolean) => void;
/** Check and confirm navigation - returns a promise that resolves to true if navigation should proceed */
confirmNavigation: () => Promise<boolean>;
}
const UnsavedChangesContext = createContext<UnsavedChangesContextValue | null>(null);
export function UnsavedChangesProvider({ children }: { children: ReactNode }) {
const { t } = useTranslation();
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const [showConfirmModal, setShowConfirmModal] = useState(false);
const [pendingResolve, setPendingResolve] = useState<((value: boolean) => void) | null>(null);
const confirmNavigation = useCallback((): Promise<boolean> => {
if (!hasUnsavedChanges) {
return Promise.resolve(true);
}
return new Promise((resolve) => {
setPendingResolve(() => resolve);
setShowConfirmModal(true);
});
}, [hasUnsavedChanges]);
const handleConfirm = useCallback(() => {
setShowConfirmModal(false);
if (pendingResolve) {
pendingResolve(true);
setPendingResolve(null);
}
}, [pendingResolve]);
const handleCancel = useCallback(() => {
setShowConfirmModal(false);
if (pendingResolve) {
pendingResolve(false);
setPendingResolve(null);
}
}, [pendingResolve]);
return (
<UnsavedChangesContext.Provider value={{ hasUnsavedChanges, setHasUnsavedChanges, confirmNavigation }}>
{children}
{showConfirmModal && (
<ConfirmModal
title={t("common.unsavedChanges.title", "Unsaved Changes")}
message={t("common.unsavedChanges.message")}
confirmLabel={t("common.unsavedChanges.leave", "Leave")}
cancelLabel={t("common.unsavedChanges.stay", "Stay")}
onConfirm={handleConfirm}
onCancel={handleCancel}
confirmVariant="danger"
/>
)}
</UnsavedChangesContext.Provider>
);
}
export function useUnsavedChanges() {
const context = useContext(UnsavedChangesContext);
if (!context) {
throw new Error("useUnsavedChanges must be used within UnsavedChangesProvider");
}
return context;
}
+5
View File
@@ -0,0 +1,5 @@
// Context barrel export
export type { AppContextValue, DayMedEntry, DoseInfo, GroupedDay } from "./AppContext";
export { AppProvider, useAppContext } from "./AppContext";
export { UnsavedChangesProvider, useUnsavedChanges } from "./UnsavedChangesContext";
+20
View File
@@ -0,0 +1,20 @@
// Hooks barrel export
export type { UseCollapsedDaysReturn } from "./useCollapsedDays";
export { useCollapsedDays } from "./useCollapsedDays";
export type { UseDosesReturn } from "./useDoses";
export { useDoses } from "./useDoses";
export type { UseMedicationFormReturn } from "./useMedicationForm";
export { defaultBlister, defaultForm, useMedicationForm } from "./useMedicationForm";
export type { UseMedicationsReturn } from "./useMedications";
export { useMedications } from "./useMedications";
export type { UseRefillReturn } from "./useRefill";
export { useRefill } from "./useRefill";
export type { Settings, UseSettingsReturn } from "./useSettings";
export { useSettings } from "./useSettings";
export type { UseShareReturn } from "./useShare";
export { useShare } from "./useShare";
export type { Theme, ThemePreference, UseThemeReturn } from "./useTheme";
export { useTheme } from "./useTheme";
export type { UseUnsavedChangesWarningReturn } from "./useUnsavedChangesWarning";
export { useUnsavedChangesWarning } from "./useUnsavedChangesWarning";
+67
View File
@@ -0,0 +1,67 @@
// =============================================================================
// useCollapsedDays Hook - Day collapse/expand state management
// =============================================================================
import { useCallback, useEffect, useState } from "react";
import { loadCollapsedDaysFromStorage, userStorageKey } from "../utils/storage";
export interface UseCollapsedDaysReturn {
manuallyCollapsedDays: Set<string>;
manuallyExpandedDays: Set<string>;
toggleDayCollapse: (dateStr: string, isAutoCollapsed: boolean) => void;
}
export function useCollapsedDays(userId: number | undefined): UseCollapsedDaysReturn {
const [manuallyCollapsedDays, setManuallyCollapsedDays] = useState<Set<string>>(new Set());
const [manuallyExpandedDays, setManuallyExpandedDays] = useState<Set<string>>(new Set());
// Load collapsed/expanded state from localStorage when user changes
useEffect(() => {
if (typeof window !== "undefined" && userId) {
const { collapsed, expanded } = loadCollapsedDaysFromStorage(
userStorageKey(userId, "collapsedDays"),
userStorageKey(userId, "expandedDays")
);
setManuallyCollapsedDays(collapsed);
setManuallyExpandedDays(expanded);
}
}, [userId]);
// Toggle day collapse/expand
const toggleDayCollapse = useCallback(
(dateStr: string, isAutoCollapsed: boolean) => {
if (isAutoCollapsed) {
// Day is auto-collapsed (all taken) - toggle the expanded override
setManuallyExpandedDays((prev) => {
const next = new Set(prev);
if (next.has(dateStr)) {
next.delete(dateStr);
} else {
next.add(dateStr);
}
if (userId) localStorage.setItem(userStorageKey(userId, "expandedDays"), JSON.stringify([...next]));
return next;
});
} else {
// Day is not auto-collapsed - toggle manual collapse
setManuallyCollapsedDays((prev) => {
const next = new Set(prev);
if (next.has(dateStr)) {
next.delete(dateStr);
} else {
next.add(dateStr);
}
if (userId) localStorage.setItem(userStorageKey(userId, "collapsedDays"), JSON.stringify([...next]));
return next;
});
}
},
[userId]
);
return {
manuallyCollapsedDays,
manuallyExpandedDays,
toggleDayCollapse,
};
}
+189
View File
@@ -0,0 +1,189 @@
// =============================================================================
// useDoses Hook - Dose tracking state and operations
// =============================================================================
import { useCallback, useEffect, useRef, useState } from "react";
export interface UseDosesReturn {
takenDoses: Set<string>;
setTakenDoses: React.Dispatch<React.SetStateAction<Set<string>>>;
takenDoseTimestamps: Map<string, number>;
dismissedDoses: Set<string>;
showClearMissedConfirm: boolean;
setShowClearMissedConfirm: (show: boolean) => void;
getDoseId: (baseDoseId: string, person: string | null) => string;
countTakenDoses: (doses: Array<{ id: string; takenBy: string[] }>) => { total: number; taken: number };
markDoseTaken: (doseId: string) => Promise<void>;
undoDoseTaken: (doseId: string) => Promise<void>;
loadTakenDoses: () => Promise<void>;
}
export function useDoses(): UseDosesReturn {
const [takenDoses, setTakenDoses] = useState<Set<string>>(new Set());
const [takenDoseTimestamps, setTakenDoseTimestamps] = useState<Map<string, number>>(new Map());
const [dismissedDoses, setDismissedDoses] = useState<Set<string>>(new Set());
const [showClearMissedConfirm, setShowClearMissedConfirm] = useState(false);
// Track in-flight mutations to prevent polling from overwriting optimistic updates
const mutationInFlightRef = useRef(0);
// Load taken doses from server
const loadTakenDoses = useCallback(async () => {
// Skip polling while mutations are in-flight to prevent race conditions
// where a poll response with stale data overwrites optimistic updates
if (mutationInFlightRef.current > 0) return;
try {
const res = await fetch("/api/doses/taken", { credentials: "include" });
if (res.ok) {
// Double-check no mutation started while we were fetching
if (mutationInFlightRef.current > 0) return;
const data = await res.json();
const taken = new Set<string>();
const timestamps = new Map<string, number>();
const dismissed = new Set<string>();
for (const d of data.doses) {
if (d.dismissed) {
dismissed.add(d.doseId);
} else {
taken.add(d.doseId);
timestamps.set(d.doseId, d.takenAt);
}
}
setTakenDoses(taken);
setTakenDoseTimestamps(timestamps);
setDismissedDoses(dismissed);
}
// Don't reset on error - keep current state
} catch {
// Don't reset on error - keep current state
}
}, []);
// Poll for taken doses from server (works with or without auth)
useEffect(() => {
loadTakenDoses();
// Poll for updates every 5 seconds (real-time sync with share links)
const interval = setInterval(loadTakenDoses, 5000);
return () => clearInterval(interval);
}, [loadTakenDoses]);
// Get dose ID with optional person suffix
const getDoseId = useCallback((baseDoseId: string, person: string | null): string => {
return person ? `${baseDoseId}-${person}` : baseDoseId;
}, []);
// Count taken doses for a day/item
const countTakenDoses = useCallback(
(doses: Array<{ id: string; takenBy: string[] }>): { total: number; taken: number } => {
let total = 0;
let taken = 0;
for (const d of doses) {
const people = (d.takenBy || []).length > 0 ? d.takenBy : [null];
for (const person of people) {
total++;
if (takenDoses.has(getDoseId(d.id, person))) taken++;
}
}
return { total, taken };
},
[takenDoses, getDoseId]
);
const markDoseTaken = useCallback(
async (doseId: string) => {
// Optimistic update
mutationInFlightRef.current++;
setTakenDoses((prev) => {
const next = new Set(prev);
next.add(doseId);
return next;
});
setTakenDoseTimestamps((prev) => {
const next = new Map(prev);
next.set(doseId, Date.now());
return next;
});
// Send to server
try {
await fetch("/api/doses/taken", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ doseId }),
});
} catch {
// Revert on error
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
setTakenDoseTimestamps((prev) => {
const next = new Map(prev);
next.delete(doseId);
return next;
});
} finally {
mutationInFlightRef.current--;
// Re-sync with server after mutation completes
loadTakenDoses();
}
},
[loadTakenDoses]
);
const undoDoseTaken = useCallback(
async (doseId: string) => {
// Optimistic update
mutationInFlightRef.current++;
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
setTakenDoseTimestamps((prev) => {
const next = new Map(prev);
next.delete(doseId);
return next;
});
// Send to server
try {
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
method: "DELETE",
credentials: "include",
});
} catch {
// Revert on error
setTakenDoses((prev) => {
const next = new Set(prev);
next.add(doseId);
return next;
});
} finally {
mutationInFlightRef.current--;
// Re-sync with server after mutation completes
loadTakenDoses();
}
},
[loadTakenDoses]
);
return {
takenDoses,
setTakenDoses,
takenDoseTimestamps,
dismissedDoses,
showClearMissedConfirm,
setShowClearMissedConfirm,
getDoseId,
countTakenDoses,
markDoseTaken,
undoDoseTaken,
loadTakenDoses,
};
}
+312
View File
@@ -0,0 +1,312 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { FieldErrors, FormBlister, FormIntake, FormState, Medication } from "../types";
import { FIELD_LIMITS } from "../types";
import { toDateValue, toTimeValue } from "../utils/formatters";
export const defaultBlister = (): FormBlister => {
const now = new Date();
return {
usage: "1",
every: "1",
startDate: toDateValue(now),
startTime: toTimeValue(now),
};
};
/**
* Create a new intake with optional per-intake takenBy
*/
export const defaultIntake = (takenBy: string = ""): FormIntake => {
const now = new Date();
return {
usage: "1",
every: "1",
startDate: toDateValue(now),
startTime: toTimeValue(now),
takenBy, // Per-intake user assignment (empty string = null/everyone)
intakeRemindersEnabled: false,
};
};
export const defaultForm = (): FormState => ({
name: "",
genericName: "",
takenBy: [],
packageType: "blister",
packCount: "1",
blistersPerPack: "1",
pillsPerBlister: "1",
totalPills: "",
looseTablets: "0",
pillWeightMg: "",
doseUnit: "mg",
expiryDate: "",
notes: "",
intakeRemindersEnabled: false,
blisters: [defaultBlister()],
intakes: [defaultIntake()],
});
export interface UseMedicationFormReturn {
form: FormState;
setForm: React.Dispatch<React.SetStateAction<FormState>>;
originalForm: FormState;
setOriginalForm: React.Dispatch<React.SetStateAction<FormState>>;
editingId: number | null;
setEditingId: React.Dispatch<React.SetStateAction<number | null>>;
showEditModal: boolean;
setShowEditModal: React.Dispatch<React.SetStateAction<boolean>>;
fieldErrors: FieldErrors;
formSaved: boolean;
setFormSaved: React.Dispatch<React.SetStateAction<boolean>>;
hasValidationErrors: boolean;
formChanged: boolean;
pendingImage: File | null;
setPendingImage: React.Dispatch<React.SetStateAction<File | null>>;
pendingImagePreview: string | null;
setPendingImagePreview: React.Dispatch<React.SetStateAction<string | null>>;
takenByInput: string;
setTakenByInput: React.Dispatch<React.SetStateAction<string>>;
validateField: (field: keyof FieldErrors, value: string | string[]) => string | undefined;
setBlisterValue: (idx: number, field: keyof FormBlister, value: string) => void;
addBlister: () => void;
removeBlister: (idx: number) => void;
// Intake management with per-intake takenBy
setIntakeValue: (idx: number, field: keyof FormIntake, value: string | boolean) => void;
addIntake: (takenBy?: string) => void;
removeIntake: (idx: number) => void;
startEdit: (med: Medication, openEditModal: () => void) => void;
resetForm: () => void;
handleValueChange: <K extends keyof FormState>(key: K, value: string) => void;
addTakenByPerson: (name: string) => void;
removeTakenByPerson: (name: string) => void;
handleTakenByKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void;
}
export function useMedicationForm(): UseMedicationFormReturn {
const { t } = useTranslation();
const [form, setForm] = useState<FormState>(defaultForm());
const [originalForm, setOriginalForm] = useState<FormState>(defaultForm());
const [editingId, setEditingId] = useState<number | null>(null);
const [showEditModal, setShowEditModal] = useState(false);
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
const [formSaved, setFormSaved] = useState(false);
const [pendingImage, setPendingImage] = useState<File | null>(null);
const [pendingImagePreview, setPendingImagePreview] = useState<string | null>(null);
const [takenByInput, setTakenByInput] = useState("");
// Validate form fields
const validateField = useCallback(
(field: keyof FieldErrors, value: string | string[]): string | undefined => {
const limits = FIELD_LIMITS[field];
// Skip validation for takenBy array (individual items validated on add)
if (field === "takenBy") return undefined;
const strValue = typeof value === "string" ? value : "";
if (field === "name" && (!strValue || strValue.trim().length === 0)) {
return t("common.validation.required");
}
if ("max" in limits && strValue.length > limits.max) {
return t("common.validation.maxLength", { max: limits.max, current: strValue.length });
}
return undefined;
},
[t]
);
// Check if form has any errors
const hasValidationErrors = useMemo(() => {
return Object.values(fieldErrors).some((error) => error !== undefined);
}, [fieldErrors]);
// Check if form has been modified from original state
const formChanged = useMemo(() => {
return JSON.stringify(form) !== JSON.stringify(originalForm);
}, [form, originalForm]);
// Reset formSaved when form changes
useEffect(() => {
if (formChanged) {
setFormSaved(false);
}
}, [formChanged]);
// Validate all fields when form changes
useEffect(() => {
const errors: FieldErrors = {};
(["name", "genericName", "notes"] as const).forEach((f) => {
const error = validateField(f, form[f]);
if (error) errors[f] = error;
});
setFieldErrors(errors);
}, [form.name, form.genericName, form.notes, validateField]);
const setBlisterValue = useCallback((idx: number, field: keyof FormBlister, value: string) => {
setForm((prev) => {
const next = [...prev.blisters];
next[idx] = { ...next[idx], [field]: value };
return { ...prev, blisters: next };
});
}, []);
const addBlister = useCallback(() => {
setForm((prev) => ({ ...prev, blisters: [...prev.blisters, defaultBlister()] }));
}, []);
const removeBlister = useCallback((idx: number) => {
setForm((prev) => ({ ...prev, blisters: prev.blisters.filter((_, i) => i !== idx) }));
}, []);
// Intake management with per-intake takenBy
const setIntakeValue = useCallback((idx: number, field: keyof FormIntake, value: string | boolean) => {
setForm((prev) => {
const next = [...prev.intakes];
next[idx] = { ...next[idx], [field]: value };
return { ...prev, intakes: next };
});
}, []);
const addIntake = useCallback((takenBy: string = "") => {
setForm((prev) => ({ ...prev, intakes: [...prev.intakes, defaultIntake(takenBy)] }));
}, []);
const removeIntake = useCallback((idx: number) => {
setForm((prev) => ({ ...prev, intakes: prev.intakes.filter((_, i) => i !== idx) }));
}, []);
const startEdit = useCallback((med: Medication, openEditModal: () => void) => {
setEditingId(med.id);
setTakenByInput(""); // Clear tag input when starting edit
setFormSaved(true); // Existing medication is already saved
// Parse intakes - prefer new format, fallback to legacy blisters
const intakesFromApi =
med.intakes && med.intakes.length > 0
? med.intakes.map((i) => ({
usage: String(i.usage),
every: String(i.every),
startDate: toDateValue(i.start),
startTime: toTimeValue(i.start),
takenBy: i.takenBy ?? "", // Convert null to empty string for form
intakeRemindersEnabled: i.intakeRemindersEnabled,
}))
: med.blisters.map((s) => ({
usage: String(s.usage),
every: String(s.every),
startDate: toDateValue(s.start),
startTime: toTimeValue(s.start),
takenBy: "", // Legacy blisters have no per-intake takenBy
intakeRemindersEnabled: med.intakeRemindersEnabled ?? false,
}));
const editForm: FormState = {
name: med.name,
genericName: med.genericName ?? "",
takenBy: med.takenBy || [], // Already an array from API
packageType: med.packageType ?? "blister",
packCount: String(med.packCount),
blistersPerPack: String(med.blistersPerPack),
pillsPerBlister: String(med.pillsPerBlister),
totalPills: med.totalPills ? String(med.totalPills) : "",
looseTablets: String(med.looseTablets),
pillWeightMg: med.pillWeightMg ? String(med.pillWeightMg) : "",
doseUnit: med.doseUnit ?? "mg",
expiryDate: med.expiryDate ? med.expiryDate.slice(0, 10) : "",
notes: med.notes ?? "",
intakeRemindersEnabled: med.intakeRemindersEnabled ?? false,
blisters: med.blisters.map((s) => ({
usage: String(s.usage),
every: String(s.every),
startDate: toDateValue(s.start),
startTime: toTimeValue(s.start),
})),
intakes: intakesFromApi,
};
setForm(editForm);
setOriginalForm(editForm);
// Show modal on mobile
if (window.innerWidth <= 768) {
openEditModal();
}
}, []);
const resetForm = useCallback(() => {
setEditingId(null);
setShowEditModal(false);
setPendingImage(null);
setPendingImagePreview(null);
setTakenByInput("");
setFormSaved(false);
const newForm = defaultForm();
setForm(newForm);
setOriginalForm(newForm);
}, []);
const handleValueChange = useCallback(<K extends keyof FormState>(key: K, value: string) => {
setForm((prev) => ({ ...prev, [key]: value }));
}, []);
// Tag input helpers for "Taken By" field
const addTakenByPerson = useCallback(
(name: string) => {
const trimmed = name.trim();
if (trimmed && trimmed.length <= FIELD_LIMITS.takenBy.max && !form.takenBy.includes(trimmed)) {
setForm((prev) => ({ ...prev, takenBy: [...prev.takenBy, trimmed] }));
}
setTakenByInput("");
},
[form.takenBy]
);
const removeTakenByPerson = useCallback((name: string) => {
setForm((prev) => ({ ...prev, takenBy: prev.takenBy.filter((p) => p !== name) }));
}, []);
const handleTakenByKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
addTakenByPerson(takenByInput);
} else if (e.key === "Backspace" && !takenByInput && form.takenBy.length > 0) {
// Remove last tag on backspace when input is empty
removeTakenByPerson(form.takenBy[form.takenBy.length - 1]);
}
},
[takenByInput, form.takenBy, addTakenByPerson, removeTakenByPerson]
);
return {
form,
setForm,
originalForm,
setOriginalForm,
editingId,
setEditingId,
showEditModal,
setShowEditModal,
fieldErrors,
formSaved,
setFormSaved,
hasValidationErrors,
formChanged,
pendingImage,
setPendingImage,
pendingImagePreview,
setPendingImagePreview,
takenByInput,
setTakenByInput,
validateField,
setBlisterValue,
addBlister,
removeBlister,
setIntakeValue,
addIntake,
removeIntake,
startEdit,
resetForm,
handleValueChange,
addTakenByPerson,
removeTakenByPerson,
handleTakenByKeyDown,
};
}
+84
View File
@@ -0,0 +1,84 @@
import { useCallback, useState } from "react";
import type { Medication } from "../types";
export interface UseMedicationsReturn {
meds: Medication[];
setMeds: React.Dispatch<React.SetStateAction<Medication[]>>;
loading: boolean;
saving: boolean;
setSaving: React.Dispatch<React.SetStateAction<boolean>>;
uploadingImage: boolean;
loadMeds: () => void;
deleteMed: (id: number, editingId: number | null, resetForm: () => void) => Promise<void>;
uploadMedImage: (medId: number, file: File) => Promise<void>;
deleteMedImage: (medId: number) => Promise<void>;
}
export function useMedications(): UseMedicationsReturn {
const [meds, setMeds] = useState<Medication[]>([]);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [uploadingImage, setUploadingImage] = useState(false);
const loadMeds = useCallback(() => {
setLoading(true);
fetch("/api/medications", { credentials: "include" })
.then((res) => res.json())
.then((data) => setMeds(Array.isArray(data) ? data : []))
.catch(() => setMeds([]))
.finally(() => setLoading(false));
}, []);
const deleteMed = useCallback(
async (id: number, editingId: number | null, resetForm: () => void) => {
await fetch(`/api/medications/${id}`, { method: "DELETE", credentials: "include" }).catch(() => null);
if (editingId === id) resetForm();
loadMeds();
},
[loadMeds]
);
const uploadMedImage = useCallback(
async (medId: number, file: File) => {
setUploadingImage(true);
const formData = new FormData();
formData.append("file", file);
try {
const res = await fetch(`/api/medications/${medId}/image`, {
method: "POST",
body: formData,
credentials: "include",
});
if (res.ok) {
loadMeds();
}
} catch {
// ignore
}
setUploadingImage(false);
},
[loadMeds]
);
const deleteMedImage = useCallback(
async (medId: number) => {
await fetch(`/api/medications/${medId}/image`, { method: "DELETE", credentials: "include" }).catch(() => null);
loadMeds();
},
[loadMeds]
);
return {
meds,
setMeds,
loading,
saving,
setSaving,
uploadingImage,
loadMeds,
deleteMed,
uploadMedImage,
deleteMedImage,
};
}

Some files were not shown because too many files have changed in this diff Show More