Compare commits

..

77 Commits

Author SHA1 Message Date
Daniel Volz 3ec1460c4e feat: frontend improvements - shared schedule, bottle type, settings UI, planner notifications (#146)
- Rewrite SharedSchedule to match DashboardPage rendering with time-based consumption
- Add bottle package type support across all views (MedDetail, Refill, Planner, Dashboard)
- Redesign settings page with colored threshold chips, validation, and stock reminder display
- Add shareStockStatus toggle and send manual reminder button
- Pill/pills singular/plural consistency across all views
- Planner send notification via push (Shoutrrr) in addition to email
- Stock overflow warning and past-missed day styling
- Update README: bottles in Smart Inventory, push in Trip Planner, new ENV section
- 708 passing frontend tests including new coverage for all changes
2026-02-09 19:33:54 +01:00
Daniel Volz f56f2b7c88 feat: backend improvements - reminder tracking, share stock status, planner notifications (#145)
- Separate stock/intake reminder tracking in DB with dedicated columns
- Add shareStockStatus setting to control stock visibility on shared links
- Rewrite planner notification to support both email and Shoutrrr push
- Add push notification footer text for intake and stock reminders
- New DB migrations: stock_reminder_tracking (0006), share_stock_status (0007)
- Update backend i18n with demandCalculator section and critically low text
- Add 514 passing backend tests including new coverage for all changes
2026-02-09 19:32:32 +01:00
github-actions[bot] 8ff652459d chore: update test count badges [skip ci] 2026-02-09 07:15:26 +00:00
Daniel Volz fb937e795b fix: planner usage calculation uses user-selected start date (#144)
The Demand Calculator used max(now, start) as the effective planner start,
which caused asymmetric counting when the current time fell between morning
and evening doses. For example, at 15:00 a medication with 07:00+20:00
intakes over 3 days showed 5 pills (2+3) instead of 6 (3+3) because the
morning dose on the start day was skipped while the evening was counted.

Changes:
- Use the user-selected start date directly instead of max(now, start)
- Optimize calculateUsageInRange to skip ahead to the relevant range
  instead of iterating from the original blister start date
- Add regression tests for asymmetric counting and blister-before-range
2026-02-09 08:10:13 +01:00
Daniel Volz 6d6f906a9a chore: update CI workflow and agent configuration (#143)
- docker-build.yml: build on tags + main, set latest only on tags
- release-manager.agent.md: add one-PR-per-feature/fix rule
2026-02-08 22:17:03 +01:00
Daniel Volz 3de1b2ef0c fix: UI polish for intake form, dashboard cards, and schedule (#142)
- Intake form: replace remind checkbox with bell icon + toggle switch
- Intake form: smart takenBy dropdown based on medication's people
- Dashboard: hide DETAILS row for pill bottles on mobile cards
- Dashboard: use status-chip with icons in schedule view (past/today/future)
- Dashboard: reduce spacing between icons and status chips on mobile
- MedDetailModal: show package type in PACKAGE DETAILS heading
- PlannerPage: show dash for bottle blisters column
- Shorten Pill Bottle label in EN/DE translations
- Update related tests
2026-02-08 22:13:52 +01:00
Daniel Volz b07b586eef chore: replace console.log with structured logging (#141)
- Add startup logger (utils/logger.ts) with LOG_LEVEL support
- Add ServiceLogger type for scheduler functions
- Replace all console.log calls with leveled log methods
- Downgrade verbose scheduler info logs to debug level
- Remove unnecessary console.log in auth plugin
2026-02-08 22:09:27 +01:00
Daniel Volz ffcd8983b4 revert: undo "fix: update backend and frontend images to use main tag" (#140)
This reverts commit cdf0088b0f.
2026-02-08 20:17:15 +00:00
daniel cdf0088b0f fix: update backend and frontend images to use 'main' tag 2026-02-08 19:47:23 +00:00
github-actions[bot] 152608731b chore: update test count badges [skip ci] 2026-02-08 19:37:42 +00:00
Daniel Volz 291a90d401 chore: release v1.9.0 (#139) 2026-02-08 20:34:29 +01:00
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
120 changed files with 14799 additions and 4490 deletions
+2 -1
View File
@@ -118,4 +118,5 @@ EXPIRY_WARNING_DAYS=30 # Days before expiry to show yellow warning
# UI defaults
# DEFAULT_LANGUAGE=en # en or de
# DEFAULT_STOCK_CALCULATION_MODE=automatic # automatic or manual
# DEFAULT_STOCK_CALCULATION_MODE=automatic # automatic or manual
# DEFAULT_SHARE_STOCK_STATUS=true # Show stock status on shared schedule links
+376
View File
@@ -0,0 +1,376 @@
---
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.
---
## PR Strategy: One PR per Feature/Fix
**Each feature or bug fix MUST be submitted as its own separate PR.** Do NOT bundle multiple unrelated changes into a single PR.
**Why:**
- Each change gets its own PR number for release notes (e.g., `(#140)`, `(#141)`)
- CI tests each change in isolation — failures are easy to trace
- Git blame and rollbacks are precise
- Code review stays focused
**Rules:**
- One logical change = one branch = one PR
- If a bug fix is discovered while working on a feature, create a **separate branch and PR** for the fix
- Related changes (e.g., a feature + its tests) belong in the **same** PR
- Squash-merge is still used — keeps `main` history clean with one commit per PR
- Branch naming reflects the change: `fix/bottle-stock-calc`, `feat/theme-dropdown`, etc.
**Example — bad (bundled):**
```
PR #138: "feat: theme dropdown, fix bottle bugs, fix planner, fix reminders"
```
**Example — good (separate):**
```
PR #138: "fix: bottle-type stock calculations across all subsystems"
PR #139: "fix: intake reminder past-intake seeding"
PR #140: "feat: theme dropdown with Light/Dark/System options"
PR #141: "fix: planner checkbox layout on single line"
```
---
## 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
```
+15 -145
View File
@@ -4,11 +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.
- **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.
- **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
@@ -136,11 +138,16 @@ Push to main / Tag created
┌─────────────────────────────────────┐
│ docker-build.yml │
─ backend-test (parallel)
│ ├─ frontend-build (parallel) │
│ └─ build-and-push (after tests) │
─ build-and-push
│ ├─ Build Docker images │
│ └─ 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 │
└─────────────────────────────────────┘
```
@@ -177,147 +184,9 @@ gh pr merge --squash --delete-branch
| File | Trigger | Purpose |
|------|---------|--------|
| `.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 |
### Adding New Code - Checklist
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.
**Release title:** Use just `vX.Y.Z` (e.g., `v1.4.1`), NOT "Release vX.Y.Z".
**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
- ❌ .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
**Only include user-relevant changes** - things that affect what users see or experience in the app.
**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.
| `.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 |
| `.github/workflows/codeql.yml` | Push to main, PRs, Weekly | Security analysis |
## Key Patterns
@@ -505,6 +374,7 @@ Example: `5-0-1735344000000` = Medication 5, Blister 0, timestamp
- **API responses**: Return objects directly, Fastify serializes to JSON
- **Environment**: Copy `.env.example``.env`, secrets must be 10+ chars
- **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!)
+22
View File
@@ -3,8 +3,30 @@ name: "CodeQL"
on:
push:
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:
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:
- cron: "0 6 * * 1" # Weekly on Monday at 6am UTC
workflow_dispatch: # Allow manual trigger
+25 -48
View File
@@ -3,11 +3,6 @@ name: Build and Push Docker Images
on:
push:
branches: [main]
paths:
- 'backend/**'
- 'frontend/**'
- 'docker-compose*.yml'
- '.github/workflows/docker-build.yml'
tags: ['v*']
workflow_dispatch:
inputs:
@@ -25,50 +20,16 @@ env:
jobs:
# =============================================================================
# Run Tests First
# =============================================================================
backend-test:
name: Backend Tests
runs-on: ubuntu-latest
permissions:
contents: read
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 Docker Images
# Triggered on pushes to main (tagged as "main") and version tags (v*).
# Tests are NOT run here — branch protection on main requires all PR checks
# (backend-test + frontend-build from test.yml) to pass before merge.
# Tags are created from main, so code is already tested.
#
# main push → "main" tag only (for testing before release)
# Tag builds → semver tags (e.g., 1.9.0, 1.9) plus "latest"
# =============================================================================
build-and-push:
needs: [backend-test, frontend-build]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -106,7 +67,7 @@ jobs:
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
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=${{ startsWith(github.ref, 'refs/tags/v') }}
- name: Build and push
uses: docker/build-push-action@v5
@@ -137,13 +98,28 @@ jobs:
with:
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
if: steps.check_release.outputs.exists == 'false'
id: prev_tag
run: |
PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
echo "tag=${PREV_TAG}" >> $GITHUB_OUTPUT
- name: Generate changelog
if: steps.check_release.outputs.exists == 'false'
id: changelog
run: |
CURRENT_TAG=${GITHUB_REF#refs/tags/}
@@ -172,6 +148,7 @@ jobs:
echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${CURRENT_TAG}" >> changelog.md
- name: Create GitHub Release
if: steps.check_release.outputs.exists == 'false'
uses: softprops/action-gh-release@v2
with:
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 }}
+32 -2
View File
@@ -10,10 +10,38 @@ permissions:
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:
name: Backend Tests
needs: changes
if: needs.changes.outputs.backend == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -53,10 +81,12 @@ jobs:
retention-days: 7
# =============================================================================
# Frontend Build Validation
# Frontend Build Validation (skipped if no frontend-related files changed)
# =============================================================================
frontend-build:
name: Frontend Build
needs: changes
if: needs.changes.outputs.frontend == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
+29 -23
View File
@@ -1,13 +1,11 @@
name: Update Test Badges
on:
push:
workflow_dispatch:
workflow_run:
workflows: ["Build and Push Docker Images"]
types: [completed]
branches: [main]
paths:
- 'backend/src/**'
- 'frontend/src/**'
- 'backend/package.json'
- 'frontend/package.json'
permissions:
contents: write
@@ -16,12 +14,14 @@ 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.GITHUB_TOKEN }}
token: ${{ secrets.BADGE_TOKEN || secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
@@ -41,21 +41,29 @@ jobs:
- 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"
# Extract "Tests X passed" from output
PASSED=$(echo "$OUTPUT" | grep -oP 'Tests\s+\K\d+(?=\s+passed)' | tail -1)
# 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
OUTPUT=$(npm run test:run 2>&1) || true
echo "$OUTPUT"
# Extract "Tests X passed" from output
PASSED=$(echo "$OUTPUT" | grep -oP 'Tests\s+\K\d+(?=\s+passed)' | tail -1)
# 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
@@ -82,16 +90,14 @@ jobs:
exit 0
fi
- name: Check for changes
id: git-check
- name: Commit and push badge updates
run: |
git diff --quiet README.md || echo "changed=true" >> $GITHUB_OUTPUT
- name: Commit and push if changed
if: steps.git-check.outputs.changed == 'true'
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add README.md
git commit -m "chore: update test count badges [skip ci]"
git push
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
+9
View File
@@ -18,6 +18,12 @@ build/
coverage/
.nyc_output/
# Playwright
/frontend/playwright-report/
/frontend/test-results/
/frontend/e2e/.auth/
/frontend/blob-report/
# ===================
# Environment
# ===================
@@ -71,4 +77,7 @@ Thumbs.db
*.local
.cache/
.turbo/
.roo/
.roomodes
AGENTS.md
docs/TECH_STACK.md
-12
View File
@@ -1,12 +0,0 @@
#!/bin/sh
echo "Running backend tests before push..."
cd backend && CI=true npm test
if [ $? -ne 0 ]; then
echo "❌ Backend tests failed. Push aborted."
echo "Use 'git push --no-verify' to skip tests if needed."
exit 1
fi
echo "✅ Backend tests passed!"
+12 -3
View File
@@ -18,8 +18,8 @@
</p>
<p align="center">
<img src="https://img.shields.io/badge/Backend_Tests-454%2F454-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
<img src="https://img.shields.io/badge/Frontend_Tests-611%2F611-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
<img src="https://img.shields.io/badge/Backend_Tests-504%2F504-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
<img src="https://img.shields.io/badge/Frontend_Tests-662%2F662-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
</p>
### 🤖 AI-Generated Code
@@ -120,7 +120,7 @@ Share your medication schedule with others via a public link.
</details>
### Smart Inventory
- Track exact stock: packs, blisters, and loose pills
- Track exact stock: packs, blisters, bottles, and loose pills
- Display remaining days of supply
- Automatic calculation based on intake schedule
@@ -141,6 +141,7 @@ Share your medication schedule with others via a public link.
### Trip Planner
- Calculate how many pills you need for a trip or date range
- Plan ahead for vacations, business trips, or hospital stays
- Send demand reports via email or push notification
### Multi-Person Support
- Manage medications for multiple people
@@ -254,6 +255,14 @@ Configure push notifications in Settings → Push, or set defaults via environme
| `DEFAULT_SHOUTRRR_STOCK_REMINDERS` | `true` | Send stock warnings via push |
| `DEFAULT_SHOUTRRR_INTAKE_REMINDERS` | `true` | Send intake reminders via push |
### Default User Settings
These defaults are applied when a new user is created. Once a user saves settings in the app, their values take precedence.
| Variable | Default | Description |
|----------|---------|-------------|
| `DEFAULT_SHARE_STOCK_STATUS` | `true` | Show stock status (Normal/Low/Critical) on shared schedule links |
#### URL Examples
**ntfy** (free, self-hostable):
+1 -1
View File
@@ -5,6 +5,6 @@ export default defineConfig({
out: "./drizzle",
dialect: "sqlite",
dbCredentials: {
url: process.env.DATABASE_URL || "./data/medassist.db",
url: process.env.DATABASE_URL || "./data/medassist-ng.db",
},
});
@@ -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;
@@ -0,0 +1,3 @@
ALTER TABLE `user_settings` ADD `last_stock_reminder_sent` text;--> statement-breakpoint
ALTER TABLE `user_settings` ADD `last_stock_reminder_channel` text;--> statement-breakpoint
ALTER TABLE `user_settings` ADD `last_stock_reminder_med_names` text;
@@ -0,0 +1 @@
ALTER TABLE `user_settings` ADD `share_stock_status` integer DEFAULT true NOT NULL;
+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": {}
}
}
+907
View File
@@ -0,0 +1,907 @@
{
"version": "6",
"dialect": "sqlite",
"id": "7cd75e33-b3d8-4930-a60b-2a0a9f644c6d",
"prevId": "fb61e5fd-152d-4e61-8836-e2fd1d28e3f0",
"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
},
"last_stock_reminder_sent": {
"name": "last_stock_reminder_sent",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_stock_reminder_channel": {
"name": "last_stock_reminder_channel",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_stock_reminder_med_names": {
"name": "last_stock_reminder_med_names",
"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": {}
}
}
+915
View File
@@ -0,0 +1,915 @@
{
"version": "6",
"dialect": "sqlite",
"id": "b6f1ee4b-cc31-4060-a4d4-bcd4fdc5bd87",
"prevId": "7cd75e33-b3d8-4930-a60b-2a0a9f644c6d",
"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'"
},
"share_stock_status": {
"name": "share_stock_status",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"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
},
"last_stock_reminder_sent": {
"name": "last_stock_reminder_sent",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_stock_reminder_channel": {
"name": "last_stock_reminder_channel",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_stock_reminder_med_names": {
"name": "last_stock_reminder_med_names",
"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": {}
}
}
+28
View File
@@ -29,6 +29,34 @@
"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
},
{
"idx": 6,
"version": "6",
"when": 1770626907896,
"tag": "0006_add_stock_reminder_tracking",
"breakpoints": true
},
{
"idx": 7,
"version": "6",
"when": 1770659669121,
"tag": "0007_add_share_stock_status",
"breakpoints": true
}
]
}
+10 -10
View File
@@ -1,12 +1,12 @@
{
"name": "medassist-ng-backend",
"version": "1.5.0",
"version": "1.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "medassist-ng-backend",
"version": "1.5.0",
"version": "1.9.0",
"dependencies": {
"@fastify/cookie": "^10.0.1",
"@fastify/cors": "^10.0.1",
@@ -20,7 +20,7 @@
"argon2": "^0.40.0",
"dotenv": "^16.4.5",
"drizzle-orm": "^0.45.1",
"fastify": "^5.0.0",
"fastify": "^5.7.3",
"nodemailer": "^7.0.11",
"openid-client": "^6.8.1",
"zod": "^3.23.8"
@@ -2182,9 +2182,9 @@
}
},
"node_modules/@isaacs/brace-expansion": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz",
"integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==",
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.1.tgz",
"integrity": "sha512-WMz71T1JS624nWj2n2fnYAuPovhv7EUhk69R6i9dsVyzxt5eM3bjwvgk9L+APE1TRscGysAVMANkB0jh0LQZrQ==",
"license": "MIT",
"dependencies": {
"@isaacs/balanced-match": "^4.0.1"
@@ -4931,9 +4931,9 @@
}
},
"node_modules/fastify": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.6.2.tgz",
"integrity": "sha512-dPugdGnsvYkBlENLhCgX8yhyGCsCPrpA8lFWbTNU428l+YOnLgYHR69hzV8HWPC79n536EqzqQtvhtdaCE0dKg==",
"version": "5.7.3",
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.7.3.tgz",
"integrity": "sha512-QHzWSmTNUg9Ba8tNXzb92FTH77K+c8yeQPH80EeSIc9wyZj85jbPisMP0rwmyKv8oJwUFPe1UpN8HkNIXwCnUQ==",
"funding": [
{
"type": "github",
@@ -4946,7 +4946,7 @@
],
"license": "MIT",
"dependencies": {
"@fastify/ajv-compiler": "^4.0.0",
"@fastify/ajv-compiler": "^4.0.5",
"@fastify/error": "^4.0.0",
"@fastify/fast-json-stringify-compiler": "^5.0.0",
"@fastify/proxy-addr": "^5.0.0",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "medassist-ng-backend",
"version": "1.5.0",
"version": "1.9.0",
"private": true,
"type": "module",
"scripts": {
@@ -29,7 +29,7 @@
"argon2": "^0.40.0",
"dotenv": "^16.4.5",
"drizzle-orm": "^0.45.1",
"fastify": "^5.0.0",
"fastify": "^5.7.3",
"nodemailer": "^7.0.11",
"openid-client": "^6.8.1",
"zod": "^3.23.8"
+67 -167
View File
@@ -1,155 +1,37 @@
import { accessSync, constants, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { existsSync, statSync } from "node:fs";
import { resolve } from "node:path";
import { type Client, createClient } from "@libsql/client";
import dotenv from "dotenv";
import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator";
import { log } from "../utils/logger.js";
// Import utilities from db-utils (side-effect-free)
import {
ensureDataDirectory,
ensureDefaultUser,
getDataDir,
getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations,
runDrizzleMigrations,
} from "./db-utils.js";
dotenv.config({ path: process.env.DOTENV_PATH || ".env" });
// Re-export all utilities so existing imports from client.ts keep working
export {
buildDbUrl,
ensureDataDirectory,
ensureDefaultUser,
getDataDir,
getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations,
runDrizzleMigrations,
} from "./db-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");
// =============================================================================
// Exported utility functions for testing
// =============================================================================
/** 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; 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`,
];
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;
}
}
// 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 });
// =============================================================================
// Database initialization (runs on import)
@@ -158,34 +40,34 @@ export async function ensureDefaultUser(client: Client, authEnabled: boolean): P
// Use absolute path to ensure it works in Docker
const { dataDir, dbPath, url } = getDbPaths();
console.log(`[DB] Data directory: ${dataDir}`);
console.log(`[DB] Database path: ${dbPath}`);
console.log(`[DB] Database URL: ${url}`);
log.debug(`[DB] Data directory: ${dataDir}`);
log.debug(`[DB] Database path: ${dbPath}`);
log.debug(`[DB] Database URL: ${url}`);
// Ensure data directory exists and is writable
const dirResult = ensureDataDirectory(dataDir);
if (!dirResult.success) {
console.error(`[DB] ERROR: Cannot access data directory: ${dirResult.error}`);
console.error(`[DB] Please ensure the volume mount has correct permissions.`);
console.error(`[DB] Try running on host: sudo chown -R 1000:1000 ${dataDir}`);
log.error(`[DB] ERROR: Cannot access data directory: ${dirResult.error}`);
log.error(`[DB] Please ensure the volume mount has correct permissions.`);
log.error(`[DB] Try running on host: sudo chown -R 1000:1000 ${dataDir}`);
process.exit(1);
} else {
console.log(`[DB] Data directory is writable`);
log.debug(`[DB] Data directory is writable`);
// Log directory stats
const stats = statSync(dataDir);
console.log(`[DB] Directory permissions: ${stats.mode.toString(8)}`);
console.log(`[DB] Directory UID: ${stats.uid}, GID: ${stats.gid}`);
console.log(`[DB] Write test successful`);
log.debug(`[DB] Directory permissions: ${stats.mode.toString(8)}`);
log.debug(`[DB] Directory UID: ${stats.uid}, GID: ${stats.gid}`);
log.debug(`[DB] Write test successful`);
}
let client: Client;
try {
client = createClient({ url });
console.log(`[DB] Database client created successfully`);
log.debug(`[DB] Database client created successfully`);
} catch (err: any) {
console.error(`[DB] ERROR: Failed to create database client: ${err.message}`);
console.error(`[DB] Database path: ${dbPath}`);
log.error(`[DB] ERROR: Failed to create database client: ${err.message}`);
log.error(`[DB] Database path: ${dbPath}`);
process.exit(1);
}
@@ -194,28 +76,46 @@ export const db = drizzle(client);
// Auto-run migrations (self-healing database)
async function runMigrations() {
// Run drizzle-kit generated migrations
console.log(`[DB] Running drizzle migrations from: ${migrationsFolder}`);
log.info(`[DB] Running migrations...`);
const migrateResult = await runDrizzleMigrations(db);
if (!migrateResult.success) {
console.error(`[DB] Migration error:`, migrateResult.error);
log.error(`[DB] Migration error: ${migrateResult.error}`);
} else if (migrateResult.warning) {
console.log(`[DB] Migration warning:`, migrateResult.warning);
log.warn(`[DB] Migration warning: ${migrateResult.warning}`);
} else {
console.log(`[DB] Drizzle migrations completed`);
log.debug(`[DB] Drizzle migrations completed`);
}
// Run ALTER TABLE migrations for backward compatibility
const alterResult = await runAlterMigrations(client);
if (alterResult.errors.length > 0) {
alterResult.errors.forEach((err) => console.error(`[DB] ALTER migration error:`, err));
alterResult.errors.forEach((err) => log.error(`[DB] ALTER migration error: ${err}`));
}
log.debug(`[DB] Tables verified/created`);
// Repair dose IDs with trailing hyphens (from frontend takenBy bug)
const trailingResult = await repairTrailingHyphenDoseIds(client);
if (trailingResult.repaired > 0) {
log.info(`[DB] Repaired ${trailingResult.repaired} dose IDs with trailing hyphens`);
}
if (trailingResult.errors.length > 0) {
trailingResult.errors.forEach((err) => log.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) {
log.info(`[DB] Repaired ${repairResult.repaired} orphaned dose tracking IDs`);
}
if (repairResult.errors.length > 0) {
repairResult.errors.forEach((err) => log.error(`[DB] Dose repair error: ${err}`));
}
console.log(`[DB] Tables verified/created`);
// If auth is disabled, ensure a default user exists (ID=1)
const authEnabled = process.env.AUTH_ENABLED === "true";
const created = await ensureDefaultUser(client, authEnabled);
if (created) {
console.log(`[DB] Created default user for auth-disabled mode`);
log.info(`[DB] Created default user for auth-disabled mode`);
}
}
+358
View File
@@ -0,0 +1,358 @@
/**
* 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 about existing schema objects, the DB is already up-to-date
// This happens when ALTER migrations in client.ts have already added the columns,
// or when tables were created before drizzle migrations were introduced
if (err.message?.includes("duplicate column") || err.message?.includes("already exists")) {
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 '[]'`,
// Added for separate stock reminder tracking
`ALTER TABLE user_settings ADD COLUMN last_stock_reminder_sent text`,
`ALTER TABLE user_settings ADD COLUMN last_stock_reminder_channel text`,
`ALTER TABLE user_settings ADD COLUMN last_stock_reminder_med_names text`,
// Added for share stock visibility toggle
`ALTER TABLE user_settings ADD COLUMN share_stock_status integer NOT NULL DEFAULT 1`,
];
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 };
}
+9 -6
View File
@@ -1,3 +1,4 @@
import { existsSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { type Client, createClient } from "@libsql/client";
@@ -5,7 +6,9 @@ import dotenv from "dotenv";
import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator";
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)
const __filename = fileURLToPath(import.meta.url);
@@ -60,17 +63,17 @@ export function getStatementPreview(stmt: string, maxLength: number = 50): strin
const url = "file:./data/medassist-ng.db";
async function main() {
console.log("Starting database setup...");
console.log("Database URL:", url);
console.log("Migrations folder:", migrationsFolder);
console.log("[DB] Starting database setup...");
console.log("[DB] Database URL:", url);
console.log("[DB] Migrations folder:", migrationsFolder);
const client = createClient({ url });
const db = drizzle(client);
console.log("Running drizzle migrations...");
console.log("[DB] Running drizzle migrations...");
await migrate(db, { migrationsFolder });
console.log("Database setup complete!");
console.log("[DB] Database setup complete!");
process.exit(0);
}
+16 -5
View File
@@ -28,16 +28,21 @@ export const medications = sqliteTable("medications", {
name: text("name", { length: 100 }).notNull(),
genericName: text("generic_name", { length: 100 }),
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),
blistersPerPack: integer("blisters_per_pack").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
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"),
usageJson: text("usage_json").notNull().default("[]"),
everyJson: text("every_json").notNull().default("[]"),
startJson: text("start_json").notNull().default("[]"),
doseUnit: text("dose_unit", { length: 20 }).default("mg"), // Unit for the dose (mg, g, mcg, ml, IU, etc.)
usageJson: text("usage_json").notNull().default("[]"), // DEPRECATED: Use intakesJson instead
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"),
expiryDate: text("expiry_date"),
notes: text("notes"),
@@ -81,12 +86,18 @@ export const userSettings = sqliteTable("user_settings", {
language: text("language", { length: 10 }).notNull().default("en"),
// Stock calculation mode: "automatic" (schedule-based) or "manual" (only marked doses)
stockCalculationMode: text("stock_calculation_mode", { length: 20 }).notNull().default("automatic"),
// Last notification tracking
// Whether shared schedule links show stock status (Critical/Low/Normal) to intake users
shareStockStatus: integer("share_stock_status", { mode: "boolean" }).notNull().default(true),
// Last notification tracking (intake reminders)
lastAutoEmailSent: text("last_auto_email_sent"),
lastNotificationType: text("last_notification_type"),
lastNotificationChannel: text("last_notification_channel"),
lastReminderMedName: text("last_reminder_med_name"),
lastReminderTakenBy: text("last_reminder_taken_by"),
// Last stock reminder tracking (separate from intake)
lastStockReminderSent: text("last_stock_reminder_sent"),
lastStockReminderChannel: text("last_stock_reminder_channel"),
lastStockReminderMedNames: text("last_stock_reminder_med_names"),
// Timestamps
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
});
+156 -27
View File
@@ -64,20 +64,29 @@ function getRegionFromTimezone(): string | undefined {
}
type TranslationKeys = {
// Stock reminder email
// Stock reminder (shared across email + push)
stockReminder: {
subject: string;
title: string;
description: string;
descriptionEmpty: string;
descriptionMixed: string;
alertSingle: string;
alertMultiple: string;
alertEmptySingle: string;
alertEmptyMultiple: string;
alertLowSingle: string;
alertLowMultiple: string;
alertLowStockSingle: string;
alertLowStockMultiple: string;
descriptionLow: string;
tableHeaders: {
medication: string;
pills: string;
days: string;
runsOut: string;
};
footer: string;
now: string;
repeatDailyNote: string;
};
// Intake reminder email
@@ -94,7 +103,6 @@ type TranslationKeys = {
};
pills: string;
takenBy: string;
footer: string;
};
// Push notifications
push: {
@@ -107,35 +115,68 @@ type TranslationKeys = {
repeatDailyNote: string;
empty: string;
low: string;
critical: string;
lowStock: string;
reorderNow: string;
emptySection: string;
lowSection: string;
criticalSection: string;
lowStockSection: string;
};
// Demand calculator email
demandCalculator: {
subject: string;
title: string;
description: string;
summaryOutOfStock: string;
summaryAllOk: string;
tableHeaders: {
medication: string;
usage: string;
needed: string;
available: string;
status: string;
};
statusEnough: string;
statusEmpty: string;
};
// Common
common: {
pill: string;
pills: string;
blister: string;
blisters: string;
day: string;
days: string;
soon: string;
footer: string;
};
};
const translations: Record<Language, TranslationKeys> = {
en: {
stockReminder: {
subject: "MedAssist-ng Auto-Reminder: {count} Medication{s} Running Low",
subject: "MedAssist-ng Auto-Reminder: {count} Medication{s} Running Critically Low",
title: "⚠️ MedAssist-ng - Automatic Reorder Reminder",
description: "The following medications are running low and need to be reordered:",
alertSingle: "⚠️ 1 medication running low!",
alertMultiple: "⚠️ {count} medications running low!",
description: "The following medications are running critically low and need to be reordered:",
descriptionEmpty: "The following medications are empty and need to be reordered immediately:",
descriptionMixed: "The following medications need to be reordered:",
alertSingle: "⚠️ 1 medication running critically low!",
alertMultiple: "⚠️ {count} medications running critically low!",
alertEmptySingle: "🚨 1 medication empty - reorder immediately!",
alertEmptyMultiple: "🚨 {count} medications empty - reorder immediately!",
alertLowSingle: "⚠️ 1 medication running critically low",
alertLowMultiple: "⚠️ {count} medications running critically low",
alertLowStockSingle: "⚠️ 1 medication running low",
alertLowStockMultiple: "⚠️ {count} medications running low",
descriptionLow: "The following medications are running low and should be reordered soon:",
tableHeaders: {
medication: "Medication",
pills: "Pills",
days: "Days",
runsOut: "Runs Out",
},
footer: "🤖 Automatic reminder from MedAssist-ng",
now: "NOW",
repeatDailyNote: "You are receiving this daily reminder because 'Repeat Daily' is enabled in settings.",
},
intakeReminder: {
@@ -151,44 +192,75 @@ const translations: Record<Language, TranslationKeys> = {
},
pills: "pills",
takenBy: "for {name}",
footer: "🤖 Automatic reminder from MedAssist-ng",
},
push: {
stockTitle: "MedAssist-ng: 1 Medication Running Low",
stockTitleMultiple: "MedAssist-ng: {count} Medications Running Low",
intakeTitle: "💊 Medication Reminder in {minutes} min",
stockTitle: "MedAssist-ng: 1 Medication Running Critically Low",
stockTitleMultiple: "MedAssist-ng: {count} Medications Running Critically Low",
intakeTitle: "💊 Reminder: Medication intake in {minutes} min",
pillsLeft: "{count} pills",
daysLeft: "{count} days left",
pillsAt: "{count} pills at {time}",
repeatDailyNote: "(Daily reminder enabled)",
empty: "Empty",
low: "Low",
low: "Critical",
critical: "Critical",
lowStock: "Low",
reorderNow: "Reorder Now!",
emptySection: "EMPTY (reorder immediately)",
lowSection: "RUNNING LOW (reorder soon)",
emptySection: "Empty (reorder immediately)",
lowSection: "Running critically low",
criticalSection: "Running critically low",
lowStockSection: "Running low",
},
demandCalculator: {
subject: "MedAssist-ng - Supply Overview ({from} - {until})",
title: "MedAssist-ng - Demand Calculator",
description: "Supply overview from {from} to {until}",
summaryOutOfStock: "⚠️ {count} medication{s} will be out of stock during this period.",
summaryAllOk: "✓ All medications have sufficient supply for this period.",
tableHeaders: {
medication: "Medication",
usage: "Usage",
needed: "Blisters needed",
available: "Available",
status: "Status",
},
statusEnough: "✓ Enough",
statusEmpty: "✗ Empty",
},
common: {
pill: "pill",
pills: "pills",
blister: "blister",
blisters: "blisters",
day: "day",
days: "days",
soon: "soon",
footer: "🤖 Sent from MedAssist-ng",
},
},
de: {
stockReminder: {
subject: "MedAssist-ng Auto-Erinnerung: {count} Medikament{e} wird knapp",
subject: "MedAssist-ng Auto-Erinnerung: {count} Medikament{e} kritisch niedrig",
title: "⚠️ MedAssist-ng - Automatische Nachbestell-Erinnerung",
description: "Die folgenden Medikamente gehen zur Neige und sollten nachbestellt werden:",
alertSingle: "⚠️ 1 Medikament wird knapp!",
alertMultiple: "⚠️ {count} Medikamente werden knapp!",
description: "Die folgenden Medikamente sind kritisch niedrig und sollten nachbestellt werden:",
descriptionEmpty: "Die folgenden Medikamente sind leer und müssen sofort nachbestellt werden:",
descriptionMixed: "Die folgenden Medikamente müssen nachbestellt werden:",
alertSingle: "⚠️ 1 Medikament kritisch niedrig!",
alertMultiple: "⚠️ {count} Medikamente kritisch niedrig!",
alertEmptySingle: "🚨 1 Medikament leer - sofort nachbestellen!",
alertEmptyMultiple: "🚨 {count} Medikamente leer - sofort nachbestellen!",
alertLowSingle: "⚠️ 1 Medikament kritisch niedrig",
alertLowMultiple: "⚠️ {count} Medikamente kritisch niedrig",
alertLowStockSingle: "⚠️ 1 Medikament niedrig",
alertLowStockMultiple: "⚠️ {count} Medikamente niedrig",
descriptionLow: "Die folgenden Medikamente werden knapp und sollten bald nachbestellt werden:",
tableHeaders: {
medication: "Medikament",
pills: "Tabletten",
days: "Tage",
runsOut: "Aufgebraucht",
},
footer: "🤖 Automatische Erinnerung von MedAssist-ng",
now: "JETZT",
repeatDailyNote:
"Sie erhalten diese tägliche Erinnerung, weil 'Täglich wiederholen' in den Einstellungen aktiviert ist.",
},
@@ -205,28 +277,50 @@ const translations: Record<Language, TranslationKeys> = {
},
pills: "Tabletten",
takenBy: "für {name}",
footer: "🤖 Automatische Erinnerung von MedAssist-ng",
},
push: {
stockTitle: "MedAssist-ng: 1 Medikament wird knapp",
stockTitleMultiple: "MedAssist-ng: {count} Medikamente werden knapp",
intakeTitle: "💊 Einnahme-Erinnerung in {minutes} Min.",
stockTitle: "MedAssist-ng: 1 Medikament kritisch niedrig",
stockTitleMultiple: "MedAssist-ng: {count} Medikamente kritisch niedrig",
intakeTitle: "💊 Erinnerung: Medikamenteneinnahme in {minutes} Min.",
pillsLeft: "{count} Tabletten",
daysLeft: "{count} Tage übrig",
pillsAt: "{count} Tabletten um {time}",
repeatDailyNote: "(Tägliche Erinnerung aktiviert)",
empty: "Leer",
low: "Knapp",
low: "Kritisch",
critical: "Kritisch",
lowStock: "Niedrig",
reorderNow: "Jetzt nachbestellen!",
emptySection: "LEER (sofort nachbestellen)",
lowSection: "WIRD KNAPP (bald nachbestellen)",
emptySection: "Leer (sofort nachbestellen)",
lowSection: "Kritisch niedrig",
criticalSection: "Kritisch niedrig",
lowStockSection: "Niedrig",
},
demandCalculator: {
subject: "MedAssist-ng - Bestandsübersicht ({from} - {until})",
title: "MedAssist-ng - Bedarfsrechner",
description: "Bestandsübersicht von {from} bis {until}",
summaryOutOfStock: "⚠️ {count} Medikament{e} wird im Zeitraum nicht ausreichen.",
summaryAllOk: "✓ Alle Medikamente reichen für diesen Zeitraum.",
tableHeaders: {
medication: "Medikament",
usage: "Verbrauch",
needed: "Blister benötigt",
available: "Verfügbar",
status: "Status",
},
statusEnough: "✓ Ausreichend",
statusEmpty: "✗ Leer",
},
common: {
pill: "Tablette",
pills: "Tabletten",
blister: "Blister",
blisters: "Blister",
day: "Tag",
days: "Tage",
soon: "bald",
footer: "🤖 Gesendet von MedAssist-ng",
},
},
};
@@ -264,3 +358,38 @@ export function getDateLocale(language: Language): string {
return "en-US";
}
}
/**
* Get the app URL from the first CORS_ORIGINS entry.
* Falls back to empty string if not set.
*/
export function getAppUrl(): string {
const origins = process.env.CORS_ORIGINS || "";
return origins.split(",")[0]?.trim() || "";
}
/**
* Get the unified footer as HTML with MedAssist-ng as a link to the instance.
* @param variant - 'planner' uses the Medication Planner footer text
*/
export function getFooterHtml(language: Language): string {
const tr = getTranslations(language);
const appUrl = getAppUrl();
const appName = appUrl
? `<a href="${appUrl}" style="color: #6b7280; text-decoration: underline;">MedAssist-ng</a>`
: "MedAssist-ng";
return tr.common.footer.replace("MedAssist-ng", appName);
}
/**
* Get the unified footer as plain text.
* @param variant - 'planner' uses the Medication Planner footer text
*/
export function getFooterPlain(language: Language): string {
const tr = getTranslations(language);
const appUrl = getAppUrl();
if (appUrl) {
return `${tr.common.footer} (${appUrl})`;
}
return tr.common.footer;
}
+7 -2
View File
@@ -10,6 +10,7 @@ import sensible from "@fastify/sensible";
import fastifyStatic from "@fastify/static";
import Fastify, { type FastifyInstance } from "fastify";
import { migrationsReady } from "./db/client.js";
import { getDataDir } from "./db/db-utils.js";
import { env } from "./plugins/env.js";
import { authRoutes } from "./routes/auth.js";
import { doseRoutes } from "./routes/doses.js";
@@ -66,7 +67,7 @@ export async function createApp(options?: {
accessTtlMinutes: options?.accessTtlMinutes ?? 15,
refreshTtlDays: options?.refreshTtlDays ?? 7,
isProduction: options?.isProduction ?? false,
imagesDir: options?.imagesDir ?? resolve(process.cwd(), "data/images"),
imagesDir: options?.imagesDir ?? resolve(getDataDir(), "images"),
};
const app = Fastify({
@@ -125,9 +126,11 @@ export async function createApp(options?: {
// Server initialization (runs on import)
// =============================================================================
import { log } from "./utils/logger.js";
// Wait for database migrations before anything else
await migrationsReady;
console.log("[DB] Migrations complete, starting server...");
log.info("[DB] Migrations complete, starting server...");
// Ensure images directory exists
const imagesDir = ensureImagesDirectory();
@@ -196,12 +199,14 @@ const start = async () => {
// Start the automatic reminder scheduler
startReminderScheduler({
info: (msg) => app.log.info(msg),
debug: (msg) => app.log.debug(msg),
error: (msg) => app.log.error(msg),
});
// Start the intake reminder scheduler (checks every minute)
startIntakeReminderScheduler({
info: (msg) => app.log.info(msg),
debug: (msg) => app.log.debug(msg),
error: (msg) => app.log.error(msg),
});
} catch (err) {
-1
View File
@@ -37,7 +37,6 @@ export async function getAnonymousUserId(): Promise<number> {
`);
anonymousUserVerified = true;
console.log(`Created anonymous user with fixed ID ${ANONYMOUS_USER_ID} for no-auth mode`);
return ANONYMOUS_USER_ID;
}
+4 -1
View File
@@ -1,7 +1,10 @@
import { existsSync } from "node:fs";
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({
NODE_ENV: z.enum(["development", "production", "test"]).default("production"),
+43 -2
View File
@@ -4,6 +4,7 @@ import { eq } from "drizzle-orm";
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 type { AuthUser } from "../types/fastify.js";
@@ -476,7 +477,7 @@ export async function authRoutes(app: FastifyInstance) {
// Save file
const fs = await import("node:fs/promises");
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 });
const buffer = await data.toBuffer();
@@ -523,7 +524,7 @@ export async function authRoutes(app: FastifyInstance) {
const fs = await import("node:fs/promises");
const path = await import("node:path");
try {
await fs.unlink(path.join(process.cwd(), "data", "images", user.avatarUrl));
await fs.unlink(path.join(getDataDir(), "images", user.avatarUrl));
} catch {
// Ignore if file doesn't exist
}
@@ -534,4 +535,44 @@ export async function authRoutes(app: FastifyInstance) {
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" });
}
);
}
+41 -35
View File
@@ -5,12 +5,14 @@ import { eq } from "drizzle-orm";
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 type { AuthUser } from "../types/fastify.js";
import { parseIntakesJson, parseTakenByJson } from "../utils/scheduler-utils.js";
const IMAGES_DIR = resolve(process.cwd(), "data/images");
const IMAGES_DIR = resolve(getDataDir(), "images");
// =============================================================================
// Export Format Version (bump this when format changes)
@@ -26,6 +28,7 @@ const scheduleSchema = z.object({
every: z.number().int().min(1),
start: z.string(), // ISO datetime string
remind: z.boolean().optional().default(false),
takenBy: z.string().nullable().optional(), // Per-intake takenBy (new field)
});
const inventorySchema = z.object({
@@ -34,6 +37,7 @@ const inventorySchema = z.object({
pillsPerBlister: z.number().int().min(1).default(1),
looseTablets: z.number().int().min(0).default(0),
stockAdjustment: z.number().int().default(0), // Manual stock correction
packageType: z.enum(["blister", "bottle"]).default("blister"),
});
const medicationExportSchema = z.object({
@@ -43,6 +47,7 @@ const medicationExportSchema = z.object({
takenBy: z.array(z.string()).default([]),
inventory: inventorySchema,
pillWeightMg: z.number().int().nullable().optional(),
doseUnit: z.enum(["mg", "g", "mcg", "ml", "IU", "units", "drops", "puffs"]).default("mg"),
schedules: z.array(scheduleSchema).default([]),
expiryDate: z.string().nullable().optional(),
notes: z.string().nullable().optional(),
@@ -125,39 +130,24 @@ async function getUserId(request: any, reply: any): Promise<number> {
return authUser.id;
}
// Parse takenByJson safely
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 [];
}
}
// Parse blisters from DB format to export format
function parseBlistersForExport(
// Parse intakes from DB format to export format (with per-intake takenBy)
function parseIntakesForExport(
row: typeof medications.$inferSelect
): Array<{ usage: number; every: number; start: string; remind: boolean }> {
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[];
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 [];
}
): Array<{ usage: number; every: number; start: string; remind: boolean; takenBy: string | null }> {
// Use the new parseIntakesJson which falls back to legacy format
const intakes = parseIntakesJson(
row.intakesJson,
{ usageJson: row.usageJson, everyJson: row.everyJson, startJson: row.startJson },
row.intakeRemindersEnabled ?? false
);
return intakes.map((intake) => ({
usage: intake.usage,
every: intake.every,
start: intake.start,
remind: intake.intakeRemindersEnabled,
takenBy: intake.takenBy, // Per-intake takenBy
}));
}
// Read image file and convert to base64 data URL
@@ -287,9 +277,11 @@ export async function exportRoutes(app: FastifyInstance) {
pillsPerBlister: med.pillsPerBlister ?? 1,
looseTablets: med.looseTablets ?? 0,
stockAdjustment: med.stockAdjustment ?? 0,
packageType: med.packageType ?? "blister",
},
pillWeightMg: med.pillWeightMg,
schedules: parseBlistersForExport(med),
doseUnit: med.doseUnit ?? "mg",
schedules: parseIntakesForExport(med),
expiryDate: med.expiryDate,
notes: med.notes,
intakeRemindersEnabled: med.intakeRemindersEnabled ?? false,
@@ -473,12 +465,23 @@ export async function exportRoutes(app: FastifyInstance) {
const exportIdToNewId = new Map<string, number>();
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 everyJson = JSON.stringify(med.schedules.map((s) => s.every));
const startJson = JSON.stringify(med.schedules.map((s) => s.start));
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
const intakeRemindersEnabled = med.schedules.some((s) => s.remind) || med.intakeRemindersEnabled;
@@ -489,6 +492,7 @@ export async function exportRoutes(app: FastifyInstance) {
name: med.name,
genericName: med.genericName || null,
takenByJson,
packageType: med.inventory.packageType ?? "blister",
packCount: med.inventory.packCount,
blistersPerPack: med.inventory.blistersPerPack,
pillsPerBlister: med.inventory.pillsPerBlister,
@@ -496,6 +500,8 @@ export async function exportRoutes(app: FastifyInstance) {
stockAdjustment: med.inventory.stockAdjustment ?? 0,
lastStockCorrectionAt: med.lastStockCorrectionAt ? new Date(med.lastStockCorrectionAt) : null,
pillWeightMg: med.pillWeightMg || null,
doseUnit: med.doseUnit ?? "mg",
intakesJson,
usageJson,
everyJson,
startJson,
+443 -122
View File
@@ -5,64 +5,55 @@ import { and, eq, like } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { doseTracking, medications } from "../db/schema.js";
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js";
import { parseLocalDateTime } from "../utils/scheduler-utils.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({
usage: z.number().nonnegative(),
every: z.number().int().min(1),
start: z.string().datetime({ local: true }),
});
const medicationSchema = z.object({
name: z.string().trim().min(1).max(100),
genericName: z.string().trim().max(100).nullable().optional(),
takenBy: z.array(z.string().trim().max(100)).default([]), // Array of person names
packCount: z.number().int().min(0).default(1),
blistersPerPack: z.number().int().min(1).default(1),
pillsPerBlister: z.number().int().min(1).default(1),
looseTablets: z.number().int().min(0).default(0),
pillWeightMg: z.number().int().min(1).nullable().optional(),
expiryDate: z.string().nullable().optional(),
notes: z.string().max(2000).nullable().optional(),
intakeRemindersEnabled: z.boolean().default(false),
blisters: z.array(blisterSchema).min(1).max(12),
});
const packageTypeSchema = z.enum(["blister", "bottle"]).default("blister");
const doseUnitSchema = z.enum(["mg", "g", "mcg", "ml", "IU", "units", "drops", "puffs"]).default("mg");
function zipBlisters(usage: number[], every: number[], start: string[]) {
const len = Math.min(usage.length, every.length, start.length);
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 [];
}
}
const medicationSchema = z
.object({
name: z.string().trim().min(1).max(100),
genericName: z.string().trim().max(100).nullable().optional(),
takenBy: z.array(z.string().trim().max(100)).default([]), // Medication-level takenBy (fallback)
packageType: packageTypeSchema,
packCount: z.number().int().min(0).default(1),
blistersPerPack: 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),
pillWeightMg: z.number().nonnegative().nullable().optional(),
doseUnit: doseUnitSchema,
expiryDate: z.string().nullable().optional(),
notes: z.string().max(2000).nullable().optional(),
intakeRemindersEnabled: z.boolean().default(false), // Medication-level (deprecated, kept for backward compat)
// 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
})
.refine((data) => data.intakes || data.blisters, { message: "Either 'intakes' or 'blisters' must be provided" });
export async function medicationRoutes(app: FastifyInstance) {
// All medication routes require auth
@@ -88,26 +79,40 @@ export async function medicationRoutes(app: FastifyInstance) {
app.get("/medications", async (request, reply) => {
const userId = await getUserId(request, reply);
const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id);
return rows.map((row) => ({
id: row.id,
name: row.name,
genericName: row.genericName,
takenBy: parseTakenByJson(row.takenByJson),
packCount: row.packCount ?? 1,
blistersPerPack: row.blistersPerPack ?? 1,
pillsPerBlister: row.pillsPerBlister ?? 1,
looseTablets: row.looseTablets ?? 0,
stockAdjustment: row.stockAdjustment ?? 0,
lastStockCorrectionAt: row.lastStockCorrectionAt?.toISOString() ?? null,
pillWeightMg: row.pillWeightMg,
blisters: parseBlisters(row),
imageUrl: row.imageUrl,
expiryDate: row.expiryDate,
notes: row.notes,
intakeRemindersEnabled: row.intakeRemindersEnabled ?? false,
dismissedUntil: row.dismissedUntil ?? null,
updatedAt: row.updatedAt,
}));
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,
name: row.name,
genericName: row.genericName,
takenBy: parseTakenByJson(row.takenByJson),
packageType: row.packageType ?? "blister",
packCount: row.packCount ?? 1,
blistersPerPack: row.blistersPerPack ?? 1,
pillsPerBlister: row.pillsPerBlister ?? 1,
totalPills: row.totalPills ?? null,
looseTablets: row.looseTablets ?? 0,
stockAdjustment: row.stockAdjustment ?? 0,
lastStockCorrectionAt: row.lastStockCorrectionAt?.toISOString() ?? null,
pillWeightMg: row.pillWeightMg,
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,
expiryDate: row.expiryDate,
notes: row.notes,
intakeRemindersEnabled: row.intakeRemindersEnabled ?? false,
dismissedUntil: row.dismissedUntil ?? null,
updatedAt: row.updatedAt,
};
});
});
app.post("/medications", async (req, reply) => {
@@ -119,19 +124,50 @@ export async function medicationRoutes(app: FastifyInstance) {
name,
genericName,
takenBy,
packageType,
packCount,
blistersPerPack,
pillsPerBlister,
totalPills,
looseTablets,
pillWeightMg,
doseUnit,
expiryDate,
notes,
intakeRemindersEnabled,
blisters,
intakes: inputIntakes,
blisters: inputBlisters,
} = parsed.data;
const usageJson = JSON.stringify(blisters.map((s) => s.usage));
const everyJson = JSON.stringify(blisters.map((s) => s.every));
const startJson = JSON.stringify(blisters.map((s) => s.start));
// 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 [inserted] = await db
@@ -141,14 +177,18 @@ export async function medicationRoutes(app: FastifyInstance) {
name,
genericName: genericName || null,
takenByJson,
packageType: packageType ?? "blister",
packCount,
blistersPerPack,
pillsPerBlister,
totalPills: totalPills || null,
looseTablets,
pillWeightMg: pillWeightMg || null,
doseUnit: doseUnit ?? "mg",
expiryDate: expiryDate || null,
notes: notes || null,
intakeRemindersEnabled: intakeRemindersEnabled ?? false,
intakesJson,
usageJson,
everyJson,
startJson,
@@ -160,14 +200,18 @@ export async function medicationRoutes(app: FastifyInstance) {
name: inserted.name,
genericName: inserted.genericName,
takenBy: parseTakenByJson(inserted.takenByJson),
packageType: inserted.packageType ?? "blister",
packCount: inserted.packCount,
blistersPerPack: inserted.blistersPerPack,
pillsPerBlister: inserted.pillsPerBlister,
totalPills: inserted.totalPills ?? null,
looseTablets: inserted.looseTablets,
stockAdjustment: inserted.stockAdjustment ?? 0,
lastStockCorrectionAt: inserted.lastStockCorrectionAt?.toISOString() ?? null,
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,
expiryDate: inserted.expiryDate,
notes: inserted.notes,
@@ -195,68 +239,208 @@ export async function medicationRoutes(app: FastifyInstance) {
name,
genericName,
takenBy,
packageType,
packCount,
blistersPerPack,
pillsPerBlister,
totalPills,
looseTablets,
pillWeightMg,
doseUnit,
expiryDate,
notes,
intakeRemindersEnabled,
blisters,
intakes: inputIntakes,
blisters: inputBlisters,
} = parsed.data;
const usageJson = JSON.stringify(blisters.map((s) => s.usage));
const everyJson = JSON.stringify(blisters.map((s) => s.every));
const startJson = JSON.stringify(blisters.map((s) => s.start));
// 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 || []);
// 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
.update(medications)
.set({
name,
genericName: genericName || null,
takenByJson,
packageType: packageType ?? "blister",
packCount,
blistersPerPack,
pillsPerBlister,
totalPills: totalPills || null,
looseTablets,
pillWeightMg: pillWeightMg || null,
doseUnit: doseUnit ?? "mg",
expiryDate: expiryDate || null,
notes: notes || null,
intakeRemindersEnabled: intakeRemindersEnabled ?? false,
intakesJson,
usageJson,
everyJson,
startJson,
updatedAt: new Date(),
...stockResetFields,
})
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
.returning();
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
const earliestStart = Math.min(...blisters.map((b) => parseLocalDateTime(b.start).getTime()));
if (!Number.isNaN(earliestStart)) {
// Get all dose tracking entries for this medication and filter out invalid ones
const allDoses = await db
.select()
.from(doseTracking)
.where(and(eq(doseTracking.userId, userId), like(doseTracking.doseId, `${idNum}-%`)));
// ---------------------------------------------------------------
// Migrate dose tracking IDs when intake schedule changes
// ---------------------------------------------------------------
// Parse old intakes from the existing medication row
const oldIntakes = parseIntakesJson(
existing.intakesJson,
{ usageJson: existing.usageJson, everyJson: existing.everyJson, startJson: existing.startJson },
existing.intakeRemindersEnabled
);
// Find doses with timestamps before the earliest start date
const dosesToDelete = allDoses.filter((dose) => {
const parts = dose.doseId.split("-");
if (parts.length >= 3) {
const timestamp = parseInt(parts[2], 10);
return !Number.isNaN(timestamp) && timestamp < earliestStart;
// Get all dose tracking entries for this medication
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
}
return false;
});
// Delete invalid doses
for (const dose of dosesToDelete) {
await db.delete(doseTracking).where(eq(doseTracking.id, dose.id));
// 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("-");
if (parts.length >= 3) {
const timestamp = parseInt(parts[2], 10);
return !Number.isNaN(timestamp) && timestamp < earliestStartDate;
}
return false;
});
for (const dose of dosesToDelete) {
await db.delete(doseTracking).where(eq(doseTracking.id, dose.id));
}
}
}
@@ -265,14 +449,18 @@ export async function medicationRoutes(app: FastifyInstance) {
name: result[0].name,
genericName: result[0].genericName,
takenBy: parseTakenByJson(result[0].takenByJson),
packageType: result[0].packageType ?? "blister",
packCount: result[0].packCount,
blistersPerPack: result[0].blistersPerPack,
pillsPerBlister: result[0].pillsPerBlister,
totalPills: result[0].totalPills ?? null,
looseTablets: result[0].looseTablets,
stockAdjustment: result[0].stockAdjustment ?? 0,
lastStockCorrectionAt: result[0].lastStockCorrectionAt?.toISOString() ?? null,
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,
expiryDate: result[0].expiryDate,
notes: result[0].notes,
@@ -413,10 +601,14 @@ export async function medicationRoutes(app: FastifyInstance) {
});
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);
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 end = new Date(endDate);
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end <= start) {
@@ -425,55 +617,168 @@ export async function medicationRoutes(app: FastifyInstance) {
const userId = await getUserId(req, reply);
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 payload = rows.map((row) => {
const blisters = parseBlisters(row);
const usageTotal = calculateUsageInRange(blisters, start, end);
// 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
);
const blisters = intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start }));
const pillsPerBlister = row.pillsPerBlister ?? 1;
const packCount = row.packCount ?? 1;
const blistersPerPack = row.blistersPerPack ?? 1;
const looseTablets = row.looseTablets ?? 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;
blisters.forEach((blister) => {
const msPerDay = 86400000;
blisters.forEach((blister, blisterIdx) => {
const blisterStart = parseLocalDateTime(blister.start);
if (Number.isNaN(blisterStart.getTime()) || blisterStart > now) return;
const msPerDay = 86400000;
if (Number.isNaN(blisterStart.getTime())) return;
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
// Always use the user-selected start date for the usage calculation.
// Using max(now, start) would cause asymmetric counting when now falls
// between morning and evening doses on the start day (e.g., morning dose
// skipped but evening counted), leading to confusing off-by-one results.
// The stock already reflects consumed doses, so no double-counting occurs.
// When includeUntilStart is true, calculate from now to end (useful for trip planning)
const effectivePlannerStart = includeUntilStart ? now : start;
const usageTotal = calculateUsageInRange(blisters, effectivePlannerStart, end);
const blistersNeeded = pillsPerBlister > 0 ? Math.ceil(usageTotal / pillsPerBlister) : 0;
// Calculate current stock using realistic consumption order (loose first, then blisters)
const consumed = originalTotalPills - currentPills;
const looseConsumed = Math.min(consumed, looseTablets);
const loosePillsRemaining = looseTablets - looseConsumed;
const blisterPillsConsumed = consumed - looseConsumed;
const originalBlisterPills = originalTotalPills - looseTablets;
const blisterPillsRemaining = Math.max(0, originalBlisterPills - blisterPillsConsumed);
// Calculate AVAILABLE = stock AFTER the planned period (currentStock - usageTotal)
const availableAfterPeriod = Math.max(0, currentStock - usageTotal);
const fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0;
const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0;
const loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose
let fullBlisters: number;
let loosePills: number;
const enough = currentPills >= usageTotal;
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 blisterPillsRemaining = Math.max(0, originalBlisterPills - blisterPillsConsumed);
fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0;
const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0;
loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose
}
const enough = currentStock >= usageTotal;
return {
medicationId: row.id,
medicationName: row.name,
totalPills: currentPills,
totalPills: currentStock,
plannerUsage: usageTotal,
blisterSize: pillsPerBlister,
blistersNeeded,
fullBlisters,
loosePills,
enough,
packageType,
};
});
@@ -539,12 +844,28 @@ function calculateUsageInRange(
end: Date
) {
let total = 0;
const msPerDay = 86400000;
blisters.forEach((blister) => {
const blisterStart = parseLocalDateTime(blister.start);
if (Number.isNaN(blisterStart.getTime())) return;
// iterate occurrences from blisterStart up to end
for (let dt = new Date(blisterStart); dt < end; dt.setDate(dt.getDate() + blister.every)) {
if (dt >= start && dt < end) total += blister.usage;
const every = Math.max(1, blister.every);
// Skip ahead to the first occurrence at or after start to avoid
// iterating through months/years of past doses
const dt = new Date(blisterStart);
if (dt < start) {
const daysToSkip = Math.floor((start.getTime() - dt.getTime()) / (every * msPerDay));
dt.setDate(dt.getDate() + daysToSkip * every);
// Fine-tune: advance until we reach or pass start
while (dt < start) {
dt.setDate(dt.getDate() + every);
}
}
// Count occurrences in [start, end)
for (; dt < end; dt.setDate(dt.getDate() + every)) {
total += blister.usage;
}
});
return Number(total.toFixed(2));
+4 -4
View File
@@ -201,7 +201,7 @@ export async function oidcRoutes(app: FastifyInstance) {
});
// Set cookies (use app's centralized cookie options)
console.log(
request.log.debug(
`[OIDC] Setting cookies for user ${user.username}, NODE_ENV=${env.NODE_ENV}, secure=${app.config.cookieOptions.secure}`
);
setAuthCookies(app, reply, accessToken, refreshToken);
@@ -241,12 +241,12 @@ async function findOrCreateOIDCUser(
if (existingByUsername.authProvider === "local" && !existingByUsername.oidcSubject) {
// Local user exists without SSO - link this OIDC account to existing user
await db.update(users).set({ oidcSubject: oidcSubject }).where(eq(users.id, existingByUsername.id));
console.log(`[OIDC] Linked OIDC to existing local user: ${username}`);
// Linked OIDC to existing local user
return { id: existingByUsername.id, username: existingByUsername.username };
} else if (existingByUsername.oidcSubject && existingByUsername.oidcSubject !== oidcSubject) {
// User already has a DIFFERENT OIDC subject - create new user with suffix
username = `${username}_sso`;
console.log(`[OIDC] Username collision (different OIDC subject), using: ${username}`);
// Username collision (different OIDC subject), use suffixed name
}
}
@@ -268,7 +268,7 @@ async function findOrCreateOIDCUser(
})
.returning({ id: users.id, username: users.username });
console.log(`[OIDC] Created new user: ${newUser.username} (ID: ${newUser.id})`);
// New OIDC user created
return newUser;
}
+278 -191
View File
@@ -1,6 +1,13 @@
import type { FastifyInstance, FastifyRequest } from "fastify";
import nodemailer from "nodemailer";
import { getDateLocale, getTranslations, type Language, t } from "../i18n/translations.js";
import {
getDateLocale,
getFooterHtml,
getFooterPlain,
getTranslations,
type Language,
t,
} from "../i18n/translations.js";
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js";
import { updateReminderSentTime, updateUserReminderSentTime } from "../services/reminder-scheduler.js";
@@ -29,6 +36,7 @@ type PlannerRow = {
fullBlisters: number;
loosePills: number;
enough: boolean;
packageType?: string;
};
type SendEmailBody = {
@@ -44,6 +52,7 @@ type LowStockItem = {
medsLeft: number;
daysLeft: number | null;
depletionDate: string | null;
isCritical?: boolean;
};
type ReminderEmailBody = {
@@ -68,32 +77,28 @@ export async function plannerRoutes(app: FastifyInstance) {
return authUser.id;
}
// Demand calculator notification (supports email and push)
app.post<{ Body: SendEmailBody }>("/planner/send-email", async (request, reply) => {
const { email, from, until, rows, language: bodyLanguage } = request.body;
if (!email || !rows || rows.length === 0) {
return reply.status(400).send({ error: "Missing email or planner data" });
if (!rows || rows.length === 0) {
return reply.status(400).send({ error: "Missing planner data" });
}
const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence
const smtpPort = parseInt(process.env.SMTP_PORT ?? "587", 10);
const smtpSecure = process.env.SMTP_SECURE === "true";
const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
if (!smtpHost || !smtpUser) {
return reply.status(400).send({ error: "SMTP not configured" });
}
// Load user settings for notification channels
const userId = await getUserId(request);
const userSettings = await loadUserSettings(userId);
const notificationSettings = {
emailEnabled: userSettings.emailEnabled,
shoutrrrEnabled: userSettings.shoutrrrEnabled,
shoutrrrUrl: userSettings.shoutrrrUrl || "",
};
// Get locale from user settings or use the language passed in the body
let language: Language = bodyLanguage || "en";
const authUser = request.user as unknown as AuthUser | null;
if (authUser?.id) {
const userSettings = await loadUserSettings(authUser.id);
language = userSettings.language;
}
const language: Language = (userSettings.language as Language) || bodyLanguage || "en";
const locale = getDateLocale(language);
const tr = getTranslations(language);
const dc = tr.demandCalculator;
// Format dates for display - escape to prevent XSS even though toLocaleDateString should be safe
const fromDate = escapeHtml(
@@ -111,47 +116,93 @@ export async function plannerRoutes(app: FastifyInstance) {
})
);
// Build HTML table with horizontal scroll for mobile
// Escape/coerce all user-provided values to prevent XSS
const tableRows = rows
.map((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 `
const outOfStockCount = rows.filter((r) => !r.enough).length;
const summaryText = outOfStockCount > 0 ? t(dc.summaryOutOfStock, { count: outOfStockCount }) : dc.summaryAllOk;
// Build plain text (shared between email and push)
const plainText = `${dc.title}
${t(dc.description, { from: fromDate, until: untilDate })}
${summaryText}
${rows
.map((r) => {
const isBottle = r.packageType === "bottle";
const usage = `${r.plannerUsage} ${tr.common.pills}`;
const needed = isBottle ? "" : `${r.blistersNeeded} × ${r.blisterSize}`;
const loosePills = Math.round((Number(r.loosePills) || 0) * 10) / 10;
const available = isBottle
? `${loosePills} ${tr.common.pills}`
: `${r.fullBlisters} ${tr.common.blisters}${loosePills > 0 ? ` + ${loosePills} ${tr.common.pills}` : ""}`;
const status = r.enough ? dc.statusEnough : dc.statusEmpty;
return `${r.medicationName}: ${usage}, ${needed}, ${available} - ${status}`;
})
.join("\n")}
---
${getFooterPlain(language)}`;
const results: { email?: boolean; push?: boolean; errors: string[] } = { errors: [] };
// Send email if enabled
if (notificationSettings.emailEnabled && email) {
const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS; // Token takes precedence
const smtpPort = parseInt(process.env.SMTP_PORT ?? "587", 10);
const smtpSecure = process.env.SMTP_SECURE === "true";
const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
if (smtpHost && smtpUser) {
// Build HTML table with horizontal scroll for mobile
// Escape/coerce all user-provided values to prevent XSS
const tableRows = rows
.map((row) => {
const safeName = escapeHtml(row.medicationName);
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 = Math.round((Number(row.loosePills) || 0) * 10) / 10;
const isBottle = row.packageType === "bottle";
// "Blisters needed" column: dash for bottles
const neededCell = isBottle ? "" : `${safeBlistersNeeded} × ${safeBlisterSize}`;
// "Available" column: match frontend format
let availableCell: string;
if (isBottle) {
availableCell = `${safeLoosePills} ${tr.common.pills}`;
} else {
availableCell = `${safeFullBlisters} ${tr.common.blisters}`;
if (safeLoosePills > 0) {
availableCell += ` + ${safeLoosePills} ${tr.common.pills}`;
}
}
return `
<tr>
<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>${safeTotalPills}</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;">${safeBlistersNeeded} × ${safeBlisterSize}</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;"><strong>${safePlannerUsage}</strong> ${tr.common.pills}</td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${neededCell}</td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${availableCell}</td>
<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; ${
row.enough ? "background: #d1fae5; color: #065f46;" : "background: #fee2e2; color: #991b1b;"
}">
${row.enough ? "✓ OK" : "✗ Out of Stock"}
${row.enough ? dc.statusEnough : dc.statusEmpty}
</span>
</td>
</tr>
`;
})
.join("");
})
.join("");
const outOfStockCount = rows.filter((r) => !r.enough).length;
const summaryText =
outOfStockCount > 0
? `⚠️ ${outOfStockCount} medication${outOfStockCount > 1 ? "s" : ""} will be out of stock during this period.`
: "✓ All medications have sufficient supply for this period.";
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="background: white; border-radius: 12px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
<h2 style="color: #1f2937; margin: 0 0 8px; font-size: 18px;">MedAssist-ng - Demand Calculator</h2>
<p style="color: #6b7280; margin: 0 0 16px; font-size: 13px;">Supply overview from <strong>${fromDate}</strong> to <strong>${untilDate}</strong></p>
<h2 style="color: #1f2937; margin: 0 0 8px; font-size: 18px;">${dc.title}</h2>
<p style="color: #6b7280; margin: 0 0 16px; font-size: 13px;">${t(dc.description, { from: `<strong>${fromDate}</strong>`, until: `<strong>${untilDate}</strong>` })}</p>
<div style="padding: 10px 14px; border-radius: 8px; margin-bottom: 16px; ${
outOfStockCount > 0
@@ -167,12 +218,11 @@ export async function plannerRoutes(app: FastifyInstance) {
<table style="width: 100%; border-collapse: collapse; background: white; min-width: 550px;">
<thead>
<tr style="background: #f3f4f6;">
<th style="padding: 10px 12px; text-align: left; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">Medication</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">Stock</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">Usage</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">Needed</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">Available</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">Status</th>
<th style="padding: 10px 12px; text-align: left; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.medication}</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.usage}</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.needed}</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.available}</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.status}</th>
</tr>
</thead>
<tbody>
@@ -182,44 +232,76 @@ export async function plannerRoutes(app: FastifyInstance) {
</div>
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
<p style="color: #9ca3af; font-size: 11px; margin: 0;">Sent from MedAssist-ng Medication Planner</p>
<p style="color: #9ca3af; font-size: 11px; margin: 0;">${getFooterHtml(language)}</p>
</div>
</div>
`;
const plainText = `MedAssist-ng - Demand Calculator
Supply overview from ${fromDate} to ${untilDate}
try {
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpSecure,
auth: {
user: smtpUser,
pass: smtpPass ?? "",
},
});
${summaryText}
await transporter.sendMail({
from: smtpFrom,
to: email,
subject: t(dc.subject, { from: fromDate, until: untilDate }),
text: plainText,
html,
});
${rows.map((r) => `${r.medicationName}: ${r.totalPills} pills in stock, ${r.plannerUsage} pills needed, ${r.fullBlisters} blisters available${r.loosePills > 0 ? ` (+${r.loosePills} loose)` : ""} (${r.blistersNeeded} needed) - ${r.enough ? "Enough" : "OUT OF STOCK"}`).join("\n")}
results.email = true;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
results.errors.push(`Email: ${errorMessage}`);
}
}
}
---
Sent from MedAssist-ng Medication Planner`;
// Send push notification if enabled
if (notificationSettings.shoutrrrEnabled && notificationSettings.shoutrrrUrl) {
const pushTitle = t(dc.subject, { from: fromDate, until: untilDate });
const pushMessage = `${summaryText}\n\n${rows
.map((r) => {
const usage = `${r.plannerUsage} ${tr.common.pills}`;
const status = r.enough ? dc.statusEnough : dc.statusEmpty;
return `${r.enough ? "✓" : "✗"} ${r.medicationName}: ${usage} - ${status}`;
})
.join("\n")}\n\n---\n${getFooterPlain(language)}`;
try {
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpSecure,
auth: {
user: smtpUser,
pass: smtpPass ?? "",
},
try {
const pushResult = await sendShoutrrrNotification(notificationSettings.shoutrrrUrl, pushTitle, pushMessage);
if (pushResult.success) {
results.push = true;
} else {
results.errors.push(`Push: ${pushResult.error}`);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
results.errors.push(`Push: ${errorMessage}`);
}
}
// Build response message
const sentChannels: string[] = [];
if (results.email) sentChannels.push("email");
if (results.push) sentChannels.push("push");
if (sentChannels.length > 0) {
return reply.send({
success: true,
message: `Notification sent via ${sentChannels.join(" and ")}`,
});
await transporter.sendMail({
from: smtpFrom,
to: email,
subject: `MedAssist-ng - Supply Overview (${fromDate} - ${untilDate})`,
text: plainText,
html,
});
return reply.send({ success: true, message: "Email sent successfully" });
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
return reply.status(500).send({ error: `Failed to send email: ${errorMessage}` });
} else if (results.errors.length > 0) {
return reply.status(500).send({ error: results.errors.join("; ") });
} else {
return reply.status(400).send({ error: "No notification channels configured" });
}
});
@@ -240,11 +322,66 @@ Sent from MedAssist-ng Medication Planner`;
shoutrrrUrl: userSettings.shoutrrrUrl || "",
};
// Get translations based on user language
const language = (userSettings.language as Language) || "en";
const tr = getTranslations(language);
const results: { email?: boolean; push?: boolean; errors: string[] } = { errors: [] };
// Separate empty from low stock medications
// Separate into 3 categories: empty, critical, and low stock
const emptyMeds = lowStock.filter((r) => r.medsLeft <= 0);
const lowMeds = lowStock.filter((r) => r.medsLeft > 0);
const criticalMeds = lowStock.filter((r) => r.medsLeft > 0 && r.isCritical !== false);
const lowStockMeds = lowStock.filter((r) => r.medsLeft > 0 && r.isCritical === false);
// Build shared notification content (method-agnostic)
const titleParts: string[] = [];
if (emptyMeds.length > 0) {
titleParts.push(`🚨 ${emptyMeds.length} ${tr.push.empty}`);
}
if (criticalMeds.length > 0) {
titleParts.push(`🚨 ${criticalMeds.length} ${tr.push.critical}`);
}
if (lowStockMeds.length > 0) {
titleParts.push(`⚠️ ${lowStockMeds.length} ${tr.push.lowStock}`);
}
const notificationTitle = `MedAssist: ${titleParts.join(", ")} - ${tr.push.reorderNow}`;
// Build description text
let descriptionText: string;
if (emptyMeds.length > 0 && (criticalMeds.length > 0 || lowStockMeds.length > 0)) {
descriptionText = tr.stockReminder.descriptionMixed;
} else if (emptyMeds.length > 0) {
descriptionText = tr.stockReminder.descriptionEmpty;
} else if (criticalMeds.length > 0) {
descriptionText = tr.stockReminder.description;
} else {
descriptionText = tr.stockReminder.descriptionLow;
}
// Build section-based message (shared between email plain text and push)
const messageParts: string[] = [];
if (emptyMeds.length > 0) {
messageParts.push(`🚨 ${tr.push.emptySection}:`);
emptyMeds.forEach((r) => messageParts.push(`${r.name}`));
}
if (criticalMeds.length > 0) {
if (messageParts.length > 0) messageParts.push("");
messageParts.push(`🚨 ${tr.push.criticalSection}:`);
criticalMeds.forEach((r) =>
messageParts.push(
`${r.name}: ${t(tr.push.pillsLeft, { count: r.medsLeft })}, ${t(tr.push.daysLeft, { count: r.daysLeft ?? 0 })}`
)
);
}
if (lowStockMeds.length > 0) {
if (messageParts.length > 0) messageParts.push("");
messageParts.push(`⚠️ ${tr.push.lowStockSection}:`);
lowStockMeds.forEach((r) =>
messageParts.push(
`${r.name}: ${t(tr.push.pillsLeft, { count: r.medsLeft })}, ${t(tr.push.daysLeft, { count: r.daysLeft ?? 0 })}`
)
);
}
// Send email if enabled
if (notificationSettings.emailEnabled && email) {
@@ -256,52 +393,59 @@ Sent from MedAssist-ng Medication Planner`;
const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
if (smtpHost && smtpUser) {
// Build subject line based on what we have
let subjectText: string;
if (emptyMeds.length > 0 && lowMeds.length > 0) {
subjectText = `🚨 ${emptyMeds.length} Empty, ⚠️ ${lowMeds.length} Running Low`;
} else if (emptyMeds.length > 0) {
subjectText = `🚨 ${emptyMeds.length} Medication${emptyMeds.length > 1 ? "s" : ""} Empty`;
} else {
subjectText = `⚠️ ${lowMeds.length} Medication${lowMeds.length > 1 ? "s" : ""} Running Low`;
}
// Build subject line from shared title parts
const subjectText = titleParts.join(", ");
// Build alert box based on what we have
let alertHtml: string;
if (emptyMeds.length > 0 && lowMeds.length > 0) {
alertHtml = `
// Build alert boxes for each category
const alertParts: string[] = [];
if (emptyMeds.length > 0) {
const emptyAlert =
emptyMeds.length === 1
? tr.stockReminder.alertEmptySingle
: t(tr.stockReminder.alertEmptyMultiple, { count: emptyMeds.length });
alertParts.push(`
<div style="padding: 10px 14px; border-radius: 8px; margin-bottom: 12px; background: #fef2f2; border: 1px solid #dc2626;">
<p style="margin: 0; color: #dc2626; font-weight: 600; font-size: 13px;">
🚨 ${emptyMeds.length} medication${emptyMeds.length > 1 ? "s" : ""} EMPTY - reorder immediately!
${emptyAlert}
</p>
</div>
<div style="padding: 10px 14px; border-radius: 8px; margin-bottom: 16px; background: #fffbeb; border: 1px solid #f59e0b;">
<p style="margin: 0; color: #b45309; font-weight: 500; font-size: 13px;">
⚠️ ${lowMeds.length} medication${lowMeds.length > 1 ? "s" : ""} running low - reorder soon
</p>
</div>`;
} else if (emptyMeds.length > 0) {
alertHtml = `
<div style="padding: 10px 14px; border-radius: 8px; margin-bottom: 16px; background: #fef2f2; border: 1px solid #dc2626;">
<p style="margin: 0; color: #dc2626; font-weight: 600; font-size: 13px;">
🚨 ${emptyMeds.length} medication${emptyMeds.length > 1 ? "s" : ""} EMPTY - reorder immediately!
</p>
</div>`;
} else {
alertHtml = `
<div style="padding: 10px 14px; border-radius: 8px; margin-bottom: 16px; background: #fffbeb; border: 1px solid #f59e0b;">
<p style="margin: 0; color: #b45309; font-weight: 500; font-size: 13px;">
⚠️ ${lowMeds.length} medication${lowMeds.length > 1 ? "s" : ""} running low - reorder soon
</p>
</div>`;
</div>`);
}
if (criticalMeds.length > 0) {
const criticalAlert =
criticalMeds.length === 1
? tr.stockReminder.alertLowSingle
: t(tr.stockReminder.alertLowMultiple, { count: criticalMeds.length });
alertParts.push(`
<div style="padding: 10px 14px; border-radius: 8px; margin-bottom: 12px; background: #fff7ed; border: 1px solid #ea580c;">
<p style="margin: 0; color: #c2410c; font-weight: 600; font-size: 13px;">
${criticalAlert}
</p>
</div>`);
}
if (lowStockMeds.length > 0) {
const lowAlert =
lowStockMeds.length === 1
? tr.stockReminder.alertLowStockSingle
: t(tr.stockReminder.alertLowStockMultiple, { count: lowStockMeds.length });
alertParts.push(`
<div style="padding: 10px 14px; border-radius: 8px; margin-bottom: 12px; background: #fffbeb; border: 1px solid #f59e0b;">
<p style="margin: 0; color: #b45309; font-weight: 500; font-size: 13px;">
${lowAlert}
</p>
</div>`);
}
const alertHtml = alertParts.join("");
// Build table rows with status indicator
const buildTableRow = (row: LowStockItem) => {
const isEmpty = row.medsLeft <= 0;
const statusIcon = isEmpty ? "🚨" : "⚠️";
const rowBg = isEmpty ? "#fef2f2" : "white";
// Escape user-provided strings and coerce numbers to prevent XSS
const isCritical = row.isCritical !== false;
const statusIcon = isEmpty ? "🚨" : isCritical ? "🚨" : "⚠️";
const rowBg = isEmpty ? "#fef2f2" : isCritical ? "#fff7ed" : "white";
const safeName = escapeHtml(row.name);
const safeMedsLeft = Number(row.medsLeft) || 0;
const safeDaysLeft = Number(row.daysLeft) || 0;
@@ -311,26 +455,16 @@ Sent from MedAssist-ng Medication Planner`;
<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>${safeMedsLeft}</strong></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>" : safeDepletionDate}</td>
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${isEmpty ? `<strong>${tr.stockReminder.now}</strong>` : safeDepletionDate}</td>
</tr>`;
};
const tableRows = lowStock.map(buildTableRow).join("");
// Build description text
let descriptionText: string;
if (emptyMeds.length > 0 && lowMeds.length > 0) {
descriptionText = "The following medications need to be reordered:";
} else if (emptyMeds.length > 0) {
descriptionText = "The following medications are EMPTY and need to be reordered immediately:";
} else {
descriptionText = "The following medications are running low and need to be reordered:";
}
const html = `
<div style="font-family: system-ui, -apple-system, sans-serif; max-width: 100%; margin: 0 auto; padding: 12px; background: #f9fafb;">
<div style="background: white; border-radius: 12px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
<h2 style="color: #1f2937; margin: 0 0 8px; font-size: 18px;">${emptyMeds.length > 0 ? "🚨" : "⚠️"} MedAssist-ng - Reorder Reminder</h2>
<h2 style="color: #1f2937; margin: 0 0 8px; font-size: 18px;">${emptyMeds.length > 0 ? "🚨" : "⚠️"} MedAssist-ng - ${tr.push.reorderNow}</h2>
<p style="color: #6b7280; margin: 0 0 16px; font-size: 13px;">${descriptionText}</p>
${alertHtml}
@@ -339,10 +473,10 @@ Sent from MedAssist-ng Medication Planner`;
<table style="width: 100%; border-collapse: collapse; background: white; min-width: 400px;">
<thead>
<tr style="background: #f3f4f6;">
<th style="padding: 10px 12px; text-align: left; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">Medication</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">Pills</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">Days</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">Runs Out</th>
<th style="padding: 10px 12px; text-align: left; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">${tr.stockReminder.tableHeaders.medication}</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">${tr.stockReminder.tableHeaders.pills}</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">${tr.stockReminder.tableHeaders.days}</th>
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">${tr.stockReminder.tableHeaders.runsOut}</th>
</tr>
</thead>
<tbody>
@@ -352,33 +486,12 @@ Sent from MedAssist-ng Medication Planner`;
</div>
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
<p style="color: #9ca3af; font-size: 11px; margin: 0;">Sent from MedAssist-ng Medication Planner</p>
<p style="color: #9ca3af; font-size: 11px; margin: 0;">${getFooterHtml(language)}</p>
</div>
</div>
`;
// Build plain text with sections
let plainTextContent: string;
if (emptyMeds.length > 0 && lowMeds.length > 0) {
plainTextContent = `🚨 EMPTY (reorder immediately):
${emptyMeds.map((r) => `${r.name}`).join("\n")}
⚠️ RUNNING LOW (reorder soon):
${lowMeds.map((r) => `${r.name}: ${r.medsLeft} pills left, ${r.daysLeft ?? 0} days remaining`).join("\n")}`;
} else if (emptyMeds.length > 0) {
plainTextContent = `🚨 EMPTY (reorder immediately):
${emptyMeds.map((r) => `${r.name}`).join("\n")}`;
} else {
plainTextContent = `⚠️ Running low:
${lowMeds.map((r) => `${r.name}: ${r.medsLeft} pills left, ${r.daysLeft ?? 0} days remaining, runs out ${r.depletionDate ?? "soon"}`).join("\n")}`;
}
const plainText = `MedAssist-ng - Reorder Reminder
${plainTextContent}
---
Sent from MedAssist-ng Medication Planner`;
const plainText = `MedAssist-ng - ${tr.push.reorderNow}\n\n${messageParts.join("\n")}\n\n---\n${getFooterPlain(language)}`;
try {
const transporter = nodemailer.createTransport({
@@ -409,38 +522,10 @@ Sent from MedAssist-ng Medication Planner`;
// Send push notification if enabled
if (notificationSettings.shoutrrrEnabled && notificationSettings.shoutrrrUrl) {
// Get translations based on user language (default to 'en')
const tr = getTranslations((userSettings.language as Language) || "en");
// Build clear title
const titleParts: string[] = [];
if (emptyMeds.length > 0) {
titleParts.push(`🚨 ${emptyMeds.length} ${tr.push.empty}`);
}
if (lowMeds.length > 0) {
titleParts.push(`⚠️ ${lowMeds.length} ${tr.push.low}`);
}
const title = `MedAssist: ${titleParts.join(", ")} - ${tr.push.reorderNow}`;
// Build clear message with sections
const messageParts: string[] = [];
if (emptyMeds.length > 0) {
messageParts.push(`🚨 ${tr.push.emptySection}:`);
emptyMeds.forEach((r) => messageParts.push(`${r.name}`));
}
if (lowMeds.length > 0) {
if (emptyMeds.length > 0) messageParts.push("");
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 })}`
)
);
}
const message = messageParts.join("\n");
const message = messageParts.join("\n") + `\n\n---\n${getFooterPlain(language)}`;
try {
const pushResult = await sendShoutrrrNotification(notificationSettings.shoutrrrUrl, title, message);
const pushResult = await sendShoutrrrNotification(notificationSettings.shoutrrrUrl, notificationTitle, message);
if (pushResult.success) {
results.push = true;
} else {
@@ -458,7 +543,9 @@ Sent from MedAssist-ng Medication Planner`;
updateReminderSentTime("stock", channel);
// Also update user settings in database so frontend can display the info
await updateUserReminderSentTime(userId, "stock", channel);
const firstMed = lowStock[0];
const medNames = lowStock.length > 1 ? `${firstMed.name} (+${lowStock.length - 1})` : firstMed?.name;
await updateUserReminderSentTime(userId, "stock", channel, medNames);
}
// Build response message
+13 -6
View File
@@ -61,6 +61,8 @@ export async function refillRoutes(app: FastifyInstance) {
.set({
packCount: newPackCount,
looseTablets: newLooseTablets,
stockAdjustment: 0, // Reset offset since we're adding to base stock
lastStockCorrectionAt: new Date(), // Reset consumed counter to now
updatedAt: new Date(),
})
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
@@ -76,9 +78,13 @@ export async function refillRoutes(app: FastifyInstance) {
})
.returning();
// Calculate pills added for response
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister;
const totalPillsAdded = packsAdded * pillsPerPack + loosePillsAdded;
// Calculate pills added for response (packageType-aware)
const isBottle = (med.packageType ?? "blister") === "bottle";
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 {
success: true,
@@ -92,7 +98,7 @@ export async function refillRoutes(app: FastifyInstance) {
newStock: {
packCount: newPackCount,
looseTablets: newLooseTablets,
totalPills: newPackCount * pillsPerPack + newLooseTablets,
totalPills: newTotalPills,
},
};
});
@@ -118,13 +124,14 @@ export async function refillRoutes(app: FastifyInstance) {
.where(eq(refillHistory.medicationId, medId))
.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) => ({
id: r.id,
packsAdded: r.packsAdded,
loosePillsAdded: r.loosePillsAdded,
totalPillsAdded: r.packsAdded * pillsPerPack + r.loosePillsAdded,
totalPillsAdded: isBottle ? r.loosePillsAdded : r.packsAdded * pillsPerPack + r.loosePillsAdded,
refillDate: r.refillDate,
}));
});
+49 -3
View File
@@ -30,11 +30,15 @@ export type UserSettings = {
highStockDays: number;
language: Language;
stockCalculationMode: "automatic" | "manual";
shareStockStatus: boolean;
lastAutoEmailSent: string | null;
lastNotificationType: string | null;
lastNotificationChannel: string | null;
lastReminderMedName: string | null;
lastReminderTakenBy: string | null;
lastStockReminderSent: string | null;
lastStockReminderChannel: string | null;
lastStockReminderMedNames: string | null;
};
type SettingsBody = {
@@ -57,6 +61,7 @@ type SettingsBody = {
maxNaggingReminders: number;
language: string;
stockCalculationMode: "automatic" | "manual";
shareStockStatus: boolean;
};
type TestEmailBody = {
@@ -104,11 +109,15 @@ function getDefaultSettings() {
highStockDays: envInt("DEFAULT_HIGH_STOCK_DAYS", 180),
language: (process.env.DEFAULT_LANGUAGE as "en" | "de") || "en",
stockCalculationMode: (process.env.DEFAULT_STOCK_CALCULATION_MODE as "automatic" | "manual") || "automatic",
shareStockStatus: envBool("DEFAULT_SHARE_STOCK_STATUS", true),
lastAutoEmailSent: null,
lastNotificationType: null,
lastNotificationChannel: null,
lastReminderMedName: null,
lastReminderTakenBy: null,
lastStockReminderSent: null,
lastStockReminderChannel: null,
lastStockReminderMedNames: null,
};
}
@@ -154,11 +163,15 @@ export async function loadUserSettings(userId: number): Promise<UserSettings> {
highStockDays: settings.highStockDays,
language: settings.language as Language,
stockCalculationMode: (settings.stockCalculationMode as "automatic" | "manual") ?? "automatic",
shareStockStatus: settings.shareStockStatus ?? true,
lastAutoEmailSent: settings.lastAutoEmailSent,
lastNotificationType: settings.lastNotificationType,
lastNotificationChannel: settings.lastNotificationChannel,
lastReminderMedName: settings.lastReminderMedName ?? null,
lastReminderTakenBy: settings.lastReminderTakenBy ?? null,
lastStockReminderSent: settings.lastStockReminderSent ?? null,
lastStockReminderChannel: settings.lastStockReminderChannel ?? null,
lastStockReminderMedNames: settings.lastStockReminderMedNames ?? null,
};
}
@@ -186,11 +199,15 @@ export async function getAllUserSettings(): Promise<UserSettings[]> {
highStockDays: settings.highStockDays,
language: settings.language as Language,
stockCalculationMode: (settings.stockCalculationMode as "automatic" | "manual") ?? "automatic",
shareStockStatus: settings.shareStockStatus ?? true,
lastAutoEmailSent: settings.lastAutoEmailSent,
lastNotificationType: settings.lastNotificationType,
lastNotificationChannel: settings.lastNotificationChannel,
lastReminderMedName: settings.lastReminderMedName ?? null,
lastReminderTakenBy: settings.lastReminderTakenBy ?? null,
lastStockReminderSent: settings.lastStockReminderSent ?? null,
lastStockReminderChannel: settings.lastStockReminderChannel ?? null,
lastStockReminderMedNames: settings.lastStockReminderMedNames ?? null,
}));
}
@@ -241,6 +258,7 @@ export async function settingsRoutes(app: FastifyInstance) {
maxNaggingReminders: settings.maxNaggingReminders ?? 5,
language: settings.language,
stockCalculationMode: settings.stockCalculationMode ?? "automatic",
shareStockStatus: settings.shareStockStatus ?? true,
// SMTP settings (from .env - shared/server-configured)
smtpHost: process.env.SMTP_HOST ?? "",
smtpPort: parseInt(process.env.SMTP_PORT ?? "587", 10),
@@ -254,6 +272,10 @@ export async function settingsRoutes(app: FastifyInstance) {
lastNotificationChannel: settings.lastNotificationChannel,
lastReminderMedName: settings.lastReminderMedName ?? null,
lastReminderTakenBy: settings.lastReminderTakenBy ?? null,
// Stock reminder tracking (separate from intake)
lastStockReminderSent: settings.lastStockReminderSent ?? null,
lastStockReminderChannel: settings.lastStockReminderChannel ?? null,
lastStockReminderMedNames: settings.lastStockReminderMedNames ?? null,
// Server settings (from .env, read-only)
expiryWarningDays: parseInt(process.env.EXPIRY_WARNING_DAYS ?? "30", 10),
});
@@ -296,6 +318,7 @@ export async function settingsRoutes(app: FastifyInstance) {
highStockDays: body.highStockDays ?? 180,
language: body.language ?? "en",
stockCalculationMode: body.stockCalculationMode ?? "automatic",
shareStockStatus: body.shareStockStatus ?? true,
updatedAt: new Date(),
};
@@ -482,10 +505,33 @@ export async function sendShoutrrrNotification(
)
.trim();
// Determine notification type based on validation result and URL pattern
const isNtfyUrl = isNtfy || sanitizedUrl.includes("ntfy.sh") || sanitizedUrl.includes("/ntfy/");
// Determine notification type based on URL hostname
// Use JSON format only for known webhook services that require it
// Use proper URL parsing to prevent bypass attacks (e.g., evil.com?hooks.slack.com)
let isJsonWebhook = false;
try {
const parsedUrl = new URL(sanitizedUrl);
const hostname = parsedUrl.hostname.toLowerCase();
const pathname = parsedUrl.pathname.toLowerCase();
if (isNtfyUrl) {
isJsonWebhook =
// 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;
}
// Default to ntfy-style (plain text with Title header) for all other HTTP URLs
// This works for ntfy, Apprise, and most simple push services
if (!isJsonWebhook) {
targetUrl = sanitizedUrl;
headers = { Title: cleanTitle, Tags: "pill" };
body = message;
+66 -34
View File
@@ -7,6 +7,12 @@ import { medications, shareTokens, userSettings, users } from "../db/schema.js";
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.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
const SHARE_TOKEN_VALIDITY_MS = 365 * 24 * 60 * 60 * 1000;
@@ -35,17 +41,6 @@ async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<
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
// =============================================================================
@@ -88,47 +83,60 @@ export async function shareRoutes(app: FastifyInstance) {
// 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));
// 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 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
const medicationsWithBlisters = meds.map((med) => {
let blisters: { usage: number; every: number; start: string }[] = [];
try {
const usageArr = JSON.parse(med.usageJson || "[]");
const everyArr = JSON.parse(med.everyJson || "[]");
const startArr = JSON.parse(med.startJson || "[]");
blisters = usageArr.map((usage: number, i: number) => ({
usage,
every: everyArr[i] ?? 1,
start: startArr[i] ?? new Date().toISOString(),
}));
} catch {
blisters = [];
}
// Parse intakes from new format, falling back to legacy
const intakes = parseIntakesJson(
med.intakesJson,
{ usageJson: med.usageJson, everyJson: med.everyJson, startJson: med.startJson },
med.intakeRemindersEnabled ?? false
);
// Convert to legacy blisters format for backward compat
const blisters = intakes.map((i) => ({
usage: i.usage,
every: i.every,
start: i.start,
}));
// Parse takenBy JSON array
const takenByArray = parseTakenByJson(med.takenByJson);
const totalPills =
med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
(med.packageType ?? "blister") === "bottle"
? med.looseTablets + (med.stockAdjustment ?? 0)
: med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
return {
id: med.id,
name: med.name,
genericName: med.genericName,
pillWeightMg: med.pillWeightMg,
doseUnit: med.doseUnit ?? "mg",
imageUrl: med.imageUrl,
totalPills,
packageType: med.packageType ?? "blister",
packCount: med.packCount,
blistersPerPack: med.blistersPerPack,
looseTablets: med.looseTablets,
pillsPerBlister: med.pillsPerBlister,
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
lastStockCorrectionAt: med.lastStockCorrectionAt?.getTime() ?? null,
stockAdjustment: med.stockAdjustment ?? 0,
};
});
@@ -139,7 +147,13 @@ export async function shareRoutes(app: FastifyInstance) {
medications: medicationsWithBlisters,
stockThresholds: {
lowStockDays: settings?.lowStockDays ?? 30,
normalStockDays: settings?.normalStockDays ?? 60,
highStockDays: settings?.highStockDays ?? 90,
reminderDaysBefore: settings?.reminderDaysBefore ?? 7,
expiryWarningDays: settings?.expiryWarningDays ?? 90,
},
stockCalculationMode: (settings?.stockCalculationMode as "automatic" | "manual") ?? "automatic",
shareStockStatus: settings?.shareStockStatus ?? true,
};
});
@@ -162,11 +176,16 @@ export async function shareRoutes(app: FastifyInstance) {
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 medsForPerson = allMeds.filter((med) => {
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) {
@@ -205,17 +224,30 @@ export async function shareRoutes(app: FastifyInstance) {
app.get("/share/people", { preHandler: requireAuth }, async (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 })
.select({
takenByJson: medications.takenByJson,
intakesJson: medications.intakesJson,
usageJson: medications.usageJson,
everyJson: medications.everyJson,
startJson: medications.startJson,
intakeRemindersEnabled: medications.intakeRemindersEnabled,
})
.from(medications)
.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>();
for (const med of meds) {
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);
}
}
+138 -85
View File
@@ -3,20 +3,29 @@ import { resolve } from "node:path";
import { and, eq, gte, lte } from "drizzle-orm";
import nodemailer from "nodemailer";
import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { doseTracking, medications } from "../db/schema.js";
import { getDateLocale, getTranslations, type Language, t } from "../i18n/translations.js";
import {
getDateLocale,
getFooterHtml,
getFooterPlain,
getTranslations,
type Language,
t,
} from "../i18n/translations.js";
import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js";
import type { ServiceLogger } from "../utils/logger.js";
// Import shared utilities
import {
type Blister,
cleanOldIntakeReminders,
createDefaultIntakeReminderState,
getTimezone,
getTodaysIntakes,
getUpcomingIntakes,
type Intake,
type IntakeReminderState,
parseBlisters,
parseIntakeReminderState,
parseIntakesJson,
parseTakenByJson,
type UpcomingIntake,
} from "../utils/scheduler-utils.js";
@@ -25,7 +34,7 @@ import { updateReminderSentTime, updateUserReminderSentTime } from "./reminder-s
const REMINDER_MINUTES_BEFORE = parseInt(process.env.REMINDER_MINUTES_BEFORE ?? "15", 10);
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 {
try {
@@ -42,10 +51,6 @@ function saveIntakeReminderState(state: IntakeReminderState): void {
writeFileSync(intakeReminderStateFile, JSON.stringify(state, null, 2));
}
function parseBlistersFromRow(row: { usageJson: string; everyJson: string; startJson: string }): Blister[] {
return parseBlisters(row);
}
async function sendIntakeReminderEmail(
email: string,
intakes: UpcomingIntake[],
@@ -79,11 +84,10 @@ async function sendIntakeReminderEmail(
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 => {
if (intake.takenBy.length > 0) {
const namesStr = intake.takenBy.join(", ");
return `${intake.medName} <span style="color: #6b7280; font-size: 12px;">${t(tr.intakeReminder.takenBy, { name: namesStr })}</span>`;
if (intake.takenBy) {
return `${intake.medName} <span style="color: #6b7280; font-size: 12px;">${t(tr.intakeReminder.takenBy, { name: intake.takenBy })}</span>`;
}
return intake.medName;
};
@@ -153,7 +157,7 @@ async function sendIntakeReminderEmail(
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
<p style="color: #9ca3af; font-size: 11px; margin: 0;">
${tr.intakeReminder.footer}
${getFooterHtml(language)}
</p>
</div>
</div>
@@ -176,13 +180,13 @@ ${description}
${intakes
.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 })}` : "";
return `${i.medName}${takenByStr}: ${formatDosagePlain(i)} - ${i.intakeTimeStr}`;
})
.join("\n")}
---
${tr.intakeReminder.footer}`;
${getFooterPlain(language)}`;
const subject = isRepeat
? `[Reminder] ${t(tr.intakeReminder.subject, { medications: intakes.map((i) => i.medName).join(", ") })}`
@@ -214,21 +218,18 @@ ${tr.intakeReminder.footer}`;
}
}
async function checkAndSendIntakeReminders(logger: {
info: (msg: string) => void;
error: (msg: string) => void;
}): Promise<void> {
logger.info(`[IntakeReminder] Checking for intake reminders...`);
async function checkAndSendIntakeReminders(logger: ServiceLogger): Promise<void> {
logger.debug(`[IntakeReminder] Checking for intake reminders...`);
// Get all user settings to iterate over each user
const allUserSettings = await getAllUserSettings();
if (allUserSettings.length === 0) {
logger.info(`[IntakeReminder] No users with settings found`);
logger.debug(`[IntakeReminder] No users with settings found`);
return; // No users with settings
}
logger.info(`[IntakeReminder] Found ${allUserSettings.length} users to check`);
logger.debug(`[IntakeReminder] Found ${allUserSettings.length} users to check`);
for (const userSettings of allUserSettings) {
await checkAndSendIntakeRemindersForUser(userSettings, logger);
@@ -237,12 +238,12 @@ async function checkAndSendIntakeReminders(logger: {
async function checkAndSendIntakeRemindersForUser(
settings: UserSettings & { userId: number },
logger: { info: (msg: string) => void; error: (msg: string) => void }
logger: ServiceLogger
): Promise<void> {
const language = settings.language;
const tr = getTranslations(language);
logger.info(
logger.debug(
`[IntakeReminder] Checking user ${settings.userId} - repeat:${settings.repeatRemindersEnabled} skip:${settings.skipRemindersForTakenDoses}`
);
@@ -251,13 +252,13 @@ async function checkAndSendIntakeRemindersForUser(
const shoutrrrEnabled = settings.shoutrrrEnabled && settings.shoutrrrUrl && settings.shoutrrrIntakeReminders;
if (!emailEnabled && !shoutrrrEnabled) {
logger.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: No intake notifications enabled (email:${emailEnabled}, shoutrrr:${shoutrrrEnabled})`
);
return; // No intake reminder notifications enabled for this user
}
logger.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Notifications enabled (email:${emailEnabled}, shoutrrr:${shoutrrrEnabled})`
);
@@ -270,11 +271,13 @@ async function checkAndSendIntakeRemindersForUser(
const medsWithReminders = rows.filter((row) => row.intakeRemindersEnabled);
if (medsWithReminders.length === 0) {
logger.info(`[IntakeReminder] User ${settings.userId}: No medications have reminders enabled`);
logger.debug(`[IntakeReminder] User ${settings.userId}: No medications have reminders enabled`);
return; // No medications have reminders enabled for this user
}
logger.info(`[IntakeReminder] User ${settings.userId}: Found ${medsWithReminders.length} medications with reminders`);
logger.debug(
`[IntakeReminder] User ${settings.userId}: Found ${medsWithReminders.length} medications with reminders`
);
const state = loadIntakeReminderState();
const allUpcoming: (UpcomingIntake & { medicationId: number; blisterIndex: number })[] = [];
@@ -289,78 +292,108 @@ async function checkAndSendIntakeRemindersForUser(
const todayEnd = new Date(now.toLocaleString("en-US", { timeZone: tz }));
todayEnd.setHours(23, 59, 59, 999);
logger.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Today range: ${todayStart.toISOString()} to ${todayEnd.toISOString()}`
);
// Find intakes: upcoming ones in reminder window + past ones for repeat reminders
for (const med of medsWithReminders) {
const blisters = parseBlistersFromRow(med);
const takenByArray = parseTakenByJson(med.takenByJson);
// Parse intakes using new format (with per-intake takenBy), falling back to legacy
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.debug(
`[IntakeReminder] User ${settings.userId}: Processing medication "${med.name}" with ${intakes.length} intakes`
);
// Process each blister separately to track blisterIndex
blisters.forEach((blister, blisterIndex) => {
logger.info(
`[IntakeReminder] User ${settings.userId}: Blister ${blisterIndex} - start: ${blister.start}, every: ${blister.every} days, usage: ${blister.usage}`
// Filter intakes that have reminders enabled (per-intake setting or medication-level)
const intakesWithReminders = intakes.filter((intake, idx) => {
const hasReminder = intake.intakeRemindersEnabled || med.intakeRemindersEnabled;
if (!hasReminder) {
logger.debug(`[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.debug(
`[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
const upcomingIntakes = getUpcomingIntakes(
med.name,
[blister],
[intake],
REMINDER_MINUTES_BEFORE,
takenByArray,
medicationTakenBy,
med.pillWeightMg,
locale,
tz
tz,
undefined, // nowOverride
med.id,
med.doseUnit ?? "mg"
);
logger.info(
`[IntakeReminder] User ${settings.userId}: Blister ${blisterIndex} found ${upcomingIntakes.length} upcoming intakes (reminder window)`
logger.debug(
`[IntakeReminder] User ${settings.userId}: Intake ${actualIndex} found ${upcomingIntakes.length} upcoming intakes (reminder window)`
);
// Add upcoming intakes for first reminders
allUpcoming.push(
...upcomingIntakes.map((intake) => ({
...intake,
...upcomingIntakes.map((upcomingIntake) => ({
...upcomingIntake,
medicationId: med.id,
blisterIndex,
blisterIndex: actualIndex,
}))
);
// If repeat reminders enabled, also check for missed intakes (past the intake time)
if (settings.repeatRemindersEnabled) {
const allTodaysIntakes = getTodaysIntakes(med.name, [blister], takenByArray, med.pillWeightMg, locale, tz);
logger.info(
`[IntakeReminder] User ${settings.userId}: Blister ${blisterIndex} - all today's intakes: ${allTodaysIntakes.length}, times: ${allTodaysIntakes.map((i) => i.intakeTime.toISOString()).join(", ")}`
const allTodaysIntakes = getTodaysIntakes(
med.name,
[intake],
medicationTakenBy,
med.pillWeightMg,
locale,
tz,
med.id,
med.doseUnit ?? "mg"
);
const missedIntakes = allTodaysIntakes.filter((intake) => intake.intakeTime.getTime() < now.getTime());
logger.info(
`[IntakeReminder] User ${settings.userId}: Blister ${blisterIndex} found ${missedIntakes.length} missed intakes (past intake time)`
logger.debug(
`[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.debug(
`[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)
const upcomingTimes = new Set(upcomingIntakes.map((i) => i.intakeTime.getTime()));
allUpcoming.push(
...missedIntakes
.filter((intake) => !upcomingTimes.has(intake.intakeTime.getTime()))
.map((intake) => ({
...intake,
.filter((missed) => !upcomingTimes.has(missed.intakeTime.getTime()))
.map((missed) => ({
...missed,
medicationId: med.id,
blisterIndex,
blisterIndex: actualIndex,
}))
);
}
});
}
logger.info(`[IntakeReminder] User ${settings.userId}: Total ${allUpcoming.length} intakes for today`);
logger.debug(`[IntakeReminder] User ${settings.userId}: Total ${allUpcoming.length} intakes for today`);
if (allUpcoming.length === 0) {
logger.info(`[IntakeReminder] User ${settings.userId}: No intakes for today`);
logger.debug(`[IntakeReminder] User ${settings.userId}: No intakes for today`);
return; // No upcoming intakes for today
}
@@ -383,15 +416,23 @@ async function checkAndSendIntakeRemindersForUser(
if (!existingEntry) {
// New dose - send first reminder
if (isIntakePast) {
// Already missed - this is first nagging reminder (count=1)
remindersToSend.push({ ...intake, currentSendCount: 1, maxReminders, isAdvanceReminder: false });
logger.info(
`[IntakeReminder] User ${settings.userId}: First nagging for missed "${intake.medName}" at ${intake.intakeTimeStr} (1/${maxReminders})`
// 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.debug(
`[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(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Advance reminder for "${intake.medName}" at ${intake.intakeTimeStr}`
);
}
@@ -406,13 +447,13 @@ async function checkAndSendIntakeRemindersForUser(
if (currentNaggingCount >= maxReminders) {
// Max nagging reminders reached - stop
logger.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Max nagging (${maxReminders}) reached for "${intake.medName}" at ${intake.intakeTimeStr}`
);
} else if (timeSinceLastReminder >= intervalMs) {
const nextSendCount = currentNaggingCount + 1;
remindersToSend.push({ ...intake, currentSendCount: nextSendCount, maxReminders, isAdvanceReminder: false });
logger.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Nagging reminder for "${intake.medName}" at ${intake.intakeTimeStr} (${nextSendCount}/${maxReminders})`
);
}
@@ -442,25 +483,36 @@ async function checkAndSendIntakeRemindersForUser(
// Filter out reminders for doses that were already taken
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
if (intake.takenBy.length > 0) {
// For multi-person medications, check if any person has taken it
const anyTaken = intake.takenBy.some((person) => {
const doseId = `${intake.medicationId}-${intake.blisterIndex}-${timestamp}-${person}`;
return takenDoseIds.has(doseId);
});
return !anyTaken; // Skip if any person has taken it
if (intake.takenBy) {
// For person-specific intake, check if that person has taken it
const doseId = `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}-${intake.takenBy}`;
const isTaken = takenDoseIds.has(doseId);
if (isTaken) {
logger.debug(
`[IntakeReminder] User ${settings.userId}: Skipping "${intake.medName}" - dose ${doseId} already taken`
);
}
return !isTaken;
} else {
// For non-person-specific medications
const doseId = `${intake.medicationId}-${intake.blisterIndex}-${timestamp}`;
return !takenDoseIds.has(doseId);
// For non-person-specific intakes
const doseId = `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}`;
const isTaken = takenDoseIds.has(doseId);
if (isTaken) {
logger.debug(
`[IntakeReminder] User ${settings.userId}: Skipping "${intake.medName}" - dose ${doseId} already taken`
);
}
return !isTaken;
}
});
if (remindersToSend.length === 0) {
logger.info(`[IntakeReminder] User ${settings.userId}: All doses taken, skipping reminders`);
logger.debug(`[IntakeReminder] User ${settings.userId}: All doses taken, skipping reminders`);
return;
}
}
@@ -514,7 +566,10 @@ async function checkAndSendIntakeRemindersForUser(
if (hasNaggingReminder && highestSendCount > 0) {
// Nagging reminder - show counter
const counterStr = `(${highestSendCount}/${maxReminderCount})`;
title = language === "de" ? `⚠️ Medikamenten-Erinnerung ${counterStr}` : `⚠️ Medication Reminder ${counterStr}`;
title =
language === "de"
? `⚠️ Erinnerung: Medikamenteneinnahme ${counterStr}`
: `⚠️ Reminder: Medication intake ${counterStr}`;
} else {
// Advance reminder - no counter
title = t(tr.push.intakeTitle, { minutes: REMINDER_MINUTES_BEFORE });
@@ -545,8 +600,7 @@ async function checkAndSendIntakeRemindersForUser(
const message =
remindersToSend
.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}`;
if (i.pillWeightMg) {
const totalMg = i.usage * i.pillWeightMg;
@@ -554,7 +608,9 @@ async function checkAndSendIntakeRemindersForUser(
}
return `${i.medName}${takenByStr}: ${dosage} @ ${i.intakeTimeStr}`;
})
.join("\n") + repeatNote;
.join("\n") +
repeatNote +
`\n\n---\n${getFooterPlain(language)}`;
const result = await sendShoutrrrNotification(settings.shoutrrrUrl!, title, message);
shoutrrrSuccess = result.success;
@@ -625,17 +681,14 @@ async function checkAndSendIntakeRemindersForUser(
// Get the first reminder's medication name and taken by for display
const firstReminder = remindersToSend[0];
const medName = firstReminder?.medName;
const takenBy = firstReminder?.takenBy?.length > 0 ? firstReminder.takenBy.join(", ") : undefined;
const takenBy = firstReminder?.takenBy || undefined;
await updateUserReminderSentTime(settings.userId, "intake", channel, medName, takenBy);
}
}
let intakeCheckInterval: NodeJS.Timeout | null = null;
export function startIntakeReminderScheduler(logger: {
info: (msg: string) => void;
error: (msg: string) => void;
}): void {
export function startIntakeReminderScheduler(logger: ServiceLogger): void {
logger.info(`[IntakeReminder] Starting intake reminder scheduler (checks every minute)...`);
// Run immediately on start
+49 -34
View File
@@ -3,10 +3,11 @@ import { resolve } from "node:path";
import { eq } from "drizzle-orm";
import nodemailer from "nodemailer";
import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { medications, userSettings } from "../db/schema.js";
import { getTranslations, type Language, t } from "../i18n/translations.js";
import { getFooterHtml, getFooterPlain, getTranslations, type Language, t } from "../i18n/translations.js";
import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js";
import type { ServiceLogger } from "../utils/logger.js";
// Import shared utilities
import {
type Blister,
@@ -25,7 +26,7 @@ import {
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 {
try {
@@ -62,6 +63,7 @@ export function updateReminderSentTime(
}
// Update user settings in database when reminder is sent
// Stock and intake reminders are tracked separately so neither overwrites the other
export async function updateUserReminderSentTime(
userId: number,
type: "stock" | "intake" = "stock",
@@ -70,16 +72,30 @@ export async function updateUserReminderSentTime(
takenBy?: string
): Promise<void> {
const now = new Date().toISOString();
await db
.update(userSettings)
.set({
lastAutoEmailSent: now,
lastNotificationType: type,
lastNotificationChannel: channel,
lastReminderMedName: medName ?? null,
lastReminderTakenBy: takenBy ?? null,
})
.where(eq(userSettings.userId, userId));
if (type === "stock") {
// Write to dedicated stock reminder columns only — do NOT touch the shared
// lastNotificationType column, as that would block intake reminder display
await db
.update(userSettings)
.set({
lastStockReminderSent: now,
lastStockReminderChannel: channel,
lastStockReminderMedNames: medName ?? null,
})
.where(eq(userSettings.userId, userId));
} else {
// Write to intake reminder columns
await db
.update(userSettings)
.set({
lastAutoEmailSent: now,
lastNotificationType: type,
lastNotificationChannel: channel,
lastReminderMedName: medName ?? null,
lastReminderTakenBy: takenBy ?? null,
})
.where(eq(userSettings.userId, userId));
}
}
function parseBlistersFromRow(row: { usageJson: string; everyJson: string; startJson: string }): Blister[] {
@@ -105,7 +121,9 @@ async function getMedicationsNeedingReminder(
for (const row of rows) {
const blisters = parseBlistersFromRow(row);
const totalPills =
row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
(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);
// Check if medication runs out within reminderDaysBefore days
@@ -188,7 +206,7 @@ async function sendReminderEmail(
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
<p style="color: #9ca3af; font-size: 11px; margin: 0;">
${tr.stockReminder.footer}
${getFooterHtml(language)}
</p>
${isRepeatDaily ? `<p style="color: #9ca3af; font-size: 11px; margin: 8px 0 0 0; font-style: italic;">${tr.stockReminder.repeatDailyNote}</p>` : ""}
</div>
@@ -202,7 +220,7 @@ ${tr.stockReminder.description}
${lowStock.map((r) => `${r.name}: ${r.medsLeft} ${tr.common.pills}, ${r.daysLeft ?? 0} ${tr.common.days}, ${tr.stockReminder.tableHeaders.runsOut}: ${r.depletionDate ?? tr.common.soon}`).join("\n")}
---
${tr.stockReminder.footer}${isRepeatDaily ? `\n\n${tr.stockReminder.repeatDailyNote}` : ""}`;
${getFooterPlain(language)}${isRepeatDaily ? `\n\n${tr.stockReminder.repeatDailyNote}` : ""}`;
const subjectPlural = lowStock.length === 1 ? "" : language === "de" ? "e" : "s";
const subject = t(tr.stockReminder.subject, { count: lowStock.length, s: subjectPlural, e: subjectPlural });
@@ -233,15 +251,12 @@ ${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: ServiceLogger): Promise<void> {
// Get all user settings to iterate over each user
const allUserSettings = await getAllUserSettings();
if (allUserSettings.length === 0) {
logger.info("[Reminder] No users with settings found");
logger.debug("[Reminder] No users with settings found");
return;
}
@@ -252,7 +267,7 @@ async function checkAndSendReminder(logger: {
async function checkAndSendReminderForUser(
settings: UserSettings & { userId: number },
logger: { info: (msg: string) => void; error: (msg: string) => void }
logger: ServiceLogger
): Promise<void> {
const language = settings.language;
const tr = getTranslations(language);
@@ -305,30 +320,30 @@ async function checkAndSendReminderForUser(
// Send Shoutrrr notification if enabled
if (shoutrrrEnabled) {
// Separate empty from low stock medications
// Separate empty from critical stock medications (all auto-reminder meds are critical by definition)
const emptyMeds = allLowStock.filter((m) => m.medsLeft <= 0);
const lowMeds = allLowStock.filter((m) => m.medsLeft > 0);
const criticalMeds = allLowStock.filter((m) => m.medsLeft > 0);
// Build clear title
const titleParts: string[] = [];
if (emptyMeds.length > 0) {
titleParts.push(`🚨 ${emptyMeds.length} ${tr.push.empty || "Empty"}`);
}
if (lowMeds.length > 0) {
titleParts.push(`⚠️ ${lowMeds.length} ${tr.push.low || "Low"}`);
if (criticalMeds.length > 0) {
titleParts.push(`🚨 ${criticalMeds.length} ${tr.push.critical || "Critical"}`);
}
const title = `MedAssist: ${titleParts.join(", ")} - ${tr.push.reorderNow || "Reorder Now!"}`;
// Build clear message with sections
const messageParts: string[] = [];
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}`));
}
if (lowMeds.length > 0) {
if (criticalMeds.length > 0) {
if (emptyMeds.length > 0) messageParts.push("");
messageParts.push(`⚠️ ${tr.push.lowSection || "RUNNING LOW (reorder soon)"}:`);
lowMeds.forEach((m) =>
messageParts.push(`🚨 ${tr.push.criticalSection || "Running critically low"}:`);
criticalMeds.forEach((m) =>
messageParts.push(
`${m.name}: ${t(tr.push.pillsLeft, { count: m.medsLeft })}, ${t(tr.push.daysLeft, { count: m.daysLeft ?? 0 })}`
)
@@ -340,7 +355,7 @@ async function checkAndSendReminderForUser(
messageParts.push(tr.push.repeatDailyNote);
}
const message = messageParts.join("\n");
const message = messageParts.join("\n") + `\n\n---\n${getFooterPlain(language)}`;
const result = await sendShoutrrrNotification(settings.shoutrrrUrl!, title, message);
shoutrrrSuccess = result.success;
@@ -374,7 +389,7 @@ async function checkAndSendReminderForUser(
let schedulerTimeout: NodeJS.Timeout | null = null;
function scheduleNextCheck(logger: { info: (msg: string) => void; error: (msg: string) => void }): void {
function scheduleNextCheck(logger: ServiceLogger): void {
const msUntilNext = getMsUntilNextCheck(REMINDER_HOUR);
const nextTime = getNextScheduledTime(REMINDER_HOUR);
@@ -385,7 +400,7 @@ function scheduleNextCheck(logger: { info: (msg: string) => void; error: (msg: s
nextScheduledCheck: nextTime.toISOString(),
});
logger.info(
logger.debug(
`[Reminder] Next check scheduled for ${formatInTimezone(nextTime)} (${getTimezone()}) (in ${Math.round(msUntilNext / 1000 / 60)} minutes)`
);
@@ -396,7 +411,7 @@ function scheduleNextCheck(logger: { info: (msg: string) => void; error: (msg: s
}, msUntilNext);
}
export function startReminderScheduler(logger: { info: (msg: string) => void; error: (msg: string) => void }): void {
export function startReminderScheduler(logger: ServiceLogger): void {
logger.info(`[Reminder] Starting reminder scheduler (timezone: ${getTimezone()})...`);
// Check if we need to run immediately (missed today's check)
+58
View File
@@ -682,4 +682,62 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
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);
});
});
});
+439 -4
View File
@@ -5,17 +5,20 @@ import { fileURLToPath } from "node:url";
import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// 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 {
buildDbUrl,
ensureDataDirectory,
ensureDefaultUser,
getDataDir,
getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations,
runDrizzleMigrations,
} from "../db/client.js";
} from "../db/db-utils.js";
// Import the exported utility functions from migrate.ts
import { executeMigration, getStatementPreview, splitSQLStatements } from "../db/migrate.js";
@@ -142,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", () => {
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");
expect(paths.dataDir).toBe("/app/data");
expect(paths.dbPath).toBe("/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", () => {
delete process.env.DATA_DIR;
const paths = getDbPaths();
expect(paths.dataDir).toContain("data");
expect(paths.dbPath).toContain("medassist-ng.db");
@@ -620,4 +686,373 @@ describe("Database Client", () => {
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);
});
});
});
+575 -23
View File
@@ -76,29 +76,33 @@ async function createSchema(client: Client) {
updated_at integer NOT NULL DEFAULT (strftime('%s','now'))
)`,
`CREATE TABLE IF NOT EXISTS medications (
id integer PRIMARY KEY AUTOINCREMENT,
user_id integer NOT NULL,
name text NOT NULL,
generic_name text,
taken_by_json text NOT NULL DEFAULT '[]',
pack_count integer NOT NULL DEFAULT 1,
blisters_per_pack integer NOT NULL DEFAULT 1,
pills_per_blister integer NOT NULL DEFAULT 1,
loose_tablets integer NOT NULL DEFAULT 0,
stock_adjustment integer NOT NULL DEFAULT 0,
last_stock_correction_at integer,
pill_weight_mg integer,
usage_json text NOT NULL DEFAULT '[]',
every_json text NOT NULL DEFAULT '[]',
start_json text NOT NULL DEFAULT '[]',
image_url text,
expiry_date text,
notes text,
intake_reminders_enabled integer NOT NULL DEFAULT 0,
dismissed_until text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
id integer PRIMARY KEY AUTOINCREMENT,
user_id integer NOT NULL,
name text NOT NULL,
generic_name text,
taken_by_json text NOT NULL DEFAULT '[]',
package_type text NOT NULL DEFAULT 'blister',
pack_count integer NOT NULL DEFAULT 1,
blisters_per_pack integer NOT NULL DEFAULT 1,
pills_per_blister integer NOT NULL DEFAULT 1,
total_pills integer,
loose_tablets integer NOT NULL DEFAULT 0,
stock_adjustment integer NOT NULL DEFAULT 0,
last_stock_correction_at integer,
pill_weight_mg integer,
dose_unit text DEFAULT 'mg',
usage_json text NOT NULL DEFAULT '[]',
every_json text NOT NULL DEFAULT '[]',
start_json text NOT NULL DEFAULT '[]',
intakes_json text NOT NULL DEFAULT '[]',
image_url text,
expiry_date text,
notes text,
intake_reminders_enabled integer NOT NULL DEFAULT 0,
dismissed_until text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
`CREATE TABLE IF NOT EXISTS user_settings (
id integer PRIMARY KEY AUTOINCREMENT,
user_id integer NOT NULL UNIQUE,
@@ -122,11 +126,15 @@ async function createSchema(client: Client) {
expiry_warning_days integer NOT NULL DEFAULT 90,
language text NOT NULL DEFAULT 'en',
stock_calculation_mode text NOT NULL DEFAULT 'automatic',
share_stock_status integer NOT NULL DEFAULT 1,
last_auto_email_sent text,
last_notification_type text,
last_notification_channel text,
last_reminder_med_name text,
last_reminder_taken_by text,
last_stock_reminder_sent text,
last_stock_reminder_channel text,
last_stock_reminder_med_names text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
@@ -1726,6 +1734,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
// ---------------------------------------------------------------------------
@@ -1912,4 +2218,250 @@ describe("E2E Tests with Real Routes", () => {
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");
});
});
});
+381 -48
View File
@@ -71,29 +71,33 @@ async function createSchema(client: Client) {
updated_at integer NOT NULL DEFAULT (strftime('%s','now'))
)`,
`CREATE TABLE IF NOT EXISTS medications (
id integer PRIMARY KEY AUTOINCREMENT,
user_id integer NOT NULL,
name text NOT NULL,
generic_name text,
taken_by_json text NOT NULL DEFAULT '[]',
pack_count integer NOT NULL DEFAULT 1,
blisters_per_pack integer NOT NULL DEFAULT 1,
pills_per_blister integer NOT NULL DEFAULT 1,
loose_tablets integer NOT NULL DEFAULT 0,
stock_adjustment integer NOT NULL DEFAULT 0,
last_stock_correction_at integer,
pill_weight_mg integer,
usage_json text NOT NULL DEFAULT '[]',
every_json text NOT NULL DEFAULT '[]',
start_json text NOT NULL DEFAULT '[]',
image_url text,
expiry_date text,
notes text,
intake_reminders_enabled integer NOT NULL DEFAULT 0,
dismissed_until text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
id integer PRIMARY KEY AUTOINCREMENT,
user_id integer NOT NULL,
name text NOT NULL,
generic_name text,
taken_by_json text NOT NULL DEFAULT '[]',
package_type text NOT NULL DEFAULT 'blister',
pack_count integer NOT NULL DEFAULT 1,
blisters_per_pack integer NOT NULL DEFAULT 1,
pills_per_blister integer NOT NULL DEFAULT 1,
total_pills integer,
loose_tablets integer NOT NULL DEFAULT 0,
stock_adjustment integer NOT NULL DEFAULT 0,
last_stock_correction_at integer,
pill_weight_mg integer,
dose_unit text DEFAULT 'mg',
usage_json text NOT NULL DEFAULT '[]',
every_json text NOT NULL DEFAULT '[]',
start_json text NOT NULL DEFAULT '[]',
intakes_json text NOT NULL DEFAULT '[]',
image_url text,
expiry_date text,
notes text,
intake_reminders_enabled integer NOT NULL DEFAULT 0,
dismissed_until text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
`CREATE TABLE IF NOT EXISTS user_settings (
id integer PRIMARY KEY AUTOINCREMENT,
user_id integer NOT NULL UNIQUE,
@@ -117,11 +121,15 @@ async function createSchema(client: Client) {
expiry_warning_days integer NOT NULL DEFAULT 90,
language text NOT NULL DEFAULT 'en',
stock_calculation_mode text NOT NULL DEFAULT 'automatic',
share_stock_status integer NOT NULL DEFAULT 1,
last_auto_email_sent text,
last_notification_type text,
last_notification_channel text,
last_reminder_med_name text,
last_reminder_taken_by text,
last_stock_reminder_sent text,
last_stock_reminder_channel text,
last_stock_reminder_med_names text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
@@ -361,6 +369,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
// ---------------------------------------------------------------------------
@@ -702,7 +900,16 @@ describe("Integration Tests", () => {
describe("Planner usage calculation", () => {
it("should calculate correct usage for daily medication", async () => {
// 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({
method: "POST",
url: "/medications",
@@ -712,17 +919,17 @@ describe("Integration Tests", () => {
blistersPerPack: 3,
pillsPerBlister: 10,
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({
method: "POST",
url: "/medications/usage",
payload: {
startDate: "2025-01-01T00:00:00.000Z",
endDate: "2025-01-11T00:00:00.000Z", // 10 days
startDate: intakeStart,
endDate: planEndStr, // 10 days
},
});
@@ -731,13 +938,22 @@ describe("Integration Tests", () => {
expect(data).toHaveLength(1);
expect(data[0].medicationName).toBe("Daily Med");
expect(data[0].plannerUsage).toBe(10); // 10 days × 1 pill
// Note: 'enough' depends on current stock after consumption since start date
// Since test runs ~364 days after Jan 1, most pills are consumed
expect(data[0].totalPills).toBe(60); // Current stock is full (no consumption yet)
expect(data[0].enough).toBe(true);
});
it("should detect insufficient stock", async () => {
// 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({
method: "POST",
url: "/medications",
@@ -747,17 +963,17 @@ describe("Integration Tests", () => {
blistersPerPack: 1,
pillsPerBlister: 5,
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({
method: "POST",
url: "/medications/usage",
payload: {
startDate: "2025-01-01T00:00:00.000Z",
endDate: "2025-01-11T00:00:00.000Z",
startDate: intakeStart,
endDate: planEndStr,
},
});
@@ -769,7 +985,16 @@ describe("Integration Tests", () => {
it("should calculate weekly medication usage correctly", async () => {
// 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({
method: "POST",
url: "/medications",
@@ -778,29 +1003,42 @@ describe("Integration Tests", () => {
packCount: 1,
blistersPerPack: 1,
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({
method: "POST",
url: "/medications/usage",
payload: {
startDate: "2025-01-01T00:00:00.000Z",
endDate: "2025-01-31T00:00:00.000Z", // 30 days
startDate: intakeStart,
endDate: planEndStr,
},
});
expect(response.statusCode).toBe(200);
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);
});
it("should handle multiple intake schedules per medication", async () => {
// Create medication with morning and evening doses
// 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({
method: "POST",
url: "/medications",
@@ -810,8 +1048,8 @@ describe("Integration Tests", () => {
blistersPerPack: 1,
pillsPerBlister: 30,
blisters: [
{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }, // Morning: 1 pill
{ usage: 0.5, every: 1, start: "2025-01-01T20:00:00.000Z" }, // Evening: 0.5 pill
{ usage: 1, every: 1, start: morningStart }, // Morning: 1 pill
{ usage: 0.5, every: 1, start: eveningStartStr }, // Evening: 0.5 pill
],
},
});
@@ -821,8 +1059,8 @@ describe("Integration Tests", () => {
method: "POST",
url: "/medications/usage",
payload: {
startDate: "2025-01-01T00:00:00.000Z",
endDate: "2025-01-11T00:00:00.000Z",
startDate: morningStart,
endDate: planEndStr,
},
});
@@ -834,6 +1072,15 @@ describe("Integration Tests", () => {
it("should calculate correct blisters needed", async () => {
// 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({
method: "POST",
url: "/medications",
@@ -842,7 +1089,7 @@ describe("Integration Tests", () => {
packCount: 5,
blistersPerPack: 1,
pillsPerBlister: 10,
blisters: [{ usage: 2.5, every: 1, start: "2025-01-01T08:00:00.000Z" }],
blisters: [{ usage: 2.5, every: 1, start: intakeStart }],
},
});
@@ -851,8 +1098,8 @@ describe("Integration Tests", () => {
method: "POST",
url: "/medications/usage",
payload: {
startDate: "2025-01-01T00:00:00.000Z",
endDate: "2025-01-11T00:00:00.000Z",
startDate: intakeStart,
endDate: planEndStr,
},
});
@@ -938,6 +1185,92 @@ describe("Integration Tests", () => {
expect(data[0].plannerUsage).toBe(10);
expect(data[0].enough).toBe(true); // 45 > 10
});
it("should use user-selected start date, not current time (fix asymmetric counting)", async () => {
// Regression test: When a planner range starts today, the old code used
// max(now, start) as the effective start. If now was between the morning
// dose (07:00) and evening dose (20:00), morning was skipped but evening
// counted, giving an asymmetric result (e.g., 5 instead of 6).
//
// Example: medication with daily morning (07:00) + evening (20:00) intakes,
// planner range [today 01:00, today+3 01:00).
// Old code at 15:00: morning 07:00 < 15:00 → skipped, evening 20:00 ≥ 15:00 → counted
// Result: 2 morning + 3 evening = 5 instead of 3+3 = 6.
// Use a past start date so the intakes predate the planner range
const intakeStart = "2025-01-01T07:00:00.000Z";
const intakeEvening = "2025-01-01T20:00:00.000Z";
// Plan range: Feb 9 00:00 to Feb 12 00:00 UTC (3 full days)
const planStart = "2026-02-09T00:00:00.000Z";
const planEnd = "2026-02-12T00:00:00.000Z";
await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Twice Daily Med Asymmetric",
packCount: 5,
blistersPerPack: 5,
pillsPerBlister: 10,
blisters: [
{ usage: 1, every: 1, start: intakeStart },
{ usage: 1, every: 1, start: intakeEvening },
],
},
});
const response = await app.inject({
method: "POST",
url: "/medications/usage",
payload: {
startDate: planStart,
endDate: planEnd,
},
});
expect(response.statusCode).toBe(200);
const data = response.json();
// Both morning and evening should have exactly 3 occurrences each
// (Feb 9, 10, 11) for a total of 6, regardless of current time
expect(data[0].plannerUsage).toBe(6);
});
it("should handle planner range starting before blister start", async () => {
// Blister starts on Feb 10, planner range starts Feb 9
// Should only count doses from Feb 10 onwards
const intakeMorning = "2026-02-10T07:00:00.000Z";
const intakeEvening = "2026-02-10T20:00:00.000Z";
await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Recent Start Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
blisters: [
{ usage: 1, every: 1, start: intakeMorning },
{ usage: 1, every: 1, start: intakeEvening },
],
},
});
const response = await app.inject({
method: "POST",
url: "/medications/usage",
payload: {
startDate: "2026-02-09T00:00:00.000Z",
endDate: "2026-02-12T00:00:00.000Z",
},
});
expect(response.statusCode).toBe(200);
const data = response.json();
// Only Feb 10 and Feb 11 have doses (blister starts Feb 10)
expect(data[0].plannerUsage).toBe(4); // 2 days × 2 intakes
});
});
// ---------------------------------------------------------------------------
+306 -25
View File
@@ -110,11 +110,15 @@ async function createSchema(client: Client) {
expiry_warning_days integer NOT NULL DEFAULT 90,
language text NOT NULL DEFAULT 'en',
stock_calculation_mode text NOT NULL DEFAULT 'automatic',
share_stock_status integer NOT NULL DEFAULT 1,
last_auto_email_sent text,
last_notification_type text,
last_notification_channel text,
last_reminder_med_name text,
last_reminder_taken_by text,
last_stock_reminder_sent text,
last_stock_reminder_channel text,
last_stock_reminder_med_names text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
@@ -161,21 +165,6 @@ describe("Planner Routes", () => {
});
describe("POST /planner/send-email", () => {
it("should reject request with missing email", async () => {
const response = await app.inject({
method: "POST",
url: "/planner/send-email",
payload: {
from: "2025-01-01",
until: "2025-01-31",
rows: [{ medicationName: "Test", totalPills: 10, plannerUsage: 5, enough: true }],
},
});
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error: "Missing email or planner data" });
});
it("should reject request with missing rows", async () => {
const response = await app.inject({
method: "POST",
@@ -189,10 +178,16 @@ describe("Planner Routes", () => {
});
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error: "Missing email or planner data" });
expect(response.json()).toEqual({ error: "Missing planner data" });
});
it("should reject when SMTP is not configured", async () => {
it("should return error when no notification channels configured", async () => {
// User settings exist but email/shoutrrr disabled
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, language) VALUES (?, 0, 0, 'en')`,
args: [999999999],
});
const response = await app.inject({
method: "POST",
url: "/planner/send-email",
@@ -217,7 +212,7 @@ describe("Planner Routes", () => {
});
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error: "SMTP not configured" });
expect(response.json()).toEqual({ error: "No notification channels configured" });
});
it("should send email successfully when SMTP is configured", async () => {
@@ -226,6 +221,12 @@ describe("Planner Routes", () => {
process.env.SMTP_USER = "user@test.com";
process.env.SMTP_PASS = "password";
// Enable email in user settings
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, language) VALUES (?, 1, 0, 'en')`,
args: [999999999],
});
mockSendMail.mockResolvedValueOnce({ messageId: "123" });
const response = await app.inject({
@@ -253,7 +254,7 @@ describe("Planner Routes", () => {
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ success: true, message: "Email sent successfully" });
expect(response.json()).toEqual({ success: true, message: "Notification sent via email" });
expect(mockSendMail).toHaveBeenCalledTimes(1);
// Cleanup
@@ -267,6 +268,11 @@ describe("Planner Routes", () => {
process.env.SMTP_USER = "user@test.com";
process.env.SMTP_PASS = "password";
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, language) VALUES (?, 1, 0, 'en')`,
args: [999999999],
});
mockSendMail.mockResolvedValueOnce({ messageId: "123" });
const response = await app.inject({
@@ -308,7 +314,7 @@ describe("Planner Routes", () => {
// Check that HTML contains out of stock warning
const mailCall = mockSendMail.mock.calls[0][0];
expect(mailCall.html).toContain("Out of Stock");
expect(mailCall.html).toContain("Empty");
expect(mailCall.html).toContain("1 medication");
delete process.env.SMTP_HOST;
@@ -321,6 +327,11 @@ describe("Planner Routes", () => {
process.env.SMTP_USER = "user@test.com";
process.env.SMTP_PASS = "password";
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, language) VALUES (?, 1, 0, 'en')`,
args: [999999999],
});
mockSendMail.mockRejectedValueOnce(new Error("Connection refused"));
const response = await app.inject({
@@ -347,7 +358,7 @@ describe("Planner Routes", () => {
});
expect(response.statusCode).toBe(500);
expect(response.json().error).toContain("Failed to send email");
expect(response.json().error).toContain("Email:");
expect(response.json().error).toContain("Connection refused");
delete process.env.SMTP_HOST;
@@ -360,6 +371,12 @@ describe("Planner Routes", () => {
process.env.SMTP_USER = "user@test.com";
process.env.SMTP_PASS = "password";
// User settings with German language
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, language) VALUES (?, 1, 0, 'de')`,
args: [999999999],
});
mockSendMail.mockResolvedValueOnce({ messageId: "123" });
const response = await app.inject({
@@ -390,12 +407,178 @@ describe("Planner Routes", () => {
// German date format should be used
const mailCall = mockSendMail.mock.calls[0][0];
expect(mailCall.subject).toContain("Supply Overview");
expect(mailCall.subject).toContain("Bestandsübersicht");
delete process.env.SMTP_HOST;
delete process.env.SMTP_USER;
delete process.env.SMTP_PASS;
});
it("should send push notification when shoutrrr is enabled", async () => {
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, shoutrrr_url, language) VALUES (?, 0, 1, 'ntfy://localhost/test', 'en')`,
args: [999999999],
});
mockSendShoutrrr.mockResolvedValueOnce({ success: true });
const response = await app.inject({
method: "POST",
url: "/planner/send-email",
payload: {
email: "test@example.com",
from: "2025-01-01",
until: "2025-01-31",
rows: [
{
medicationId: 1,
medicationName: "Aspirin",
totalPills: 30,
plannerUsage: 10,
blisterSize: 10,
blistersNeeded: 1,
fullBlisters: 3,
loosePills: 0,
enough: true,
},
],
},
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ success: true, message: "Notification sent via push" });
expect(mockSendShoutrrr).toHaveBeenCalledTimes(1);
// Verify push message contains medication info
const [_url, title, message] = mockSendShoutrrr.mock.calls[0];
expect(title).toContain("Supply Overview");
expect(message).toContain("Aspirin");
});
it("should send both email and push when both enabled", async () => {
process.env.SMTP_HOST = "smtp.test.com";
process.env.SMTP_USER = "user@test.com";
process.env.SMTP_PASS = "password";
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, shoutrrr_url, language) VALUES (?, 1, 1, 'ntfy://localhost/test', 'en')`,
args: [999999999],
});
mockSendMail.mockResolvedValueOnce({ messageId: "123" });
mockSendShoutrrr.mockResolvedValueOnce({ success: true });
const response = await app.inject({
method: "POST",
url: "/planner/send-email",
payload: {
email: "test@example.com",
from: "2025-01-01",
until: "2025-01-31",
rows: [
{
medicationId: 1,
medicationName: "Aspirin",
totalPills: 5,
plannerUsage: 30,
blisterSize: 10,
blistersNeeded: 3,
fullBlisters: 0,
loosePills: 5,
enough: false,
},
],
},
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ success: true, message: "Notification sent via email and push" });
expect(mockSendMail).toHaveBeenCalledTimes(1);
expect(mockSendShoutrrr).toHaveBeenCalledTimes(1);
// Verify push message contains out of stock info
const [_url, _title, message] = mockSendShoutrrr.mock.calls[0];
expect(message).toContain("Aspirin");
expect(message).toContain("Empty");
delete process.env.SMTP_HOST;
delete process.env.SMTP_USER;
delete process.env.SMTP_PASS;
});
it("should send push with German translations", async () => {
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, shoutrrr_url, language) VALUES (?, 0, 1, 'ntfy://localhost/test', 'de')`,
args: [999999999],
});
mockSendShoutrrr.mockResolvedValueOnce({ success: true });
const response = await app.inject({
method: "POST",
url: "/planner/send-email",
payload: {
email: "test@example.com",
from: "2025-01-01",
until: "2025-01-31",
rows: [
{
medicationId: 1,
medicationName: "Aspirin",
totalPills: 5,
plannerUsage: 30,
blisterSize: 10,
blistersNeeded: 3,
fullBlisters: 0,
loosePills: 5,
enough: false,
},
],
},
});
expect(response.statusCode).toBe(200);
// Check German translations in push
const [_url, title] = mockSendShoutrrr.mock.calls[0];
expect(title).toContain("Bestandsübersicht");
});
it("should handle push error gracefully", async () => {
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, shoutrrr_url, language) VALUES (?, 0, 1, 'ntfy://localhost/test', 'en')`,
args: [999999999],
});
mockSendShoutrrr.mockResolvedValueOnce({ success: false, error: "Connection failed" });
const response = await app.inject({
method: "POST",
url: "/planner/send-email",
payload: {
email: "test@example.com",
from: "2025-01-01",
until: "2025-01-31",
rows: [
{
medicationId: 1,
medicationName: "Aspirin",
totalPills: 30,
plannerUsage: 10,
blisterSize: 10,
blistersNeeded: 1,
fullBlisters: 3,
loosePills: 0,
enough: true,
},
],
},
});
expect(response.statusCode).toBe(500);
expect(response.json().error).toContain("Push:");
expect(response.json().error).toContain("Connection failed");
});
});
describe("POST /reminder/send-email", () => {
@@ -503,10 +686,10 @@ describe("Planner Routes", () => {
expect(response.statusCode).toBe(200);
// Check email contains EMPTY warning
// Check email contains empty warning
const mailCall = mockSendMail.mock.calls[0][0];
expect(mailCall.subject).toContain("Empty");
expect(mailCall.html).toContain("EMPTY");
expect(mailCall.html).toContain("empty");
delete process.env.SMTP_HOST;
delete process.env.SMTP_USER;
@@ -541,7 +724,7 @@ describe("Planner Routes", () => {
const mailCall = mockSendMail.mock.calls[0][0];
expect(mailCall.subject).toContain("Empty");
expect(mailCall.subject).toContain("Running Low");
expect(mailCall.subject).toContain("Critical");
delete process.env.SMTP_HOST;
delete process.env.SMTP_USER;
@@ -698,5 +881,103 @@ describe("Planner Routes", () => {
expect(response.json().error).toContain("Push:");
expect(response.json().error).toContain("Network error");
});
it("should differentiate critical and low stock in push notification", async () => {
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, shoutrrr_url, language) VALUES (?, 0, 1, 'ntfy://localhost/test', 'en')`,
args: [999999999],
});
mockSendShoutrrr.mockResolvedValueOnce({ success: true });
const response = await app.inject({
method: "POST",
url: "/reminder/send-email",
payload: {
email: "test@example.com",
lowStock: [
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03", isCritical: true },
{ name: "Ibuprofen", medsLeft: 49, daysLeft: 24, depletionDate: "2025-01-24", isCritical: false },
],
},
});
expect(response.statusCode).toBe(200);
const [_url, title, message] = mockSendShoutrrr.mock.calls[0];
// Title should contain both Critical and Low labels
expect(title).toContain("Critical");
expect(title).toContain("Low");
// Message should have separate sections
expect(message).toContain("Running critically low");
expect(message).toContain("Aspirin");
expect(message).toContain("Running low");
expect(message).toContain("Ibuprofen");
});
it("should differentiate critical and low stock in email", async () => {
process.env.SMTP_HOST = "smtp.test.com";
process.env.SMTP_USER = "user@test.com";
process.env.SMTP_PASS = "password";
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, language) VALUES (?, 1, 0, 'en')`,
args: [999999999],
});
mockSendMail.mockResolvedValueOnce({ messageId: "123" });
const response = await app.inject({
method: "POST",
url: "/reminder/send-email",
payload: {
email: "test@example.com",
lowStock: [
{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03", isCritical: true },
{ name: "Ibuprofen", medsLeft: 49, daysLeft: 24, depletionDate: "2025-01-24", isCritical: false },
],
},
});
expect(response.statusCode).toBe(200);
const mailCall = mockSendMail.mock.calls[0][0];
// Subject should contain both Critical and Low
expect(mailCall.subject).toContain("Critical");
expect(mailCall.subject).toContain("Low");
// HTML should have separate alert boxes
expect(mailCall.html).toContain("critically low");
expect(mailCall.html).toContain("running low");
delete process.env.SMTP_HOST;
delete process.env.SMTP_USER;
delete process.env.SMTP_PASS;
});
it("should label all meds as critical when isCritical not provided", async () => {
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, shoutrrr_url, language) VALUES (?, 0, 1, 'ntfy://localhost/test', 'en')`,
args: [999999999],
});
mockSendShoutrrr.mockResolvedValueOnce({ success: true });
const response = await app.inject({
method: "POST",
url: "/reminder/send-email",
payload: {
email: "test@example.com",
lowStock: [{ name: "Aspirin", medsLeft: 5, daysLeft: 3, depletionDate: "2025-01-03" }],
},
});
expect(response.statusCode).toBe(200);
const [_url, title, message] = mockSendShoutrrr.mock.calls[0];
// Should be treated as critical (backwards compat)
expect(title).toContain("Critical");
expect(title).not.toContain("Low");
expect(message).toContain("Running critically low");
});
});
});
+48 -33
View File
@@ -16,12 +16,24 @@ import {
getTodayInTimezone,
getTodaysIntakes,
getUpcomingIntakes,
type Intake,
parseBlisters,
parseIntakeReminderState,
parseReminderState,
parseTakenByJson,
} 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", () => {
let originalTz: string | undefined;
@@ -333,45 +345,45 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
describe("getUpcomingIntakes", () => {
it("should return empty array when no intakes in window", () => {
// With parseLocalDateTime, times are treated as local - use same format for consistency
const blisters: Blister[] = [{ usage: 1, every: 1, start: "2025-01-01T08:00:00" }];
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00" })];
// 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([]);
});
it("should find intake within reminder window", () => {
// 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" }];
const intakes: Intake[] = [blisterToIntake({ usage: 2, every: 1, start: "2025-01-01T08:00:00" }, "Alice")];
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[0].medName).toBe("TestMed");
expect(result[0].usage).toBe(2);
expect(result[0].takenBy).toEqual(["Alice"]);
expect(result[0].takenBy).toBe("Alice");
expect(result[0].pillWeightMg).toBe(500);
});
it("should skip blisters with zero interval", () => {
const blisters: Blister[] = [{ usage: 1, every: 0, start: "2025-01-01T08:00:00" }];
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 0, start: "2025-01-01T08:00:00" })];
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([]);
});
it("should handle multiple blisters", () => {
// Two intakes at 08:00 and 08:01 local
const blisters: Blister[] = [
{ usage: 1, every: 1, start: "2025-01-01T08:00:00" },
{ usage: 2, every: 1, start: "2025-01-01T08:01:00" },
const intakes: Intake[] = [
blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00" }),
blisterToIntake({ usage: 2, every: 1, start: "2025-01-01T08:01:00" }),
];
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
expect(result.length).toBeGreaterThanOrEqual(1);
@@ -382,10 +394,10 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
it("should return all intakes for today", () => {
// Daily medication at 08:00 starting yesterday
// With parseLocalDateTime, "08:00:00.000Z" is treated as 08:00 local time
const blisters: Blister[] = [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }];
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" })];
// 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);
const intake = result.find((i) => i.intakeTime.getHours() === 8);
@@ -399,20 +411,23 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
const todayMidnight = new Date();
todayMidnight.setUTCHours(0, 1, 0, 0);
const blisters: Blister[] = [
{
usage: 2,
every: 1,
start: todayMidnight.toISOString(),
},
const intakes: Intake[] = [
blisterToIntake(
{
usage: 2,
every: 1,
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[0].medName).toBe("PastMed");
expect(result[0].usage).toBe(2);
expect(result[0].takenBy).toEqual(["Bob"]);
expect(result[0].takenBy).toBe("Bob");
expect(result[0].pillWeightMg).toBe(250);
});
@@ -424,12 +439,12 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
const evening = new Date(today);
evening.setUTCHours(20, 0, 0, 0);
const blisters: Blister[] = [
{ usage: 1, every: 1, start: morning.toISOString() },
{ usage: 1, every: 1, start: evening.toISOString() },
const intakes: Intake[] = [
blisterToIntake({ usage: 1, every: 1, start: morning.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);
});
@@ -439,16 +454,16 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
const lastWeek = new Date();
lastWeek.setDate(lastWeek.getDate() - 7);
const blisters: Blister[] = [
{
const intakes: Intake[] = [
blisterToIntake({
usage: 1,
every: 7,
start: lastWeek.toISOString(),
},
}),
];
// 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
expect(Array.isArray(result)).toBe(true);
@@ -458,15 +473,15 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
// With parseLocalDateTime, the Z suffix is ignored and time is treated as local server time
// 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 blisters: Blister[] = [
{
const intakes: Intake[] = [
blisterToIntake({
usage: 1,
every: 1,
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);
if (result.length > 0) {
+66 -2
View File
@@ -51,6 +51,7 @@ async function registerSettingsRoutes(ctx: TestContext) {
expiryWarningDays: 90,
language: "en",
stockCalculationMode: "automatic",
shareStockStatus: true,
};
}
@@ -76,6 +77,7 @@ async function registerSettingsRoutes(ctx: TestContext) {
expiryWarningDays: s.expiry_warning_days,
language: s.language,
stockCalculationMode: s.stock_calculation_mode,
shareStockStatus: Boolean(s.share_stock_status ?? 1),
};
});
@@ -102,6 +104,7 @@ async function registerSettingsRoutes(ctx: TestContext) {
expiryWarningDays?: number;
language?: string;
stockCalculationMode?: "automatic" | "manual";
shareStockStatus?: boolean;
};
}>("/settings", async (request, reply) => {
const userId = 1;
@@ -150,8 +153,8 @@ async function registerSettingsRoutes(ctx: TestContext) {
reminder_days_before, repeat_daily_reminders, skip_reminders_for_taken_doses,
repeat_reminders_enabled, reminder_repeat_interval_minutes, max_nagging_reminders,
low_stock_days, normal_stock_days, high_stock_days,
expiry_warning_days, language, stock_calculation_mode
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
expiry_warning_days, language, stock_calculation_mode, share_stock_status
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
args: [
userId,
body.emailEnabled ? 1 : 0,
@@ -174,6 +177,7 @@ async function registerSettingsRoutes(ctx: TestContext) {
body.expiryWarningDays ?? 90,
body.language || "en",
body.stockCalculationMode || "automatic",
body.shareStockStatus !== false ? 1 : 0,
],
});
} else {
@@ -200,6 +204,7 @@ async function registerSettingsRoutes(ctx: TestContext) {
expiry_warning_days = ?,
language = ?,
stock_calculation_mode = ?,
share_stock_status = ?,
updated_at = strftime('%s','now')
WHERE user_id = ?`,
args: [
@@ -223,6 +228,7 @@ async function registerSettingsRoutes(ctx: TestContext) {
body.expiryWarningDays ?? 90,
body.language || "en",
body.stockCalculationMode || "automatic",
body.shareStockStatus !== false ? 1 : 0,
userId,
],
});
@@ -542,6 +548,64 @@ describe("Settings API", () => {
});
});
// ---------------------------------------------------------------------------
// Share Stock Status
// ---------------------------------------------------------------------------
describe("Share Stock Status", () => {
it("should default to true (show stock on shared links)", async () => {
const response = await ctx.app.inject({
method: "GET",
url: "/settings",
});
expect(response.statusCode).toBe(200);
expect(response.json().shareStockStatus).toBe(true);
});
it("should disable share stock status", async () => {
const response = await ctx.app.inject({
method: "PUT",
url: "/settings",
payload: { shareStockStatus: false },
});
expect(response.statusCode).toBe(200);
const getResponse = await ctx.app.inject({
method: "GET",
url: "/settings",
});
expect(getResponse.json().shareStockStatus).toBe(false);
});
it("should re-enable share stock status", async () => {
// Disable first
await ctx.app.inject({
method: "PUT",
url: "/settings",
payload: { shareStockStatus: false },
});
// Re-enable
const response = await ctx.app.inject({
method: "PUT",
url: "/settings",
payload: { shareStockStatus: true },
});
expect(response.statusCode).toBe(200);
const getResponse = await ctx.app.inject({
method: "GET",
url: "/settings",
});
expect(getResponse.json().shareStockStatus).toBe(true);
});
});
// ---------------------------------------------------------------------------
// Repeat Reminders & Skip Reminders Settings
// ---------------------------------------------------------------------------
+12 -5
View File
@@ -216,13 +216,14 @@ export interface UpdateUserSettingsOptions {
userId: number;
stockCalculationMode?: "automatic" | "manual";
lowStockDays?: number;
shareStockStatus?: boolean;
}
/**
* Create or update user settings
*/
export async function setUserSettings(client: Client, options: UpdateUserSettingsOptions): Promise<void> {
const { userId, stockCalculationMode = "automatic", lowStockDays = 30 } = options;
const { userId, stockCalculationMode = "automatic", lowStockDays = 30, shareStockStatus } = options;
// Check if settings exist
const existing = await client.execute({
@@ -232,13 +233,19 @@ export async function setUserSettings(client: Client, options: UpdateUserSetting
if (existing.rows.length > 0) {
await client.execute({
sql: `UPDATE user_settings SET stock_calculation_mode = ?, low_stock_days = ? WHERE user_id = ?`,
args: [stockCalculationMode, lowStockDays, userId],
sql: `UPDATE user_settings SET stock_calculation_mode = ?, low_stock_days = ?${shareStockStatus !== undefined ? ", share_stock_status = ?" : ""} WHERE user_id = ?`,
args:
shareStockStatus !== undefined
? [stockCalculationMode, lowStockDays, shareStockStatus ? 1 : 0, userId]
: [stockCalculationMode, lowStockDays, userId],
});
} else {
await client.execute({
sql: `INSERT INTO user_settings (user_id, stock_calculation_mode, low_stock_days) VALUES (?, ?, ?)`,
args: [userId, stockCalculationMode, lowStockDays],
sql: `INSERT INTO user_settings (user_id, stock_calculation_mode, low_stock_days${shareStockStatus !== undefined ? ", share_stock_status" : ""}) VALUES (?, ?, ?${shareStockStatus !== undefined ? ", ?" : ""})`,
args:
shareStockStatus !== undefined
? [userId, stockCalculationMode, lowStockDays, shareStockStatus ? 1 : 0]
: [userId, stockCalculationMode, lowStockDays],
});
}
}
+45
View File
@@ -10,6 +10,7 @@ import {
createTestMedication,
createTestShareToken,
createTestUser,
setUserSettings,
type TestContext,
} from "./setup.js";
@@ -141,6 +142,14 @@ async function registerShareRoutes(ctx: TestContext) {
const lowStockDays = settingsResult.rows.length > 0 ? (settingsResult.rows[0].low_stock_days as number) : 30;
// Get shareStockStatus setting
const shareStockResult = await client.execute({
sql: `SELECT share_stock_status FROM user_settings WHERE user_id = ?`,
args: [share.user_id],
});
const shareStockStatus =
shareStockResult.rows.length > 0 ? Boolean(shareStockResult.rows[0].share_stock_status ?? 1) : true;
return {
takenBy: share.taken_by,
sharedBy: share.owner_username,
@@ -149,6 +158,7 @@ async function registerShareRoutes(ctx: TestContext) {
stockThresholds: {
lowStockDays,
},
shareStockStatus,
};
});
@@ -421,6 +431,41 @@ describe("Share Link API", () => {
expect(med.blisters).toHaveLength(1);
expect(med.blisters[0].usage).toBe(1);
expect(med.blisters[0].every).toBe(1);
// shareStockStatus should default to true
expect(data.shareStockStatus).toBe(true);
});
it("should respect shareStockStatus setting when disabled", async () => {
// Create medication
await createTestMedication(ctx.client, {
userId,
name: "TestMed",
takenBy: ["Daniel"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
});
// Set shareStockStatus to false
await setUserSettings(ctx.client, { userId, shareStockStatus: false });
// Create share token
const token = await createTestShareToken(ctx.client, {
userId,
takenBy: "Daniel",
scheduleDays: 30,
});
const response = await ctx.app.inject({
method: "GET",
url: `/share/${token}`,
});
expect(response.statusCode).toBe(200);
expect(response.json().shareStockStatus).toBe(false);
});
it("should return 404 for invalid token", async () => {
+4 -4
View File
@@ -69,8 +69,8 @@ describe("Translations Module", () => {
});
it("should replace multiple placeholders", () => {
const result = t("{count} {type} running low", { count: 3, type: "medications" });
expect(result).toBe("3 medications running low");
const result = t("{count} {type} running critically low", { count: 3, type: "medications" });
expect(result).toBe("3 medications running critically low");
});
it("should replace same placeholder multiple times", () => {
@@ -98,7 +98,7 @@ describe("Translations Module", () => {
// Stock reminder subject
const subject = t(translations.stockReminder.subject, { count: 3, s: "s" });
expect(subject).toBe("MedAssist-ng Auto-Reminder: 3 Medications Running Low");
expect(subject).toBe("MedAssist-ng Auto-Reminder: 3 Medications Running Critically Low");
// Intake reminder description
const description = t(translations.intakeReminder.description, { minutes: 30 });
@@ -113,7 +113,7 @@ describe("Translations Module", () => {
const translations = getTranslations("de");
const subject = t(translations.stockReminder.subject, { count: 2, e: "e" });
expect(subject).toBe("MedAssist-ng Auto-Erinnerung: 2 Medikamente wird knapp");
expect(subject).toBe("MedAssist-ng Auto-Erinnerung: 2 Medikamente kritisch niedrig");
const takenBy = t(translations.intakeReminder.takenBy, { name: "Daniel" });
expect(takenBy).toBe("für Daniel");
+46
View File
@@ -0,0 +1,46 @@
/**
* Simple startup logger that respects LOG_LEVEL environment variable.
* Used for code that runs before Fastify is initialized (db/client.ts, migrations).
* Once Fastify is running, use app.log instead.
*/
const LOG_LEVELS: Record<string, number> = {
silent: 60,
fatal: 60,
error: 50,
warn: 40,
info: 30,
debug: 20,
trace: 10,
};
function getLevel(): number {
const envLevel = (process.env.LOG_LEVEL || "info").toLowerCase();
return LOG_LEVELS[envLevel] ?? LOG_LEVELS.info;
}
function shouldLog(level: string): boolean {
return LOG_LEVELS[level] >= getLevel();
}
export const log = {
debug(msg: string): void {
if (shouldLog("debug")) console.log(msg);
},
info(msg: string): void {
if (shouldLog("info")) console.log(msg);
},
warn(msg: string): void {
if (shouldLog("warn")) console.warn(msg);
},
error(msg: string): void {
if (shouldLog("error")) console.error(msg);
},
};
/** Logger interface for services that receive a logger from the caller */
export type ServiceLogger = {
info: (msg: string) => void;
debug: (msg: string) => void;
error: (msg: string) => void;
};
+130 -21
View File
@@ -5,8 +5,18 @@
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 };
// 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
// =============================================================================
@@ -147,7 +157,7 @@ export function parseLocalDateTime(isoString: string): Date {
);
}
/** Parse blister schedules from JSON columns */
/** Parse blister schedules from JSON columns (DEPRECATED: use parseIntakesJson instead) */
export function parseBlisters(row: { usageJson: string; everyJson: string; startJson: string }): Blister[] {
try {
const usage = JSON.parse(row.usageJson) as number[];
@@ -164,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 */
export function parseTakenByJson(takenByJson: string | null | undefined): string[] {
if (!takenByJson) return [];
@@ -175,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
// =============================================================================
@@ -209,24 +294,30 @@ export function calculateDepletionInfo(
export type UpcomingIntake = {
medName: string;
medicationId?: number;
blisterIndex?: number;
usage: number;
intakeTime: Date;
intakeTimeStr: string;
takenBy: string[];
takenBy: string | null; // Single person for this intake (null = no specific person)
pillWeightMg: number | null;
doseUnit?: string;
};
/**
* Get all intakes for today (past and future) - used for repeat reminders.
* Returns all intakes scheduled for today in user's timezone.
* Now uses per-intake takenBy instead of medication-level.
*/
export function getTodaysIntakes(
medName: string,
blisters: Blister[],
takenBy: string[],
intakes: Intake[],
medicationTakenBy: string[], // Medication-level takenBy as fallback
pillWeightMg: number | null,
locale: string,
tz?: string
tz?: string,
medicationId?: number,
doseUnit?: string
): UpcomingIntake[] {
const timezone = tz ?? getTimezone();
const now = new Date();
@@ -238,14 +329,19 @@ export function getTodaysIntakes(
const todayEnd = new Date(now.toLocaleString("en-US", { timeZone: timezone }));
todayEnd.setHours(23, 59, 59, 999);
const intakes: UpcomingIntake[] = [];
const result: UpcomingIntake[] = [];
for (const blister of blisters) {
const startTime = parseLocalDateTime(blister.start).getTime();
const intervalMs = blister.every * 24 * 60 * 60 * 1000;
for (let blisterIdx = 0; blisterIdx < intakes.length; blisterIdx++) {
const intake = intakes[blisterIdx];
const startTime = parseLocalDateTime(intake.start).getTime();
const intervalMs = intake.every * 24 * 60 * 60 * 1000;
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
let currentTime = startTime;
@@ -260,39 +356,45 @@ export function getTodaysIntakes(
while (currentTime <= todayEnd.getTime()) {
if (currentTime >= todayStart.getTime()) {
const intakeDate = new Date(currentTime);
intakes.push({
result.push({
medName,
usage: blister.usage,
medicationId,
blisterIndex: blisterIdx,
usage: intake.usage,
intakeTime: intakeDate,
intakeTimeStr: intakeDate.toLocaleTimeString(locale, {
hour: "2-digit",
minute: "2-digit",
timeZone: timezone,
}),
takenBy,
takenBy: effectiveTakenBy,
pillWeightMg,
doseUnit,
});
}
currentTime += intervalMs;
}
}
return intakes;
return result;
}
/**
* Get upcoming intakes that fall within the reminder window.
* Returns intakes that should be notified about right now.
* Now uses per-intake takenBy instead of medication-level.
*/
export function getUpcomingIntakes(
medName: string,
blisters: Blister[],
intakes: Intake[],
minutesBefore: number,
takenBy: string[],
medicationTakenBy: string[], // Medication-level takenBy as fallback
pillWeightMg: number | null,
locale: string,
tz?: string,
nowOverride?: number
nowOverride?: number,
medicationId?: number,
doseUnit?: string
): UpcomingIntake[] {
const now = nowOverride ?? Date.now();
const timezone = tz ?? getTimezone();
@@ -303,12 +405,16 @@ export function getUpcomingIntakes(
const upcoming: UpcomingIntake[] = [];
for (const blister of blisters) {
const startTime = parseLocalDateTime(blister.start).getTime();
const intervalMs = blister.every * 24 * 60 * 60 * 1000;
for (let blisterIdx = 0; blisterIdx < intakes.length; blisterIdx++) {
const intake = intakes[blisterIdx];
const startTime = parseLocalDateTime(intake.start).getTime();
const intervalMs = intake.every * 24 * 60 * 60 * 1000;
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)
let nextTime = startTime;
@@ -339,15 +445,18 @@ export function getUpcomingIntakes(
const intakeDate = new Date(nextTime);
upcoming.push({
medName,
usage: blister.usage,
medicationId,
blisterIndex: blisterIdx,
usage: intake.usage,
intakeTime: intakeDate,
intakeTimeStr: intakeDate.toLocaleTimeString(locale, {
hour: "2-digit",
minute: "2-digit",
timeZone: timezone,
}),
takenBy,
takenBy: effectiveTakenBy,
pillWeightMg,
doseUnit,
});
}
}
+2 -2
View File
@@ -6,6 +6,7 @@
import { existsSync, mkdirSync } from "node:fs";
import { resolve } from "node:path";
import type { CookieSerializeOptions } from "@fastify/cookie";
import { getDataDir } from "../db/db-utils.js";
/**
* Parse comma-separated CORS origins string
@@ -81,8 +82,7 @@ export function buildAppConfig(options: AppConfigOptions): AppConfig {
* Ensure images directory exists
*/
export function ensureImagesDirectory(cwd?: string): string {
const basePath = cwd || process.cwd();
const imagesDir = resolve(basePath, "data/images");
const imagesDir = resolve(getDataDir(cwd), "images");
if (!existsSync(imagesDir)) {
mkdirSync(imagesDir, { recursive: true });
}
+1 -1
View File
@@ -2,7 +2,7 @@
"$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"]
"includes": ["backend/src/**/*.ts", "frontend/src/**/*.ts", "frontend/src/**/*.tsx", "frontend/src/**/*.css", "frontend/e2e/**/*.ts", "frontend/playwright.config.ts"]
},
"linter": {
"enabled": true,
+2
View File
@@ -9,6 +9,8 @@ services:
- ./data:/app/data
env_file:
- .env
environment:
- DATA_DIR=/app/data
ports:
- "3000:3000"
security_opt:
+3
View File
@@ -7,6 +7,7 @@ services:
environment:
- PUID=${PUID:-1000}
- PGID=${PGID:-1000}
- DATA_DIR=/app/data
volumes:
- ./data:/app/data
ports:
@@ -34,6 +35,8 @@ services:
frontend:
image: ghcr.io/danielvolz/medassist-ng-frontend:latest
container_name: medassist-ng-frontend
environment:
- BACKEND_URL=backend:3000
ports:
- "4174:8080"
networks:
+9 -3
View File
@@ -32,8 +32,14 @@ RUN npm run build
# -----------------------------------------------------------------------------
FROM nginxinc/nginx-unprivileged:1.27-alpine AS runner
# Copy custom nginx config (must listen on 8080, not 80)
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Redirect envsubst output to /tmp (writable under read_only: true)
# 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 --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)
USER nginx
# Start nginx
# Start nginx (entrypoint processes templates automatically)
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/ {
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 X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+66 -2
View File
@@ -1,12 +1,12 @@
{
"name": "medassist-ng-frontend",
"version": "1.5.0",
"version": "1.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "medassist-ng-frontend",
"version": "1.5.0",
"version": "1.9.0",
"dependencies": {
"i18next": "^24.2.2",
"i18next-browser-languagedetector": "^8.0.4",
@@ -18,6 +18,7 @@
},
"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",
@@ -1210,6 +1211,22 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@playwright/test": {
"version": "1.58.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.1.tgz",
"integrity": "sha512-6LdVIUERWxQMmUSSQi0I53GgCBYgM2RpGngCPY7hSeju+VrKjq3lvs7HpJoPbDiY5QM5EYRtRX5fvrinnMAz3w==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.58.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@rolldown/pluginutils": {
"version": "1.0.0-beta.27",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
@@ -2783,6 +2800,53 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/playwright": {
"version": "1.58.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.1.tgz",
"integrity": "sha512-+2uTZHxSCcxjvGc5C891LrS1/NlxglGxzrC4seZiVjcYVQfUa87wBL6rTDqzGjuoWNjnBzRqKmF6zRYGMvQUaQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.58.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.58.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.1.tgz",
"integrity": "sha512-bcWzOaTxcW+VOOGBCQgnaKToLJ65d6AqfLVKEWvexyS3AS6rbXl+xdpYRMGSRBClPvyj44njOWoxjNdL/H9UNg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/playwright/node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/postcss": {
"version": "8.5.6",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
+9 -2
View File
@@ -1,7 +1,7 @@
{
"name": "medassist-ng-frontend",
"private": true,
"version": "1.5.0",
"version": "1.9.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -12,7 +12,13 @@
"format": "npx biome format --write .",
"check": "npx biome check . && tsc --noEmit",
"test": "vitest",
"test:coverage": "vitest run --coverage"
"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": {
"i18next": "^24.2.2",
@@ -25,6 +31,7 @@
},
"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",
+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,
// },
// ],
});
+8 -5
View File
@@ -44,7 +44,7 @@ function AppRouter() {
return (
<div className="auth-container">
<div className="auth-card" style={{ textAlign: "center" }}>
<h1 className="auth-title">💊 MedAssist</h1>
<h1 className="auth-title">💊 MedAssist-ng</h1>
<p>Loading...</p>
</div>
</div>
@@ -56,7 +56,7 @@ function AppRouter() {
return (
<div className="auth-container">
<div className="auth-card" style={{ textAlign: "center" }}>
<h1 className="auth-title">💊 MedAssist</h1>
<h1 className="auth-title">💊 MedAssist-ng</h1>
<div className="auth-error" style={{ marginBottom: "1rem" }}>
<strong>Connection Error</strong>
<br />
@@ -78,7 +78,7 @@ function AppRouter() {
return (
<div className="auth-container">
<div className="auth-card" style={{ textAlign: "center" }}>
<h1 className="auth-title">💊 MedAssist</h1>
<h1 className="auth-title">💊 MedAssist-ng</h1>
<p>Initializing...</p>
</div>
</div>
@@ -185,6 +185,9 @@ function AppContent() {
const [showProfile, setShowProfile] = useState(false);
const [showAbout, setShowAbout] = useState(false);
// Get centralized stockThresholds from context
const { stockThresholds } = ctx;
// Close modal on Escape key
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
@@ -417,7 +420,7 @@ function AppContent() {
<MedDetailModal
selectedMed={selectedMed}
coverage={coverage}
settings={settings}
settings={stockThresholds}
showImageLightbox={showImageLightbox}
showRefillModal={showRefillModal}
showEditStockModal={showEditStockModal}
@@ -450,7 +453,7 @@ function AppContent() {
selectedUser={selectedUser}
meds={meds}
coverage={coverage}
settings={settings}
settings={stockThresholds}
onClose={closeUserFilter}
onOpenMedDetail={openMedDetail}
/>
+33 -57
View File
@@ -3,9 +3,8 @@ import { useTranslation } from "react-i18next";
import { FRONTEND_VERSION, GITHUB_URL } from "../App";
interface UpdateCheckResult {
status: "checking" | "up-to-date" | "update-available" | "error";
status: "up-to-date" | "update-available" | "error";
latestVersion?: string;
lastChecked?: string;
}
interface AboutModalProps {
@@ -15,52 +14,37 @@ interface AboutModalProps {
export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
const { t } = useTranslation();
const [backendVersion, setBackendVersion] = useState<string | null>(null);
const [isChecking, setIsChecking] = useState(false);
const [updateCheckResult, setUpdateCheckResult] = useState<UpdateCheckResult | null>(null);
// Fetch backend version and cached update result on mount
// Reset check result when modal opens so stale results are never shown
useEffect(() => {
if (!isOpen) return;
// Fetch backend version
fetch("/api/health")
.then((res) => res.json())
.then((data) => setBackendVersion(data.version || "unknown"))
.catch(() => setBackendVersion("unknown"));
// Load cached update check result
const cached = sessionStorage.getItem("updateCheckResult");
if (cached) {
try {
const parsed = JSON.parse(cached);
if (parsed && typeof parsed === "object") {
setUpdateCheckResult(parsed);
}
} catch {
// ignore
}
if (isOpen) {
setUpdateCheckResult(null);
}
}, [isOpen]);
async function checkForUpdates() {
setUpdateCheckResult({ status: "checking" });
setIsChecking(true);
const minDelay = new Promise((resolve) => setTimeout(resolve, 1000));
try {
const res = await fetch(`https://api.github.com/repos/DanielVolz/medassist-ng/releases/latest`);
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;
const result: UpdateCheckResult = {
setUpdateCheckResult({
status: isUpToDate ? "up-to-date" : "update-available",
latestVersion,
lastChecked: new Date().toISOString(),
};
setUpdateCheckResult(result);
// Cache the result
sessionStorage.setItem("updateCheckResult", JSON.stringify(result));
});
} catch {
setUpdateCheckResult({ status: "error" });
} finally {
setIsChecking(false);
}
}
@@ -74,32 +58,27 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
</button>
<div className="about-header">
<div className="about-logo">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
<path d="M19.5 12c0 4.14-3.36 7.5-7.5 7.5S4.5 16.14 4.5 12 7.86 4.5 12 4.5s7.5 3.36 7.5 7.5z" />
<path d="M12 8v4l2.5 2.5" />
<path d="M9 2h6M12 2v2" />
</svg>
<img src="/favicon.svg" alt="MedAssist-ng" />
</div>
<h2>{t("about.appName", "MedAssist")}</h2>
<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.frontendVersion", "Frontend")}</span>
<span className="about-version-value">{FRONTEND_VERSION}</span>
</div>
<div className="about-version-row">
<span className="about-version-label">{t("about.backendVersion", "Backend")}</span>
<span className="about-version-value">{backendVersion || "..."}</span>
<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={updateCheckResult?.status === "checking"}
>
{updateCheckResult?.status === "checking" ? (
<button className="about-update-btn" onClick={checkForUpdates} disabled={isChecking}>
{isChecking ? (
<>
<span className="spinner-small"></span>
{t("about.checking", "Checking...")}
@@ -116,14 +95,14 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
</>
)}
</button>
{updateCheckResult && updateCheckResult.status !== "checking" && (
{updateCheckResult && (
<div className={`about-update-result ${updateCheckResult.status}`}>
{updateCheckResult.status === "up-to-date" && (
<span className="update-status-text"> {t("about.upToDate", "You are up to date!")}</span>
<span className="update-status-text">&#10003; {t("about.upToDate", "You are up to date!")}</span>
)}
{updateCheckResult.status === "update-available" && (
<span className="update-status-text">
{t("about.updateAvailable", "Update available")}:{" "}
&#11014; {t("about.updateAvailable", "Update available")}:{" "}
<strong>v{updateCheckResult.latestVersion}</strong>
<a
href={`${GITHUB_URL}/releases/latest`}
@@ -136,11 +115,8 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
</span>
)}
{updateCheckResult.status === "error" && (
<span className="update-status-text"> {t("about.checkFailed", "Could not check for updates")}</span>
)}
{updateCheckResult.lastChecked && (
<span className="update-last-checked">
{t("about.lastChecked", "Last checked")}: {new Date(updateCheckResult.lastChecked).toLocaleString()}
<span className="update-status-text">
&#9888; {t("about.checkFailed", "Could not check for updates")}
</span>
)}
</div>
+75 -9
View File
@@ -1,10 +1,11 @@
/**
* AppHeader - Main application header with navigation and user menu
*/
import { useEffect, useState } from "react";
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";
@@ -19,9 +20,25 @@ export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
const location = useLocation();
const currentPath = location.pathname;
const { user, authState, logout } = useAuth();
const { theme, toggleTheme } = useTheme();
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()) {
@@ -94,13 +111,62 @@ export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
</button>
)}
<button
className="icon-btn"
onClick={toggleTheme}
title={theme === "dark" ? t("tooltips.lightMode") : t("tooltips.darkMode")}
>
{theme === "dark" ? "☀️" : "🌙"}
</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)}>
+87 -18
View File
@@ -1,5 +1,7 @@
import { createContext, type ReactNode, useCallback, useContext, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { ConfirmModal } from "./ConfirmModal";
import { PasswordInput } from "./PasswordInput";
// =============================================================================
// Types (no roles - all users are equal)
@@ -32,6 +34,7 @@ interface AuthContextType {
updateProfile: (data: { currentPassword?: string; newPassword?: string }) => Promise<void>;
uploadAvatar: (file: File) => Promise<void>;
deleteAvatar: () => Promise<void>;
deleteAccount: () => Promise<void>;
authFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}
@@ -87,7 +90,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user, authState?.authEnabled]);
async function fetchAuthState() {
async function fetchAuthState(retryCount = 0) {
const maxRetries = 3;
const retryDelay = 1000; // 1 second
try {
setAuthError(null);
const res = await fetch("/api/auth/state");
@@ -101,10 +107,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
if (state.authEnabled) {
await refreshUser();
}
setLoading(false);
} 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");
} finally {
setLoading(false);
}
}
@@ -244,6 +257,21 @@ export function AuthProvider({ children }: { children: ReactNode }) {
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
const authFetch = useCallback(
async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
@@ -285,6 +313,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
updateProfile,
uploadAvatar,
deleteAvatar,
deleteAccount,
authFetch,
}}
>
@@ -329,7 +358,7 @@ export function LoginForm({
return (
<div className="auth-container">
<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>
{/* SSO Login Button */}
@@ -374,9 +403,8 @@ export function LoginForm({
<div className="form-group">
<label htmlFor="password">{t("auth.password", "Password")}</label>
<input
<PasswordInput
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
@@ -445,7 +473,7 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
return (
<div className="auth-container">
<div className="auth-card">
<h1 className="auth-title">💊 MedAssist</h1>
<h1 className="auth-title">💊 MedAssist-ng</h1>
<h2 className="auth-subtitle">{t("auth.register", "Create Account")}</h2>
{/* SSO Login Button - also show on registration */}
@@ -494,9 +522,8 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
<div className="form-group">
<label htmlFor="password">{t("auth.password", "Password")} *</label>
<input
<PasswordInput
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
@@ -508,9 +535,8 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
<div className="form-group">
<label htmlFor="confirmPassword">{t("auth.confirmPassword", "Confirm Password")} *</label>
<input
<PasswordInput
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
@@ -541,7 +567,7 @@ export function RegisterForm({ onSuccess, onSwitchToLogin }: { onSuccess?: () =>
// =============================================================================
export function UserProfile({ onClose }: { onClose?: () => void }) {
const { t } = useTranslation();
const { user, updateProfile, uploadAvatar, deleteAvatar } = useAuth();
const { user, updateProfile, uploadAvatar, deleteAvatar, deleteAccount } = useAuth();
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
@@ -549,6 +575,8 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
const [success, setSuccess] = useState("");
const [loading, setLoading] = useState(false);
const [avatarLoading, setAvatarLoading] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// Close on Escape key
@@ -625,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;
const hasChanges = currentPassword || newPassword || confirmPassword;
@@ -680,9 +720,8 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
<div className="form-group">
<label htmlFor="current-password">{t("auth.currentPassword", "Current Password")}</label>
<input
<PasswordInput
id="current-password"
type="password"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
autoComplete="current-password"
@@ -692,9 +731,8 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
<div className="form-group">
<label htmlFor="new-password">{t("auth.newPassword", "New Password")}</label>
<input
<PasswordInput
id="new-password"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
autoComplete="new-password"
@@ -705,9 +743,8 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
<div className="form-group">
<label htmlFor="confirm-new-password">{t("auth.confirmPassword", "Confirm Password")}</label>
<input
<PasswordInput
id="confirm-new-password"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
autoComplete="new-password"
@@ -725,6 +762,38 @@ export function UserProfile({ onClose }: { onClose?: () => void }) {
</button>
</div>
</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>
);
}
+165 -90
View File
@@ -171,25 +171,40 @@ export function MedDetailModal({
<div className="med-detail-section">
<h3>{t("modal.stockInfo")}</h3>
<div className="med-detail-grid">
<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 full-width">
{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} / {packageSize}
{currentStock} /{" "}
{selectedMed.packageType === "bottle" ? (selectedMed.totalPills ?? packageSize) : packageSize}
{currentStock >
(selectedMed.packageType === "bottle" ? (selectedMed.totalPills ?? packageSize) : packageSize) && (
<span
className="info-tooltip tooltip-align-left warning-text"
data-tooltip={t("tooltips.stockExceedsCapacity")}
>
{" "}
</span>
)}
</span>
</div>
</div>
@@ -197,24 +212,38 @@ export function MedDetailModal({
{/* Package Details Section */}
<div className="med-detail-section">
<h3>{t("modal.packageDetails")}</h3>
<h3>
{t("modal.packageDetails")} (
{selectedMed.packageType === "bottle" ? t("form.packageTypeBottle") : t("form.packageTypeBlister")})
</h3>
<div className="med-detail-grid">
<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>
{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} mg</span>
<span className="med-detail-value">
{selectedMed.pillWeightMg} {selectedMed.doseUnit ?? "mg"}
</span>
</div>
)}
{selectedMed.expiryDate && (
@@ -247,13 +276,19 @@ export function MedDetailModal({
</h3>
<div className="med-detail-schedules">
{selectedMed.blisters.map((blister, idx) => {
const personCount = Math.max(1, selectedMed.takenBy?.length || 1);
// When using new intakes format with per-intake takenBy,
// each intake already represents one person's dose — don't multiply.
// For legacy intakes (no per-intake takenBy), multiply by personCount.
const intake = selectedMed.intakes?.[idx];
const hasPerIntakeTakenBy = !!intake?.takenBy;
const personCount = hasPerIntakeTakenBy ? 1 : 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} mg)`}
{selectedMed.pillWeightMg &&
` (${totalUsage * selectedMed.pillWeightMg} ${selectedMed.doseUnit ?? "mg"})`}
</span>
<span className="med-schedule-freq">
{t("form.blisters.every")} {blister.every}{" "}
@@ -330,10 +365,14 @@ export function MedDetailModal({
})}
</span>
<span className="refill-amount">
+
{entry.packsAdded * selectedMed.blistersPerPack * selectedMed.pillsPerBlister +
entry.loosePillsAdded}{" "}
{t("common.pills")}
{(() => {
const total =
selectedMed.packageType === "bottle"
? entry.loosePillsAdded
: entry.packsAdded * selectedMed.blistersPerPack * selectedMed.pillsPerBlister +
entry.loosePillsAdded;
return `+${total} ${total === 1 ? t("common.pill") : t("common.pills")}`;
})()}
</span>
</div>
))}
@@ -388,24 +427,38 @@ export function MedDetailModal({
<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>
{selectedMed.packageType === "blister" ? (
<>
<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>
</>
) : (
<label>
{t("refill.pillsToAdd")}
<input
type="number"
min="0"
value={refillLoose}
onChange={(e) => onRefillLooseChange(parseInt(e.target.value, 10) || 0)}
/>
</label>
)}
</div>
<div className="modal-footer">
@@ -420,12 +473,17 @@ export function MedDetailModal({
>
{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>
)}
{(() => {
const totalRefill =
selectedMed.packageType === "blister"
? refillPacks * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + refillLoose
: refillLoose;
return totalRefill > 0 ? (
<span className="refill-preview">
+{totalRefill} {totalRefill === 1 ? t("common.pill") : t("common.pills")}
</span>
) : null;
})()}
</div>
</div>
</div>
@@ -452,50 +510,67 @@ export function MedDetailModal({
{(() => {
const dbTotal = getMedTotal(selectedMed);
const currentTotal = medCoverage ? Math.round(medCoverage.medsLeft) : dbTotal;
const newTotal = editStockFullBlisters * selectedMed.pillsPerBlister + editStockPartialBlisterPills;
const isBottle = selectedMed.packageType === "bottle";
const newTotal = isBottle
? editStockPartialBlisterPills
: 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>
{isBottle ? (
<label>
{t("editStock.totalPills")}
<input
type="number"
min="0"
value={editStockPartialBlisterPills}
onChange={(e) => onEditStockPartialBlisterPillsChange(parseInt(e.target.value, 10) || 0)}
/>
</label>
) : (
<>
<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")}
{currentTotal} {currentTotal === 1 ? t("common.pill") : t("common.pills")}
</span>
</div>
<div className="summary-row">
<span>{t("editStock.newTotal")}:</span>
<span>
{newTotal} {t("common.pills")}
{newTotal} {newTotal === 1 ? t("common.pill") : t("common.pills")}
</span>
</div>
<div
@@ -504,7 +579,7 @@ export function MedDetailModal({
<span>{t("editStock.difference")}:</span>
<span>
{difference > 0 ? "+" : ""}
{difference} {t("common.pills")}
{difference} {Math.abs(difference) === 1 ? t("common.pill") : t("common.pills")}
</span>
</div>
</div>
+197 -97
View File
@@ -3,7 +3,9 @@
* Handles new medication creation and editing existing medications
*/
import { useTranslation } from "react-i18next";
import type { FieldErrors, FormBlister, FormState, Medication } from "../types";
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 = {
@@ -30,10 +32,14 @@ export interface MobileEditModalProps {
onAddTakenByPerson: (person: string) => void;
onRemoveTakenByPerson: (person: string) => void;
onTakenByKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void;
// Blister helpers
// 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)
@@ -53,12 +59,17 @@ export interface MobileEditModalProps {
onSaveMedication: (e: React.FormEvent) => void;
}
function deriveTotal(form: FormState) {
/** 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 packCount * blistersPerPack * pillsPerBlister + looseTablets;
return deriveTotal(packCount, blistersPerPack, pillsPerBlister, looseTablets);
}
export function MobileEditModal({
@@ -80,6 +91,9 @@ export function MobileEditModal({
onSetBlisterValue,
onAddBlister,
onRemoveBlister,
onSetIntakeValue,
onAddIntake,
onRemoveIntake,
onHandleValueChange,
refillPacks,
onRefillPacksChange,
@@ -178,57 +192,107 @@ export function MobileEditModal({
</div>
{fieldErrors.takenBy && <span className="field-error">{fieldErrors.takenBy}</span>}
</label>
<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 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> {deriveTotal(form)} {t("common.pills")}
<strong>{t("form.total")}:</strong> {deriveTotalFromForm(form)}{" "}
{deriveTotalFromForm(form) === 1 ? t("common.pill") : t("common.pills")}
</p>
</div>
<label className="full">
{t("form.pillWeight")}
<input
type="number"
min="0"
step="0.1"
value={form.pillWeightMg}
onChange={(e) => onFormChange({ ...form, pillWeightMg: e.target.value })}
placeholder={t("form.placeholders.weight")}
/>
{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")}
@@ -244,24 +308,38 @@ export function MobileEditModal({
<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>
{form.packageType === "blister" ? (
<>
<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>
</>
) : (
<label>
{t("refill.pillsToAdd")}
<input
type="number"
min="0"
value={refillLoose}
onChange={(e) => onRefillLooseChange(parseInt(e.target.value, 10) || 0)}
/>
</label>
)}
<button
type="button"
className="success"
@@ -270,12 +348,18 @@ export function MobileEditModal({
>
{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>
)}
{(() => {
const totalRefill =
form.packageType === "blister"
? refillPacks * Number(form.blistersPerPack || 0) * Number(form.pillsPerBlister || 1) +
refillLoose
: refillLoose;
return totalRefill > 0 ? (
<span className="refill-preview">
+{totalRefill} {totalRefill === 1 ? t("common.pill") : t("common.pills")}
</span>
) : null;
})()}
</div>
</div>
)}
@@ -325,19 +409,8 @@ export function MobileEditModal({
) : null}
<fieldset className="full blister-section">
<legend>
{t("form.blisters.title")}
<label className="toggle-switch small" title={t("form.blisters.remindTooltip")}>
<input
type="checkbox"
checked={form.intakeRemindersEnabled}
onChange={(e) => onFormChange({ ...form, intakeRemindersEnabled: e.target.checked })}
/>
<span className="toggle-slider"></span>
</label>
<span className="legend-hint">{t("form.blisters.remind")}</span>
</legend>
{form.blisters.map((b, idx) => (
<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>
@@ -345,8 +418,8 @@ export function MobileEditModal({
type="number"
min="0"
step="0.1"
value={b.usage}
onChange={(e) => onSetBlisterValue(idx, "usage", e.target.value)}
value={intake.usage}
onChange={(e) => onSetIntakeValue(idx, "usage", e.target.value)}
/>
</label>
<label className="compact">
@@ -354,34 +427,61 @@ export function MobileEditModal({
<input
type="number"
min="1"
value={b.every}
onChange={(e) => onSetBlisterValue(idx, "every", e.target.value)}
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={b.startDate}
onChange={(e) => onSetBlisterValue(idx, "startDate", e.target.value)}
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={b.startTime}
onChange={(e) => onSetBlisterValue(idx, "startTime", e.target.value)}
value={intake.startTime}
onChange={(e) => onSetIntakeValue(idx, "startTime", e.target.value)}
/>
</label>
{form.blisters.length > 1 && (
<button type="button" className="danger remove-blister-btn" onClick={() => onRemoveBlister(idx)}>
{form.takenBy.length === 0 ? null : (
<label className="compact full-row">
<span>{t("form.blisters.takenByIntake")}</span>
<select value={intake.takenBy} onChange={(e) => onSetIntakeValue(idx, "takenBy", e.target.value)}>
{form.takenBy.map((person) => (
<option key={person} value={person}>
{person}
</option>
))}
</select>
</label>
)}
<div className="remind-toggle-row" title={t("form.blisters.remindTooltip")}>
<span className="legend-hint">🔔</span>
<label className="toggle-switch small">
<input
type="checkbox"
checked={intake.intakeRemindersEnabled}
onChange={(e) => onSetIntakeValue(idx, "intakeRemindersEnabled", e.target.checked)}
/>
<span className="toggle-slider"></span>
</label>
</div>
{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={onAddBlister}>
<button
type="button"
className="ghost add-blister"
onClick={() => onAddIntake(form.takenBy.length === 1 ? form.takenBy[0] : undefined)}
>
+ {t("form.blisters.addIntake")}
</button>
</fieldset>
+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>
);
}
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -66,7 +66,8 @@ export function UserFilterModal({
</div>
<div className="user-med-stats">
<span className="user-med-pills">
{currentStock}/{formatNumber(packageSize)} {t("common.pills")}
{currentStock}/{formatNumber(packageSize)}{" "}
{packageSize === 1 ? t("common.pill") : t("common.pills")}
</span>
{status && <span className={`status-chip ${status.className}`}>{t(status.label)}</span>}
</div>
+1
View File
@@ -13,6 +13,7 @@ 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";
+67 -75
View File
@@ -3,9 +3,9 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useState }
import { useTranslation } from "react-i18next";
import { useAuth } from "../components/Auth";
import { useCollapsedDays, useDoses, useMedications, useRefill, useSettings, useShare } from "../hooks";
import type { Coverage, Medication, ScheduleEvent } from "../types";
import type { Coverage, Medication, ScheduleEvent, StockThresholds } from "../types";
import { getSystemLocale } from "../utils/formatters";
import { buildSchedulePreview, calculateCoverage } from "../utils/schedule";
import { buildSchedulePreview, calculateCoverage, computeMissedPastDoseIds, isDoseDismissed } from "../utils/schedule";
// =============================================================================
// Types
@@ -134,6 +134,7 @@ export interface AppContextValue {
coverage: { all: Coverage[]; low: Coverage[] };
coverageByMed: Record<string, Coverage>;
depletionByMed: Record<string, number | null>;
stockThresholds: StockThresholds;
existingPeople: string[];
groupedSchedule: GroupedDay[];
pastDays: GroupedDay[];
@@ -277,7 +278,8 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
systemLocale,
settingsHook.settings.reminderDaysBefore,
settingsHook.settings.stockCalculationMode,
doses.takenDoses
doses.takenDoses,
doses.takenDoseTimestamps
),
[
medications.meds,
@@ -286,6 +288,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
settingsHook.settings.reminderDaysBefore,
settingsHook.settings.stockCalculationMode,
doses.takenDoses,
doses.takenDoseTimestamps,
]
);
@@ -296,6 +299,24 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
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();
@@ -332,38 +353,47 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
const groupedSchedule = useMemo(() => {
const days = new Map<string, { dateStr: string; date: Date; isPast: boolean; meds: Map<string, DayMedEntry> }>();
schedule.events.slice(0, 2000).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 || [],
// 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);
});
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]);
}, [schedule.events, scheduleDays]);
const pastDays = useMemo(() => groupedSchedule.filter((d) => d.isPast), [groupedSchedule]);
@@ -393,52 +423,10 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
.slice(0, scheduleDays);
}, [groupedSchedule, scheduleDays]);
// Build a map of medId -> dismissedUntil date string from medication records
// This is robust against timestamp changes from schedule updates or timezone fixes
const _dismissedUntilByMed = useMemo(() => {
const map = new Map<string, string>();
for (const med of medications.meds) {
if (med.dismissedUntil) {
map.set(String(med.id), med.dismissedUntil);
}
}
return map;
}, [medications.meds]);
// Helper to check if a dose date is on or before the dismissedUntil date
const isDoseDismissed = useCallback((doseId: string, dismissedUntilDate: string | undefined): boolean => {
if (!dismissedUntilDate) return false;
// Extract timestamp from dose ID (format: medId-blisterIdx-timestamp or medId-blisterIdx-timestamp-person)
const parts = doseId.split("-");
if (parts.length < 3) return false;
const timestamp = parseInt(parts[2], 10);
if (Number.isNaN(timestamp)) return false;
// Compare date strings (YYYY-MM-DD format sorts correctly)
const doseDate = new Date(timestamp);
const doseDateStr = `${doseDate.getFullYear()}-${String(doseDate.getMonth() + 1).padStart(2, "0")}-${String(doseDate.getDate()).padStart(2, "0")}`;
return doseDateStr <= dismissedUntilDate;
}, []);
const missedPastDoseIds = useMemo(() => {
const totalPastDoses = pastDays.flatMap((d) =>
d.meds.flatMap((m) => {
// Find the medication to get its dismissedUntil
const med = medications.meds.find((med) => med.name === m.medName);
const dismissedUntilDate = med?.dismissedUntil ?? undefined;
return m.doses.flatMap((dose) => {
// Check if this dose is on or before the dismissed date for this medication
if (isDoseDismissed(dose.id, dismissedUntilDate)) {
return [];
}
return (dose.takenBy || []).length > 0 ? dose.takenBy.map((p: string) => `${dose.id}-${p}`) : [dose.id];
});
})
);
// Also filter out doses that are marked as taken or individually dismissed (legacy)
return totalPastDoses.filter((id) => !doses.takenDoses.has(id) && !doses.dismissedDoses.has(id));
}, [pastDays, medications.meds, doses.takenDoses, doses.dismissedDoses, isDoseDismissed]);
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(
@@ -627,7 +615,9 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
settings.repeatRemindersEnabled !== savedSettings.repeatRemindersEnabled ||
settings.reminderRepeatIntervalMinutes !== savedSettings.reminderRepeatIntervalMinutes ||
settings.maxNaggingReminders !== savedSettings.maxNaggingReminders ||
settings.stockCalculationMode !== savedSettings.stockCalculationMode
settings.stockCalculationMode !== savedSettings.stockCalculationMode ||
settings.shareStockStatus !== savedSettings.shareStockStatus ||
settings.expiryWarningDays !== savedSettings.expiryWarningDays
);
}, [settingsHook.settings, settingsHook.savedSettings]);
@@ -769,6 +759,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
coverage,
coverageByMed,
depletionByMed,
stockThresholds,
existingPeople,
groupedSchedule,
pastDays,
@@ -832,6 +823,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
coverage,
coverageByMed,
depletionByMed,
stockThresholds,
existingPeople,
groupedSchedule,
pastDays,
+1 -1
View File
@@ -14,7 +14,7 @@ export type { Settings, UseSettingsReturn } from "./useSettings";
export { useSettings } from "./useSettings";
export type { UseShareReturn } from "./useShare";
export { useShare } from "./useShare";
export type { Theme, UseThemeReturn } from "./useTheme";
export type { Theme, ThemePreference, UseThemeReturn } from "./useTheme";
export { useTheme } from "./useTheme";
export type { UseUnsavedChangesWarningReturn } from "./useUnsavedChangesWarning";
export { useUnsavedChangesWarning } from "./useUnsavedChangesWarning";
+92 -45
View File
@@ -2,11 +2,12 @@
// useDoses Hook - Dose tracking state and operations
// =============================================================================
import { useCallback, useEffect, useState } from "react";
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;
@@ -19,25 +20,39 @@ export interface UseDosesReturn {
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
@@ -77,59 +92,91 @@ export function useDoses(): UseDosesReturn {
[takenDoses, getDoseId]
);
const markDoseTaken = useCallback(async (doseId: string) => {
// Optimistic update
setTakenDoses((prev) => {
const next = new Set(prev);
next.add(doseId);
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;
});
}
}, []);
const undoDoseTaken = useCallback(async (doseId: string) => {
// Optimistic update
setTakenDoses((prev) => {
const next = new Set(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
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,
+69 -1
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { FieldErrors, FormBlister, FormState, Medication } from "../types";
import type { FieldErrors, FormBlister, FormIntake, FormState, Medication } from "../types";
import { FIELD_LIMITS } from "../types";
import { toDateValue, toTimeValue } from "../utils/formatters";
@@ -14,19 +14,38 @@ export const defaultBlister = (): FormBlister => {
};
};
/**
* 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 {
@@ -53,6 +72,10 @@ export interface UseMedicationFormReturn {
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;
@@ -134,19 +157,60 @@ export function useMedicationForm(): UseMedicationFormReturn {
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,
@@ -156,6 +220,7 @@ export function useMedicationForm(): UseMedicationFormReturn {
startDate: toDateValue(s.start),
startTime: toTimeValue(s.start),
})),
intakes: intakesFromApi,
};
setForm(editForm);
setOriginalForm(editForm);
@@ -234,6 +299,9 @@ export function useMedicationForm(): UseMedicationFormReturn {
setBlisterValue,
addBlister,
removeBlister,
setIntakeValue,
addIntake,
removeIntake,
startEdit,
resetForm,
handleValueChange,
+4 -3
View File
@@ -22,7 +22,7 @@ export function useMedications(): UseMedicationsReturn {
const loadMeds = useCallback(() => {
setLoading(true);
fetch("/api/medications")
fetch("/api/medications", { credentials: "include" })
.then((res) => res.json())
.then((data) => setMeds(Array.isArray(data) ? data : []))
.catch(() => setMeds([]))
@@ -31,7 +31,7 @@ export function useMedications(): UseMedicationsReturn {
const deleteMed = useCallback(
async (id: number, editingId: number | null, resetForm: () => void) => {
await fetch(`/api/medications/${id}`, { method: "DELETE" }).catch(() => null);
await fetch(`/api/medications/${id}`, { method: "DELETE", credentials: "include" }).catch(() => null);
if (editingId === id) resetForm();
loadMeds();
},
@@ -48,6 +48,7 @@ export function useMedications(): UseMedicationsReturn {
const res = await fetch(`/api/medications/${medId}/image`, {
method: "POST",
body: formData,
credentials: "include",
});
if (res.ok) {
loadMeds();
@@ -62,7 +63,7 @@ export function useMedications(): UseMedicationsReturn {
const deleteMedImage = useCallback(
async (medId: number) => {
await fetch(`/api/medications/${medId}/image`, { method: "DELETE" }).catch(() => null);
await fetch(`/api/medications/${medId}/image`, { method: "DELETE", credentials: "include" }).catch(() => null);
loadMeds();
},
[loadMeds]
+3 -3
View File
@@ -1,6 +1,6 @@
import { useCallback, useState } from "react";
import type { Coverage, FormState, Medication, RefillEntry } from "../types";
import { getMedTotal } from "../types";
import { getMedTotal, getPackageSize } from "../types";
export interface UseRefillReturn {
// Refill state
@@ -146,8 +146,8 @@ export function useRefill(): UseRefillReturn {
const desiredTotal = finalFullBlisters * selectedMed.pillsPerBlister + finalPartialPills;
// The "base" from DB structure (without any stockAdjustment)
const baseTotal =
selectedMed.packCount * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + selectedMed.looseTablets;
// Use getPackageSize() which handles both blister and bottle types correctly
const baseTotal = getPackageSize(selectedMed);
// stockAdjustment = what we need to make getMedTotal() return desiredTotal
const newStockAdjustment = desiredTotal - baseTotal;
+18
View File
@@ -30,6 +30,9 @@ export interface Settings {
lastNotificationChannel: "email" | "push" | "both" | null;
lastReminderMedName: string | null;
lastReminderTakenBy: string | null;
lastStockReminderSent: string | null;
lastStockReminderChannel: "email" | "push" | "both" | null;
lastStockReminderMedNames: string | null;
shoutrrrEnabled: boolean;
shoutrrrUrl: string;
emailStockReminders: boolean;
@@ -37,6 +40,7 @@ export interface Settings {
shoutrrrStockReminders: boolean;
shoutrrrIntakeReminders: boolean;
stockCalculationMode: "automatic" | "manual";
shareStockStatus: boolean;
expiryWarningDays: number;
}
@@ -65,6 +69,9 @@ const defaultSettings: Settings = {
lastNotificationChannel: null,
lastReminderMedName: null,
lastReminderTakenBy: null,
lastStockReminderSent: null,
lastStockReminderChannel: null,
lastStockReminderMedNames: null,
shoutrrrEnabled: false,
shoutrrrUrl: "",
emailStockReminders: true,
@@ -72,6 +79,7 @@ const defaultSettings: Settings = {
shoutrrrStockReminders: true,
shoutrrrIntakeReminders: true,
stockCalculationMode: "automatic",
shareStockStatus: true,
expiryWarningDays: 30,
};
@@ -141,6 +149,9 @@ export function useSettings(): UseSettingsReturn {
lastNotificationChannel: data.lastNotificationChannel ?? prev.lastNotificationChannel,
lastReminderMedName: data.lastReminderMedName ?? prev.lastReminderMedName,
lastReminderTakenBy: data.lastReminderTakenBy ?? prev.lastReminderTakenBy,
lastStockReminderSent: data.lastStockReminderSent ?? prev.lastStockReminderSent,
lastStockReminderChannel: data.lastStockReminderChannel ?? prev.lastStockReminderChannel,
lastStockReminderMedNames: data.lastStockReminderMedNames ?? prev.lastStockReminderMedNames,
}));
setSavedSettings((prev) => ({
...prev,
@@ -149,6 +160,9 @@ export function useSettings(): UseSettingsReturn {
lastNotificationChannel: data.lastNotificationChannel ?? prev.lastNotificationChannel,
lastReminderMedName: data.lastReminderMedName ?? prev.lastReminderMedName,
lastReminderTakenBy: data.lastReminderTakenBy ?? prev.lastReminderTakenBy,
lastStockReminderSent: data.lastStockReminderSent ?? prev.lastStockReminderSent,
lastStockReminderChannel: data.lastStockReminderChannel ?? prev.lastStockReminderChannel,
lastStockReminderMedNames: data.lastStockReminderMedNames ?? prev.lastStockReminderMedNames,
}));
})
.catch(() => {});
@@ -198,6 +212,7 @@ export function useSettings(): UseSettingsReturn {
shoutrrrStockReminders: settings.shoutrrrStockReminders,
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
stockCalculationMode: settings.stockCalculationMode,
shareStockStatus: settings.shareStockStatus,
language: i18n.language,
smtpHost: settings.smtpHost,
smtpPort: settings.smtpPort,
@@ -210,6 +225,7 @@ export function useSettings(): UseSettingsReturn {
await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify(payload),
}).catch(() => null);
@@ -233,6 +249,7 @@ export function useSettings(): UseSettingsReturn {
const res = await fetch("/api/settings/test-email", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ email: settings.notificationEmail }),
});
const data = await res.json();
@@ -254,6 +271,7 @@ export function useSettings(): UseSettingsReturn {
const res = await fetch("/api/settings/test-shoutrrr", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ url: settings.shoutrrrUrl }),
});
const data = await res.json();
+1
View File
@@ -59,6 +59,7 @@ export function useShare(): UseShareReturn {
const res = await fetch("/api/share", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
takenBy: shareSelectedPerson,
scheduleDays: shareSelectedDays,
+58 -10
View File
@@ -1,32 +1,80 @@
// =============================================================================
// useTheme Hook - Theme (dark/light mode) state management
// useTheme Hook - Theme (dark/light/system mode) state management
// =============================================================================
import { useCallback, useEffect, useState } from "react";
export type Theme = "light" | "dark";
export type ThemePreference = "light" | "dark" | "system";
export interface UseThemeReturn {
/** The resolved theme applied to the DOM ("light" | "dark") */
theme: Theme;
/** The user's preference ("light" | "dark" | "system") */
themePreference: ThemePreference;
/** Set the theme preference */
setThemePreference: (pref: ThemePreference) => void;
/** Legacy toggle: cycles light → dark → system → light */
toggleTheme: () => void;
}
function getSystemTheme(): Theme {
if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: light)").matches) {
return "light";
}
return "dark";
}
function resolveTheme(pref: ThemePreference): Theme {
return pref === "system" ? getSystemTheme() : pref;
}
export function useTheme(): UseThemeReturn {
const [theme, setTheme] = useState<Theme>(() => {
const [themePreference, setThemePreferenceState] = useState<ThemePreference>(() => {
if (typeof window !== "undefined") {
return (localStorage.getItem("theme") as Theme) || "dark";
const stored = localStorage.getItem("theme") as ThemePreference | null;
if (stored === "light" || stored === "dark" || stored === "system") return stored;
return "dark";
}
return "dark";
});
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
}, [theme]);
const [theme, setTheme] = useState<Theme>(() => resolveTheme(themePreference));
const toggleTheme = useCallback(() => {
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
// Apply resolved theme to DOM whenever preference or system theme changes
useEffect(() => {
const resolved = resolveTheme(themePreference);
setTheme(resolved);
document.documentElement.setAttribute("data-theme", resolved);
localStorage.setItem("theme", themePreference);
}, [themePreference]);
// Listen for system theme changes when preference is "system"
useEffect(() => {
if (themePreference !== "system") return;
const mq = window.matchMedia?.("(prefers-color-scheme: light)");
if (!mq) return;
const handler = () => {
const resolved = resolveTheme("system");
setTheme(resolved);
document.documentElement.setAttribute("data-theme", resolved);
};
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, [themePreference]);
const setThemePreference = useCallback((pref: ThemePreference) => {
setThemePreferenceState(pref);
}, []);
return { theme, toggleTheme };
const toggleTheme = useCallback(() => {
setThemePreferenceState((prev) => {
if (prev === "light") return "dark";
if (prev === "dark") return "system";
return "light";
});
}, []);
return { theme, themePreference, setThemePreference, toggleTheme };
}
+84 -31
View File
@@ -17,11 +17,16 @@
},
"dashboard": {
"reorder": {
"title": "Nachbestell-Erinnerung",
"title": "Nachll-Erinnerung",
"badge": "Bestandsüberwachung",
"noMeds": "Noch keine Medikamente konfiguriert.",
"allGood": "Alles in Ordnung, genug Vorrat.", "lowWarning": "Genug Vorrat, aber {{count}} Medikament wird knapp.",
"lowWarning_other": "Genug Vorrat, aber {{count}} Medikamente werden knapp.", "sendReminder": "🔔 Erinnerung jetzt senden"
"allGood": "Alles in Ordnung, genug Vorrat.",
"lowWarning": "Genug Vorrat, aber {{meds}} ist kritisch niedrig.",
"lowWarning_other": "Genug Vorrat, aber {{meds}} sind kritisch niedrig.",
"lowWarningPrefix": "Genug Vorrat, aber",
"lowWarningSuffix": "ist kritisch niedrig.",
"lowWarningSuffix_other": "sind kritisch niedrig.",
"sendReminder": "🔔 Erinnerung jetzt senden"
},
"overview": {
"title": "Medikamentenübersicht",
@@ -54,22 +59,23 @@
"reminders": {
"active": "Automatische Erinnerungen aktiv",
"status": "Status",
"allStockOk": "Bestand OK",
"allOk": "Alles OK",
"allStockOk": "Bestand gut",
"allOk": "Alles gut",
"lastReminder": "Letzte Einnahme-Erinnerung",
"lastSent": "Letzte Einnahme-Erinnerung",
"lastStockSent": "Letzte Bestands-Erinnerung",
"next": "Nachbestell-Erinnerung",
"nextIn": "Nachbestell-Erinnerung",
"inDays": "in {{days}} Tagen",
"inDays_one": "in {{days}} Tag",
"inDays_other": "in {{days}} Tagen",
"noRemindersNeeded": "Keine Erinnerungen nötig",
"needReorder": "{{count}} Medikament nachbestellen",
"needReorder_other": "{{count}} Medikamente nachbestellen",
"needRefill": "{{count}} Medikament nachllen",
"needRefill_other": "{{count}} Medikamente nachllen",
"emptyStock": "{{count}} Medikament leer",
"emptyStock_other": "{{count}} Medikamente leer",
"lowWarning": "{{count}} Medikament wird knapp",
"lowWarning_other": "{{count}} Medikamente werden knapp",
"lowWarning": "{{count}} Medikament kritisch niedrig",
"lowWarning_other": "{{count}} Medikamente kritisch niedrig",
"waitingFirstCheck": "Warte auf erste Prüfung",
"type": "Typ",
"typeStock": "Bestand",
@@ -81,7 +87,10 @@
"criticalMeds": "{{count}} Medikament kritisch",
"criticalMeds_other": "{{count}} Medikamente kritisch",
"lowMeds": "{{count}} Medikament knapp",
"lowMeds_other": "{{count}} Medikamente knapp"
"lowMeds_other": "{{count}} Medikamente knapp",
"daysLeft": "{{days}} Tag übrig",
"daysLeft_other": "{{days}} Tage übrig",
"needsRefill": "Nachfüllen nötig"
}
},
"table": {
@@ -91,11 +100,16 @@
"currentPills": "Aktuelle Tabletten",
"fullBlisters": "Volle Blister",
"openBlister": "Offener Blister",
"stock": "Bestand",
"stockDetails": "Details",
"daysLeft": "Tage übrig",
"status": "Bestand",
"status": "Status",
"runsOut": "Aufgebraucht",
"autoRemind": "Auto-Erinnerung",
"expiry": "Ablaufdatum"
"expiry": "Ablaufdatum",
"pillsCount": "{{count}} Tabletten",
"pillsCount_one": "{{count}} Tablette",
"pillsCount_other": "{{count}} Tabletten"
},
"medications": {
"list": {
@@ -109,7 +123,10 @@
"blisters": "Blister pro Packung",
"pillsPerBlister": "Tabletten pro Blister",
"loose": "Lose",
"total": "Gesamt"
"total": "Gesamt",
"stock": "Bestand",
"totalCapacity": "Kapazität",
"type": "Typ"
}
},
"form": {
@@ -119,11 +136,16 @@
"commercialName": "Handelsname",
"genericName": "Wirkstoff",
"takenBy": "Eingenommen von",
"packageType": "Verpackungsart",
"packageTypeBlister": "Blisterpackung",
"packageTypeBottle": "Pillendose",
"packs": "Packungen",
"blistersPerPack": "Blister pro Packung",
"pillsPerBlister": "Tabletten pro Blister",
"totalCapacity": "Gesamtkapazität",
"currentPills": "Aktuelle Tabletten",
"loosePills": "Lose Tabletten",
"pillWeight": "Tablettengewicht (mg)",
"pillWeight": "Dosis pro Tablette",
"total": "Gesamt (Tabletten)",
"expiryDate": "Ablaufdatum",
"notes": "Notizen",
@@ -147,7 +169,9 @@
"every": "alle",
"from": "ab",
"startDate": "Datum",
"startTime": "Uhrzeit"
"startTime": "Uhrzeit",
"takenByIntake": "Eingenommen von",
"takenByEveryone": "Alle"
}
},
"planner": {
@@ -155,9 +179,12 @@
"badge": "Vorrat planen",
"from": "Von",
"until": "Bis",
"includeUntilStart": "Aktuellen Verbrauch einrechnen",
"includeUntilStartTooltip": "Wenn aktiviert, werden die Pillen, die zwischen heute und dem gewählten Startdatum verbraucht werden, vom aktuellen Bestand abgezogen. So erhältst du ein genaueres Bild davon, wie viel du zu Beginn des Planungszeitraums tatsächlich noch übrig hast.",
"calculate": "Berechnen",
"calculating": "Wird berechnet...",
"sendEmail": "📧 Per E-Mail senden",
"sendNotification": "🔔 Bedarf senden",
"table": {
"medication": "Medikament",
"usage": "Verbrauch",
@@ -206,25 +233,34 @@
"intakeCheck": "Einnahmeprüfung",
"15minBefore": "15 Min. vor geplanter Zeit",
"nextCheck": "Nächste Bestandsprüfung",
"lastSent": "Zuletzt gesendet",
"lastSent": "Letzte Benachrichtigung",
"lastStockSent": "Letzte Bestands-Erinnerung",
"lastIntakeSent": "Letzte Einnahme-Erinnerung",
"envHint": "Diese Werte können über REMINDER_HOUR und REMINDER_MINUTES_BEFORE in .env konfiguriert werden"
},
"stock": {
"title": "Bestand",
"threshold": "Erinnerungsschwelle",
"remindWhen": "Erinnern wenn Vorrat unter",
"repeatDaily": "Täglich wiederholen",
"repeatTooltip": "Wenn aktiviert, wird täglich eine Erinnerung gesendet solange der Bestand niedrig ist. Andernfalls nur einmal pro Medikament bis zum Auffüllen.",
"calculationMode": "Bestandsberechnung",
"automatic": "Automatisch",
"automaticDesc": "Bestand wird automatisch anhand des Einnahmeplans reduziert",
"manual": "Manuell",
"manualDesc": "Bestand wird nur reduziert wenn Dosen als genommen markiert werden",
"display": "Anzeige",
"lowStockDays": "Niedriger Bestand (Tage)",
"lowStockTooltip": "Gelbe Warnung ab diesem Schwellenwert",
"highStockDays": "Hoher Bestand (Tage)",
"highStockTooltip": "Grün mit Stern ab diesem Schwellenwert"
"thresholds": "Schwellenwerte",
"criticalStockDays": "Kritisch (Tage)",
"criticalStockTooltip": "Bestand unter diesem Wert ist kritisch und erfordert sofortige Aufmerksamkeit",
"lowStockDays": "Niedrig (Tage)",
"lowStockTooltip": "Bestand unter diesem Wert bedeutet, dass bald nachbestellt werden sollte",
"highStockDays": "Hoch (Tage)",
"highStockTooltip": "Bestand über diesem Wert bedeutet, dass du gut versorgt bist",
"thresholdValidation": "Werte müssen sein: Kritisch < Niedrig < Hoch",
"shareStockStatus": "Bestand auf geteilten Links anzeigen",
"shareStockStatusDesc": "Bestandsstatus (Normal/Niedrig/Kritisch) und farbige Rahmen auf geteilten Zeitplan-Links für Einnahme-Nutzer anzeigen"
},
"stockReminder": {
"title": "Bestands-Erinnerung",
"description": "Benachrichtigung wenn Medikamentenbestand erreicht",
"repeatDaily": "Täglich wiederholen",
"repeatTooltip": "Wenn aktiviert, wird täglich eine Erinnerung gesendet solange der Bestand kritisch ist. Andernfalls nur einmal pro Medikament bis zum Auffüllen."
},
"saveSettings": "Einstellungen speichern"
},
@@ -253,6 +289,7 @@
},
"status": {
"outOfStock": "Leer",
"criticalStock": "Kritisch",
"lowStock": "Niedrig",
"normal": "Normal",
"highStock": "Hoch",
@@ -264,9 +301,16 @@
"tooltips": {
"intakeReminders": "Einnahme-Erinnerungen aktiviert",
"hasNotes": "Hat Notizen",
"stockExceedsCapacity": "Bestand überschreitet Packungskapazität — Packungsanzahl anpassen",
"lightMode": "Zum hellen Modus wechseln",
"darkMode": "Zum dunklen Modus wechseln"
},
"theme": {
"title": "Design",
"light": "Hell",
"dark": "Dunkel",
"system": "System"
},
"dose": {
"takenBy": "eingenommen von",
"markAsTaken": "Als eingenommen markieren"
@@ -309,11 +353,18 @@
"avatarUpdated": "Avatar aktualisiert",
"avatarRemoved": "Avatar entfernt",
"loginWithSSO": "Mit {{provider}} anmelden",
"or": "oder"
"or": "oder",
"deleteAccount": "Konto löschen",
"deleteAccountConfirmTitle": "Konto löschen?",
"deleteAccountConfirmText": "Dadurch werden dein Konto und alle deine Daten (Medikamente, Einstellungen, Verlauf) dauerhaft gelöscht. Diese Aktion kann nicht rückgängig gemacht werden.",
"deleteAccountButton": "Ja, mein Konto löschen"
},
"common": {
"loading": "Wird geladen...",
"sending": "Wird gesendet...",
"sent": "Gesendet!",
"sendFailed": "Senden fehlgeschlagen",
"networkError": "Netzwerkfehler",
"saving": "Wird gespeichert...",
"unsavedChanges": {
"title": "Ungespeicherte Änderungen",
@@ -352,6 +403,9 @@
"fullBlisters": "volle Blister",
"inBlister": "in 1 Blister",
"total": "gesamt",
"pillsTotal": "{{count}} Tabletten gesamt",
"pillsTotal_one": "{{count}} Tablette gesamt",
"pillsTotal_other": "{{count}} Tabletten gesamt",
"max": "max"
},
"share": {
@@ -410,12 +464,13 @@
"importSuccess": "Daten erfolgreich importiert",
"importSuccessDetails": "Importiert: {{medications}} Medikamente, {{doses}} Dosen, {{shares}} Teilen-Links",
"importError": "Daten konnten nicht importiert werden",
"invalidFile": "Ungültiges Dateiformat. Bitte wähle eine gültige MedAssist-Exportdatei.",
"invalidFile": "Ungültiges Dateiformat. Bitte wähle eine gültige MedAssist-ng-Exportdatei.",
"downloadFilename": "medassist-export"
},
"refill": {
"title": "Nachfüllen",
"packs": "Packungen hinzufügen",
"pillsToAdd": "Tabletten hinzufügen",
"loosePills": "Lose Tabletten hinzufügen",
"pillsPerPack": "1 Packung = {{count}} Tabletten",
"addToStock": "Zum Bestand hinzufügen",
@@ -432,6 +487,7 @@
"editStock": {
"title": "Bestand korrigieren",
"hint": "Dies ist für die Korrektur von Bestandsabweichungen. Für normale Bestandsänderungen nutze 'Nachfüllen'.",
"totalPills": "Gesamte Tabletten",
"fullBlisters": "Volle Blister",
"partialBlisterPills": "Angebrochener Blister",
"pillsPerBlister": "(je {{count}} Tabletten)",
@@ -447,16 +503,13 @@
"appName": "MedAssist-ng",
"description": "Open-Source Medikamentenverwaltung und Planungsanwendung für selbst gehostete Umgebungen.",
"version": "Version",
"frontend": "Frontend",
"backend": "Backend",
"checkForUpdates": "Nach Updates suchen",
"checking": "Prüfe...",
"upToDate": "Du bist auf dem neuesten Stand!",
"updateAvailable": "Update verfügbar",
"viewOnGitHub": "Auf GitHub ansehen",
"downloadUpdate": "Update herunterladen",
"checkFailed": "Update-Prüfung fehlgeschlagen",
"lastChecked": "Zuletzt geprüft",
"viewOnGitHub": "Auf GitHub ansehen",
"github": "GitHub",
"license": "MIT-Lizenz",
"copyright": "© {{year}} Daniel Volz",
+82 -31
View File
@@ -17,12 +17,15 @@
},
"dashboard": {
"reorder": {
"title": "Reorder Reminder",
"title": "Refill Reminder",
"badge": "Stock watch",
"noMeds": "No medications configured yet.",
"allGood": "All good, enough stock.",
"lowWarning": "Enough stock for now, but {{count}} medication is running low.",
"lowWarning_other": "Enough stock for now, but {{count}} medications are running low.",
"lowWarning": "Enough stock for now, but {{meds}} is running critically low.",
"lowWarning_other": "Enough stock for now, but {{meds}} are running critically low.",
"lowWarningPrefix": "Enough stock for now, but",
"lowWarningSuffix": "is running critically low.",
"lowWarningSuffix_other": "are running critically low.",
"sendReminder": "🔔 Send Reminder Now"
},
"overview": {
@@ -56,22 +59,23 @@
"reminders": {
"active": "Automatic reminders active",
"status": "Status",
"allStockOk": "All stock OK",
"allOk": "All OK",
"allStockOk": "All stock good",
"allOk": "All good",
"lastReminder": "Last intake reminder",
"lastSent": "Last intake reminder",
"lastStockSent": "Last stock reminder",
"next": "Refill reminder",
"nextIn": "Refill reminder",
"inDays": "in {{days}} days",
"inDays_one": "in {{days}} day",
"inDays_other": "in {{days}} days",
"noRemindersNeeded": "No reminders needed",
"needReorder": "{{count}} med needs reorder",
"needReorder_other": "{{count}} meds need reorder",
"needRefill": "{{count}} med needs refill",
"needRefill_other": "{{count}} meds need refill",
"emptyStock": "{{count}} med is empty",
"emptyStock_other": "{{count}} meds are empty",
"lowWarning": "{{count}} medication running low",
"lowWarning_other": "{{count}} medications running low",
"lowWarning": "{{count}} medication running critically low",
"lowWarning_other": "{{count}} medications running critically low",
"waitingFirstCheck": "Waiting for first check",
"type": "Type",
"typeStock": "Stock",
@@ -83,7 +87,10 @@
"criticalMeds": "{{count}} medication critical",
"criticalMeds_other": "{{count}} medications critical",
"lowMeds": "{{count}} medication low",
"lowMeds_other": "{{count}} medications low"
"lowMeds_other": "{{count}} medications low",
"daysLeft": "{{days}} day left",
"daysLeft_other": "{{days}} days left",
"needsRefill": "Needs refill"
}
},
"table": {
@@ -93,11 +100,16 @@
"currentPills": "Current pills",
"fullBlisters": "Full blisters",
"openBlister": "Open blister",
"stock": "Stock",
"stockDetails": "Details",
"daysLeft": "Days left",
"status": "Stock",
"status": "Status",
"runsOut": "Runs out",
"autoRemind": "Auto-remind",
"expiry": "Expiry"
"expiry": "Expiry",
"pillsCount": "{{count}} pills",
"pillsCount_one": "{{count}} pill",
"pillsCount_other": "{{count}} pills"
},
"medications": {
"list": {
@@ -111,7 +123,10 @@
"blisters": "Blisters per pack",
"pillsPerBlister": "Pills per blister",
"loose": "Loose",
"total": "Total"
"total": "Total",
"stock": "Stock",
"totalCapacity": "Capacity",
"type": "Type"
}
},
"form": {
@@ -121,11 +136,16 @@
"commercialName": "Commercial Name",
"genericName": "Generic Name",
"takenBy": "Taken by",
"packageType": "Package Type",
"packageTypeBlister": "Blister Pack",
"packageTypeBottle": "Pill Bottle",
"packs": "Packs",
"blistersPerPack": "Blisters per pack",
"pillsPerBlister": "Pills per blister",
"totalCapacity": "Total Capacity",
"currentPills": "Current Pills",
"loosePills": "Loose pills",
"pillWeight": "Pill weight (mg)",
"pillWeight": "Dose per pill",
"total": "Total (pills)",
"expiryDate": "Expiry Date",
"notes": "Notes",
@@ -149,7 +169,9 @@
"every": "every",
"from": "from",
"startDate": "Date",
"startTime": "Time"
"startTime": "Time",
"takenByIntake": "Taken by",
"takenByEveryone": "Everyone"
}
},
"planner": {
@@ -157,9 +179,12 @@
"badge": "Plan your supply",
"from": "From",
"until": "Until",
"includeUntilStart": "Include current consumption",
"includeUntilStartTooltip": "When enabled, pills consumed between today and the selected start date are subtracted from your current stock. This gives a more accurate picture of how much you'll actually have left when the planning period begins.",
"calculate": "Calculate",
"calculating": "Calculating...",
"sendEmail": "📧 Send via Email",
"sendNotification": "🔔 Send Demand",
"table": {
"medication": "Medication",
"usage": "Usage",
@@ -208,25 +233,34 @@
"intakeCheck": "Intake check",
"15minBefore": "15 min before scheduled time",
"nextCheck": "Next stock check",
"lastSent": "Last sent",
"lastSent": "Last notification sent",
"lastStockSent": "Last stock reminder",
"lastIntakeSent": "Last intake reminder",
"envHint": "These values can be configured via REMINDER_HOUR and REMINDER_MINUTES_BEFORE in .env"
},
"stock": {
"title": "Stock",
"threshold": "Reminder Threshold",
"remindWhen": "Remind when supply drops below",
"repeatDaily": "Repeat daily",
"repeatTooltip": "When enabled, sends reminders every day while stock is low. Otherwise, only notifies once per medication until restocked.",
"calculationMode": "Stock Calculation",
"automatic": "Automatic",
"automaticDesc": "Stock automatically decreases based on schedule",
"manual": "Manual",
"manualDesc": "Stock only decreases when doses are marked as taken",
"display": "Display",
"lowStockDays": "Low Stock (days)",
"lowStockTooltip": "Yellow warning color threshold",
"highStockDays": "High Stock (days)",
"highStockTooltip": "Green with star threshold"
"thresholds": "Thresholds",
"criticalStockDays": "Critical (days)",
"criticalStockTooltip": "Stock below this value is critical and needs immediate attention",
"lowStockDays": "Low (days)",
"lowStockTooltip": "Stock below this value means you should reorder soon",
"highStockDays": "High (days)",
"highStockTooltip": "Stock above this value means you are well supplied",
"thresholdValidation": "Values must be: Critical < Low < High",
"shareStockStatus": "Show Stock on Shared Links",
"shareStockStatusDesc": "Show stock status (Normal/Low/Critical) and colored borders on shared schedule links for intake users"
},
"stockReminder": {
"title": "Stock Reminder",
"description": "Sends notification when medication stock reaches",
"repeatDaily": "Repeat daily",
"repeatTooltip": "When enabled, sends reminders every day while stock is critical. Otherwise, only notifies once per medication until restocked."
},
"saveSettings": "Save Settings"
},
@@ -255,6 +289,7 @@
},
"status": {
"outOfStock": "Empty",
"criticalStock": "Critical",
"lowStock": "Low",
"normal": "Normal",
"highStock": "High",
@@ -266,9 +301,16 @@
"tooltips": {
"intakeReminders": "Intake reminders enabled",
"hasNotes": "Has notes",
"stockExceedsCapacity": "Stock exceeds package capacity — consider updating pack count",
"lightMode": "Switch to light mode",
"darkMode": "Switch to dark mode"
},
"theme": {
"title": "Theme",
"light": "Light",
"dark": "Dark",
"system": "System"
},
"dose": {
"takenBy": "taken by",
"markAsTaken": "Mark as taken"
@@ -311,11 +353,18 @@
"avatarUpdated": "Avatar updated",
"avatarRemoved": "Avatar removed",
"loginWithSSO": "Login with {{provider}}",
"or": "or"
"or": "or",
"deleteAccount": "Delete Account",
"deleteAccountConfirmTitle": "Delete Account?",
"deleteAccountConfirmText": "This will permanently delete your account and all your data (medications, settings, history). This action cannot be undone.",
"deleteAccountButton": "Yes, delete my account"
},
"common": {
"loading": "Loading...",
"sending": "Sending...",
"sent": "Sent!",
"sendFailed": "Failed to send",
"networkError": "Network error",
"saving": "Saving...",
"unsavedChanges": {
"title": "Unsaved Changes",
@@ -354,6 +403,9 @@
"fullBlisters": "full blisters",
"inBlister": "in 1 blister",
"total": "total",
"pillsTotal": "{{count}} pills total",
"pillsTotal_one": "{{count}} pill total",
"pillsTotal_other": "{{count}} pills total",
"max": "max"
},
"share": {
@@ -412,12 +464,13 @@
"importSuccess": "Data imported successfully",
"importSuccessDetails": "Imported: {{medications}} medications, {{doses}} doses, {{shares}} share links",
"importError": "Failed to import data",
"invalidFile": "Invalid file format. Please select a valid MedAssist export file.",
"invalidFile": "Invalid file format. Please select a valid MedAssist-ng export file.",
"downloadFilename": "medassist-export"
},
"refill": {
"title": "Refill",
"packs": "Packs to add",
"pillsToAdd": "Pills to add",
"loosePills": "Loose pills to add",
"pillsPerPack": "1 pack = {{count}} pills",
"addToStock": "Add to Stock",
@@ -434,6 +487,7 @@
"editStock": {
"title": "Correct Stock",
"hint": "This is for correcting stock discrepancies. For regular stock changes, use 'Refill'.",
"totalPills": "Total pills",
"fullBlisters": "Full blisters",
"partialBlisterPills": "Partial blister",
"pillsPerBlister": "({{count}} pills each)",
@@ -449,16 +503,13 @@
"appName": "MedAssist-ng",
"description": "Open-source medication tracking and planning application for self-hosted environments.",
"version": "Version",
"frontend": "Frontend",
"backend": "Backend",
"checkForUpdates": "Check for Updates",
"checking": "Checking...",
"upToDate": "You're up to date!",
"updateAvailable": "Update available",
"viewOnGitHub": "View on GitHub",
"downloadUpdate": "Download Update",
"checkFailed": "Could not check for updates",
"lastChecked": "Last checked",
"viewOnGitHub": "View on GitHub",
"github": "GitHub",
"license": "MIT License",
"copyright": "© {{year}} Daniel Volz",
+315 -279
View File
@@ -5,24 +5,13 @@ import { useAuth } from "../components/Auth";
import { useAppContext } from "../context";
import type { Coverage } from "../types";
import { formatNumber, getExpiryClass, getSystemLocale } from "../utils/formatters";
import { expandDoseIds, getStockStatus } from "../utils/schedule";
// Helper for user-specific localStorage keys
function userStorageKey(userId: number | undefined, key: string): string {
return userId ? `user_${userId}_${key}` : key;
}
// Helper function to get stock status
function getStockStatus(
daysLeft: number | null,
medsLeft: number,
settings: { lowStockDays: number; normalStockDays: number; highStockDays: number }
) {
if (medsLeft <= 0 || daysLeft === null || daysLeft <= 0) return { className: "danger", label: "status.outOfStock" };
if (daysLeft <= settings.lowStockDays) return { className: "danger", label: "status.lowStock" };
if (daysLeft >= settings.highStockDays) return { className: "success", label: "status.highStock" };
return { className: "success", label: "status.normal" };
}
// Helper function to calculate blister stock
function getBlisterStock(totalPills: number, pillsPerBlister: number, _looseTablets: number, _originalTotal: number) {
const fullBlisters = Math.floor(totalPills / pillsPerBlister);
@@ -46,30 +35,21 @@ function formatOpenBlisterAndLoose(
return `${openBlisterPills} ${t("common.of")} ${pillsPerBlister} ${t("common.pills")}`;
}
// Get total pills for a medication
// Get total pills for a medication (packageType-aware)
function getMedTotal(med: {
packCount: number;
blistersPerPack: number;
pillsPerBlister: number;
looseTablets: number;
stockAdjustment?: number | null;
packageType?: string;
}): number {
if (med.packageType === "bottle") {
return med.looseTablets + (med.stockAdjustment ?? 0);
}
return med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
}
// Get next reminder date for a medication
function getNextReminderForMed(row: Coverage, reminderDaysBefore: number, locale: string): string {
if (!row.depletionDate) return "-";
const depletionDate = new Date(row.depletionDate);
const reminderDate = new Date(depletionDate);
reminderDate.setDate(reminderDate.getDate() - reminderDaysBefore);
const now = new Date();
if (reminderDate <= now) return "-";
return reminderDate.toLocaleDateString(locale, { day: "2-digit", month: "short" });
}
// Notification bell SVG icon (no emoji)
function NotificationBellIcon() {
return (
@@ -101,18 +81,22 @@ function getReminderStatusData(
_lastNotificationChannel: string | null,
lastReminderMedName: string | null,
lastReminderTakenBy: string | null,
lastStockReminderSent: string | null,
_lastStockReminderChannel: string | null,
lastStockReminderMedNames: string | null,
t: (key: string, options?: Record<string, unknown>) => string,
locale: string
): {
status: { text: string; className: string };
next: { name: string; days: number } | null;
lastSent: { date: string; medName: string | null; takenBy: string | null } | null;
lowStockMeds: { name: string; daysLeft: number; isCritical: boolean }[];
lastStockSent: { date: string; medNames: string | null } | null;
lastIntakeSent: { date: string; medName: string | null; takenBy: string | null } | null;
} {
const criticalCount = lowCoverage.length;
const lowCount = allCoverage.filter((c) => {
if (c.medsLeft <= 0) return false;
if (c.daysLeft === null) return false;
return c.daysLeft < lowStockDays && c.daysLeft > 3;
return c.daysLeft < lowStockDays && c.daysLeft > reminderDaysBefore;
}).length;
// Determine status
@@ -134,36 +118,68 @@ function getReminderStatusData(
};
}
// Find next medication to hit reminder threshold
const nextToRunOut = allCoverage
.filter((c) => c.daysLeft !== null && c.daysLeft > reminderDaysBefore)
.sort((a, b) => (a.daysLeft ?? Infinity) - (b.daysLeft ?? Infinity))[0];
// Collect all low stock medications (critical + low), deduplicated by name
const lowStockMap = new Map<string, { name: string; daysLeft: number; isCritical: boolean }>();
let next: { name: string; days: number } | null = null;
if (nextToRunOut && nextToRunOut.daysLeft !== null) {
const daysUntilReminder = Math.round(nextToRunOut.daysLeft - reminderDaysBefore);
next = { name: nextToRunOut.name, days: daysUntilReminder };
// Add critical meds (from lowCoverage - these are ≤3 days)
for (const c of lowCoverage) {
if (c.daysLeft !== null) {
const existing = lowStockMap.get(c.name);
if (!existing || c.daysLeft < existing.daysLeft) {
lowStockMap.set(c.name, { name: c.name, daysLeft: Math.round(c.daysLeft), isCritical: true });
}
}
}
// Parse last sent info
let lastSent: { date: string; medName: string | null; takenBy: string | null } | null = null;
if (lastAutoEmailSent) {
const lastSentDate = new Date(lastAutoEmailSent);
const formattedDate = lastSentDate.toLocaleDateString(locale, {
// Add low but not critical meds
for (const c of allCoverage) {
if (c.medsLeft <= 0) continue;
if (c.daysLeft === null) continue;
if (c.daysLeft < lowStockDays && c.daysLeft > reminderDaysBefore) {
const existing = lowStockMap.get(c.name);
if (!existing || c.daysLeft < existing.daysLeft) {
lowStockMap.set(c.name, { name: c.name, daysLeft: Math.round(c.daysLeft), isCritical: false });
}
}
}
// Convert to array and sort by days left (most urgent first)
const lowStockMeds = Array.from(lowStockMap.values()).sort((a, b) => a.daysLeft - b.daysLeft);
// Parse last stock reminder sent info (from dedicated stock tracking columns)
let lastStockSent: { date: string; medNames: string | null } | null = null;
if (lastStockReminderSent) {
const sentDate = new Date(lastStockReminderSent);
const formattedDate = sentDate.toLocaleDateString(locale, {
day: "2-digit",
month: "short",
hour: "2-digit",
minute: "2-digit",
});
lastStockSent = {
date: formattedDate,
medNames: lastStockReminderMedNames,
};
}
lastSent = {
// Parse last intake reminder sent info (from intake tracking columns)
let lastIntakeSent: { date: string; medName: string | null; takenBy: string | null } | null = null;
if (lastAutoEmailSent) {
const sentDate = new Date(lastAutoEmailSent);
const formattedDate = sentDate.toLocaleDateString(locale, {
day: "2-digit",
month: "short",
hour: "2-digit",
minute: "2-digit",
});
lastIntakeSent = {
date: formattedDate,
medName: lastReminderMedName,
takenBy: lastReminderTakenBy,
};
}
return { status, next, lastSent };
return { status, lowStockMeds, lastStockSent, lastIntakeSent };
}
export function DashboardPage() {
@@ -202,38 +218,10 @@ export function DashboardPage() {
openUserFilter,
openShareDialog,
openScheduleLightbox,
stockThresholds,
loadSettings,
} = useAppContext();
// Local state for reminder email
const [sendingReminderEmail, setSendingReminderEmail] = useState(false);
const [reminderEmailResult, setReminderEmailResult] = useState<{ success: boolean; message: string } | null>(null);
async function sendReminderEmail() {
if (!settings.notificationEmail || coverage.low.length === 0) return;
setSendingReminderEmail(true);
setReminderEmailResult(null);
try {
const res = await fetch("/api/reminder/send-email", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: settings.notificationEmail,
lowStock: coverage.low,
}),
});
const data = await res.json();
if (res.ok) {
setReminderEmailResult({ success: true, message: data.message || "Email sent!" });
} else {
setReminderEmailResult({ success: false, message: data.error || "Failed to send" });
}
} catch {
setReminderEmailResult({ success: false, message: "Network error" });
}
setSendingReminderEmail(false);
}
// Get structured reminder data
const reminderData = getReminderStatusData(
settings.reminderDaysBefore,
@@ -245,6 +233,9 @@ export function DashboardPage() {
settings.lastNotificationChannel,
settings.lastReminderMedName,
settings.lastReminderTakenBy,
settings.lastStockReminderSent,
settings.lastStockReminderChannel,
settings.lastStockReminderMedNames,
t,
getSystemLocale(i18n.language)
);
@@ -258,6 +249,50 @@ export function DashboardPage() {
(settings.shoutrrrEnabled && settings.shoutrrrIntakeReminders);
const anyRemindersEnabled = stockRemindersEnabled || intakeRemindersEnabled;
// Manual reminder send state
const [sendingReminder, setSendingReminder] = useState(false);
const [reminderResult, setReminderResult] = useState<{ success: boolean; message: string } | null>(null);
async function sendManualReminder() {
if (!stockRemindersEnabled || reminderData.lowStockMeds.length === 0) return;
setSendingReminder(true);
setReminderResult(null);
try {
const lowStock = reminderData.lowStockMeds.map((m) => {
const cov = coverage.all.find((c) => c.name === m.name);
return {
name: m.name,
medsLeft: cov?.medsLeft ?? 0,
daysLeft: m.daysLeft,
depletionDate: cov?.depletionDate ?? null,
isCritical: m.isCritical,
};
});
const res = await fetch("/api/reminder/send-email", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
email: settings.notificationEmail,
lowStock,
}),
});
const data = await res.json();
if (res.ok) {
setReminderResult({ success: true, message: data.message || t("common.sent") });
// Refresh settings so "Last stock reminder" row appears immediately
loadSettings();
} else {
setReminderResult({ success: false, message: data.error || t("common.sendFailed") });
}
} catch {
setReminderResult({ success: false, message: t("common.networkError") });
}
setSendingReminder(false);
}
return (
<>
{anyRemindersEnabled && (
@@ -267,172 +302,173 @@ export function DashboardPage() {
<NotificationBellIcon />
</span>
<span className="reminder-status-title">{t("dashboard.reminders.active")}</span>
<span className={`reminder-status-badge ${reminderData.status.className}`}>
{reminderData.status.className === "success" && "✓ "}
{reminderData.status.text}
</span>
<span className={`status-chip small ${reminderData.status.className}`}>{reminderData.status.text}</span>
</div>
<div className="reminder-status-details">
{stockRemindersEnabled && reminderData.next && (
<div className="reminder-status-row">
<span className="reminder-status-label">{t("dashboard.reminders.next")}:</span>
<span className="reminder-status-value">
{reminderData.next.name}{" "}
{t("dashboard.reminders.inDays", { count: reminderData.next.days, days: reminderData.next.days })}
{(reminderData.lowStockMeds.length > 0 ||
(stockRemindersEnabled && reminderData.lastStockSent) ||
(intakeRemindersEnabled && reminderData.lastIntakeSent)) && (
<div className="reminder-status-details">
{stockRemindersEnabled && reminderData.lowStockMeds.length > 0 && (
<div className="reminder-status-row">
<span className="reminder-status-label">{t("dashboard.reminders.needsRefill")}:</span>
<span className="reminder-status-value">
{reminderData.lowStockMeds.map((med, idx) => {
const medication = meds.find((m) => m.name === med.name);
const cov = coverage.all.find((c) => c.name === med.name);
const status = cov ? getStockStatus(cov.daysLeft, cov.medsLeft, stockThresholds) : null;
const textClass =
status?.className === "danger"
? "danger-text"
: status?.className === "warning"
? "warning-text"
: "";
return (
<span key={med.name}>
{idx > 0 && ", "}
<span
className={`med-link clickable ${textClass}`}
onClick={() => medication && openMedDetail(medication)}
>
{med.name}
</span>
<span className={`reminder-days-left ${textClass}`}>
{" "}
{t("dashboard.reminders.daysLeft", { count: med.daysLeft, days: med.daysLeft })}
</span>
</span>
);
})}
</span>
</div>
)}
{stockRemindersEnabled && reminderData.lastStockSent && (
<div className="reminder-status-row">
<span className="reminder-status-label">{t("dashboard.reminders.lastStockSent")}:</span>
<span className="reminder-status-value">
{reminderData.lastStockSent.medNames &&
(() => {
// Extract first med name (medNames may be "Name (+N)")
const rawName = reminderData.lastStockSent!.medNames!;
const firstName = rawName.replace(/\s*\(\+\d+\)$/, "");
const suffix = rawName.includes("(+") ? rawName.slice(firstName.length) : "";
const medication = meds.find((m) => m.name === firstName);
return medication ? (
<>
<span className="med-link clickable" onClick={() => openMedDetail(medication)}>
{firstName}
</span>
{suffix && <span className="reminder-med-name">{suffix}</span>}
</>
) : (
<span className="reminder-med-name">{rawName}</span>
);
})()}
<span className="reminder-date"> {reminderData.lastStockSent.date}</span>
</span>
</div>
)}
{intakeRemindersEnabled && reminderData.lastIntakeSent && (
<div className="reminder-status-row">
<span className="reminder-status-label">{t("dashboard.reminders.lastSent")}:</span>
<span className="reminder-status-value">
{reminderData.lastIntakeSent.medName &&
(() => {
const medication = meds.find((m) => m.name === reminderData.lastIntakeSent!.medName);
return medication ? (
<span className="med-link clickable" onClick={() => openMedDetail(medication)}>
{reminderData.lastIntakeSent!.medName}
</span>
) : (
<span className="reminder-med-name">{reminderData.lastIntakeSent!.medName}</span>
);
})()}
{reminderData.lastIntakeSent.takenBy && (
<span className="reminder-taken-by"> ({reminderData.lastIntakeSent.takenBy})</span>
)}
<span className="reminder-date"> {reminderData.lastIntakeSent.date}</span>
</span>
</div>
)}
</div>
)}
{stockRemindersEnabled && reminderData.lowStockMeds.length > 0 && (
<div className="reminder-send-row">
<button type="button" className="ghost" onClick={sendManualReminder} disabled={sendingReminder}>
{sendingReminder ? t("common.sending") : t("dashboard.reorder.sendReminder")}
</button>
{reminderResult && (
<span className={`reminder-send-result ${reminderResult.success ? "success" : "error"}`}>
{reminderResult.message}
</span>
</div>
)}
{intakeRemindersEnabled && reminderData.lastSent && (
<div className="reminder-status-row">
<span className="reminder-status-label">{t("dashboard.reminders.lastSent")}:</span>
<span className="reminder-status-value">
{reminderData.lastSent.medName && (
<span className="reminder-med-name">{reminderData.lastSent.medName}</span>
)}
{reminderData.lastSent.takenBy && (
<span className="reminder-taken-by">({reminderData.lastSent.takenBy})</span>
)}
<span className="reminder-date">{reminderData.lastSent.date}</span>
</span>
</div>
)}
</div>
)}
</div>
)}
</section>
)}
<section className="grid">
<article className="card">
<div className="card-head">
<h2>{t("dashboard.reorder.title")}</h2>
</div>
{(() => {
if (meds.length === 0) {
return <p className="muted">{t("dashboard.reorder.noMeds")}</p>;
}
{/* Reorder Reminder card: Only show when reminders are NOT enabled (otherwise Reminder Bar shows the same info) */}
{!anyRemindersEnabled && (
<section className="grid">
<article className="card">
<div className="card-head">
<h2>{t("dashboard.reorder.title")}</h2>
</div>
{(() => {
if (meds.length === 0) {
return <p className="muted">{t("dashboard.reorder.noMeds")}</p>;
}
// Count medications with "Low" stock status (based on lowStockDays setting)
const lowStockCount = coverage.all.filter((c) => {
if (c.medsLeft <= 0) return true; // out of stock
if (c.daysLeft === null) return false; // no schedule
return c.daysLeft < settings.lowStockDays;
}).length;
// Count medications with low stock (based on lowStockDays setting), deduplicated by name
const lowStockMap = new Map<string, Coverage>();
for (const c of coverage.all) {
if (c.daysLeft === null && c.medsLeft > 0) continue; // no schedule, has stock
if (c.medsLeft <= 0 || c.daysLeft === null || c.daysLeft < settings.lowStockDays) {
const existing = lowStockMap.get(c.name);
if (!existing || (c.daysLeft ?? 0) < (existing.daysLeft ?? 0)) {
lowStockMap.set(c.name, c);
}
}
}
const lowStockMeds = Array.from(lowStockMap.values());
const lowStockCount = lowStockMeds.length;
if (coverage.low.length === 0) {
// No critical meds (≤3 days)
if (lowStockCount === 0) {
// All good - everything is Normal or High
return <p className="success-text">{t("dashboard.reorder.allGood")}</p>;
} else {
// Some meds are Low but not critical
return <p className="warning-text">{t("dashboard.reorder.lowWarning", { count: lowStockCount })}</p>;
}
}
return (
<>
<div className="table table-7">
<div className="table-head">
<span>{t("table.name")}</span>
<span>{t("table.fullBlisters")}</span>
<span>{t("table.openBlister")}</span>
<span>{t("table.daysLeft")}</span>
<span>{t("table.status")}</span>
<span>{t("table.runsOut")}</span>
<span>{t("table.autoRemind")}</span>
</div>
{coverage.low.map((row) => {
const status = getStockStatus(row.daysLeft, row.medsLeft, settings);
const med = meds.find((m) => m.name === row.name);
// Some meds are low - show simple text with clickable names and days left
return (
<p>
{t("dashboard.reorder.lowWarningPrefix")}{" "}
{lowStockMeds.map((c, idx) => {
const med = meds.find((m) => m.name === c.name);
const status = getStockStatus(c.daysLeft, c.medsLeft, stockThresholds);
const textClass =
status.className === "danger"
? "danger-text"
: status.className === "warning"
? "warning-text"
: "success-text";
const stock = getBlisterStock(
Math.round(row.medsLeft),
med?.pillsPerBlister ?? 1,
med?.looseTablets ?? 0,
med ? getMedTotal(med) : Math.round(row.medsLeft)
);
: "";
return (
<div key={row.name} className="table-row clickable" onClick={() => med && openMedDetail(med)}>
<span data-label={t("table.name")} className="cell-with-avatar">
<MedicationAvatar name={row.name} imageUrl={med?.imageUrl} />
<span className="med-name-text">{row.name}</span>
{med?.takenBy &&
med.takenBy.length > 0 &&
med.takenBy.map((person) => (
<span
key={person}
className="taken-by-badge clickable"
onClick={(e) => {
e.stopPropagation();
openUserFilter(person);
}}
>
{person}
</span>
))}
{(med?.intakeRemindersEnabled || med?.notes) && (
<span className="med-icons">
{med?.intakeRemindersEnabled && (
<span
className="reminder-icon info-tooltip"
data-tooltip={t("tooltips.intakeReminders")}
>
🔔
</span>
)}
{med?.notes && (
<span className="notes-icon info-tooltip" data-tooltip={t("tooltips.hasNotes")}>
📝
</span>
)}
</span>
)}
<span key={c.name}>
{idx > 0 && ", "}
<span className={`med-link clickable ${textClass}`} onClick={() => med && openMedDetail(med)}>
{c.name}
</span>
<span data-label={t("table.fullBlisters")} className={textClass}>
{formatFullBlisters(stock.fullBlisters, t)}
<span className={`reminder-days-left ${textClass}`}>
{" "}
({t("dashboard.reminders.daysLeft", { count: c.daysLeft ?? 0, days: c.daysLeft ?? 0 })})
</span>
<span data-label={t("table.openBlister")} className={textClass}>
{formatOpenBlisterAndLoose(
stock.openBlisterPills,
stock.loosePills,
med?.pillsPerBlister ?? 1,
t
)}
</span>
<span data-label={t("table.days")} className={textClass}>
{formatNumber(row.daysLeft)}
</span>
<span data-label={t("table.status")} className={`status-chip ${status.className}`}>
{t(status.label)}
</span>
<span data-label={t("table.runsOut")}>{row.depletionDate ?? "-"}</span>
<span data-label={t("table.autoRemind")} className="next-reminder-date">
{getNextReminderForMed(row, settings.reminderDaysBefore, getSystemLocale(i18n.language))}
</span>
</div>
);
})}
</div>
{(settings.emailEnabled || settings.shoutrrrEnabled) && (
<div className="email-send-action">
<button type="button" className="ghost" onClick={sendReminderEmail} disabled={sendingReminderEmail}>
{sendingReminderEmail ? t("common.sending") : t("dashboard.reorder.sendReminder")}
</button>
{reminderEmailResult && (
<span className={reminderEmailResult.success ? "success-text" : "danger-text"}>
{reminderEmailResult.message}
</span>
)}
</div>
)}
</>
);
})()}
</article>
</section>
);
})}{" "}
{t("dashboard.reorder.lowWarningSuffix", { count: lowStockCount })}
</p>
);
})()}
</article>
</section>
)}
<section className="grid">
<article className="card">
@@ -442,15 +478,15 @@ export function DashboardPage() {
<div className="table table-7">
<div className="table-head">
<span>{t("table.name")}</span>
<span>{t("table.fullBlisters")}</span>
<span>{t("table.openBlister")}</span>
<span>{t("table.stock")}</span>
<span>{t("table.stockDetails")}</span>
<span>{t("table.daysLeft")}</span>
<span>{t("table.runsOut")}</span>
<span>{t("table.expiry")}</span>
<span>{t("table.status")}</span>
</div>
{coverage.all.map((row) => {
const status = getStockStatus(row.daysLeft, row.medsLeft, settings);
const status = getStockStatus(row.daysLeft, row.medsLeft, stockThresholds);
const med = meds.find((m) => m.name === row.name);
const expiryClass = getExpiryClass(med?.expiryDate, settings.expiryWarningDays);
const textClass =
@@ -501,11 +537,23 @@ export function DashboardPage() {
</span>
)}
</span>
<span data-label={t("table.fullBlisters")} className={textClass}>
{formatFullBlisters(stock.fullBlisters, t)}
<span data-label={t("table.stock")} className={textClass}>
{med?.packageType === "bottle"
? t("table.pillsCount", { count: Math.round(row.medsLeft) })
: formatFullBlisters(stock.fullBlisters, t)}
</span>
<span data-label={t("table.openBlister")} className={textClass}>
{formatOpenBlisterAndLoose(stock.openBlisterPills, stock.loosePills, med?.pillsPerBlister ?? 1, t)}
<span
data-label={t("table.stockDetails")}
className={`${textClass}${med?.packageType === "bottle" ? " hide-on-card" : ""}`}
>
{med?.packageType === "bottle"
? "—"
: formatOpenBlisterAndLoose(
stock.openBlisterPills,
stock.loosePills,
med?.pillsPerBlister ?? 1,
t
)}
</span>
<span data-label={t("table.daysLeft")} className={textClass}>
{formatNumber(row.daysLeft)}
@@ -560,13 +608,7 @@ export function DashboardPage() {
{pastDays.length > 0 &&
(() => {
const missedCount = missedPastDoseIds.length;
const totalPastDoses = pastDays.flatMap((d) =>
d.meds.flatMap((m) =>
m.doses.flatMap((dose) =>
(dose.takenBy || []).length > 0 ? dose.takenBy.map((p) => `${dose.id}-${p}`) : [dose.id]
)
)
);
const totalPastDoses = pastDays.flatMap((d) => d.meds.flatMap((m) => expandDoseIds(m.doses)));
return (
<div className="past-days-header">
<div
@@ -613,9 +655,10 @@ export function DashboardPage() {
{showPastDays &&
pastDays.map((day) => {
const allDoseIds = day.meds.flatMap((item) =>
item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
)
item.doses.flatMap((d) => {
const takenByArray = Array.isArray(d.takenBy) ? d.takenBy : [];
return takenByArray.length > 0 ? takenByArray.map((p) => `${d.id}-${p}`) : [d.id];
})
);
const allDayTaken =
allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id) || dismissedDoses.has(id));
@@ -628,7 +671,7 @@ export function DashboardPage() {
return (
<div
key={day.dateStr}
className={`day-block past ${isCollapsed ? "collapsed" : ""} ${allDayTaken ? "all-taken" : ""} stock-${worstStatus}`}
className={`day-block past ${isCollapsed ? "collapsed" : ""} ${allDayTaken ? "all-taken" : allDoseIds.length > 0 ? "past-missed" : ""}`}
>
<div
className="day-divider clickable"
@@ -660,9 +703,10 @@ export function DashboardPage() {
const med = meds.find((m) => m.name === item.medName);
const medCov = coverageByMed[item.medName];
const isEmpty = medCov ? medCov.medsLeft <= 0 : false;
const itemDoseIds = item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
);
const status = medCov
? getStockStatus(medCov.daysLeft, medCov.medsLeft, stockThresholds)
: null;
const itemDoseIds = expandDoseIds(item.doses);
const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
@@ -685,21 +729,23 @@ export function DashboardPage() {
)}
</div>
<div className="tag-row">
<span className="tag subtle">
{item.total} {t("common.pills")} {t("common.total")}
</span>
<span className="tag subtle">{t("common.pillsTotal", { count: item.total })}</span>
{status && (
<span className={`status-chip small ${status.className}`}>{t(status.label)}</span>
)}
</div>
</div>
<div className="doses-col">
{item.doses.map((dose) => {
// If no takenBy, show single checkbox; otherwise show one per person
const people = (dose.takenBy || []).length > 0 ? dose.takenBy : [null];
const people = dose.takenBy.length > 0 ? dose.takenBy : [null];
return (
<div key={dose.id} className="dose-item past">
<span className="dose-time">{dose.timeStr}</span>
<span className="dose-usage">
{dose.usage} {dose.usage !== 1 ? t("common.pills") : t("common.pill")}
{med?.pillWeightMg && ` (${dose.usage * med.pillWeightMg} mg)`}
{med?.pillWeightMg &&
` (${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"})`}
</span>
<div className="dose-checks">
{people.map((person) => {
@@ -751,11 +797,7 @@ export function DashboardPage() {
{todayDay &&
(() => {
const day = todayDay;
const allDoseIds = day.meds.flatMap((item) =>
item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
)
);
const allDoseIds = day.meds.flatMap((item) => expandDoseIds(item.doses));
const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id));
const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length;
@@ -765,7 +807,7 @@ export function DashboardPage() {
const willBeOutOfStock = typeof depletionTime === "number" && item.lastWhen > depletionTime;
if (willBeOutOfStock) return "danger";
if (!medCoverage) return "success";
const status = getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings);
const status = getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, stockThresholds);
return status.className;
});
const worstStatus = dayStockStatuses.includes("danger")
@@ -812,11 +854,9 @@ export function DashboardPage() {
const status = willBeOutOfStock
? { className: "danger", label: "status.outOfStock" }
: medCoverage
? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings)
? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, stockThresholds)
: null;
const itemDoseIds = item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
);
const itemDoseIds = expandDoseIds(item.doses);
const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
@@ -839,16 +879,16 @@ export function DashboardPage() {
)}
</div>
<div className="tag-row">
<span className="tag subtle">
{item.total} {t("common.pills")} {t("common.total")}
</span>
{status && <span className={`tag ${status.className}`}>{t(status.label)}</span>}
<span className="tag subtle">{t("common.pillsTotal", { count: item.total })}</span>
{status && (
<span className={`status-chip small ${status.className}`}>{t(status.label)}</span>
)}
</div>
</div>
<div className="doses-col">
{item.doses.map((dose) => {
const isOverdue = dose.when < Date.now();
const people = (dose.takenBy || []).length > 0 ? dose.takenBy : [null];
const people = dose.takenBy.length > 0 ? dose.takenBy : [null];
const allTaken = people.every((person) => takenDoses.has(getDoseId(dose.id, person)));
return (
<div
@@ -858,7 +898,8 @@ export function DashboardPage() {
<span className="dose-time">{dose.timeStr}</span>
<span className="dose-usage">
{dose.usage} {dose.usage !== 1 ? t("common.pills") : t("common.pill")}
{med?.pillWeightMg && ` (${dose.usage * med.pillWeightMg} mg)`}
{med?.pillWeightMg &&
` (${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"})`}
</span>
<div className="dose-checks">
{people.map((person) => {
@@ -912,7 +953,7 @@ export function DashboardPage() {
const totalFutureDoses = futureDays.flatMap((d) =>
d.meds.flatMap((m) =>
m.doses.flatMap((dose) =>
(dose.takenBy || []).length > 0 ? dose.takenBy.map((p) => `${dose.id}-${p}`) : [dose.id]
dose.takenBy.length > 0 ? dose.takenBy.map((p) => `${dose.id}-${p}`) : [dose.id]
)
)
);
@@ -944,11 +985,7 @@ export function DashboardPage() {
{/* Future days */}
{showFutureDays &&
futureDays.map((day) => {
const allDoseIds = day.meds.flatMap((item) =>
item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
)
);
const allDoseIds = day.meds.flatMap((item) => expandDoseIds(item.doses));
const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id));
const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length;
@@ -958,7 +995,7 @@ export function DashboardPage() {
const willBeOutOfStock = typeof depletionTime === "number" && item.lastWhen > depletionTime;
if (willBeOutOfStock) return "danger";
if (!medCoverage) return "success";
const status = getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings);
const status = getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, stockThresholds);
return status.className;
});
const worstStatus = dayStockStatuses.includes("danger")
@@ -1004,11 +1041,9 @@ export function DashboardPage() {
const status = willBeOutOfStock
? { className: "danger", label: "status.outOfStock" }
: medCoverage
? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings)
? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, stockThresholds)
: null;
const itemDoseIds = item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
);
const itemDoseIds = expandDoseIds(item.doses);
const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
@@ -1031,22 +1066,23 @@ export function DashboardPage() {
)}
</div>
<div className="tag-row">
<span className="tag subtle">
{item.total} {t("common.pills")} {t("common.total")}
</span>
{status && <span className={`tag ${status.className}`}>{t(status.label)}</span>}
<span className="tag subtle">{t("common.pillsTotal", { count: item.total })}</span>
{status && (
<span className={`status-chip small ${status.className}`}>{t(status.label)}</span>
)}
</div>
</div>
<div className="doses-col">
{item.doses.map((dose) => {
const people = (dose.takenBy || []).length > 0 ? dose.takenBy : [null];
const people = dose.takenBy.length > 0 ? dose.takenBy : [null];
const allTaken = people.every((person) => takenDoses.has(getDoseId(dose.id, person)));
return (
<div key={dose.id} className={`dose-item future ${allTaken ? "all-taken" : ""}`}>
<span className="dose-time">{dose.timeStr}</span>
<span className="dose-usage">
{dose.usage} {dose.usage !== 1 ? t("common.pills") : t("common.pill")}
{med?.pillWeightMg && ` (${dose.usage * med.pillWeightMg} mg)`}
{med?.pillWeightMg &&
` (${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"})`}
</span>
<div className="dose-checks">
{people.map((person) => {
+263 -109
View File
@@ -3,8 +3,8 @@ import { useTranslation } from "react-i18next";
import { ConfirmModal, MedicationAvatar, MobileEditModal } from "../components";
import { useAppContext, useUnsavedChanges } from "../context";
import { useMedicationForm, useUnsavedChangesWarning } from "../hooks";
import type { Medication } from "../types";
import { FIELD_LIMITS, getPackageSize } from "../types";
import type { DoseUnit, Medication } from "../types";
import { DOSE_UNITS, FIELD_LIMITS, getPackageSize } from "../types";
import { combineDateAndTime, formatDateTime, formatNumber } from "../utils/formatters";
export function MedicationsPage() {
@@ -25,6 +25,7 @@ export function MedicationsPage() {
setRefillLoose,
refillSaving,
submitRefill,
coverageByMed,
} = useAppContext();
// Use the medication form hook
@@ -47,6 +48,9 @@ export function MedicationsPage() {
addBlister,
removeBlister,
setBlisterValue,
addIntake,
removeIntake,
setIntakeValue,
resetForm,
startEdit,
} = useMedicationForm();
@@ -87,12 +91,17 @@ export function MedicationsPage() {
// Calculate total tablets
const totalTablets = useMemo(() => {
if (form.packageType === "bottle") {
// For bottle type, looseTablets is the current stock
return Number(form.looseTablets) || 0;
}
// For blister type
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 packCount * blistersPerPack * pillsPerBlister + looseTablets;
}, [form.packCount, form.blistersPerPack, form.pillsPerBlister, form.looseTablets]);
}, [form.packageType, form.packCount, form.blistersPerPack, form.pillsPerBlister, form.looseTablets]);
// Open mobile edit modal
function openEditModal() {
@@ -158,26 +167,39 @@ export function MedicationsPage() {
if (saving) return;
setSaving(true);
// Prepare medication data
const blisters = form.blisters.map((b) => ({
usage: Number(b.usage) || 1,
every: Number(b.every) || 1,
start: combineDateAndTime(b.startDate, b.startTime),
// Prepare intakes data with per-intake takenBy
const intakes = form.intakes.map((intake) => ({
usage: Number(intake.usage) || 1,
every: Number(intake.every) || 1,
start: combineDateAndTime(intake.startDate, intake.startTime),
takenBy: intake.takenBy.trim() || null, // Empty string becomes null
intakeRemindersEnabled: intake.intakeRemindersEnabled,
}));
// Also prepare legacy blisters for backward compatibility
const blisters = intakes.map((i) => ({
usage: i.usage,
every: i.every,
start: i.start,
}));
const body = {
name: form.name.trim(),
genericName: form.genericName.trim() || null,
takenBy: form.takenBy.length > 0 ? form.takenBy : [],
packageType: form.packageType,
packCount: Number(form.packCount) || 0,
blistersPerPack: Number(form.blistersPerPack) || 1,
pillsPerBlister: Number(form.pillsPerBlister) || 1,
totalPills: Number(form.totalPills) || null,
looseTablets: Number(form.looseTablets) || 0,
pillWeightMg: Number(form.pillWeightMg) || null,
doseUnit: form.doseUnit,
expiryDate: form.expiryDate || null,
notes: form.notes.trim() || null,
intakeRemindersEnabled: form.intakeRemindersEnabled,
blisters,
blisters, // Legacy format for backward compatibility
intakes, // New format with per-intake takenBy
};
try {
@@ -192,6 +214,7 @@ export function MedicationsPage() {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
credentials: "include",
});
if (!res.ok) {
@@ -308,7 +331,7 @@ export function MedicationsPage() {
</div>
<div className="med-list">
{meds.map((med) => (
<div key={med.id} className="med-row">
<div key={med.id} className={`med-row${editingId === med.id ? " editing" : ""}`}>
<div className="med-header">
<div className="med-info">
<div className="med-name-row">
@@ -317,20 +340,46 @@ export function MedicationsPage() {
</div>
<div className="med-details">
<span>
{t("medications.details.packs")}: <strong>{med.packCount}</strong>
</span>
<span>
{t("medications.details.blisters")}: <strong>{med.blistersPerPack}</strong>
</span>
<span>
{t("medications.details.pillsPerBlister")}: <strong>{med.pillsPerBlister}</strong>
</span>
<span>
{t("medications.details.loose")}: <strong>{med.looseTablets}</strong>
{t("medications.details.type")}:{" "}
<strong>
{med.packageType === "bottle" ? t("form.packageTypeBottle") : t("form.packageTypeBlister")}
</strong>
</span>
{med.packageType === "blister" ? (
<>
<span>
{t("medications.details.packs")}: <strong>{med.packCount}</strong>
</span>
<span>
{t("medications.details.blisters")}: <strong>{med.blistersPerPack}</strong>
</span>
<span>
{t("medications.details.pillsPerBlister")}: <strong>{med.pillsPerBlister}</strong>
</span>
<span>
{t("medications.details.loose")}: <strong>{med.looseTablets}</strong>
</span>
</>
) : (
<span>
{t("medications.details.totalCapacity")}: <strong>{med.totalPills ?? med.looseTablets}</strong>
</span>
)}
</div>
<div className="med-total">
{t("medications.details.total")}: {getPackageSize(med)} {t("common.pills")}
{t("medications.details.stock")}:{" "}
{coverageByMed[med.name] ? Math.round(coverageByMed[med.name].medsLeft) : getPackageSize(med)} /{" "}
{getPackageSize(med)} {getPackageSize(med) === 1 ? t("common.pill") : t("common.pills")}
{(coverageByMed[med.name] ? Math.round(coverageByMed[med.name].medsLeft) : getPackageSize(med)) >
getPackageSize(med) && (
<span
className="info-tooltip tooltip-align-left warning-text"
data-tooltip={t("tooltips.stockExceedsCapacity")}
>
{" "}
</span>
)}
</div>
</div>
<div className="med-actions">
@@ -358,7 +407,20 @@ export function MedicationsPage() {
<article className="card form desktop-only">
<div className="card-head">
<h2>{editingId ? t("form.editEntry") : t("form.newEntry")}</h2>
{editingId ? (
<div className="edit-header">
<MedicationAvatar
name={meds.find((m) => m.id === editingId)?.name || ""}
imageUrl={meds.find((m) => m.id === editingId)?.imageUrl}
size="md"
/>
<h2>
{t("form.editEntry")}: {meds.find((m) => m.id === editingId)?.name}
</h2>
</div>
) : (
<h2>{t("form.newEntry")}</h2>
)}
</div>
<form className="form-grid" onSubmit={saveMedication}>
<label className={fieldErrors.name ? "has-error" : ""}>
@@ -417,50 +479,100 @@ export function MedicationsPage() {
{fieldErrors.takenBy && <span className="field-error">{fieldErrors.takenBy}</span>}
</label>
<label>
{t("form.packs")}
<input
type="number"
min="0"
value={form.packCount}
onChange={(e) => handleValueChange("packCount", e.target.value)}
/>
{t("form.packageType")}
<select
className="package-type-select"
value={form.packageType}
onChange={(e) => handleValueChange("packageType", e.target.value)}
>
<option value="blister">{t("form.packageTypeBlister")}</option>
<option value="bottle">{t("form.packageTypeBottle")}</option>
</select>
</label>
<label>
{t("form.blistersPerPack")}
<input
type="number"
min="1"
value={form.blistersPerPack}
onChange={(e) => handleValueChange("blistersPerPack", e.target.value)}
/>
</label>
<label>
{t("form.pillsPerBlister")}
<input
type="number"
min="1"
value={form.pillsPerBlister}
onChange={(e) => handleValueChange("pillsPerBlister", e.target.value)}
/>
</label>
<label>
{t("form.loosePills")}
<input
type="number"
min="0"
value={form.looseTablets}
onChange={(e) => handleValueChange("looseTablets", e.target.value)}
/>
</label>
<label>
{t("form.pillWeight")}
<input
type="number"
min="1"
value={form.pillWeightMg}
onChange={(e) => handleValueChange("pillWeightMg", e.target.value)}
placeholder={t("form.placeholders.weight")}
/>
{form.packageType === "blister" ? (
<>
<label>
{t("form.packs")}
<input
type="number"
min="0"
value={form.packCount}
onChange={(e) => handleValueChange("packCount", e.target.value)}
/>
</label>
<label>
{t("form.blistersPerPack")}
<input
type="number"
min="1"
value={form.blistersPerPack}
onChange={(e) => handleValueChange("blistersPerPack", e.target.value)}
/>
</label>
<label>
{t("form.pillsPerBlister")}
<input
type="number"
min="1"
value={form.pillsPerBlister}
onChange={(e) => handleValueChange("pillsPerBlister", e.target.value)}
/>
</label>
<label>
{t("form.loosePills")}
<input
type="number"
min="0"
value={form.looseTablets}
onChange={(e) => handleValueChange("looseTablets", e.target.value)}
/>
</label>
</>
) : (
<>
<label>
{t("form.totalCapacity")}
<input
type="number"
min="1"
value={form.totalPills}
onChange={(e) => handleValueChange("totalPills", e.target.value)}
/>
</label>
<label>
{t("form.currentPills")}
<input
type="number"
min="0"
value={form.looseTablets}
onChange={(e) => handleValueChange("looseTablets", e.target.value)}
/>
</label>
</>
)}
<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) => handleValueChange("pillWeightMg", e.target.value)}
placeholder={t("form.placeholders.weight")}
/>
<select
value={form.doseUnit}
onChange={(e) => handleValueChange("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>
{t("form.total")}
@@ -481,24 +593,38 @@ export function MedicationsPage() {
<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) => setRefillPacks(parseInt(e.target.value, 10) || 0)}
/>
</label>
<label>
{t("refill.loosePills")}
<input
type="number"
min="0"
value={refillLoose}
onChange={(e) => setRefillLoose(parseInt(e.target.value, 10) || 0)}
/>
</label>
{form.packageType === "blister" ? (
<>
<label>
{t("refill.packs")}
<input
type="number"
min="0"
value={refillPacks}
onChange={(e) => setRefillPacks(parseInt(e.target.value, 10) || 0)}
/>
</label>
<label>
{t("refill.loosePills")}
<input
type="number"
min="0"
value={refillLoose}
onChange={(e) => setRefillLoose(parseInt(e.target.value, 10) || 0)}
/>
</label>
</>
) : (
<label>
{t("refill.pillsToAdd")}
<input
type="number"
min="0"
value={refillLoose}
onChange={(e) => setRefillLoose(parseInt(e.target.value, 10) || 0)}
/>
</label>
)}
<button
type="button"
className="success"
@@ -507,12 +633,18 @@ export function MedicationsPage() {
>
{refillSaving ? t("refill.adding") : 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>
)}
{(() => {
const totalRefill =
form.packageType === "blister"
? refillPacks * Number(form.blistersPerPack || 0) * Number(form.pillsPerBlister || 1) +
refillLoose
: refillLoose;
return totalRefill > 0 ? (
<span className="refill-preview">
+{totalRefill} {totalRefill === 1 ? t("common.pill") : t("common.pills")}
</span>
) : null;
})()}
</div>
</div>
)}
@@ -544,20 +676,16 @@ export function MedicationsPage() {
<div className="card-head">
<h3>{t("form.blisters.title")}</h3>
<div className="blisters-actions">
<label className="inline-checkbox" title={t("form.blisters.remindTooltip")}>
<input
type="checkbox"
checked={form.intakeRemindersEnabled}
onChange={(e) => setForm((prev) => ({ ...prev, intakeRemindersEnabled: e.target.checked }))}
/>
<span>🔔 {t("form.blisters.remind")}</span>
</label>
<button type="button" className="primary" onClick={addBlister}>
<button
type="button"
className="primary"
onClick={() => addIntake(form.takenBy.length === 1 ? form.takenBy[0] : undefined)}
>
+ {t("form.blisters.addIntake")}
</button>
</div>
</div>
{form.blisters.map((s, idx) => (
{form.intakes.map((intake, idx) => (
<div key={idx} className="blister-row">
<div className="blister-inputs">
<label>
@@ -566,8 +694,8 @@ export function MedicationsPage() {
type="number"
min="0"
step="0.1"
value={s.usage}
onChange={(e) => setBlisterValue(idx, "usage", e.target.value)}
value={intake.usage}
onChange={(e) => setIntakeValue(idx, "usage", e.target.value)}
/>
</label>
<label>
@@ -575,29 +703,52 @@ export function MedicationsPage() {
<input
type="number"
min="1"
value={s.every}
onChange={(e) => setBlisterValue(idx, "every", e.target.value)}
value={intake.every}
onChange={(e) => setIntakeValue(idx, "every", e.target.value)}
/>
</label>
<label>
{t("form.blisters.startDate")}
<input
type="date"
value={s.startDate}
onChange={(e) => setBlisterValue(idx, "startDate", e.target.value)}
value={intake.startDate}
onChange={(e) => setIntakeValue(idx, "startDate", e.target.value)}
/>
</label>
<label>
{t("form.blisters.startTime")}
<input
type="time"
value={s.startTime}
onChange={(e) => setBlisterValue(idx, "startTime", e.target.value)}
value={intake.startTime}
onChange={(e) => setIntakeValue(idx, "startTime", e.target.value)}
/>
</label>
{form.takenBy.length === 0 ? null : (
<label title={t("form.blisters.takenByTooltip")}>
{t("form.blisters.takenByIntake")}
<select value={intake.takenBy} onChange={(e) => setIntakeValue(idx, "takenBy", e.target.value)}>
{form.takenBy.map((person) => (
<option key={person} value={person}>
{person}
</option>
))}
</select>
</label>
)}
<div className="remind-toggle-row" title={t("form.blisters.remindTooltip")}>
<span>🔔</span>
<label className="toggle-switch small">
<input
type="checkbox"
checked={intake.intakeRemindersEnabled}
onChange={(e) => setIntakeValue(idx, "intakeRemindersEnabled", e.target.checked)}
/>
<span className="toggle-slider"></span>
</label>
</div>
</div>
{form.blisters.length > 1 && (
<button type="button" className="danger" onClick={() => removeBlister(idx)}>
{form.intakes.length > 1 && (
<button type="button" className="danger" onClick={() => removeIntake(idx)}>
{t("common.remove")}
</button>
)}
@@ -702,6 +853,9 @@ export function MedicationsPage() {
onSetBlisterValue={setBlisterValue}
onAddBlister={addBlister}
onRemoveBlister={removeBlister}
onSetIntakeValue={setIntakeValue}
onAddIntake={addIntake}
onRemoveIntake={removeIntake}
onHandleValueChange={handleValueChange}
refillPacks={refillPacks}
onRefillPacksChange={setRefillPacks}
+54 -13
View File
@@ -41,6 +41,7 @@ export function PlannerPage() {
start: toInputValue(todayIso()),
end: toInputValue(plusDaysIso(3)),
});
const [includeUntilStart, setIncludeUntilStart] = useState(false);
const [sendingPlannerEmail, setSendingPlannerEmail] = useState(false);
const [plannerEmailResult, setPlannerEmailResult] = useState<{ success: boolean; message: string } | null>(null);
@@ -49,6 +50,7 @@ export function PlannerPage() {
if (typeof window !== "undefined" && user?.id) {
const savedRows = localStorage.getItem(userStorageKey(user.id, "plannerRows"));
const savedRange = localStorage.getItem(userStorageKey(user.id, "plannerRange"));
const savedIncludeUntilStart = localStorage.getItem(userStorageKey(user.id, "plannerIncludeUntilStart"));
if (savedRows) {
try {
@@ -69,19 +71,27 @@ export function PlannerPage() {
} else {
setRange({ start: toInputValue(todayIso()), end: toInputValue(plusDaysIso(3)) });
}
if (savedIncludeUntilStart) {
setIncludeUntilStart(savedIncludeUntilStart === "true");
} else {
setIncludeUntilStart(false);
}
} else {
setPlannerRows([]);
setRange({ start: toInputValue(todayIso()), end: toInputValue(plusDaysIso(3)) });
setIncludeUntilStart(false);
}
}, [user?.id]);
async function runPlanner(e: React.FormEvent) {
e.preventDefault();
setPlannerLoading(true);
const body = { startDate: toIsoString(range.start), endDate: toIsoString(range.end) };
const body = { startDate: toIsoString(range.start), endDate: toIsoString(range.end), includeUntilStart };
const rows = (await fetch("/api/medications/usage", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify(body),
})
.then((res) => res.json())
@@ -92,20 +102,26 @@ export function PlannerPage() {
if (user?.id) {
localStorage.setItem(userStorageKey(user.id, "plannerRange"), JSON.stringify(range));
localStorage.setItem(userStorageKey(user.id, "plannerRows"), JSON.stringify(rows));
localStorage.setItem(userStorageKey(user.id, "plannerIncludeUntilStart"), String(includeUntilStart));
}
}
function resetRange() {
setRange({ start: toInputValue(todayIso()), end: toInputValue(plusDaysIso(3)) });
setIncludeUntilStart(false);
setPlannerRows([]);
if (user?.id) {
localStorage.removeItem(userStorageKey(user.id, "plannerRange"));
localStorage.removeItem(userStorageKey(user.id, "plannerRows"));
localStorage.removeItem(userStorageKey(user.id, "plannerIncludeUntilStart"));
}
}
async function sendPlannerEmail() {
if (!settings.notificationEmail || plannerRows.length === 0) return;
const canSendNotification =
(settings.emailEnabled && settings.notificationEmail) || (settings.shoutrrrEnabled && settings.shoutrrrUrl);
async function sendPlannerNotification() {
if (!canSendNotification || plannerRows.length === 0) return;
setSendingPlannerEmail(true);
setPlannerEmailResult(null);
@@ -113,6 +129,7 @@ export function PlannerPage() {
const res = await fetch("/api/planner/send-email", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
email: settings.notificationEmail,
from: range.start,
@@ -122,12 +139,12 @@ export function PlannerPage() {
});
const data = await res.json();
if (res.ok) {
setPlannerEmailResult({ success: true, message: data.message || "Email sent!" });
setPlannerEmailResult({ success: true, message: data.message || t("common.sent") });
} else {
setPlannerEmailResult({ success: false, message: data.error || "Failed to send" });
setPlannerEmailResult({ success: false, message: data.error || t("common.sendFailed") });
}
} catch {
setPlannerEmailResult({ success: false, message: "Network error" });
setPlannerEmailResult({ success: false, message: t("common.networkError") });
}
setSendingPlannerEmail(false);
}
@@ -157,6 +174,17 @@ export function PlannerPage() {
onChange={(e) => setRange({ ...range, end: e.target.value })}
/>
</label>
<label className="planner-checkbox">
<input
type="checkbox"
checked={includeUntilStart}
onChange={(e) => setIncludeUntilStart(e.target.checked)}
/>
{t("planner.includeUntilStart")}
<span className="info-tooltip small" data-tooltip={t("planner.includeUntilStartTooltip")}>
</span>
</label>
<div className="planner-actions">
<button type="button" className="ghost" onClick={resetRange}>
{t("common.reset")}
@@ -185,14 +213,22 @@ export function PlannerPage() {
{row.medicationName}
</span>
<span data-label={t("planner.table.usage")}>
<strong>{row.plannerUsage}</strong>&nbsp;{t("common.pills")}
<strong>{row.plannerUsage}</strong>&nbsp;
{row.plannerUsage === 1 ? t("common.pill") : t("common.pills")}
</span>
<span data-label={t("planner.table.blisters")}>
{row.blistersNeeded} × {row.blisterSize}
{row.packageType === "bottle" ? "" : `${row.blistersNeeded} × ${row.blisterSize}`}
</span>
<span data-label={t("planner.table.available")}>
{row.fullBlisters} {t("common.blisters")}
{row.loosePills > 0 && ` + ${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`}
{row.packageType === "bottle" ? (
`${Math.round(row.loosePills * 10) / 10} ${Math.round(row.loosePills * 10) / 10 === 1 ? t("common.pill") : t("common.pills")}`
) : (
<>
{row.fullBlisters} {t("common.blisters")}
{row.loosePills > 0 &&
` + ${Math.round(row.loosePills * 10) / 10} ${Math.round(row.loosePills * 10) / 10 === 1 ? t("common.pill") : t("common.pills")}`}
</>
)}
</span>
<span
data-label={t("table.status")}
@@ -204,10 +240,15 @@ export function PlannerPage() {
);
})}
</div>
{settings.emailEnabled && settings.notificationEmail && (
{canSendNotification && (
<div className="planner-email-action">
<button type="button" className="ghost" onClick={sendPlannerEmail} disabled={sendingPlannerEmail}>
{sendingPlannerEmail ? t("common.sending") : t("planner.sendEmail")}
<button
type="button"
className="ghost"
onClick={sendPlannerNotification}
disabled={sendingPlannerEmail}
>
{sendingPlannerEmail ? t("common.sending") : t("planner.sendNotification")}
</button>
{plannerEmailResult && (
<span className={plannerEmailResult.success ? "success-text" : "danger-text"}>
+30 -38
View File
@@ -3,21 +3,30 @@ import { MedicationAvatar } from "../components";
import { useAuth } from "../components/Auth";
import { useAppContext } from "../context";
import type { Coverage } from "../types";
import { expandDoseIds } from "../utils/schedule";
// Helper for user-specific localStorage keys
function userStorageKey(userId: number | undefined, key: string): string {
return userId ? `user_${userId}_${key}` : key;
}
// Helper function to get stock status
// Helper function to get stock status based on thresholds
function getStockStatus(
daysLeft: number | null,
medsLeft: number,
settings: { lowStockDays: number; normalStockDays: number; highStockDays: number }
settings: { lowStockDays: number; normalStockDays: number; highStockDays: number; reminderDaysBefore: number }
) {
if (medsLeft <= 0 || daysLeft === null || daysLeft <= 0) return { className: "danger", label: "status.outOfStock" };
if (daysLeft <= settings.lowStockDays) return { className: "danger", label: "status.lowStock" };
if (daysLeft >= settings.highStockDays) return { className: "success", label: "status.highStock" };
// Out of stock or completely depleted = danger (red)
if (medsLeft <= 0 || daysLeft === 0) return { className: "danger", label: "status.outOfStock" };
// No schedule, but has stock = normal
if (daysLeft === null) return { className: "success", label: "status.noSchedule" };
// Critical: at or below reminder threshold = danger (red)
if (daysLeft <= settings.reminderDaysBefore) return { className: "danger", label: "status.criticalStock" };
// Low: below low stock threshold = warning (yellow)
if (daysLeft < settings.lowStockDays) return { className: "warning", label: "status.lowStock" };
// High stock
if (daysLeft >= settings.highStockDays) return { className: "high", label: "status.highStock" };
// Normal stock
return { className: "success", label: "status.normal" };
}
@@ -25,7 +34,7 @@ function getStockStatus(
function getDayStockStatus(
dayMeds: Array<{ medName: string }>,
coverageByMed: Record<string, Coverage>,
settings: { lowStockDays: number; normalStockDays: number; highStockDays: number }
settings: { lowStockDays: number; normalStockDays: number; highStockDays: number; reminderDaysBefore: number }
): string {
let worstLevel = 3; // 3=success, 2=warning, 1=danger
for (const item of dayMeds) {
@@ -63,6 +72,7 @@ export function SchedulePage() {
manuallyExpandedDays,
toggleDayCollapse,
openUserFilter,
missedPastDoseIds,
} = useAppContext();
return (
@@ -88,17 +98,11 @@ export function SchedulePage() {
{/* Past days toggle */}
{pastDays.length > 0 &&
(() => {
const totalPastDoses = pastDays.flatMap((d) =>
d.meds.flatMap((m) =>
m.doses.flatMap((dose) =>
(dose.takenBy || []).length > 0 ? dose.takenBy.map((p) => `${dose.id}-${p}`) : [dose.id]
)
)
);
const missedPastDoses = totalPastDoses.filter((id) => !takenDoses.has(id)).length;
// Use context's missedPastDoseIds which handles dismissed doses and previous schedule detection
const missedCount = missedPastDoseIds.length;
return (
<div
className={`past-days-toggle ${showPastDays ? "expanded" : ""} ${missedPastDoses > 0 ? "has-missed" : ""}`}
className={`past-days-toggle ${showPastDays ? "expanded" : ""} ${missedCount > 0 ? "has-missed" : ""}`}
onClick={() => setShowPastDays(!showPastDays)}
>
<span className="past-days-icon">{showPastDays ? "▼" : "▶"}</span>
@@ -108,12 +112,12 @@ export function SchedulePage() {
<span className="past-days-count">
({t("dashboard.schedules.pastDaysCount", { count: pastDays.length })})
</span>
{missedPastDoses > 0 && (
{missedCount > 0 && (
<span
className="past-days-warning"
title={t("dashboard.schedules.missedDoses", { count: missedPastDoses })}
title={t("dashboard.schedules.missedDoses", { count: missedCount })}
>
{missedPastDoses}
{missedCount}
</span>
)}
</div>
@@ -122,11 +126,7 @@ export function SchedulePage() {
{/* Past days (when expanded) */}
{showPastDays &&
pastDays.map((day) => {
const allDoseIds = day.meds.flatMap((item) =>
item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
)
);
const allDoseIds = day.meds.flatMap((item) => expandDoseIds(item.doses));
const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id));
const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length;
const isManuallyExpanded = manuallyExpandedDays.has(day.dateStr);
@@ -136,7 +136,7 @@ export function SchedulePage() {
return (
<div
key={day.dateStr}
className={`day-block past ${isCollapsed ? "collapsed" : ""} ${allDayTaken ? "all-taken" : ""} stock-${worstStatus}`}
className={`day-block past ${isCollapsed ? "collapsed" : ""} ${allDayTaken ? "all-taken" : allDoseIds.length > 0 ? "past-missed" : ""}`}
>
<div
className="day-divider clickable"
@@ -168,9 +168,7 @@ export function SchedulePage() {
const med = meds.find((m) => m.name === item.medName);
const medCov = coverageByMed[item.medName];
const isEmpty = medCov ? medCov.medsLeft <= 0 : false;
const itemDoseIds = item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
);
const itemDoseIds = expandDoseIds(item.doses);
const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
@@ -188,9 +186,7 @@ export function SchedulePage() {
)}
</div>
<div className="tag-row">
<span className="tag subtle">
{item.total} {t("common.pills")} {t("common.total")}
</span>
<span className="tag subtle">{t("common.pillsTotal", { count: item.total })}</span>
</div>
</div>
<div className="doses-col">
@@ -202,7 +198,7 @@ export function SchedulePage() {
<span className="dose-time">{dose.timeStr}</span>
<span className="dose-usage">
{dose.usage} {dose.usage !== 1 ? t("common.pills") : t("common.pill")}
{med?.pillWeightMg && ` (${dose.usage * med.pillWeightMg} mg)`}
{med?.pillWeightMg && ` (${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"})`}
</span>
<div className="dose-checks">
{people.map((person) => {
@@ -272,9 +268,7 @@ export function SchedulePage() {
: medCoverage
? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings)
: null;
const itemDoseIds = item.doses.flatMap((d) =>
(d.takenBy || []).length > 0 ? d.takenBy.map((p) => `${d.id}-${p}`) : [d.id]
);
const itemDoseIds = expandDoseIds(item.doses);
const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
@@ -289,9 +283,7 @@ export function SchedulePage() {
)}
</div>
<div className="tag-row">
<span className="tag subtle">
{item.total} {t("common.pills")} {t("common.total")}
</span>
<span className="tag subtle">{t("common.pillsTotal", { count: item.total })}</span>
{status && <span className={`tag ${status.className}`}>{t(status.label)}</span>}
</div>
</div>
@@ -306,7 +298,7 @@ export function SchedulePage() {
<span className="dose-time">{dose.timeStr}</span>
<span className="dose-usage">
{dose.usage} {dose.usage !== 1 ? t("common.pills") : t("common.pill")}
{med?.pillWeightMg && ` (${dose.usage * med.pillWeightMg} mg)`}
{med?.pillWeightMg && ` (${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"})`}
</span>
<div className="dose-checks">
{people.map((person) => {
+166 -60
View File
@@ -236,6 +236,75 @@ export function SettingsPage() {
)}
</div>
<div className="setting-section">
<div className="section-header">
<h3>{t("settings.stockReminder.title")}</h3>
</div>
<div className="setting-row compact">
<label className="setting-label">
{t("settings.stockReminder.description")}{" "}
<span className="status-chip small danger">{t("status.criticalStock")}</span>
</label>
<label
className={`toggle-switch small${!settings.emailEnabled && !settings.shoutrrrEnabled ? " disabled" : ""}`}
>
<input
type="checkbox"
checked={
(settings.emailEnabled && settings.emailStockReminders) ||
(settings.shoutrrrEnabled && settings.shoutrrrStockReminders)
}
onChange={(e) => {
const newVal = e.target.checked;
if (newVal) {
setSettings({
...settings,
emailStockReminders: settings.emailEnabled ? true : settings.emailStockReminders,
shoutrrrStockReminders: settings.shoutrrrEnabled ? true : settings.shoutrrrStockReminders,
});
} else {
setSettings({
...settings,
emailStockReminders: false,
shoutrrrStockReminders: false,
repeatDailyReminders: false,
});
}
}}
disabled={!settings.emailEnabled && !settings.shoutrrrEnabled}
/>
<span className="toggle-slider"></span>
</label>
</div>
<div className="setting-row compact" style={{ marginTop: "4px" }}>
<label className="setting-label">
{t("settings.stockReminder.repeatDaily")}
<span
className="info-tooltip small tooltip-align-left"
data-tooltip={t("settings.stockReminder.repeatTooltip")}
>
</span>
</label>
<label
className={`toggle-switch small${!((settings.emailEnabled && settings.emailStockReminders) || (settings.shoutrrrEnabled && settings.shoutrrrStockReminders)) ? " disabled" : ""}`}
>
<input
type="checkbox"
checked={settings.repeatDailyReminders}
onChange={(e) => setSettings({ ...settings, repeatDailyReminders: e.target.checked })}
disabled={
!(
(settings.emailEnabled && settings.emailStockReminders) ||
(settings.shoutrrrEnabled && settings.shoutrrrStockReminders)
)
}
/>
<span className="toggle-slider"></span>
</label>
</div>
</div>
<div className="setting-section">
<div className="section-header">
<h3>{t("settings.notifications.email")}</h3>
@@ -400,9 +469,23 @@ export function SettingsPage() {
</span>
</div>
)}
{settings.lastStockReminderSent && (
<div className="schedule-row">
<span className="schedule-label">{t("settings.schedule.lastStockSent")}</span>
<span className="schedule-value">
{new Date(settings.lastStockReminderSent).toLocaleString(getSystemLocale(i18n.language), {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
})}
</span>
</div>
)}
{settings.lastAutoEmailSent && (
<div className="schedule-row">
<span className="schedule-label">{t("settings.schedule.lastSent")}</span>
<span className="schedule-label">{t("settings.schedule.lastIntakeSent")}</span>
<span className="schedule-value">
{new Date(settings.lastAutoEmailSent).toLocaleString(getSystemLocale(i18n.language), {
day: "2-digit",
@@ -423,51 +506,6 @@ export function SettingsPage() {
<h2>{t("settings.stock.title")}</h2>
</div>
<div className="setting-section">
<div className="section-header">
<h3>{t("settings.stock.threshold")}</h3>
</div>
<div className="threshold-input">
<label>
<span className="threshold-label">{t("settings.stock.remindWhen")}</span>
<div className="threshold-field">
<input
type="number"
min="1"
max="90"
value={settings.reminderDaysBefore}
onChange={(e) => setSettings({ ...settings, reminderDaysBefore: Number(e.target.value) || 7 })}
/>
<span className="threshold-unit">{t("common.days")}</span>
</div>
</label>
</div>
<div className="setting-row compact">
<label className="setting-label">
{t("settings.stock.repeatDaily")}
<span className="info-tooltip small" data-tooltip={t("settings.stock.repeatTooltip")}>
</span>
</label>
<label
className={`toggle-switch small${!((settings.emailEnabled && settings.emailStockReminders && settings.notificationEmail) || (settings.shoutrrrEnabled && settings.shoutrrrStockReminders && settings.shoutrrrUrl)) ? " disabled" : ""}`}
>
<input
type="checkbox"
checked={settings.repeatDailyReminders}
onChange={(e) => setSettings({ ...settings, repeatDailyReminders: e.target.checked })}
disabled={
!(
(settings.emailEnabled && settings.emailStockReminders && settings.notificationEmail) ||
(settings.shoutrrrEnabled && settings.shoutrrrStockReminders && settings.shoutrrrUrl)
)
}
/>
<span className="toggle-slider"></span>
</label>
</div>
</div>
<div className="setting-section">
<div className="section-header">
<h3>{t("settings.stock.calculationMode")}</h3>
@@ -512,40 +550,100 @@ export function SettingsPage() {
<div className="setting-section">
<div className="section-header">
<h3>{t("settings.stock.display")}</h3>
<h3>{t("settings.stock.thresholds")}</h3>
</div>
<div className="setting-group">
<label>
<span className="field-label">{t("settings.stock.lowStockDays")}</span>
<div className="setting-group threshold-chips-group">
<label className={settings.reminderDaysBefore >= settings.lowStockDays ? "threshold-invalid" : ""}>
<span className="field-label threshold-chip-label">
<span className="status-chip small danger">{t("status.criticalStock")}</span>
<span
className="info-tooltip small tooltip-align-left"
data-tooltip={t("settings.stock.criticalStockTooltip")}
>
</span>
</span>
<div className="input-with-tooltip">
<input
type="number"
min="1"
max="364"
value={settings.reminderDaysBefore}
onChange={(e) => setSettings({ ...settings, reminderDaysBefore: Number(e.target.value) || 7 })}
/>
</div>
</label>
<label
className={
settings.lowStockDays <= settings.reminderDaysBefore ||
settings.lowStockDays >= settings.highStockDays
? "threshold-invalid"
: ""
}
>
<span className="field-label threshold-chip-label">
<span className="status-chip small warning">{t("status.lowStock")}</span>
<span
className="info-tooltip small tooltip-align-left"
data-tooltip={t("settings.stock.lowStockTooltip")}
>
</span>
</span>
<div className="input-with-tooltip">
<input
type="number"
min="2"
max="365"
value={settings.lowStockDays}
onChange={(e) => setSettings({ ...settings, lowStockDays: Number(e.target.value) || 30 })}
/>
<span className="info-tooltip" data-tooltip={t("settings.stock.lowStockTooltip")}>
</span>
</div>
</label>
<label>
<span className="field-label">{t("settings.stock.highStockDays")}</span>
<label className={settings.highStockDays <= settings.lowStockDays ? "threshold-invalid" : ""}>
<span className="field-label threshold-chip-label">
<span className="status-chip small high">{t("status.highStock")}</span>
<span
className="info-tooltip small tooltip-align-left"
data-tooltip={t("settings.stock.highStockTooltip")}
>
</span>
</span>
<div className="input-with-tooltip">
<input
type="number"
min="1"
min="3"
max="730"
value={settings.highStockDays}
onChange={(e) => setSettings({ ...settings, highStockDays: Number(e.target.value) || 180 })}
/>
<span className="info-tooltip" data-tooltip={t("settings.stock.highStockTooltip")}>
</span>
</div>
</label>
</div>
{(settings.reminderDaysBefore >= settings.lowStockDays ||
settings.lowStockDays >= settings.highStockDays) && (
<p className="threshold-validation-error">{t("settings.stock.thresholdValidation")}</p>
)}
</div>
<div className="setting-section">
<div className="setting-row compact">
<div className="setting-label">
<span>{t("settings.stock.shareStockStatus")}</span>
<span className="info-tooltip small" data-tooltip={t("settings.stock.shareStockStatusDesc")}>
</span>
</div>
<label className="toggle-switch small">
<input
type="checkbox"
checked={settings.shareStockStatus}
onChange={(e) => setSettings({ ...settings, shareStockStatus: e.target.checked })}
/>
<span className="toggle-slider"></span>
</label>
</div>
</div>
</article>
@@ -651,7 +749,15 @@ export function SettingsPage() {
</article>
<div className="form-footer">
<button type="submit" disabled={settingsSaving || (!settingsChanged && settingsSaved)}>
<button
type="submit"
disabled={
settingsSaving ||
(!settingsChanged && settingsSaved) ||
settings.reminderDaysBefore >= settings.lowStockDays ||
settings.lowStockDays >= settings.highStockDays
}
>
{settingsSaving
? t("common.saving")
: settingsSaved && !settingsChanged
+432 -35
View File
@@ -152,6 +152,90 @@ body.modal-open {
background: rgba(47, 134, 246, 0.12);
}
/* =============================================================================
Theme Dropdown Menu
============================================================================= */
.theme-menu {
position: relative;
}
.theme-dropdown {
position: absolute;
top: calc(100% + 0.5rem);
right: 0;
min-width: 160px;
background: rgba(15, 23, 42, 0.85);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px;
box-shadow:
0 12px 32px rgba(0, 0, 0, 0.4),
inset 0 0 0 1px rgba(255, 255, 255, 0.05);
opacity: 0;
visibility: hidden;
transform: translateY(-6px) scale(0.95);
transition: all 0.2s ease;
z-index: 1000;
overflow: hidden;
padding: 0.375rem;
}
[data-theme="light"] .theme-dropdown {
background: rgba(255, 255, 255, 0.85);
border: 1px solid rgba(0, 0, 0, 0.08);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
}
.theme-menu.open .theme-dropdown {
opacity: 1;
visibility: visible;
transform: translateY(0) scale(1);
}
.theme-dropdown-item {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
padding: 0.625rem 0.75rem;
border: none;
background: none;
color: var(--text-primary);
font-size: 0.875rem;
cursor: pointer;
border-radius: 8px;
transition: background 0.15s ease;
text-align: left;
box-shadow: none;
}
.theme-dropdown-item:hover {
background: rgba(59, 130, 246, 0.15);
}
.theme-dropdown-item.active {
color: var(--accent-primary);
}
.theme-dropdown-item svg {
width: 18px;
height: 18px;
flex-shrink: 0;
opacity: 0.7;
}
.theme-dropdown-item.active svg {
opacity: 1;
color: var(--accent-primary);
}
.theme-check {
margin-left: auto;
font-size: 0.8rem;
opacity: 0.8;
}
.hero-title {
display: flex;
align-items: center;
@@ -195,7 +279,7 @@ body.modal-open {
.reminder-status-header {
display: flex;
align-items: center;
gap: 0.5rem;
gap: 0.75rem;
flex-wrap: wrap;
}
@@ -212,11 +296,10 @@ body.modal-open {
}
.reminder-status-badge {
padding: 0.2rem 0.5rem;
border-radius: 4px;
padding: 0.25rem 0.6rem;
border-radius: 6px;
font-size: 0.75rem;
font-weight: 500;
margin-left: auto;
}
.reminder-status-badge.success {
@@ -282,6 +365,56 @@ body.modal-open {
color: var(--text-secondary);
}
.reminder-days-left {
color: var(--warning);
font-size: 0.8rem;
}
.critical .reminder-days-left {
color: var(--danger);
}
.reminder-send-row {
display: flex;
align-items: center;
gap: 0.75rem;
padding-left: 1.75rem;
padding-top: 0.25rem;
}
.reminder-send-row .ghost {
font-size: 0.8rem;
padding: 0.25rem 0.75rem;
}
.reminder-send-result {
font-size: 0.8rem;
}
.reminder-send-result.success {
color: var(--success);
}
.reminder-send-result.error {
color: var(--danger);
}
.med-link {
font-weight: 600;
text-decoration: underline;
text-decoration-style: dotted;
text-underline-offset: 2px;
}
.med-link.clickable {
cursor: pointer;
}
.med-link.clickable:hover {
color: var(--accent);
text-decoration-style: solid;
}
@media (max-width: 600px) {
.reminder-status-bar {
padding: 0.75rem;
@@ -300,6 +433,9 @@ body.modal-open {
flex-direction: column;
gap: 0.15rem;
}
.reminder-low-stock-list {
padding-left: 0;
}
}
.tabs {
@@ -362,7 +498,6 @@ body.modal-open {
border-radius: 14px;
padding: 1.25rem;
box-shadow: 0 14px 36px var(--shadow);
overflow: hidden;
transition:
background 200ms ease,
border-color 200ms ease;
@@ -387,6 +522,19 @@ body.modal-open {
color: var(--accent-light);
}
.edit-header {
display: flex;
align-items: center;
gap: 0.75rem;
}
.edit-header h2 {
margin: 0;
font-size: 1.1rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.schedule-full {
max-width: 100%;
}
@@ -468,6 +616,11 @@ body.modal-open {
background 200ms ease,
border-color 200ms ease;
}
.med-row.editing {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 8%, var(--bg-tertiary));
box-shadow: 0 0 0 1px var(--accent);
}
.med-header {
display: flex;
justify-content: space-between;
@@ -928,6 +1081,27 @@ textarea.auto-resize {
gap: 0.75rem;
}
/* Package type selector - simple dropdown style */
.package-type-select {
width: 100%;
padding: 0.6rem 2rem 0.6rem 0.75rem;
font-size: 0.9rem;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
color: var(--text-primary);
cursor: pointer;
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236b7280' d='M2 4l4 4 4-4'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 0.75rem center;
}
.package-type-select:focus {
outline: none;
border-color: var(--accent);
}
/* Form field validation */
.form-grid label.has-error input,
.form-grid label.has-error textarea {
@@ -949,6 +1123,42 @@ textarea.auto-resize {
margin-top: 0.25rem;
}
/* Dose input with unit selector */
.dose-input-group {
display: flex;
gap: 0.5rem;
align-items: stretch;
}
.dose-input-group input {
flex: 1;
min-width: 100px;
}
.dose-unit-select {
width: auto;
min-width: unset;
max-width: 120px;
flex-shrink: 0;
padding: 0.5rem 0.75rem;
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--input-radius);
color: var(--text-primary);
font-size: 0.9rem;
cursor: pointer;
transition: border-color 150ms ease;
}
.dose-unit-select:focus {
outline: none;
border-color: var(--accent);
}
.dose-unit-select:hover {
border-color: var(--accent);
}
/* Tag input for multi-value fields (e.g., Taken By) */
.tag-input-container {
display: flex;
@@ -1230,6 +1440,20 @@ textarea.auto-resize {
}
.day-block.all-taken {
border-color: rgba(57, 217, 138, 0.3);
background: linear-gradient(135deg, rgba(57, 217, 138, 0.06) 0%, rgba(57, 217, 138, 0.015) 100%);
}
.day-block.all-taken .day-divider,
.day-block.all-taken.stock-warning .day-divider,
.day-block.all-taken.stock-danger .day-divider {
color: var(--success);
opacity: 0.8;
}
.day-block.past-missed {
border-color: rgba(252, 211, 77, 0.35);
}
.day-block.past-missed .day-divider {
color: var(--warning);
opacity: 0.8;
}
.day-block.today.all-taken {
border-color: var(--success);
@@ -1700,6 +1924,10 @@ textarea.auto-resize {
.status-chip.high::before {
content: "★";
}
.status-chip.small {
font-size: 0.7rem;
padding: 0.2rem 0.5rem;
}
@media (max-width: 760px) {
.table-head,
@@ -1710,6 +1938,9 @@ textarea.auto-resize {
.table-head {
display: none;
}
.table-row .hide-on-card {
display: none;
}
.table-row {
padding: 0.75rem;
display: flex;
@@ -1736,8 +1967,8 @@ textarea.auto-resize {
/* First span (name cell) - centered horizontal layout */
.table-row span:first-child {
justify-content: center;
padding-bottom: 0.5rem;
margin-bottom: 0.25rem;
padding-bottom: 0.15rem;
margin-bottom: 0;
}
.table-row span:first-child::before {
display: none; /* Hide "NAME" label on mobile */
@@ -1745,6 +1976,11 @@ textarea.auto-resize {
/* Status chip in table row - left aligned */
.table-row span.status-chip {
align-self: flex-start;
justify-content: flex-start;
gap: 0.4rem;
}
.table-row span.status-chip::before {
margin-right: 0;
}
/* Avatar + name layout - centered */
.table-row .cell-with-avatar {
@@ -1919,6 +2155,26 @@ textarea.auto-resize {
text-transform: uppercase;
letter-spacing: 0.04em;
}
.planner label.planner-checkbox {
grid-column: 1 / -1;
display: flex;
flex-direction: row;
align-items: center;
flex-wrap: nowrap;
gap: 0.75rem;
color: var(--text-secondary);
font-size: 0.875rem;
font-weight: 400;
text-transform: none;
letter-spacing: normal;
cursor: pointer;
}
.planner-checkbox input[type="checkbox"] {
width: 1.125rem;
height: 1.125rem;
cursor: pointer;
accent-color: var(--accent-primary);
}
.planner-actions {
grid-column: 1 / -1;
display: flex;
@@ -2275,6 +2531,16 @@ textarea.auto-resize {
z-index: 101;
}
/* Tooltip aligned to left edge of icon (prevents clipping inside modals) */
.info-tooltip.tooltip-align-left::after {
left: 0;
transform: none;
}
.info-tooltip.tooltip-align-left::before {
left: 50%;
transform: translateX(-50%);
}
.info-tooltip:hover::after,
.info-tooltip:hover::before,
.info-tooltip:focus::after,
@@ -2751,6 +3017,62 @@ textarea.auto-resize {
font-size: 0.9rem;
}
/* Threshold Chips Group - 3-column grid for Critical/Low/High */
.threshold-chips-group {
grid-template-columns: 1fr 1fr 1fr;
}
.threshold-chips-group label {
text-transform: none;
letter-spacing: normal;
}
.threshold-chip-label {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.5rem;
}
.threshold-chip-label .status-chip {
pointer-events: none;
}
.threshold-invalid input {
border-color: var(--danger) !important;
box-shadow: 0 0 0 1px var(--danger);
}
.threshold-validation-error {
margin: 0.75rem 0 0;
padding: 0.5rem 0.75rem;
background: rgba(255, 94, 94, 0.1);
border: 1px solid rgba(255, 94, 94, 0.3);
border-radius: 6px;
color: #fca5a5;
font-size: 0.8rem;
font-weight: 500;
}
/* Stock Reminder Trigger in Notifications */
.stock-reminder-trigger {
margin-bottom: 0.5rem;
}
.stock-reminder-trigger .setting-desc {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
margin: 0;
font-size: 0.9rem;
color: var(--text-secondary);
}
.stock-reminder-trigger .status-chip {
pointer-events: none;
}
/* Compact Setting Row - for inline toggles without card styling */
.setting-row.compact {
padding: 0.75rem 0;
@@ -2926,6 +3248,9 @@ textarea.auto-resize {
.setting-group {
grid-template-columns: 1fr;
}
.threshold-chips-group {
grid-template-columns: 1fr 1fr 1fr;
}
}
/* Medication Avatar */
@@ -3856,6 +4181,41 @@ h3 .reminder-icon.info-tooltip {
cursor: pointer;
}
/* Password Input with Toggle */
.password-input-wrapper {
position: relative;
display: flex;
align-items: center;
}
.password-input-wrapper input {
width: 100%;
padding-right: 2.5rem;
}
.password-toggle-btn {
position: absolute;
right: 0.5rem;
background: none;
border: none;
padding: 0.25rem;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-tertiary);
transition: color 0.15s ease;
}
.password-toggle-btn:hover {
color: var(--text-secondary);
}
.password-toggle-btn svg {
width: 1.25rem;
height: 1.25rem;
}
.auth-links {
display: flex;
flex-direction: column;
@@ -4164,7 +4524,8 @@ h3 .reminder-icon.info-tooltip {
.profile-modal {
max-width: 420px;
padding: 0;
overflow: hidden;
overflow-y: auto;
max-height: 90vh;
}
.profile-container {
@@ -4269,8 +4630,7 @@ h3 .reminder-icon.info-tooltip {
text-transform: uppercase;
letter-spacing: 0.5px;
margin: 0 0 1rem 0;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--border-primary);
padding-bottom: 0;
}
.profile-form .form-group {
@@ -4309,9 +4669,8 @@ h3 .reminder-icon.info-tooltip {
display: flex;
gap: 0.75rem;
justify-content: flex-end;
padding-top: 0.5rem;
border-top: 1px solid var(--border-primary);
margin-top: 1rem;
padding-top: 0;
margin-top: 0.5rem;
}
.profile-actions .btn {
@@ -4348,6 +4707,36 @@ h3 .reminder-icon.info-tooltip {
cursor: not-allowed;
}
/* Profile danger zone */
.profile-danger-zone {
margin: 0 1.5rem 1.5rem;
padding-top: 1rem;
}
.profile-danger-zone .profile-section-title {
margin-bottom: 0.75rem;
}
.btn-danger {
background: #dc2626;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 6px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s ease;
}
.btn-danger:hover:not(:disabled) {
background: #b91c1c;
}
.btn-danger:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* =============================================================================
About Modal
============================================================================= */
@@ -4368,18 +4757,12 @@ h3 .reminder-icon.info-tooltip {
width: 64px;
height: 64px;
margin: 0 auto 1rem;
background: linear-gradient(135deg, var(--accent) 0%, var(--accent-hover) 100%);
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 12px rgba(var(--accent-rgb, 59, 130, 246), 0.25);
}
.about-logo svg {
width: 36px;
height: 36px;
stroke: white;
.about-logo img {
width: 64px;
height: 64px;
border-radius: 16px;
}
.about-header h2 {
@@ -4403,15 +4786,12 @@ h3 .reminder-icon.info-tooltip {
.about-version-row {
display: flex;
justify-content: space-between;
justify-content: center;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 0;
}
.about-version-row:not(:last-child) {
border-bottom: 1px dashed var(--border-secondary);
}
.about-version-label {
font-size: 0.875rem;
color: var(--text-secondary);
@@ -4427,6 +4807,16 @@ h3 .reminder-icon.info-tooltip {
border-radius: 4px;
}
a.about-version-link {
color: var(--accent-primary);
text-decoration: none;
transition: text-decoration 0.15s ease;
}
a.about-version-link:hover {
text-decoration: underline;
}
.about-update-section {
padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--border-primary);
@@ -4528,13 +4918,6 @@ h3 .reminder-icon.info-tooltip {
background: var(--accent-hover);
}
.update-last-checked {
display: block;
margin-top: 0.5rem;
font-size: 0.75rem;
opacity: 0.8;
}
.about-links {
padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--border-primary);
@@ -5259,6 +5642,20 @@ h3 .reminder-icon.info-tooltip {
justify-self: start;
}
.mobile-edit-form .blister-row .remind-toggle-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.blister-inputs .remind-toggle-row {
display: flex;
align-items: center;
gap: 0.5rem;
align-self: end;
padding-bottom: 0.5rem;
}
.mobile-edit-form .blister-row .datetime-inputs {
display: flex;
gap: 0.5rem;
@@ -16,10 +16,6 @@ describe("AboutModal", () => {
beforeEach(() => {
vi.clearAllMocks();
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: true,
json: () => Promise.resolve({ version: "1.0.0" }),
});
});
it("returns null when not open", () => {
@@ -65,8 +61,10 @@ describe("AboutModal", () => {
expect(links.length).toBeGreaterThan(0);
});
it("fetches backend version on open", async () => {
it("renders version as link to GitHub release", () => {
render(<AboutModal {...defaultProps} />);
expect(fetch).toHaveBeenCalledWith("/api/health");
const versionLink = screen.getByText("1.0.0").closest("a");
expect(versionLink).toHaveAttribute("href", "https://github.com/test/repo/releases/tag/v1.0.0");
expect(versionLink).toHaveAttribute("target", "_blank");
});
});
@@ -14,6 +14,15 @@ vi.mock("react-router-dom", async () => {
};
});
// Mock useUnsavedChanges
vi.mock("../../context", () => ({
useUnsavedChanges: () => ({
setHasUnsavedChanges: vi.fn(),
hasUnsavedChanges: false,
confirmNavigation: vi.fn().mockReturnValue(true),
}),
}));
describe("AppHeader", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -73,7 +82,7 @@ describe("AppHeader", () => {
});
});
it("renders theme toggle button", async () => {
it("renders theme menu button", async () => {
const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn();
@@ -86,12 +95,33 @@ describe("AppHeader", () => {
);
await waitFor(() => {
const buttons = screen.getAllByRole("button");
const themeBtn = buttons.find((btn) => btn.textContent?.includes("🌙") || btn.textContent?.includes("☀️"));
const themeBtn = screen.getByTitle(/theme\.title/i);
expect(themeBtn).toBeInTheDocument();
});
});
it("opens theme dropdown and shows Light/Dark/System options", async () => {
const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn();
render(
<MemoryRouter initialEntries={["/dashboard"]}>
<AuthProvider>
<AppHeader onOpenProfile={mockOnOpenProfile} onOpenAbout={mockOnOpenAbout} />
</AuthProvider>
</MemoryRouter>
);
await waitFor(() => {
const themeBtn = screen.getByTitle(/theme\.title/i);
fireEvent.click(themeBtn);
});
expect(screen.getByText(/theme\.light/i)).toBeInTheDocument();
expect(screen.getByText(/theme\.dark/i)).toBeInTheDocument();
expect(screen.getByText(/theme\.system/i)).toBeInTheDocument();
});
it("renders settings button when auth is disabled", async () => {
const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn();
@@ -7,12 +7,15 @@ const defaultSettings: StockThresholds = {
lowStockDays: 7,
normalStockDays: 30,
highStockDays: 90,
criticalStockDays: 3,
expiryWarningDays: 30,
};
const mockMedication: Medication = {
id: 1,
name: "Test Med",
genericName: "Generic Name",
packageType: "blister",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
@@ -383,3 +386,197 @@ describe("MedDetailModal with refill history", () => {
}
});
});
describe("MedDetailModal intake schedule usage display", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("does not multiply usage by personCount when intakes have per-intake takenBy", () => {
// Two people at medication level, but each intake has its own takenBy
const med: Medication = {
...mockMedication,
takenBy: ["Alice", "Bob"],
blisters: [
{ usage: 1, every: 1, start: "2024-01-01T09:00:00" },
{ usage: 1, every: 1, start: "2024-01-01T21:00:00" },
],
intakes: [
{ usage: 1, every: 1, start: "2024-01-01T09:00:00", takenBy: "Alice", intakeRemindersEnabled: false },
{ usage: 1, every: 1, start: "2024-01-01T21:00:00", takenBy: "Bob", intakeRemindersEnabled: false },
],
};
render(<MedDetailModal {...defaultProps} selectedMed={med} />);
const usageElements = document.querySelectorAll(".med-schedule-usage");
// Each intake should show "1 pill" (not "2 pills")
usageElements.forEach((el) => {
expect(el.textContent).toContain("1");
expect(el.textContent).not.toMatch(/^2\b/);
});
});
it("multiplies usage by personCount for legacy blisters without per-intake takenBy", () => {
// Two people at medication level, legacy blisters without intakes
const med: Medication = {
...mockMedication,
takenBy: ["Alice", "Bob"],
blisters: [{ usage: 1, every: 1, start: "2024-01-01T09:00:00" }],
// No intakes array - legacy format
};
render(<MedDetailModal {...defaultProps} selectedMed={med} />);
const usageElements = document.querySelectorAll(".med-schedule-usage");
// Legacy: 1 pill * 2 people = "2 pills"
expect(usageElements.length).toBe(1);
expect(usageElements[0].textContent).toContain("2");
});
it("shows correct usage for single person with per-intake takenBy", () => {
const med: Medication = {
...mockMedication,
takenBy: ["Alice"],
pillWeightMg: 500,
blisters: [{ usage: 2, every: 1, start: "2024-01-01T09:00:00" }],
intakes: [{ usage: 2, every: 1, start: "2024-01-01T09:00:00", takenBy: "Alice", intakeRemindersEnabled: false }],
};
render(<MedDetailModal {...defaultProps} selectedMed={med} />);
const usageElements = document.querySelectorAll(".med-schedule-usage");
expect(usageElements.length).toBe(1);
// Should show "2 pills (1000 mg)" - usage=2, not multiplied
expect(usageElements[0].textContent).toContain("2");
expect(usageElements[0].textContent).toContain("1000");
});
});
describe("MedDetailModal stock overflow warning", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("shows warning icon when stock exceeds package capacity", () => {
const overflowCoverage: Coverage = {
name: "Test Med",
medsLeft: 49,
daysLeft: 49,
depletionDate: "2024-03-01",
depletionTime: Date.now() + 49 * 86400000,
nextDose: null,
};
render(<MedDetailModal {...defaultProps} coverage={{ all: [overflowCoverage] }} />);
// packageSize = 1 * 1 * 30 + 0 = 30, currentStock = 49 > 30
const warningIcon = document.querySelector(".info-tooltip.tooltip-align-left.warning-text");
expect(warningIcon).toBeInTheDocument();
expect(warningIcon?.getAttribute("data-tooltip")).toBe("tooltips.stockExceedsCapacity");
});
it("does not show warning icon when stock is within package capacity", () => {
render(<MedDetailModal {...defaultProps} />);
// packageSize = 30, currentStock = 25 < 30
const warningIcon = document.querySelector(".info-tooltip.tooltip-align-left.warning-text");
expect(warningIcon).not.toBeInTheDocument();
});
it("does not show warning icon when stock equals package capacity", () => {
const exactCoverage: Coverage = {
name: "Test Med",
medsLeft: 30,
daysLeft: 30,
depletionDate: "2024-02-01",
depletionTime: Date.now() + 30 * 86400000,
nextDose: null,
};
render(<MedDetailModal {...defaultProps} coverage={{ all: [exactCoverage] }} />);
// packageSize = 30, currentStock = 30 — equal, no warning
const warningIcon = document.querySelector(".info-tooltip.tooltip-align-left.warning-text");
expect(warningIcon).not.toBeInTheDocument();
});
});
describe("MedDetailModal bottle package type", () => {
const bottleMed: Medication = {
id: 2,
name: "Bottle Med",
genericName: null,
packageType: "bottle",
packCount: 0,
blistersPerPack: 1,
pillsPerBlister: 1,
looseTablets: 80,
totalPills: 100,
takenBy: [],
blisters: [{ usage: 1, every: 1, start: "2024-01-01T09:00:00" }],
updatedAt: null,
expiryDate: null,
notes: null,
};
const bottleCoverage: Coverage = {
name: "Bottle Med",
medsLeft: 80,
daysLeft: 80,
depletionDate: "2024-06-01",
depletionTime: Date.now() + 80 * 86400000,
nextDose: null,
};
const bottleProps = {
...defaultProps,
selectedMed: bottleMed,
coverage: { all: [bottleCoverage] },
};
beforeEach(() => {
vi.clearAllMocks();
});
it("does not show blister fields in stock info section", () => {
render(<MedDetailModal {...bottleProps} />);
// Should show current stock
expect(screen.getByText(/modal\.currentStock/i)).toBeInTheDocument();
// Should NOT show full blisters or open blister labels
expect(screen.queryByText(/table\.fullBlisters/i)).not.toBeInTheDocument();
expect(screen.queryByText(/table\.openBlister/i)).not.toBeInTheDocument();
});
it("shows bottle type in package details section", () => {
render(<MedDetailModal {...bottleProps} />);
// Should show package type as bottle
expect(screen.getByText(/form\.packageTypeBottle/i)).toBeInTheDocument();
// Should show total capacity
expect(screen.getByText(/form\.totalCapacity/i)).toBeInTheDocument();
});
it("shows pills-only refill modal for bottle type", () => {
render(<MedDetailModal {...bottleProps} showRefillModal={true} />);
// Should show pills to add label
expect(screen.getByText(/refill\.pillsToAdd/i)).toBeInTheDocument();
// Should NOT show packs label in refill
const refillModal = document.querySelector(".refill-modal");
// Packs label should not be present for bottle type
expect(screen.queryByText("refill.packs")).not.toBeInTheDocument();
});
it("shows total pills input in edit stock modal for bottle type", () => {
render(<MedDetailModal {...bottleProps} showEditStockModal={true} />);
// Should show total pills label
expect(screen.getByText(/editStock\.totalPills/i)).toBeInTheDocument();
// Should NOT show full blisters or partial blister labels
expect(screen.queryByText(/editStock\.fullBlisters/i)).not.toBeInTheDocument();
expect(screen.queryByText(/editStock\.partialBlisterPills/i)).not.toBeInTheDocument();
});
});
@@ -7,10 +7,12 @@ const defaultForm: FormState = {
name: "",
genericName: "",
takenBy: [],
packageType: "blister",
packCount: "1",
blistersPerPack: "1",
pillsPerBlister: "1",
looseTablets: "0",
totalPills: "",
pillWeightMg: "",
expiryDate: "",
notes: "",
@@ -23,6 +25,16 @@ const defaultForm: FormState = {
startTime: "09:00",
},
],
intakes: [
{
usage: "1",
every: "1",
startDate: "2024-01-01",
startTime: "09:00",
takenBy: "",
intakeRemindersEnabled: false,
},
],
};
const defaultProps = {
@@ -44,6 +56,9 @@ const defaultProps = {
onSetBlisterValue: vi.fn(),
onAddBlister: vi.fn(),
onRemoveBlister: vi.fn(),
onSetIntakeValue: vi.fn(),
onAddIntake: vi.fn(),
onRemoveIntake: vi.fn(),
onHandleValueChange: vi.fn(),
refillPacks: 0,
onRefillPacksChange: vi.fn(),
@@ -99,8 +114,7 @@ describe("MobileEditModal", () => {
it("calls onClose when close button clicked", () => {
const onClose = vi.fn();
const onResetForm = vi.fn();
render(<MobileEditModal {...defaultProps} onClose={onClose} onResetForm={onResetForm} />);
render(<MobileEditModal {...defaultProps} onClose={onClose} />);
const closeBtn = document.querySelector(".modal-close");
if (closeBtn) {
@@ -108,7 +122,6 @@ describe("MobileEditModal", () => {
}
expect(onClose).toHaveBeenCalledTimes(1);
expect(onResetForm).toHaveBeenCalledTimes(1);
});
it("renders form element", () => {
@@ -187,14 +200,14 @@ describe("MobileEditModal", () => {
expect(screen.getByText(/form\.blisters\.addIntake/i)).toBeInTheDocument();
});
it("calls onAddBlister when add intake clicked", () => {
const onAddBlister = vi.fn();
render(<MobileEditModal {...defaultProps} onAddBlister={onAddBlister} />);
it("calls onAddIntake when add intake clicked", () => {
const onAddIntake = vi.fn();
render(<MobileEditModal {...defaultProps} onAddIntake={onAddIntake} />);
const addBtn = screen.getByText(/form\.blisters\.addIntake/i);
fireEvent.click(addBtn);
expect(onAddBlister).toHaveBeenCalledTimes(1);
expect(onAddIntake).toHaveBeenCalledTimes(1);
});
it("renders modal content", () => {
@@ -263,6 +276,24 @@ describe("MobileEditModal blister management", () => {
{ usage: "1", every: "1", startDate: "2024-01-01", startTime: "09:00" },
{ usage: "2", every: "7", startDate: "2024-01-01", startTime: "10:00" },
],
intakes: [
{
usage: "1",
every: "1",
startDate: "2024-01-01",
startTime: "09:00",
takenBy: "",
intakeRemindersEnabled: false,
},
{
usage: "2",
every: "7",
startDate: "2024-01-01",
startTime: "10:00",
takenBy: "",
intakeRemindersEnabled: false,
},
],
};
render(<MobileEditModal {...defaultProps} form={form} />);
@@ -271,34 +302,52 @@ describe("MobileEditModal blister management", () => {
expect(blisterRows.length).toBe(2);
});
it("calls onRemoveBlister when remove button clicked", () => {
const onRemoveBlister = vi.fn();
it("calls onRemoveIntake when remove button clicked", () => {
const onRemoveIntake = vi.fn();
const form = {
...defaultForm,
blisters: [
{ usage: "1", every: "1", startDate: "2024-01-01", startTime: "09:00" },
{ usage: "2", every: "7", startDate: "2024-01-01", startTime: "10:00" },
],
intakes: [
{
usage: "1",
every: "1",
startDate: "2024-01-01",
startTime: "09:00",
takenBy: "",
intakeRemindersEnabled: false,
},
{
usage: "2",
every: "7",
startDate: "2024-01-01",
startTime: "10:00",
takenBy: "",
intakeRemindersEnabled: false,
},
],
};
render(<MobileEditModal {...defaultProps} form={form} onRemoveBlister={onRemoveBlister} />);
render(<MobileEditModal {...defaultProps} form={form} onRemoveIntake={onRemoveIntake} />);
const removeButtons = document.querySelectorAll(".blister-row button.danger");
if (removeButtons.length > 0) {
fireEvent.click(removeButtons[0]);
expect(onRemoveBlister).toHaveBeenCalled();
expect(onRemoveIntake).toHaveBeenCalled();
}
});
it("calls onSetBlisterValue when changing blister field", () => {
const onSetBlisterValue = vi.fn();
it("calls onSetIntakeValue when changing blister field", () => {
const onSetIntakeValue = vi.fn();
render(<MobileEditModal {...defaultProps} onSetBlisterValue={onSetBlisterValue} />);
render(<MobileEditModal {...defaultProps} onSetIntakeValue={onSetIntakeValue} />);
const usageInputs = document.querySelectorAll('.blister-row input[type="number"]');
if (usageInputs.length > 0) {
fireEvent.change(usageInputs[0], { target: { value: "2" } });
expect(onSetBlisterValue).toHaveBeenCalled();
expect(onSetIntakeValue).toHaveBeenCalled();
}
});
});
@@ -310,8 +359,9 @@ describe("MobileEditModal form submission", () => {
it("calls onSaveMedication when form submitted", () => {
const onSaveMedication = vi.fn((e: Event) => e.preventDefault());
const validForm = { ...defaultForm, name: "TestMed" };
render(<MobileEditModal {...defaultProps} onSaveMedication={onSaveMedication} />);
render(<MobileEditModal {...defaultProps} form={validForm} onSaveMedication={onSaveMedication} />);
const form = document.querySelector("form");
if (form) {
@@ -374,8 +424,14 @@ describe("MobileEditModal takenBy", () => {
render(<MobileEditModal {...defaultProps} form={form} />);
expect(screen.getByText("John")).toBeInTheDocument();
expect(screen.getByText("Jane")).toBeInTheDocument();
// Check tags are rendered (use getAllByText since names also appear in intake dropdowns)
const johnElements = screen.getAllByText("John");
const janeElements = screen.getAllByText("Jane");
expect(johnElements.length).toBeGreaterThanOrEqual(1);
expect(janeElements.length).toBeGreaterThanOrEqual(1);
// Verify the tag elements specifically exist
expect(johnElements.some((el) => el.closest(".tag"))).toBe(true);
expect(janeElements.some((el) => el.closest(".tag"))).toBe(true);
});
it("calls onRemoveTakenByPerson when tag removed", () => {
@@ -485,3 +541,52 @@ describe("MobileEditModal optional fields", () => {
expect(toggle).toBeInTheDocument();
});
});
describe("MobileEditModal bottle package type", () => {
const bottleForm: FormState = {
...defaultForm,
packageType: "bottle",
packCount: "0",
blistersPerPack: "1",
pillsPerBlister: "1",
looseTablets: "80",
totalPills: "100",
};
it("shows pills-only refill form for bottle type when editing", () => {
render(<MobileEditModal {...defaultProps} form={bottleForm} editingId={1} />);
// Should show "pillsToAdd" label for bottle
expect(screen.getByText(/refill\.pillsToAdd/i)).toBeInTheDocument();
// Should NOT show "packs" label in refill section
const refillSection = document.querySelector(".refill-section");
expect(refillSection).toBeInTheDocument();
expect(refillSection!.textContent).not.toContain("refill.packs");
expect(refillSection!.textContent).not.toContain("refill.loosePills");
});
it("shows packs and loose refill form for blister type when editing", () => {
render(<MobileEditModal {...defaultProps} form={defaultForm} editingId={1} />);
// Should show "packs" and "loosePills" labels for blister
const refillSection = document.querySelector(".refill-section");
expect(refillSection).toBeInTheDocument();
expect(refillSection!.textContent).toContain("refill.packs");
expect(refillSection!.textContent).toContain("refill.loosePills");
});
it("shows totalCapacity and currentPills fields for bottle form", () => {
render(<MobileEditModal {...defaultProps} form={bottleForm} />);
// Should show total capacity field
expect(screen.getByText(/form\.totalCapacity/i)).toBeInTheDocument();
// Should show current pills field
expect(screen.getByText(/form\.currentPills/i)).toBeInTheDocument();
// Should NOT show blister-specific fields
expect(screen.queryByText("form.packs")).not.toBeInTheDocument();
expect(screen.queryByText("form.blistersPerPack")).not.toBeInTheDocument();
expect(screen.queryByText("form.pillsPerBlister")).not.toBeInTheDocument();
});
});
@@ -0,0 +1,89 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { PasswordInput } from "../../components/PasswordInput";
describe("PasswordInput", () => {
it("renders password input with hidden text by default", () => {
render(<PasswordInput id="test-password" value="secret123" onChange={() => {}} />);
const input = document.getElementById("test-password") as HTMLInputElement;
expect(input).toBeInTheDocument();
expect(input.type).toBe("password");
});
it("toggles password visibility when eye button is clicked", () => {
render(<PasswordInput id="test-password" value="secret123" onChange={() => {}} />);
const input = document.getElementById("test-password") as HTMLInputElement;
const toggleButton = screen.getByRole("button", { name: /show password/i });
// Initially password is hidden
expect(input.type).toBe("password");
// Click to show password
fireEvent.click(toggleButton);
expect(input.type).toBe("text");
// Click again to hide password
fireEvent.click(toggleButton);
expect(input.type).toBe("password");
});
it("calls onChange when input value changes", () => {
const handleChange = vi.fn();
render(<PasswordInput id="test-password" value="" onChange={handleChange} />);
const input = document.getElementById("test-password") as HTMLInputElement;
fireEvent.change(input, { target: { value: "newpassword" } });
expect(handleChange).toHaveBeenCalled();
});
it("passes through required attribute", () => {
render(<PasswordInput id="test-password" value="" onChange={() => {}} required />);
const input = document.getElementById("test-password") as HTMLInputElement;
expect(input.required).toBe(true);
});
it("passes through minLength and maxLength attributes", () => {
render(<PasswordInput id="test-password" value="" onChange={() => {}} minLength={8} maxLength={128} />);
const input = document.getElementById("test-password") as HTMLInputElement;
expect(input.minLength).toBe(8);
expect(input.maxLength).toBe(128);
});
it("passes through placeholder attribute", () => {
render(<PasswordInput id="test-password" value="" onChange={() => {}} placeholder="Enter password" />);
const input = document.getElementById("test-password") as HTMLInputElement;
expect(input.placeholder).toBe("Enter password");
});
it("passes through autoComplete attribute", () => {
render(<PasswordInput id="test-password" value="" onChange={() => {}} autoComplete="new-password" />);
const input = document.getElementById("test-password") as HTMLInputElement;
expect(input.autocomplete).toBe("new-password");
});
it("toggle button has correct aria-label", () => {
render(<PasswordInput id="test-password" value="" onChange={() => {}} />);
const toggleButton = screen.getByRole("button", { name: /show password/i });
expect(toggleButton).toBeInTheDocument();
fireEvent.click(toggleButton);
const hideButton = screen.getByRole("button", { name: /hide password/i });
expect(hideButton).toBeInTheDocument();
});
it("toggle button has tabIndex -1 to prevent focus during form navigation", () => {
render(<PasswordInput id="test-password" value="" onChange={() => {}} />);
const toggleButton = screen.getByRole("button");
expect(toggleButton.tabIndex).toBe(-1);
});
});

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