Compare commits

...

206 Commits

Author SHA1 Message Date
Daniel Volz 2f2edfa479 chore: release v1.17.1 (#351) 2026-02-27 01:53:09 +01:00
Daniel Volz b009d9e158 fix: frontend nginx restart loop from invalid log_format scope (#350)
* fix: place nginx log_format in valid context

* fix: unblock required checks for nginx hotfix

* fix: restore mandatory doku files in nginx hotfix pr
2026-02-27 01:47:59 +01:00
dependabot[bot] 8e4cb5dcd4 build(deps): bump minimatch from 10.2.2 to 10.2.4 in /backend (#338)
Bumps [minimatch](https://github.com/isaacs/minimatch) from 10.2.2 to 10.2.4.
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v10.2.2...v10.2.4)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 10.2.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-27 01:29:04 +01:00
dependabot[bot] 7f26dca7a7 build(deps-dev): bump @types/node (#343)
Bumps the minor-and-patch group in /backend with 1 update: [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node).


Updates `@types/node` from 25.3.0 to 25.3.2
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.3.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-27 01:29:00 +01:00
dependabot[bot] 46d768dd4e build(deps): bump the minor-and-patch group in /frontend with 5 updates (#344)
Bumps the minor-and-patch group in /frontend with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [react](https://github.com/facebook/react/tree/HEAD/packages/react) | `19.2.0` | `19.2.4` |
| [@types/react](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react) | `19.2.2` | `19.2.14` |
| [react-dom](https://github.com/facebook/react/tree/HEAD/packages/react-dom) | `19.2.0` | `19.2.4` |
| [@types/react-dom](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react-dom) | `19.2.2` | `19.2.3` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `25.3.0` | `25.3.2` |


Updates `react` from 19.2.0 to 19.2.4
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.4/packages/react)

Updates `@types/react` from 19.2.2 to 19.2.14
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

Updates `react-dom` from 19.2.0 to 19.2.4
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.4/packages/react-dom)

Updates `@types/react-dom` from 19.2.2 to 19.2.3
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react-dom)

Updates `@types/node` from 25.3.0 to 25.3.2
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `@types/react` from 19.2.2 to 19.2.14
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

Updates `@types/react-dom` from 19.2.2 to 19.2.3
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react-dom)

---
updated-dependencies:
- dependency-name: react
  dependency-version: 19.2.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@types/react"
  dependency-version: 19.2.14
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: react-dom
  dependency-version: 19.2.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@types/react-dom"
  dependency-version: 19.2.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@types/node"
  dependency-version: 25.3.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@types/react"
  dependency-version: 19.2.14
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@types/react-dom"
  dependency-version: 19.2.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-27 01:28:55 +01:00
dependabot[bot] c62b6d7893 build(deps): bump actions/upload-artifact from 6 to 7 (#345)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-27 01:28:51 +01:00
dependabot[bot] 1668eb935c build(deps-dev): bump @types/supertest from 6.0.3 to 7.2.0 in /backend (#346)
Bumps [@types/supertest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/supertest) from 6.0.3 to 7.2.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/supertest)

---
updated-dependencies:
- dependency-name: "@types/supertest"
  dependency-version: 7.2.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-27 01:28:47 +01:00
Daniel Volz 1ea4919323 chore: release v1.17.0 (#348) 2026-02-27 01:19:39 +01:00
Daniel Volz ba0ab672b9 docs: update memory and report for multi-pr delivery (#347) 2026-02-27 01:15:40 +01:00
Daniel Volz 57c998ba09 chore: update dependabot automation and agent governance (#341)
* chore: update dependabot automation and agent governance

* chore: trigger required CI checks for governance PR
2026-02-27 01:11:05 +01:00
Daniel Volz cc22f80209 fix: align frontend types and tests for react 19 (#339) 2026-02-27 01:01:48 +01:00
Daniel Volz 6b27d234d9 chore: reduce polling log noise across backend and nginx (#336) 2026-02-27 00:54:21 +01:00
Daniel Volz 19ba4bb7d2 feat: add FORM_LOGIN_ENABLED auth toggle (#334) 2026-02-27 00:48:58 +01:00
dependabot[bot] 8b3901c1e1 build(deps): bump rollup from 4.53.5 to 4.59.0 in /frontend (#333)
Bumps [rollup](https://github.com/rollup/rollup) from 4.53.5 to 4.59.0.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.53.5...v4.59.0)

---
updated-dependencies:
- dependency-name: rollup
  dependency-version: 4.59.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-26 06:29:10 +01:00
dependabot[bot] fd7cc56bb7 build(deps): bump rollup from 4.57.1 to 4.59.0 in /backend (#332)
Bumps [rollup](https://github.com/rollup/rollup) from 4.57.1 to 4.59.0.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.57.1...v4.59.0)

---
updated-dependencies:
- dependency-name: rollup
  dependency-version: 4.59.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-26 06:28:51 +01:00
Daniel Volz aabe58d05f ci: add path filters to Docker build workflow
Only build Docker images when backend/, frontend/, docker-compose,
or the workflow itself changes. Prevents unnecessary image builds
for docs-only or config-only changes on main.

Note: paths filter is not evaluated for tag pushes (GitHub Actions
behavior), so release tags always trigger a full build.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-26 00:22:08 +01:00
Daniel Volz b35101d339 docs: update AI model credits to Claude Opus 4.6 and GPT-5.3 Codex
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-26 00:16:10 +01:00
dependabot[bot] 8420c74a55 build(deps): bump bn.js from 4.12.2 to 4.12.3 in /backend (#330)
Bumps [bn.js](https://github.com/indutny/bn.js) from 4.12.2 to 4.12.3.
- [Release notes](https://github.com/indutny/bn.js/releases)
- [Changelog](https://github.com/indutny/bn.js/blob/master/CHANGELOG.md)
- [Commits](https://github.com/indutny/bn.js/compare/v4.12.2...v4.12.3)

---
updated-dependencies:
- dependency-name: bn.js
  dependency-version: 4.12.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-26 00:14:46 +01:00
Daniel Volz 872b63f665 docs: add explicit scope rule to release-manager agent
Prevent release-manager from chaining unrequested steps.
If user asks for PR+merge only, do not also start a release.
If user asks for release only, do not also create PRs.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-26 00:03:07 +01:00
github-actions[bot] f599ac45ab chore: update test count badges [skip ci] 2026-02-25 22:57:37 +00:00
Daniel Volz f36d56c523 test: update modal tests to reflect global ESC handler
Remove ESC-keydown tests from ProfileModal.test.tsx since the
useEscapeKey hook was removed from individual modals. Escape key
handling is now centralized in App.tsx's global handler, making
per-component ESC tests invalid (the component no longer responds
to ESC in isolation).
2026-02-25 23:54:21 +01:00
Daniel Volz f0496e8ca5 fix: remove duplicate ESC handlers causing double history.back()
AboutModal, ProfileModal, and ShareDialog each had their own
useEscapeKey hook AND were handled by the global ESC handler in
App.tsx. When ESC was pressed, both fired synchronously, calling
history.back() twice — navigating past the current page instead
of just closing the modal.

Removed the per-modal useEscapeKey calls since the global handler
in App.tsx already manages ESC priority for all modals.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-25 23:50:07 +01:00
Daniel Volz de300ad919 chore: release v1.16.1 (#326) 2026-02-25 22:26:19 +01:00
Daniel Volz 06bf608913 fix: support core shoutrrr provider schemes (#317)
* fix: support core shoutrrr provider schemes

* fix(ci): resolve backend lint failures and harden shoutrrr URL handling

* fix(codeql): mark validated gotify target as intentional external call

* fix(codeql): route gotify scheme through validated webhook sink
2026-02-25 22:22:50 +01:00
Daniel Volz a47bde0956 chore: sync lockfile package versions to 1.16.0 (#325)
* chore: sync lockfile package versions to 1.16.0

* fix(ci): align medications route formatting with biome
2026-02-25 22:15:43 +01:00
Daniel Volz d02f16af3a fix: stabilize e2e CI and local playwright workers (#321)
* fix: stabilize e2e CI and local playwright workers

* fix(ci): apply biome formatting and import order for frontend build
2026-02-25 22:15:38 +01:00
Daniel Volz dbdf3b61cb fix: harden reminder scheduler dedupe and boundary timing (#319)
* fix: harden reminder scheduler dedupe and boundary timing

* fix(ci): align medications route formatting with biome
2026-02-25 22:15:35 +01:00
Daniel Volz aa29d1c699 docs: align agent instructions and README guidance (#323) 2026-02-25 21:35:35 +01:00
Daniel Volz bfc9aaaa6d fix: tag releases on merged PR commit (#315) 2026-02-25 21:35:32 +01:00
Copilot 2a9ca39c24 Allow medications with only a generic name (no commercial name required) (#311)
* Initial plan

* feat: allow generic name only for medications (frontend changes)

- Add getMedDisplayName() helper for consistent name display
- Update validation to require either commercial or generic name
- Update all display locations to use display name fallback
- Add i18n keys for nameOrGenericRequired in en.json and de.json
- Remove required attribute from commercial name field
- Update FIELD_LIMITS.name.min from 1 to 0

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

* feat: allow generic name only for medications (backend changes)

- Update Zod schema to allow empty name with cross-field refinement
- Update reminder scheduler to use name || genericName for display
- Update planner routes to match medications by display name
- Update existing tests to match new validation behavior

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

* fix: update placeholder text and fix FIELD_LIMITS test

- Remove "(optional)" from generic name placeholder in en/de
- Update types.test.ts to expect FIELD_LIMITS.name.min = 0

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

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>
2026-02-25 21:29:25 +01:00
dependabot[bot] 691550fb33 build(deps): bump bn.js from 4.12.2 to 4.12.3 in /backend (#305)
Bumps [bn.js](https://github.com/indutny/bn.js) from 4.12.2 to 4.12.3.
- [Release notes](https://github.com/indutny/bn.js/releases)
- [Changelog](https://github.com/indutny/bn.js/blob/master/CHANGELOG.md)
- [Commits](https://github.com/indutny/bn.js/compare/v4.12.2...v4.12.3)

---
updated-dependencies:
- dependency-name: bn.js
  dependency-version: 4.12.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-25 21:29:13 +01:00
Daniel Volz 0fded0d42f chore: release v1.16.0 (#308) 2026-02-25 00:19:56 +01:00
Daniel Volz badee6067c chore: add .claude/ to gitignore (#307) 2026-02-25 00:09:20 +01:00
Daniel Volz 6161c14a7b fix: logo optimization, deprecated meta tag, and clipboard copy fallback (#306)
- Replace 2 MB favicon.svg (base64-PNG-in-SVG) with optimized 43 KB app-logo.png (256x256)
- Update AppHeader and AboutModal references to use new logo
- Remove SVG favicon link from index.html (PNG/ICO favicons remain)
- Fix deprecated apple-mobile-web-app-capable → mobile-web-app-capable meta tag
- Add clipboard copy fallback for non-secure contexts (LAN IP over HTTP)

Closes #303
2026-02-25 00:04:35 +01:00
Daniel Volz 96b2a0c96f feat: image upload optimization with sharp, thumbnails, and structured error codes (#304)
- Add sharp for server-side image processing (WebP conversion + thumbnails)
- New shared backend utility for image upload, optimization, and cleanup
- Return structured error codes from upload endpoints (IMAGE_TOO_LARGE, INVALID_TYPE, etc.)
- Frontend error code mapping with i18n support (EN + DE)
- MedicationAvatar tries thumbnail first, falls back to full image
- Error display in MedicationsPage, MobileEditModal, and Auth avatar upload

Closes #302
2026-02-24 23:52:59 +01:00
Daniel Volz 7a32b2045e fix: run one stock reminder catch-up after restart (#300)
* fix: run one stock reminder catch-up after restart

* fix(backend): persist scheduler stock-check timestamp in reminder state
2026-02-24 21:21:34 +01:00
Daniel Volz 26475fd3d0 feat: add correlation ids and tighten frontend security headers (#299)
* feat: add correlation ids and tighten frontend security headers

* docs: remove obsolete project setup guide

* fix: restore health config flags for compatibility

* test(frontend): align auth fetch assertions with correlation headers
2026-02-24 21:21:30 +01:00
Daniel Volz 63cd9ef19b fix: harden share link dose operations and token reuse (#298)
* fix: harden share link dose operations and token reuse

* fix: restore share dose compatibility and add correlation helper
2026-02-24 21:12:43 +01:00
github-actions[bot] f15c2dd79f chore: update test count badges [skip ci] 2026-02-23 18:58:48 +00:00
Daniel Volz b0c5d48095 chore: update bug template guidance and include app test changes (#293) 2026-02-23 19:54:18 +01:00
dependabot[bot] 05226cc500 build(deps): bump the minor-and-patch group in /frontend with 4 updates (#291)
Bumps the minor-and-patch group in /frontend with 4 updates: [i18next](https://github.com/i18next/i18next), [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react), [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom) and [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome).


Updates `i18next` from 25.8.10 to 25.8.13
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v25.8.10...v25.8.13)

Updates `lucide-react` from 0.574.0 to 0.575.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/0.575.0/packages/lucide-react)

Updates `react-router-dom` from 7.13.0 to 7.13.1
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.13.1/packages/react-router-dom)

Updates `@biomejs/biome` from 2.4.1 to 2.4.4
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.4.4/packages/@biomejs/biome)

---
updated-dependencies:
- dependency-name: i18next
  dependency-version: 25.8.13
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: lucide-react
  dependency-version: 0.575.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: react-router-dom
  dependency-version: 7.13.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@biomejs/biome"
  dependency-version: 2.4.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-23 19:25:28 +01:00
dependabot[bot] 3e4f1440a9 build(deps-dev): bump the minor-and-patch group (#290)
Bumps the minor-and-patch group in /backend with 3 updates: [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome), [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) and [@types/nodemailer](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/nodemailer).


Updates `@biomejs/biome` from 2.4.1 to 2.4.4
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.4.4/packages/@biomejs/biome)

Updates `@types/node` from 25.2.3 to 25.3.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `@types/nodemailer` from 7.0.10 to 7.0.11
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/nodemailer)

---
updated-dependencies:
- dependency-name: "@biomejs/biome"
  dependency-version: 2.4.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@types/node"
  dependency-version: 25.3.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: "@types/nodemailer"
  dependency-version: 7.0.11
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-23 19:25:24 +01:00
dependabot[bot] d64a833bda build(deps-dev): bump @biomejs/biome from 2.4.1 to 2.4.4 (#289)
Bumps [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) from 2.4.1 to 2.4.4.
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.4.4/packages/@biomejs/biome)

---
updated-dependencies:
- dependency-name: "@biomejs/biome"
  dependency-version: 2.4.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-23 19:25:19 +01:00
Daniel Volz ba36f67371 fix: smooth mobile edit transition and align modal validation behavior (#286)
* fix: reliable Escape key close for all modals via useEscapeKey hook

- Add useEscapeKey hook (document-level keydown listener)
- Retrofit all 12 modal/overlay components to use it
- Remove redundant overlay onKeyDown Escape handlers
- Simplify modal-content onKeyDown to plain stopPropagation
- Replace MedDetailModal's capture-phase useEffect with 3 useEscapeKey calls
- Replace SharedSchedule's inline useEffect with useEscapeKey
- Add mandatory modal rules to UI Consistency skill
- All 777 frontend + 569 backend tests pass

* fix: smooth mobile edit transition and align modal validation behavior

* fix: keep overlay keydown non-closing for Enter key

* fix: show mobile name error when validation already exists

* fix: restore app-level escape priority handling

* fix: prioritize schedule lightbox on Escape
2026-02-23 06:42:06 +01:00
Daniel Volz 2aa6b1f406 fix: prevent background scroll when any modal is open (#284)
Replace CSS-only modal-open class toggle with a shared useScrollLock
hook that uses position:fixed + scroll position save/restore. This
reliably prevents background scrolling on all browsers including
iOS Safari.

The hook supports nesting (lock counter) so stacked modals (e.g.
MedDetail → RefillModal) work correctly.

Also adds missing modal states to the scroll lock: showRefillModal,
showEditStockModal, showImageLightbox, scheduleLightboxImage.

Replaces the inline 40-line scroll lock in MobileEditModal with the
shared hook.
2026-02-22 18:40:39 +01:00
Daniel Volz 3238a22fd6 test: add E2E regression tests for MedDetail tooltip visibility (#282)
Guard against tooltip pseudo-elements being clipped by ancestor
overflow:hidden or hidden behind modal overlays. Covers edit,
stock correction, export, and close button tooltips.
2026-02-22 18:07:58 +01:00
Daniel Volz b139660241 chore: release v1.15.1 (#280) 2026-02-22 18:02:32 +01:00
Daniel Volz 259f00e7a0 fix: unify number stepper layout and detail modal padding (#279)
Reorder stepper DOM elements (input first) and apply refill-number-stepper
class to both steppers for consistent CSS order-based layout.
Fix missing bottom padding on .med-detail-body.
2026-02-22 17:57:36 +01:00
github-actions[bot] e9f2760815 chore: update test count badges [skip ci] 2026-02-22 16:55:21 +00:00
Daniel Volz d0e2ee0783 fix: trim whitespace from username on login and registration (#277)
Add .trim() to both loginSchema and registerSchema Zod validators so
leading/trailing spaces are stripped before validation and DB lookup.
Includes 5 new test cases covering trim behavior for both endpoints.
2026-02-22 17:51:41 +01:00
Daniel Volz c620146c4b chore: release v1.15.0 (#275) 2026-02-22 16:54:49 +01:00
Daniel Volz 33c1095e77 feat: add FormNumberStepper to medication edit forms (#274)
Replace plain numeric inputs with a reusable +/− stepper component in
both desktop (MedicationsPage) and mobile (MobileEditModal) edit forms.

Applied to Stock, Schedule, and Prescription tab fields. Reorder tabs
so Schedule appears before Prescription. Add responsive grid overrides
for narrow sidebar and compact schedule rows.

Fix label-hover ghost activation by placing <input> first in DOM
(CSS order restores visual [−] [value] [+] layout).

Closes #273
2026-02-22 16:49:51 +01:00
Daniel Volz 5d657558f7 chore: release v1.14.4 (#272) 2026-02-22 14:00:02 +01:00
Daniel Volz 0c28999c89 chore: release v1.14.3 (#271) 2026-02-22 11:05:09 +01:00
Daniel Volz 2296303236 fix: prevent duplicate scheduler reminder sends (#270) 2026-02-22 10:56:13 +01:00
Daniel Volz 9a2d42b8b9 fix: stabilize dashboard modal and image click behavior (#267)
* feat: make medication names clickable in Dashboard dose schedule

Add click handlers to med-name-stack divs in all three dose schedule
sections (past, current/overdue, future) on DashboardPage, opening the
MedDetail modal on click.

Add early-return guards to all four modal openers in AppContext
(openMedDetail, openImageLightbox, openScheduleLightbox, openUserFilter)
to prevent duplicate pushState entries on double-click, which caused
unexpected navigation to the Medications page.

Closes #266

* fix: stabilize dashboard modal and image click handling

* fix: close medication detail on first backdrop click
2026-02-22 10:50:58 +01:00
Daniel Volz 088a6c1a05 chore: fix all Biome lint warnings and MedDetail intake bell icons (#265)
- Backend: refactor nested ternaries, remove unused imports/any types
- Frontend: fix exhaustive deps, a11y label associations, array index keys,
  empty CSS blocks, unused vars, type annotations
- MedDetail modal: fix intake schedule bell icons not rendering (use unified
  intake source with fallback), place bell inline after person name
- MedDetail modal: revert schedule rows from grid to flexbox layout

Closes #264
2026-02-22 08:52:03 +01:00
Daniel Volz 228fd4cd7e chore: release v1.14.2 (#263) 2026-02-21 20:56:12 +01:00
Daniel Volz e346d60f39 chore: release v1.14.1 (#262) 2026-02-21 20:51:28 +01:00
Daniel Volz afb8e5028c fix: auto-mark intakes at due time and show robot marker (#261)
* fix: auto-mark intakes at due time and show robot marker

* test: add taken_source to integration schema

* test: align e2e route schema with taken_source
2026-02-21 20:45:05 +01:00
Daniel Volz 9ab077a037 chore: release v1.14.0 (#259) 2026-02-21 18:04:20 +01:00
Daniel Volz 976d7356ec feat: improve medication detail modal layout and display (#258)
Widen detail modal on desktop (711px, up from 500px) with max-width
override to beat modals-base.css specificity. Limit fullscreen mode
to actual phones (<=500px) instead of all screens <=900px. Move intake
schedule section before prescription details. Show per-intake takenBy
person and bell icon with proper warning color. Right-align time in
schedule rows. Move notes icon after label text. Replace emoji bell
icons with Lucide Bell component in SchedulePage and MobileEditModal.
Add common.on/common.off i18n keys.

Closes #254
2026-02-21 18:00:23 +01:00
Daniel Volz 943148fb49 feat: close modals with browser back button on mobile (#257)
* feat: close modals with browser back button on mobile

Create reusable useModalHistory hook that pushes history state when a
modal opens and listens for popstate to close it. Apply to ReportModal,
ClearMissedConfirm, ExportModal, ImportConfirm, and all modals using
ConfirmModal/ShareDialog/Auth/ExportModal base components. Escape key
handling was already in place for desktop.

Closes #253

* fix: update tests for renamed button labels and missing useModalHistory mock
2026-02-21 18:00:12 +01:00
Daniel Volz 94bd8bd6e8 feat: improve mobile edit modal swipe gestures and tab navigation (#256)
* feat: improve mobile edit modal swipe gestures and tab navigation

Replace React passive touch handlers with native non-passive
addEventListener via useEffect for reliable horizontal swipe blocking.
Reduce axis-lock threshold from 18-26px to 6px for more responsive
gesture detection. Remove isInteractive() guard so swipe works on
input fields. Add tab strip auto-scroll via scrollIntoView when
active tab changes. Fix vertical scrolling by changing readonly
fieldset from display:block to display:flex.

Closes #252

* fix: guard scrollIntoView for jsdom test compatibility
2026-02-21 18:00:02 +01:00
Daniel Volz 0cf1c5353e fix: notification channel toggles snap back after being enabled (#255)
* fix: notification channel toggles snap back after being enabled

The checked props for email/push notification toggles had redundant
conditions (smtpHost/shoutrrrUrl checks) that forced them to false,
causing immediate visual snap-back. Additionally, performSave()
overwrote emailEnabled/shoutrrrEnabled in local state with effective
values, disabling toggles when no SMTP host or Shoutrrr URL was set.

Remove redundant checked prop conditions (disabled attr already handles
interaction gating) and stop overwriting enabled flags in local state
after save.

Closes #250

* fix: remove leaked useModalHistory import from SettingsPage

* fix: update useSettings tests to match new toggle behavior
2026-02-21 17:59:50 +01:00
github-actions[bot] 98cf1ce1d2 chore: update test count badges [skip ci] 2026-02-21 14:51:05 +00:00
Daniel Volz 75c201cab5 fix: keep med detail stock and package values consistent (#249) 2026-02-21 15:47:44 +01:00
github-actions[bot] 74f079d13e chore: update test count badges [skip ci] 2026-02-21 14:28:27 +00:00
Daniel Volz fd3b770a81 fix: improve mobile edit modal scrolling behavior (#247) 2026-02-21 15:24:57 +01:00
Daniel Volz 612aa007aa fix: unify stock semantics across planner and scheduler (#245)
* fix: unify stock semantics across planner and scheduler

* fix: stabilize dashboard hmr and align stock helper tests
2026-02-21 15:24:53 +01:00
Daniel Volz 02af93ec55 chore: release v1.13.0 (#243) 2026-02-20 19:55:26 +01:00
dependabot[bot] 8f57aa8bc9 build(deps): bump ajv from 8.17.1 to 8.18.0 in /backend (#238)
Bumps [ajv](https://github.com/ajv-validator/ajv) from 8.17.1 to 8.18.0.
- [Release notes](https://github.com/ajv-validator/ajv/releases)
- [Commits](https://github.com/ajv-validator/ajv/compare/v8.17.1...v8.18.0)

---
updated-dependencies:
- dependency-name: ajv
  dependency-version: 8.18.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-20 19:51:41 +01:00
dependabot[bot] f42ed87d94 build(deps): bump minimatch from 10.2.0 to 10.2.2 in /backend (#237)
Bumps [minimatch](https://github.com/isaacs/minimatch) from 10.2.0 to 10.2.2.
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v10.2.0...v10.2.2)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 10.2.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-20 19:51:37 +01:00
Daniel Volz 8de54b9065 docs: sync README feature list with recent app changes (#241) 2026-02-20 19:50:55 +01:00
Daniel Volz b489e1e117 fix: keep mobile med detail actions visible while scrolling (#240) 2026-02-20 19:31:59 +01:00
Daniel Volz 8c97abd3c9 Merge branch 'main' of github.com:DanielVolz/medassist-ng
* 'main' of github.com:DanielVolz/medassist-ng:
  chore: update test count badges [skip ci]
2026-02-20 18:58:44 +01:00
Daniel Volz 2eec415af6 docs: enforce hard PR scope and size splitting rule in copilot instructions 2026-02-20 18:56:55 +01:00
github-actions[bot] 243a46f960 chore: update test count badges [skip ci] 2026-02-20 17:56:42 +00:00
Daniel Volz 052751b2ba feat: reports, timeline toggles, and stock correction improvements (#236)
* refactor(frontend): modularize styles and polish modal/ui interactions

* feat: add report workflow and timeline/settings improvements

* fix: resolve CI failures for backend typing, lint, and playwright config
2026-02-20 18:52:59 +01:00
Daniel Volz 89d565bc9d chore: fix lint errors and reduce warnings across codebase (#234)
* chore: fix lint errors and reduce warnings across codebase

- Fix noExplicitAny catches in backend routes and plugins
- Fix noNestedTernary issues in backend services
- Add keyboard event handlers for useKeyWithClickEvents in frontend
- Disable noImportantStyles rule in biome.json
- Fix formatting errors across all changed files
- Fix test file lint issues

Closes #233

* fix: restore any types in test files for TS compatibility

* fix: revert Auth.tsx dependency array changes that caused infinite re-render

* fix: null-safe user.username access in AppContext dependency array
2026-02-17 05:21:47 +01:00
Daniel Volz 08a18fc14a fix: improve export filename and import confirmation UX (#232)
Export filename:
- Include username for multi-user/instance distinction
- Include timestamp with time (YYYYMMDD-HHMM) instead of date only
- Example: medassist-export-daniel-20260216-2108.json

Import confirmation:
- Show friendly 'Import Data?' dialog on empty instances instead of
  scary 'Replace All Data?' warning with danger button
- Only show destructive warning when there is existing data to replace
- Use primary button style for empty-state import

Closes #231
2026-02-16 22:20:20 +01:00
Daniel Volz e41efdf98b fix: disable nginx temp file buffering for proxied responses (#230)
Replace increased proxy buffer sizes with proxy_max_temp_file_size 0
to stream upstream responses directly to clients instead of buffering
to temp files. Eliminates warnings for large medication images without
increasing per-connection RAM usage.
2026-02-16 22:03:11 +01:00
Daniel Volz cefac8cc4e fix: nginx proxy buffering warnings and LOG_LEVEL propagation (#229)
- Increase proxy buffer sizes to prevent upstream image responses being
  buffered to temporary files (16k header + 8x256k body + 512k busy)
- Add env_file to frontend service in docker-compose.dev.yml for LOG_LEVEL
- Normalize LOG_LEVEL in nginx-entrypoint.sh (case-insensitive, trim whitespace)
- Add startup logging showing LOG_LEVEL → access_log mapping

Closes #226
2026-02-16 21:52:03 +01:00
Daniel Volz 779870960c fix: frontend UI polish — tooltips, planner checkbox, settings layout (#228)
- Fix mobile tooltip positioning (above icon instead of centered)
- Place planner checkbox and send-now button on same row
- Move settings tooltips beside input fields instead of overlapping
- Fix input-with-tooltip layout for narrow screens
- Add daily/everyNDays i18n keys for dose frequency display
- Fix lint formatting in page components

Closes #225
2026-02-16 21:51:51 +01:00
Daniel Volz 871e6066ec fix: export/import missing refill history, prescription, and bottle fields (#227)
- Add refill history export/import with medication reference mapping
- Include totalPills (bottle type capacity) in inventory export
- Include dismissedUntil field for past dose dismissal state
- Add expiryWarningDays and shareStockStatus to settings export
- Bump export version to 1.1
- Add refill count to import result reporting
- Update i18n import success details to include refill count

Closes #224
2026-02-16 21:51:39 +01:00
dependabot[bot] ff100dfea5 build(deps-dev): bump @types/nodemailer in /backend (#223)
Bumps [@types/nodemailer](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/nodemailer) from 6.4.21 to 7.0.10.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/nodemailer)

---
updated-dependencies:
- dependency-name: "@types/nodemailer"
  dependency-version: 7.0.10
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-16 19:06:28 +01:00
dependabot[bot] 47581ca7ad build(deps-dev): bump @biomejs/biome (#222)
Bumps the minor-and-patch group in /backend with 1 update: [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome).


Updates `@biomejs/biome` from 2.3.15 to 2.4.1
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.4.1/packages/@biomejs/biome)

---
updated-dependencies:
- dependency-name: "@biomejs/biome"
  dependency-version: 2.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-16 19:06:18 +01:00
dependabot[bot] 39e9ebbf28 build(deps): bump the minor-and-patch group in /frontend with 3 updates (#221)
Bumps the minor-and-patch group in /frontend with 3 updates: [i18next](https://github.com/i18next/i18next), [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) and [jsdom](https://github.com/jsdom/jsdom).


Updates `i18next` from 25.8.7 to 25.8.10
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v25.8.7...v25.8.10)

Updates `@biomejs/biome` from 2.3.15 to 2.4.1
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.4.1/packages/@biomejs/biome)

Updates `jsdom` from 28.0.0 to 28.1.0
- [Release notes](https://github.com/jsdom/jsdom/releases)
- [Changelog](https://github.com/jsdom/jsdom/blob/main/Changelog.md)
- [Commits](https://github.com/jsdom/jsdom/compare/28.0.0...28.1.0)

---
updated-dependencies:
- dependency-name: i18next
  dependency-version: 25.8.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@biomejs/biome"
  dependency-version: 2.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: jsdom
  dependency-version: 28.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-16 19:06:06 +01:00
dependabot[bot] 41b20bb4e6 build(deps): bump actions/github-script from 7 to 8 (#220)
Bumps [actions/github-script](https://github.com/actions/github-script) from 7 to 8.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v7...v8)

---
updated-dependencies:
- dependency-name: actions/github-script
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-16 19:05:55 +01:00
dependabot[bot] f9c51956d5 build(deps-dev): bump @biomejs/biome from 2.3.15 to 2.4.1 (#219)
Bumps [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) from 2.3.15 to 2.4.1.
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.4.1/packages/@biomejs/biome)

---
updated-dependencies:
- dependency-name: "@biomejs/biome"
  dependency-version: 2.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-16 19:05:41 +01:00
Daniel Volz 543b42b540 docs: add mandatory PR metadata fields to release-manager agent (#218)
- Add PR Metadata section with assignee, label, and project requirements
- Update gh pr create command template to include --assignee, --label, --project flags
- Add label mapping table for branch prefix to label type
- Update workflow summary to mention metadata fields
2026-02-15 23:52:15 +01:00
Daniel Volz 36a2f7d537 chore: release v1.12.0 (#216) 2026-02-15 23:28:35 +01:00
Daniel Volz 4b697374f6 feat: obsolete medication archiving, start date, and UI improvements (#215)
* feat: obsolete medication archiving, start date, and UI improvements

- Add soft-archive (obsolete) for medications with dedicated section and toggle
- Add medication start date field with date picker and validation
- Add obsolete/reactivate API endpoints with proper auth
- Filter obsolete meds from schedule, coverage, planner, and notifications
- Improve UserFilterModal with intake schedules, stock badges, and click-to-open
- Improve dashboard taken-by badges with per-intake bell icons
- Add Escape key support to ConfirmModal and MobileEditModal
- Fix Lightbox close button positioning near image
- Add read-only mode support for MobileEditModal
- DB migrations: 0008 (is_obsolete, obsolete_at), 0009 (medication_start_date)
- All user-facing text uses i18n keys (en + de)

* test: fix tests for obsolete medications and UI changes

- Backend: add is_obsolete, obsolete_at, medication_start_date columns to test schemas
- Backend: add test medication inserts in planner tests for active-med filtering
- Frontend: update useMedications URL to include includeObsolete param
- Frontend: fix MobileEditModal selectors and validation assertions
- Frontend: add onClearUser prop to UserFilterModal test renders
- Frontend: fix MedicationsPage and DashboardPage test assertions
2026-02-15 23:23:38 +01:00
Daniel Volz c47a35d642 fix: use COPY --chmod instead of RUN chmod in frontend Dockerfile (#214)
The nginx-unprivileged base image runs as non-root, so RUN chmod
on / fails with 'Operation not permitted'. Use COPY --chmod=755
to set the executable bit at build time instead.
2026-02-14 21:12:51 +01:00
Daniel Volz d8d8c4a07e chore: release v1.11.1 (#213) 2026-02-14 21:07:14 +01:00
Daniel Volz 3f041f26aa feat: respect LOG_LEVEL in frontend nginx container (#212)
Add entrypoint wrapper that translates LOG_LEVEL into nginx
access_log control. When LOG_LEVEL is warn or higher, nginx
access logs are suppressed. The frontend container now receives
LOG_LEVEL via env_file (.env) — no new env vars needed.
2026-02-14 21:04:45 +01:00
Daniel Volz 1e043c8bf3 chore: release v1.11.0 (#210) 2026-02-14 20:33:54 +01:00
Daniel Volz a016e45ef2 feat: frontend LOG_LEVEL support via logger utility (#209)
- Inject LOG_LEVEL at build time via Vite define (__LOG_LEVEL__, default: warn)
- Create frontend logger utility (frontend/src/utils/logger.ts) mirroring backend API
- Replace all console.error calls with log.error in MedicationsPage, AppContext, Auth
- Supports levels: silent > error > warn > info > debug

Closes #205
2026-02-14 20:28:06 +01:00
Daniel Volz cbc71822b0 fix: highlight empty medications in planner email with red background (#208)
- Add light red background (#fef2f2) to table rows where medication is out of stock
- Consistent with stock reminder email styling

Closes #204
2026-02-14 20:24:28 +01:00
Daniel Volz 150be1e114 feat: add prescription refills column to planner table and email (#207)
- Add 6th column 'Prescription refills' to frontend Planner table
- Add matching column to backend planner email (HTML + plaintext)
- Show remaining refills for meds with prescription tracking, '–' otherwise
- Add backend translations for new column header (EN + DE)
- Add frontend i18n keys for prescription refills column
- Update planner tests with medications table schema

Closes #203
2026-02-14 20:21:09 +01:00
Daniel Volz 6ff0ad2745 fix: mobile modal UX improvements (delete confirm, browser-back, z-index) (#206)
- Replace browser confirm() with ConfirmModal for delete confirmation
- Add dedicated history entry for delete dialog so browser back dismisses it
- Track unsaved-changes warning source to restore correct context on cancel
- Add overlayClassName prop to ConfirmModal for nested z-index layering
- Add .nested-confirm CSS class for proper modal stacking
- Add i18n keys for delete confirmation dialog (EN + DE)

Closes #202
2026-02-14 20:17:01 +01:00
Daniel Volz 0ffab23b6d feat: add back button in medication edit header (#201) 2026-02-14 19:22:37 +01:00
github-actions[bot] b4ddf9fd65 chore: update test count badges [skip ci] 2026-02-14 18:12:36 +00:00
Daniel Volz 8273b07231 feat: track number of prescription repeats (#193)
* feat: track prescription repeats and refill reminders

* test: align backend and frontend suites with current prescription and UI behavior

* test: update frontend and backend expectations for latest reminders and refill flow
2026-02-14 19:07:36 +01:00
Daniel Volz edf42bb068 fix: show reminder icon per intake dose in schedule (#198)
* fix: show reminder icon per intake dose in schedule

* test: align schedule reminder icon test with intake-level flag
2026-02-14 18:53:52 +01:00
github-actions[bot] e2c274014f chore: update test count badges [skip ci] 2026-02-14 17:47:54 +00:00
Daniel Volz 732a28dcc5 chore: sync copilot guidance and docker dev proxy defaults (#199) 2026-02-14 18:43:49 +01:00
Daniel Volz 684abd7fb6 fix: handle usernames case-insensitively in auth and oidc (#197) 2026-02-14 18:43:30 +01:00
dependabot[bot] bb693243c1 build(deps): bump github/codeql-action from 3 to 4 (#176)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3 to 4.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:28:14 +01:00
dependabot[bot] fcc84e2d0b build(deps): bump actions/upload-artifact from 4 to 6 (#174)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 6.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:28:10 +01:00
dependabot[bot] 91c55f8cc3 build(deps): bump docker/build-push-action from 5 to 6 (#172)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 5 to 6.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:27:58 +01:00
dependabot[bot] 12d1fbbb30 build(deps-dev): bump @vitejs/plugin-react in /frontend (#178)
Bumps [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) from 4.7.0 to 5.1.4.
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@5.1.4/packages/plugin-react)

---
updated-dependencies:
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 5.1.4
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:27:46 +01:00
dependabot[bot] 836c48264f build(deps-dev): bump jsdom from 27.4.0 to 28.0.0 in /frontend (#183)
Bumps [jsdom](https://github.com/jsdom/jsdom) from 27.4.0 to 28.0.0.
- [Release notes](https://github.com/jsdom/jsdom/releases)
- [Changelog](https://github.com/jsdom/jsdom/blob/main/Changelog.md)
- [Commits](https://github.com/jsdom/jsdom/compare/27.4.0...28.0.0)

---
updated-dependencies:
- dependency-name: jsdom
  dependency-version: 28.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:27:42 +01:00
dependabot[bot] 12bfc61565 build(deps): bump i18next from 24.2.3 to 25.8.7 in /frontend (#181)
Bumps [i18next](https://github.com/i18next/i18next) from 24.2.3 to 25.8.7.
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v24.2.3...v25.8.7)

---
updated-dependencies:
- dependency-name: i18next
  dependency-version: 25.8.7
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:27:38 +01:00
dependabot[bot] 2c829da924 build(deps): bump zod from 3.25.76 to 4.3.6 in /frontend (#185)
Bumps [zod](https://github.com/colinhacks/zod) from 3.25.76 to 4.3.6.
- [Release notes](https://github.com/colinhacks/zod/releases)
- [Commits](https://github.com/colinhacks/zod/compare/v3.25.76...v4.3.6)

---
updated-dependencies:
- dependency-name: zod
  dependency-version: 4.3.6
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:27:35 +01:00
dependabot[bot] 874babe1d8 build(deps-dev): bump @types/node from 22.19.3 to 25.2.3 in /backend (#191)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 22.19.3 to 25.2.3.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.2.3
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:20:40 +01:00
dependabot[bot] c9039b6e87 build(deps): bump dotenv from 16.6.1 to 17.3.1 in /backend (#190)
Bumps [dotenv](https://github.com/motdotla/dotenv) from 16.6.1 to 17.3.1.
- [Changelog](https://github.com/motdotla/dotenv/blob/master/CHANGELOG.md)
- [Commits](https://github.com/motdotla/dotenv/compare/v16.6.1...v17.3.1)

---
updated-dependencies:
- dependency-name: dotenv
  dependency-version: 17.3.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:20:37 +01:00
dependabot[bot] 5918eb5aae build(deps): bump nodemailer from 7.0.11 to 8.0.1 in /backend (#189)
Bumps [nodemailer](https://github.com/nodemailer/nodemailer) from 7.0.11 to 8.0.1.
- [Release notes](https://github.com/nodemailer/nodemailer/releases)
- [Changelog](https://github.com/nodemailer/nodemailer/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodemailer/nodemailer/compare/v7.0.11...v8.0.1)

---
updated-dependencies:
- dependency-name: nodemailer
  dependency-version: 8.0.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:20:33 +01:00
dependabot[bot] 19d3f83aef build(deps): bump @fastify/static from 8.3.0 to 9.0.0 in /backend (#187)
Bumps [@fastify/static](https://github.com/fastify/fastify-static) from 8.3.0 to 9.0.0.
- [Release notes](https://github.com/fastify/fastify-static/releases)
- [Commits](https://github.com/fastify/fastify-static/compare/v8.3.0...v9.0.0)

---
updated-dependencies:
- dependency-name: "@fastify/static"
  dependency-version: 9.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:20:30 +01:00
dependabot[bot] 6922a856c0 build(deps): bump @fastify/cors from 10.1.0 to 11.2.0 in /backend (#186)
Bumps [@fastify/cors](https://github.com/fastify/fastify-cors) from 10.1.0 to 11.2.0.
- [Release notes](https://github.com/fastify/fastify-cors/releases)
- [Commits](https://github.com/fastify/fastify-cors/compare/v10.1.0...v11.2.0)

---
updated-dependencies:
- dependency-name: "@fastify/cors"
  dependency-version: 11.2.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:20:26 +01:00
dependabot[bot] 45a319dc06 build(deps): bump @fastify/cookie from 10.0.1 to 11.0.2 in /backend (#184)
Bumps [@fastify/cookie](https://github.com/fastify/fastify-cookie) from 10.0.1 to 11.0.2.
- [Release notes](https://github.com/fastify/fastify-cookie/releases)
- [Commits](https://github.com/fastify/fastify-cookie/compare/v10.0.1...v11.0.2)

---
updated-dependencies:
- dependency-name: "@fastify/cookie"
  dependency-version: 11.0.2
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:11:18 +01:00
dependabot[bot] 81ac12ba60 build(deps): bump the minor-and-patch group in /frontend with 7 updates (#177)
Bumps the minor-and-patch group in /frontend with 7 updates:

| Package | From | To |
| --- | --- | --- |
| [i18next-browser-languagedetector](https://github.com/i18next/i18next-browser-languageDetector) | `8.2.0` | `8.2.1` |
| [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom) | `7.12.0` | `7.13.0` |
| [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) | `2.3.12` | `2.3.15` |
| [@playwright/test](https://github.com/microsoft/playwright) | `1.58.1` | `1.58.2` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.0.17` | `4.0.18` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `7.3.0` | `7.3.1` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.0.17` | `4.0.18` |


Updates `i18next-browser-languagedetector` from 8.2.0 to 8.2.1
- [Changelog](https://github.com/i18next/i18next-browser-languageDetector/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next-browser-languageDetector/compare/v8.2.0...v8.2.1)

Updates `react-router-dom` from 7.12.0 to 7.13.0
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.13.0/packages/react-router-dom)

Updates `@biomejs/biome` from 2.3.12 to 2.3.15
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.3.15/packages/@biomejs/biome)

Updates `@playwright/test` from 1.58.1 to 1.58.2
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.58.1...v1.58.2)

Updates `@vitest/coverage-v8` from 4.0.17 to 4.0.18
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.0.18/packages/coverage-v8)

Updates `vite` from 7.3.0 to 7.3.1
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v7.3.1/packages/vite)

Updates `vitest` from 4.0.17 to 4.0.18
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.0.18/packages/vitest)

---
updated-dependencies:
- dependency-name: i18next-browser-languagedetector
  dependency-version: 8.2.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: react-router-dom
  dependency-version: 7.13.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: "@biomejs/biome"
  dependency-version: 2.3.15
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@playwright/test"
  dependency-version: 1.58.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.0.18
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: vite
  dependency-version: 7.3.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: vitest
  dependency-version: 4.0.18
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:11:01 +01:00
dependabot[bot] 6c10f9af0c build(deps): bump the minor-and-patch group in /backend with 10 updates (#182)
Bumps the minor-and-patch group in /backend with 10 updates:

| Package | From | To |
| --- | --- | --- |
| [@fastify/multipart](https://github.com/fastify/fastify-multipart) | `9.3.0` | `9.4.0` |
| [@libsql/client](https://github.com/tursodatabase/libsql-client-ts/tree/HEAD/packages/libsql-client) | `0.10.0` | `0.17.0` |
| [argon2](https://github.com/ranisalt/node-argon2) | `0.40.3` | `0.44.0` |
| [fastify](https://github.com/fastify/fastify) | `5.7.3` | `5.7.4` |
| [openid-client](https://github.com/panva/openid-client) | `6.8.1` | `6.8.2` |
| [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) | `2.3.12` | `2.3.15` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.0.16` | `4.0.18` |
| [drizzle-kit](https://github.com/drizzle-team/drizzle-orm) | `0.31.8` | `0.31.9` |
| [supertest](https://github.com/ladjs/supertest) | `7.1.4` | `7.2.2` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.0.16` | `4.0.18` |


Updates `@fastify/multipart` from 9.3.0 to 9.4.0
- [Release notes](https://github.com/fastify/fastify-multipart/releases)
- [Commits](https://github.com/fastify/fastify-multipart/compare/v9.3.0...v9.4.0)

Updates `@libsql/client` from 0.10.0 to 0.17.0
- [Release notes](https://github.com/tursodatabase/libsql-client-ts/releases)
- [Changelog](https://github.com/tursodatabase/libsql-client-ts/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tursodatabase/libsql-client-ts/commits/v0.17.0/packages/libsql-client)

Updates `argon2` from 0.40.3 to 0.44.0
- [Release notes](https://github.com/ranisalt/node-argon2/releases)
- [Commits](https://github.com/ranisalt/node-argon2/commits/v0.44.0)

Updates `fastify` from 5.7.3 to 5.7.4
- [Release notes](https://github.com/fastify/fastify/releases)
- [Commits](https://github.com/fastify/fastify/compare/v5.7.3...v5.7.4)

Updates `openid-client` from 6.8.1 to 6.8.2
- [Release notes](https://github.com/panva/openid-client/releases)
- [Changelog](https://github.com/panva/openid-client/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/openid-client/compare/v6.8.1...v6.8.2)

Updates `@biomejs/biome` from 2.3.12 to 2.3.15
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.3.15/packages/@biomejs/biome)

Updates `@vitest/coverage-v8` from 4.0.16 to 4.0.18
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.0.18/packages/coverage-v8)

Updates `drizzle-kit` from 0.31.8 to 0.31.9
- [Release notes](https://github.com/drizzle-team/drizzle-orm/releases)
- [Commits](https://github.com/drizzle-team/drizzle-orm/compare/drizzle-kit@0.31.8...drizzle-kit@0.31.9)

Updates `supertest` from 7.1.4 to 7.2.2
- [Release notes](https://github.com/ladjs/supertest/releases)
- [Commits](https://github.com/ladjs/supertest/compare/v7.1.4...v7.2.2)

Updates `vitest` from 4.0.16 to 4.0.18
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.0.18/packages/vitest)

---
updated-dependencies:
- dependency-name: "@fastify/multipart"
  dependency-version: 9.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: "@libsql/client"
  dependency-version: 0.17.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: argon2
  dependency-version: 0.44.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: fastify
  dependency-version: 5.7.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: openid-client
  dependency-version: 6.8.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@biomejs/biome"
  dependency-version: 2.3.15
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.0.18
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: drizzle-kit
  dependency-version: 0.31.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: supertest
  dependency-version: 7.2.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: vitest
  dependency-version: 4.0.18
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:10:51 +01:00
dependabot[bot] 6eb7bf6d0d build(deps-dev): bump lint-staged from 15.5.2 to 16.2.7 (#175)
Bumps [lint-staged](https://github.com/lint-staged/lint-staged) from 15.5.2 to 16.2.7.
- [Release notes](https://github.com/lint-staged/lint-staged/releases)
- [Changelog](https://github.com/lint-staged/lint-staged/blob/main/CHANGELOG.md)
- [Commits](https://github.com/lint-staged/lint-staged/compare/v15.5.2...v16.2.7)

---
updated-dependencies:
- dependency-name: lint-staged
  dependency-version: 16.2.7
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:10:39 +01:00
dependabot[bot] 2a97a78810 build(deps-dev): bump @biomejs/biome from 2.3.12 to 2.3.15 (#173)
Bumps [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) from 2.3.12 to 2.3.15.
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.3.15/packages/@biomejs/biome)

---
updated-dependencies:
- dependency-name: "@biomejs/biome"
  dependency-version: 2.3.15
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:10:28 +01:00
dependabot[bot] 92ea6d5f8b build(deps): bump actions/setup-node from 4 to 6 (#171)
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4 to 6.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:10:05 +01:00
dependabot[bot] 0c83648a56 build(deps): bump actions/checkout from 4 to 6 (#170)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 20:08:56 +01:00
Daniel Volz 77b0f3a0f9 chore: improve dev tooling (CI tests, dependabot, coverage) (#169)
- Add frontend unit tests with coverage to CI test workflow
- Add dependabot.yml for automated dependency updates (npm + GitHub Actions)
- Add backend coverage thresholds (60/65/50/60) to vitest.config.ts
- Exclude services/ and logger from coverage (untestable schedulers)
2026-02-13 19:52:33 +01:00
Daniel Volz 82d8bec91b chore: add noNestedTernary biome rule (warn) (#168)
- Enforce no nested ternary expressions via biome linter
- No existing code violations found
- Complements clarity-over-brevity coding guideline
2026-02-13 19:32:17 +01:00
Daniel Volz 7122121c12 chore: release v1.10.3 (#167) 2026-02-13 19:02:38 +01:00
Daniel Volz 36ee80b554 chore: add workflow to auto-move project items to Done on close/merge (#165)
- New workflow project-auto-done.yml triggers on issue close and PR merge
- Uses GraphQL to find the project item and update Status to Done
- Handles both issues and pull requests with proper type detection
- Skips gracefully if item is not on the board or already Done
- Update release-manager.agent.md to reflect automation (manual is now fallback)
2026-02-13 18:45:51 +01:00
Daniel Volz 33342e7e25 docs: add mandatory project board update steps to release-manager (#164)
- Add critical safety rule: always verify project board status after merge
- Correct misleading claim that Closes #N auto-moves project status (it doesn't)
- Add concrete GraphQL mutation commands for moving items to Done
- Include known project field IDs for Status column
2026-02-13 18:42:08 +01:00
github-actions[bot] 19d5ef71ab chore: update test count badges [skip ci] 2026-02-13 17:37:51 +00:00
Daniel Volz 5c09f97cb3 test: improve frontend test coverage (#163)
- Export DashboardPage helper functions for testability
- Add new test files: App, SharedSchedule, AppContext, UnsavedChangesContext, useUnsavedChangesWarning
- Expand existing test coverage for Auth, MedDetailModal, MobileEditModal, DashboardPage, MedicationsPage, PlannerPage, and more
- Add edge case and error handling tests across components, hooks, and pages
2026-02-13 18:34:19 +01:00
Copilot 0b0472f2f5 Fix OIDC token exchange behind HTTPS reverse proxy (#162)
* Initial plan

* Fix OIDC callback URL construction for HTTPS reverse proxy

- Replace hardcoded http:// URL with OIDC_REDIRECT_URI from environment
- Build complete callback URL with query parameters for proper validation
- Fixes token exchange 401 errors when running behind HTTPS reverse proxy

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

* Update OIDC_REDIRECT_URI documentation to clarify full URL requirement

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

* fix: format oidc.ts to pass biome check

---------

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-13 18:29:33 +01:00
dependabot[bot] 38f3533dd9 build(deps-dev): bump qs from 6.14.1 to 6.14.2 in /backend (#158)
Bumps [qs](https://github.com/ljharb/qs) from 6.14.1 to 6.14.2.
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.14.1...v6.14.2)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.14.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-12 21:43:41 +01:00
dependabot[bot] 463c756447 build(deps): bump fast-xml-parser and @aws-sdk/client-ses in /backend (#157)
Bumps [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) and [@aws-sdk/client-ses](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/clients/client-ses). These dependencies needed to be updated together.

Updates `fast-xml-parser` from 5.2.5 to 5.3.4
- [Release notes](https://github.com/NaturalIntelligence/fast-xml-parser/releases)
- [Changelog](https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.2.5...v5.3.4)

Updates `@aws-sdk/client-ses` from 3.956.0 to 3.988.0
- [Release notes](https://github.com/aws/aws-sdk-js-v3/releases)
- [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/clients/client-ses/CHANGELOG.md)
- [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.988.0/clients/client-ses)

---
updated-dependencies:
- dependency-name: fast-xml-parser
  dependency-version: 5.3.4
  dependency-type: indirect
- dependency-name: "@aws-sdk/client-ses"
  dependency-version: 3.988.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-12 21:43:35 +01:00
Daniel Volz 4275dca838 fix: improve modal scroll lock and e2e script workflow (#156) 2026-02-12 21:43:28 +01:00
Daniel Volz 6072d8eb2e docs: consolidate copilot governance and add medassist skills (#160) 2026-02-12 21:18:50 +01:00
Daniel Volz 98939877db feat: expand Playwright E2E coverage (#155)
* feat: comprehensive Playwright E2E test rewrite

Rewrite all E2E tests with correct CSS selectors, add new spec files,
and implement robust auth handling to work within backend rate limits.

Changes:
- Rewrite fixtures/index.ts with JWT-based /auth/me mock to avoid
  10 req/min rate limit on /auth/me during test runs
- Rewrite auth.setup.ts with offline JWT validity check to reuse
  existing auth state across runs (saves login rate-limit budget)
- Rewrite auth.spec.ts (6 tests) - login page, fields, submit,
  redirect guard, invalid credentials, login/register toggle
- Rewrite dashboard.spec.ts (8 tests) - header, nav tabs,
  navigation, overview/schedules sections, days selector, redirect
- Rewrite medications.spec.ts (8 tests) - form fields, stock
  inventory, package type toggle, intake schedule, save/cancel,
  unsaved changes guard
- Rewrite settings.spec.ts (12 tests) - language, notification
  matrix, thresholds, calculation mode, toggle switch, export/import,
  user menu navigation
- Create planner.spec.ts (9 tests) - form, date inputs, calculate,
  reset, checkbox, submit, tab state, eyebrow heading
- Create schedule.spec.ts (12 tests) - timeline, days selector,
  past/future toggles, day blocks, today highlight, collapse/expand,
  overview table, share button
- Update playwright.config.ts: remove mobile projects, enable
  webServer section for CI
- Add .github/workflows/e2e.yml CI workflow for Playwright tests

Total: 57 E2E tests across 6 spec files, all passing consistently
across 5+ consecutive runs without backend restart.

Closes #154

* feat: add comprehensive E2E data tests with medication CRUD, dashboard, planner, schedule

Add 48 new Playwright E2E tests covering real medication data scenarios:
- medication-crud: 14 tests for create/edit/delete/list via UI form
- dashboard-data: 13 tests for overview table, timeline, dose tracking
- planner-data: 9 tests for demand calculator with results/status chips
- schedule-data: 11 tests for timeline, collapse/expand, dose mark/undo

Infrastructure improvements:
- Add API helpers (createMedicationViaAPI, deleteMedicationViaAPI,
  deleteAllMedicationsViaAPI) with retry logic for rate-limit resilience
- Configure chromium-data project for serial execution with retry:1
- Add /auth/me mock to avoid rate-limit exhaustion on auth endpoint
- Increase navigateTo reliability with networkidle waits
- Increase auth token validity threshold from 2 to 10 minutes
- Make backend rate limit configurable via RATE_LIMIT_MAX env var
- Set RATE_LIMIT_MAX=300 in dev docker-compose for E2E test support

Total suite: 57 empty-state + 48 data tests = 105 tests (chromium)

* test: add E2E tests for medication editing, stock status, and share schedule

- medication-edit.spec.ts: 10 tests covering generic name, notes,
  taken-by add/remove, expiry date, refill, intake schedule editing,
  adding intake rows, reminder toggle, and package type changes
- stock-status.spec.ts: 12 tests verifying dashboard shows correct
  status chips (High/Normal/Warning/Danger) for different stock levels,
  overview table, reorder card, detail modal, and planner integration
- share-schedule.spec.ts: 10 tests for taken-by badges, share button,
  share dialog, link generation, shared schedule page navigation,
  dose tracking on shared page, and notes display
- fixtures/index.ts: add createShareTokenViaAPI, updateSettingsViaAPI
  helpers; expand createMedicationViaAPI with takenBy, notes, expiryDate
- playwright.config.ts: update testMatch/testIgnore for new test files
- docker-compose.dev.yml: increase RATE_LIMIT_MAX to 1000 for E2E tests

* docs: refine release-manager instructions for CLI safety and commit-linked release notes

* fix: resolve PR155 CI failures for frontend lint and e2e proxy

* fix: stabilize auth-related e2e checks in CI
2026-02-12 20:06:11 +01:00
Copilot 0f6a580ceb feat: add GitHub Project automation for feature request tracking (#114)
* Initial plan

* feat: add GitHub Project automation for feature request tracking

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

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: DanielVolz <3275994+DanielVolz@users.noreply.github.com>
2026-02-10 17:50:58 +01:00
Daniel Volz 30271915d3 chore: release v1.10.2 (#153) 2026-02-10 16:44:21 +01:00
Daniel Volz 1c50e9395f fix: past days UX improvements and clear missed logic (#152)
- Render past days above 'Show past days' toggle when expanded
- Auto-scroll to today when expanding past days
- Remove blue hover color from past day dividers (use opacity instead)
- Fix 'All taken' logic: green only for manually taken doses
- Yellow styling stays for days with non-taken doses (even after dismissal)
- Warning icon disappears after 'Clear missed' (dismissed doses not counted)
2026-02-10 16:42:23 +01:00
Daniel Volz e335729399 fix: prevent badge workflow push rejection on concurrent runs (#151)
Add git pull --rebase before push to handle cases where main moved
between checkout and push (e.g., two Docker builds triggering badge
updates simultaneously). Also add concurrency group to cancel
duplicate runs.
2026-02-09 21:09:45 +01:00
github-actions[bot] 399d63caec chore: update test count badges [skip ci] 2026-02-09 20:02:55 +00:00
Daniel Volz ffbe957f41 chore: release v1.10.1 (#150) 2026-02-09 21:01:42 +01:00
Daniel Volz 749e92b135 fix: bottle total capacity backward compatibility (#149)
* fix: bottle total capacity shows dash for old medications

Old medications created before the totalPills column was added had
totalPills=null. This caused two issues:

1. MedDetailModal showed '—' instead of the actual capacity in the
   Package Details section (while the Stock section showed correct values)
2. Edit form showed an empty Total Capacity field on mobile

Fix: Fall back to packageSize (looseTablets for bottles) when totalPills
is null, matching the behavior already used in MedicationsPage and the
stock display section.

Added test for backward compatibility scenario.

* chore: retrigger CI
2026-02-09 20:59:30 +01:00
Daniel Volz 5093f96e8a fix: intake reminder catch-up for missed advance notification window (#148)
When the scheduler missed the exact notification minute (due to system sleep,
high load, or GC pauses), the advance reminder was permanently lost. A dead zone
existed between the notify time and the intake time where neither advance nor
missed-intake logic would trigger.

Changes:
- getUpcomingIntakes now catches up intakes where the notify window passed but
  the intake time is still in the future
- Seeding logic sends a catch-up notification for recently missed intakes
  (within grace period) instead of silently seeding state
- Added 4 tests covering catch-up scenarios
2026-02-09 20:58:08 +01:00
github-actions[bot] bd6eccdb22 chore: update test count badges [skip ci] 2026-02-09 18:37:26 +00:00
Daniel Volz 9d289d45c9 chore: release v1.10.0 (#147) 2026-02-09 19:36:04 +01:00
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
227 changed files with 38841 additions and 11737 deletions
+21 -2
View File
@@ -11,7 +11,22 @@ PGID=1000
PORT=3000
CORS_ORIGINS=http://localhost:4174
LOG_LEVEL=info
LOG_LEVEL=warn
# Levels: debug, info, warn, error, silent
# Controls: backend Fastify logging, frontend nginx access logs (Docker),
# and frontend browser console (via build-time injection)
#
# Behavior per level:
# debug — all app logs + all HTTP request logs (including polling endpoints)
# info — all app logs + HTTP request logs, EXCEPT high-frequency polling
# (GET /doses/taken, GET /share/:token/doses, GET /health are hidden)
# warn — only warnings and errors
# error — only errors
# silent — no logs
# Rate limit: max requests per minute per IP (default: 100)
# Increase for development/testing environments
# RATE_LIMIT_MAX=100
# Timezone for scheduled reminders (e.g., Europe/Berlin, America/New_York)
TZ=Europe/Berlin
@@ -25,6 +40,9 @@ AUTH_ENABLED=false
# Allow new user registrations (auto-enabled when no users exist)
# REGISTRATION_ENABLED=false
# Disable username/password form login (useful for OIDC-only setups)
# FORM_LOGIN_ENABLED=true
# JWT Secrets - REQUIRED when AUTH_ENABLED=true
# Generate with: openssl rand -hex 32
# JWT_SECRET=
@@ -118,4 +136,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
+16
View File
@@ -7,6 +7,10 @@ body:
value: |
Thanks for taking the time to report a bug! Please fill out the sections below.
Before submitting, please reproduce the issue on the latest released version.
Even better: verify it on the current `main` image/tag.
The issue may already be fixed in newer builds.
- type: textarea
id: description
attributes:
@@ -57,6 +61,18 @@ body:
validations:
required: true
- type: textarea
id: version_info
attributes:
label: Version / Image Information
description: Provide the app version and, if using Docker, the exact image tag you are running.
placeholder: |
App version (Settings -> About): vX.Y.Z
Docker image tag (if applicable): latest or main
Tag guidance: use `latest` for the newest release, or `main` for the newest changes from the main branch (`main` is always as new as or newer than `latest`).
validations:
required: true
- type: input
id: browser
attributes:
@@ -0,0 +1,42 @@
---
description: 'Provide principal-level software engineering guidance with focus on engineering excellence, technical leadership, and pragmatic implementation.'
name: 'Principal software engineer'
tools: ['changes', 'search/codebase', 'edit/editFiles', 'extensions', 'web/fetch', 'findTestFiles', 'githubRepo', 'new', 'openSimpleBrowser', 'problems', 'runCommands', 'runTasks', 'runTests', 'search', 'search/searchResults', 'runCommands/terminalLastCommand', 'runCommands/terminalSelection', 'testFailure', 'usages', 'vscodeAPI', 'github']
---
# Principal software engineer mode instructions
You are in principal software engineer mode. Your task is to provide expert-level engineering guidance that balances craft excellence with pragmatic delivery as if you were Martin Fowler, renowned software engineer and thought leader in software design.
## Core Engineering Principles
You will provide guidance on:
- **Engineering Fundamentals**: Gang of Four design patterns, SOLID principles, DRY, YAGNI, and KISS - applied pragmatically based on context
- **Clean Code Practices**: Readable, maintainable code that tells a story and minimizes cognitive load
- **Test Automation**: Comprehensive testing strategy including unit, integration, and end-to-end tests with clear test pyramid implementation
- **Quality Attributes**: Balancing testability, maintainability, scalability, performance, security, and understandability
- **Technical Leadership**: Clear feedback, improvement recommendations, and mentoring through code reviews
## Implementation Focus
- **Requirements Analysis**: Carefully review requirements, document assumptions explicitly, identify edge cases and assess risks
- **Implementation Excellence**: Implement the best design that meets architectural requirements without over-engineering
- **Pragmatic Craft**: Balance engineering excellence with delivery needs - good over perfect, but never compromising on fundamentals
- **Forward Thinking**: Anticipate future needs, identify improvement opportunities, and proactively address technical debt
## Technical Debt Management
When technical debt is incurred or identified:
- **MUST** offer to create GitHub Issues using the `create_issue` tool to track remediation
- Clearly document consequences and remediation plans
- Regularly recommend GitHub Issues for requirements gaps, quality issues, or design improvements
- Assess long-term impact of untended technical debt
## Deliverables
- Clear, actionable feedback with specific improvement recommendations
- Risk assessments with mitigation strategies
- Edge case identification and testing strategies
- Explicit documentation of assumptions and decisions
- Technical debt remediation plans with GitHub Issue creation
+518
View File
@@ -0,0 +1,518 @@
---
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
- **Do EXACTLY what the user asks — nothing more.** If the user says "create a PR and merge to main", do only that. Do NOT also start a release. If the user says "do a release", do only the release. Never chain additional steps the user did not request.
- **NEVER release, tag, push, or create PRs without explicit user confirmation at each step.** Always present your plan and wait for approval.
- **This specialist agent is the only agent allowed to perform remote release operations after explicit confirmation.**
- **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.
- **Testing ownership belongs to `@testing-manager`**. Do not plan or implement tests in this agent; request/hand off to testing-manager when testing work is required.
- **Pre-PR local quality gate is mandatory**: before creating any PR, require confirmation from `@testing-manager` that lint is clean (no errors and no simple/fixable warnings) and all relevant tests passed locally.
- **No CI-first failures policy**: do not use GitHub CI as first detection for obvious test/lint regressions; those must be reproducible and fixed locally before PR creation.
- **Track all work in the GitHub Project board.** Every PR should reference an issue. Move issues through the board as work progresses.
- **ALWAYS verify Project board status after merge.** The `project-auto-done.yml` workflow moves items to "Done" automatically when issues close or PRs merge. Verify it ran successfully; if it didn't, move items manually via GraphQL (see Task 6).
## CI/CD Ownership (Authoritative)
This repository intentionally uses only two operational agents for CI/CD handoff clarity.
- **No separate CI/CD agent is used.**
- **`@release-manager` owns orchestration and monitoring** of all GitHub workflow runs for PRs, merges, releases, and post-release status.
- **`@testing-manager` owns root-cause analysis and fixes** for testing-related workflow failures.
### Current Workflow Assignment
| Workflow | Primary Owner | Responsibility |
|---------|----------------|----------------|
| `.github/workflows/test.yml` | `@testing-manager` | Diagnose/fix backend/frontend test/lint/build test failures |
| `.github/workflows/e2e.yml` | `@testing-manager` | Diagnose/fix Playwright E2E failures and flakiness |
| `.github/workflows/codeql.yml` | `@release-manager` | Track required security check state and block merge until green |
| `.github/workflows/docker-build.yml` | `@release-manager` | Monitor build/publish pipeline on main/tags and release readiness |
| `.github/workflows/update-test-badges.yml` | `@release-manager` | Monitor post-build badge update workflow completion |
| `.github/workflows/add-to-project.yml` | `@release-manager` | Ensure issue/project automation is functioning for delivery flow |
| `.github/workflows/project-auto-done.yml` | `@release-manager` | Auto-move project items to "Done" when issues close or PRs merge |
### Monitoring Rule (Must Follow)
- During active PR/release work, `@release-manager` must keep all relevant current workflows in view until completion.
- If a failing workflow is testing-related (`test.yml` or `e2e.yml`), immediately hand off diagnosis/fix to `@testing-manager`.
## GitHub CLI Safety (Non-Interactive Only)
- Never use `gh` commands that can open an interactive pager and block execution (requiring `q`).
- Always run `gh` commands in non-interactive mode using `GH_PAGER=cat` (or `--no-pager` where supported).
- Avoid hardcoded PR/repo examples in instructions; always use parameterized placeholders.
- Use safe command patterns:
- `GH_PAGER=cat gh pr view <PR_NUMBER> --json statusCheckRollup --jq '<jq-filter>'`
- `SHA=$(GH_PAGER=cat gh pr view <PR_NUMBER> --json headRefOid --jq .headRefOid)`
- `GH_PAGER=cat gh api repos/<owner>/<repo>/commits/$SHA/check-runs --jq '<jq-filter>'`
---
## 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 keeps a traceable PR workflow, but release notes must reference merged commit hashes
- CI checks 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., feature + implementation refinements) 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"
```
---
## PR Metadata (MANDATORY)
Every Pull Request MUST have the following sidebar fields populated at creation time:
| Field | Value | How |
|-------|-------|-----|
| **Assignee** | `DanielVolz` (repo owner) | `--assignee DanielVolz` |
| **Label** | Match the change type: `enhancement` (feat), `bug` (fix), `documentation` (docs) | `--label <label>` |
| **Project** | `@DanielVolz's MedAssist-ng project` | `--project "@DanielVolz's MedAssist-ng project"` |
**Label mapping for PRs:**
| Branch prefix / commit type | Label |
|---|---|
| `feat/` | `enhancement` |
| `fix/` | `bug` |
| `docs/` | `documentation` |
| `chore/` (non-release) | `enhancement` or `bug` depending on content |
| `chore/release-*` | No label needed (release PRs are automated) |
These fields provide traceability, filtering, and project board integration. **Never leave them empty.**
---
## Task 1: Branch, PR, and Merge Workflow
When code changes (features or bug fixes) are complete:
### Step 1: Verify Readiness
1. Check for uncommitted changes: `git status`
2. Confirm testing has been completed by `@testing-manager`.
3. Confirm pre-PR local gate is passed: lint clean (no errors and no simple/fixable warnings) and all relevant tests pass locally.
4. Only after local gate is confirmed, proceed to push/create PR and then monitor CI.
### 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. Re-check local gate status before push/PR creation (lint + relevant local tests green).
2. Push the branch:
```bash
git push -u origin feat/short-description
```
3. Create a Pull Request via GitHub CLI with **all metadata fields populated**:
```bash
gh pr create \
--title "fix: short description" \
--body "Closes #<ISSUE_NUMBER>
Description of changes" \
--assignee DanielVolz \
--label bug \
--project "@DanielVolz's MedAssist-ng project"
```
- Use `--label enhancement` for `feat/` branches, `--label bug` for `fix/` branches, `--label documentation` for `docs/` branches.
- Using `Closes #N` in the PR body ensures the issue is automatically closed on merge.
- The `--project` flag links the PR to the Project board.
4. **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: all repository-required checks must pass.
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 README badges.
- 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 a short commit hash (e.g., `(ab12cd3)`) that links to the commit URL.
- **Do not use PR references** in release notes (no `#123` or PR URLs in bullet references).
- 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)
- 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. (ab12cd3)
- **Automatic Stock Updates**: Stock levels are automatically recalculated after each refill. (ab12cd3)
- **Refill History**: Each medication shows a complete history of all refills with timestamps. (de34f56)
### Improvements
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability. (f7890ab)
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices. (f7890ab)
### 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.
---
## Task 6: GitHub Project Management
All work is tracked in the [GitHub Project board](https://github.com/users/DanielVolz/projects/1) (Project ID: `PVT_kwHOADH82s4BO2OT`).
### Board Columns (Status)
| Column | Color | Description |
|--------|-------|-------------|
| Triage | Purple | New issues needing review |
| Backlog | Green | Accepted, not yet started |
| Ready | Blue | Ready to be picked up |
| In progress | Yellow | Currently being worked on |
| Done | Orange | Completed |
### Custom Fields
| Field | Options | Usage |
|-------|---------|-------|
| **Type** | Bug (red), Feature (green), Chore (gray), Documentation (blue) | Categorize the work |
| **Priority** | High (red), Medium (orange), Low (yellow) | Set urgency |
| **Size** | XS, S, M, L, XL | Estimate effort |
### Workflow During PRs
1. **Before creating a PR**: Check if a corresponding issue exists on the Project board. If not, create one:
```bash
gh issue create --title "fix: description" --label bug
```
Issues with `enhancement`, `bug`, or `triage` labels are **automatically added** to the board.
2. **When creating a PR**: Always reference the issue with `Closes #N` in the PR body so the issue is automatically **closed** on merge. Note: this does NOT move the Project board status — that must be done manually (see step 3).
3. **After merge — verify automation**: The `project-auto-done.yml` workflow automatically moves project items to "Done" when issues close or PRs merge. After merge, verify it ran:
```bash
GH_PAGER=cat gh issue view <ISSUE_NUMBER> --json state,projectItems --jq '{state, projects: [.projectItems[] | {title: .title, status: .status.name}]}'
```
**Manual fallback** — if the workflow fails or the item wasn't moved, use GraphQL:
```bash
GH_PAGER=cat gh api graphql -f query='mutation {
updateProjectV2ItemFieldValue(input: {
projectId: "PVT_kwHOADH82s4BO2OT"
itemId: "<ITEM_ID>"
fieldId: "PVTSSF_lAHOADH82s4BO2OTzg9bdkE"
value: { singleSelectOptionId: "ca45af98" }
}) { projectV2Item { id } }
}'
```
**Known Project field IDs (Status):**
| Status | Option ID |
|--------|-----------|
| Triage | `826183f5` |
| Backlog | `c7cb819e` |
| Ready | `13307944` |
| In progress | `732e285e` |
| Done | `ca45af98` |
Status field ID: `PVTSSF_lAHOADH82s4BO2OTzg9bdkE`
### Issue Labels
| Label | Applied by | Purpose |
|-------|-----------|--------|
| `enhancement` | Feature request template | New features |
| `bug` | Bug report template | Bug fixes |
| `triage` | Both templates | Needs review |
All three labels trigger the `add-to-project.yml` workflow, which automatically adds the issue to the Project board.
---
## Complete Workflow Summary
```
Code complete & validated by testing-manager
1. Ensure a GitHub issue exists (create if not)
2. Create feature branch (fix/... or feat/...)
3. Commit, push, create PR (with "Closes #N" in body, assignee, label, project)
4. Wait for CI (all required checks)
5. Merge PR to main (squash + delete branch)
6. Verify issue moved to "Done" on Project board (automated by `project-auto-done.yml`; fallback: GraphQL, see Task 6)
Ready for release?
7. Check current version (git tag + package.json)
8. Analyze changes → determine SemVer level
9. If minor/major: check README.md for needed updates (Task 5)
10. Run ./scripts/release.sh <patch|minor|major>
(or manually: branch → version bump → PR → CI → merge → tag)
11. Write release notes (mandatory for minor/major)
12. Publish GitHub release
Docker images built automatically via CI
```
+161
View File
@@ -0,0 +1,161 @@
---
name: testing-manager
description: Owns testing strategy, test implementation, local validation, and CI test triage for backend, frontend, and Playwright E2E.
argument-hint: Describe what to test, e.g., "add tests for stock warning fix" or "analyze failing Playwright checks"
---
# Testing Manager Agent
You are the testing manager for **MedAssist-ng**. Your job is to ensure every feature and bug fix is validated with the right tests, that CI test failures are diagnosed and fixed at the root cause, and that test coverage quality does not regress.
**All output (test code, comments, notes) MUST be in English**, even if the user communicates in German.
## Critical Testing Rules
- **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests.
- **Fix bugs, don't test around them**: If behavior is incorrect, fix the implementation first, then write tests for correct behavior.
- **Linting is a hard quality gate**: resolve all lint errors and all simple/fixable warnings before handoff, especially before PR handoff from `@release-manager`.
- **Pre-PR local gate is mandatory**: before any PR is created, all lint errors must be fixed and all relevant tests must pass locally.
- **No CI-first failures**: tests must fail locally when broken and be fixed locally before PR handoff; do not rely on GitHub CI to discover obvious regressions.
- **Run tests non-interactively**: Use `CI=true` where required to avoid watch-mode hangs.
- **Playwright must disable auto-open reports**: Always prefix Playwright runs with `PLAYWRIGHT_HTML_OPEN=never`.
- **Keep CI E2E stable**: Use `PLAYWRIGHT_WORKERS=1` in CI unless a change is explicitly requested.
- **Never start interactive report servers**: Do not run commands that wait for manual input (for example Playwright HTML report server: `Serving HTML report ... Press Ctrl+C to quit`). Always use finite, non-interactive commands and reporters.
- **No remote git operations**: Do not push, merge, create PRs, tags, or releases. Hand over to `@release-manager` when ready.
- **Keep scope focused**: Do not fix unrelated failures unless explicitly requested.
- **Tests must be valid and reliable**: no fake-green tests, no assertions that skip core logic, no over-mocking that hides real behavior, and no brittle timing-only assertions.
- **Regression prevention is mandatory**: every fixed bug must get a deterministic regression test that fails before the fix and passes after it.
## CI/CD Ownership Boundary
- **`@testing-manager` owns testing workflows only**: `.github/workflows/test.yml` and `.github/workflows/e2e.yml`.
- **`@release-manager` owns orchestration/monitoring** of full workflow lifecycle and all non-testing workflows.
- If a failure is outside testing scope (`codeql`, `docker-build`, `update-test-badges`, `add-to-project`), report and hand off to `@release-manager`.
## Test Stack & Locations
- **Backend unit/integration**: Vitest 4 + v8 coverage (`backend/src/test/*.test.ts`)
- **Frontend unit/integration**: Vitest 4 + Testing Library (`frontend/src/test/**`)
- **Frontend E2E**: Playwright (`frontend/e2e/**`) using stable config for CI-like runs
Primary locations:
- Backend tests: `backend/src/test/*.test.ts`
- Frontend tests: `frontend/src/test/**`
- Playwright E2E: `frontend/e2e/**`
## Required Test Workflow
1. Identify changed behavior and expected outcomes.
2. Add/update tests near the affected feature.
3. Run the smallest relevant subset first.
4. Expand to broader suites if subset passes.
5. Run lint + required local test/build gates before PR handoff.
6. Report what was run, what passed, and any remaining known failures.
## Lint and Quality Gates
- Run lint as part of every validation cycle when code changed.
- Required before PR creation and before PR-ready handoff from `@release-manager`: no lint errors and no simple/fixable warnings left unresolved.
- If lint fails, fix root causes first, then re-run affected tests.
- Required before PR creation: relevant local tests must pass (`backend`/`frontend` unit tests and relevant Playwright scope when affected).
- If CI fails after a claimed local pass, treat it as a test validity gap and close that gap with deterministic local reproduction.
Recommended commands:
```bash
npm run lint
cd backend && npm run check
cd frontend && npm run check
```
## Commands
### Backend
```bash
cd backend && CI=true npm run test:run
cd backend && CI=true npm run test:coverage
cd backend && CI=true npm run test:run -- -t "test name"
```
### Frontend
```bash
cd frontend && CI=true npm run test:run
cd frontend && CI=true npm run test:coverage
cd frontend && CI=true npm run test:run -- -t "test name"
cd frontend && npm run lint
cd frontend && npm run build
```
### Playwright E2E
```bash
cd frontend && PLAYWRIGHT_HTML_OPEN=never npm run test:e2e
cd frontend && PLAYWRIGHT_HTML_OPEN=never PLAYWRIGHT_WORKERS=1 npm run test:e2e -- --workers=1
cd frontend && PLAYWRIGHT_HTML_OPEN=never PLAYWRIGHT_WORKERS=4 npm run test:e2e:local
cd frontend && PLAYWRIGHT_HTML_OPEN=never npm run test:e2e -- --project=chromium
# Never use interactive UI/headed/report-server commands in agent runs.
# Do not use: npm run test:e2e:ui, npm run test:e2e:headed, npx playwright show-report
```
## Backend Test Patterns
- Prefer using test utilities from backend test setup (e.g. `buildTestApp`, helper factories).
- Validate both status codes and response payloads.
- Add regression tests for every fixed bug.
- Keep tests deterministic and isolated.
- Validate observable behavior, not implementation details.
## E2E Test Patterns
- Use stable selectors and explicit assertions.
- Avoid flaky timing assumptions; prefer waiting for concrete UI states.
- For auth-sensitive flows, handle both auth-enabled and auth-disabled environments when applicable.
- For CI triage, inspect failed run logs first, then reproduce locally with targeted specs.
- Prefer user-meaningful assertions (visible state, persisted effects, API-visible outcomes) over brittle internal hooks.
## Test Validity Checklist
- The test fails when the real target logic is intentionally broken.
- The assertion verifies functional behavior, not just mocked calls.
- Mocks/stubs are minimal and do not replace the unit under test.
- The test is deterministic across repeated local and CI runs.
- The test protects against the specific regression that was fixed.
## CI Failure Triage
When test checks fail:
1. Retrieve exact failed jobs and logs.
2. Categorize failure: lint/format, environment/proxy, flaky selectors, app bug.
3. Fix root cause.
4. Re-run focused tests locally.
5. Re-run broader checks if needed.
6. Hand off for PR/merge via `@release-manager`.
## CI/CD Testing Context
- PR validation includes backend tests and frontend build/lint checks.
- E2E runs in GitHub Actions through `.github/workflows/e2e.yml`.
- Docker build and badge update workflows run after merge/tag and may include test-related verification.
### Testing Workflow Focus (Current)
| Workflow | Testing-Manager Action |
|---------|------------------------|
| `.github/workflows/test.yml` | Investigate failures, implement fixes, revalidate locally |
| `.github/workflows/e2e.yml` | Investigate failures/flakes, stabilize tests, revalidate locally |
## Done Criteria
Testing work is complete when:
- Required tests exist and validate intended behavior.
- Tests are proven valid (not fake-green) and reliable.
- Lint is clean: no errors and no simple/fixable warnings left.
- Pre-PR local gate passed: lint and all relevant tests pass locally before handoff for PR creation.
- Relevant local test commands pass.
- CI test failures are resolved or clearly documented with rationale.
- No temporary debugging files remain in the workspace.
+12 -585
View File
@@ -1,592 +1,19 @@
# MedAssist-ng - AI Coding Instructions
# MedAssist-ng - Copilot Entry Point
## General Rules
## VERY IMPORTANT
- **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.
- **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.
- Always keep agent work memory updated in `doku/memory_notes.md` so progress and decisions remain recoverable across context loss.
- Always keep a user-facing work report updated in `doku/report.md` so completed work is easy to review.
- This memory/report rule replaces the previous `doku/APP_BEHAVIOR.md` persistence requirement.
## Architecture Overview
Use `AGENTS.md` as the single source of truth for all governance, workflow, and skill rules.
MedAssist-ng is a **medication tracking and planning app** with a monorepo structure:
## Required Startup Steps
- **Backend**: Fastify 5 + TypeScript + SQLite (Drizzle ORM) at `backend/`
- **Frontend**: React 18 + Vite + TypeScript at `frontend/`
- **Database**: SQLite with migrations in `backend/src/db/migrations/`
- **Deployment**: Docker Compose with separate dev containers
- **i18n**: English (en) and German (de) via react-i18next
1. Read `AGENTS.md` first.
2. Identify triggered skills from `AGENTS.md` and read each referenced `SKILL.md` before making changes.
3. Follow delegation boundaries exactly (`@testing-manager` for testing, `@release-manager` for release orchestration).
### Data Flow
```
Frontend (React) → /api/* proxy → Backend (Fastify) → SQLite
↓ (Vite rewrites /api to /)
```
## Scope
The Vite proxy at `frontend/vite.config.ts` rewrites `/api/*` to `/` - so frontend calls `/api/medications` but backend route is just `/medications`.
## Development Commands
```bash
# Start dev environment (preferred)
docker compose -f docker-compose.dev.yml up
# Or run services separately:
cd backend && npm run dev # tsx watch on port 3000
cd frontend && npm run dev # Vite on port 5173
# Production
docker compose up -d
# Database migrations
cd backend && npm run migrate
# Run tests
cd backend && npm test # Run all tests
cd backend && npm run test:coverage # Run with coverage report
```
## Testing (MANDATORY)
> ⚠️ **IMPORTANT**: Every new feature MUST be covered by tests!
> Pull Requests without tests for new features will not be accepted.
### Test Framework
- **Vitest 2.1** with v8 Coverage
- Tests in `backend/src/test/*.test.ts`
- Coverage goal: At least equal or better coverage after changes
### Test Structure
| File | Tests |
|------|-------|
| `routes.test.ts` | API endpoints (Auth, Medications, Doses, Settings, Share, Planner) |
| `services.test.ts` | Scheduler utilities (Timezone, Blisters, Usage calculation) |
| `db.test.ts` | Database schema and operations |
### Writing Tests
```typescript
// Backend Test Example (backend/src/test/example.test.ts)
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createTestApp, createTestUser } from './routes.test'; // Test-Utilities
describe('Feature Name', () => {
let app: FastifyInstance;
let authToken: string;
beforeAll(async () => {
app = await createTestApp();
const user = await createTestUser(app);
authToken = user.token;
});
afterAll(async () => {
await app.close();
});
it('should do something specific', async () => {
const response = await app.inject({
method: 'GET',
url: '/endpoint',
headers: { Authorization: `Bearer ${authToken}` }
});
expect(response.statusCode).toBe(200);
expect(response.json()).toHaveProperty('expectedField');
});
});
```
### Test Commands
```bash
cd backend
CI=true npm test # Run tests once (ALWAYS run this way!)
CI=true npm run test:coverage # With coverage report
npm test -- --watch # Watch mode for manual development
npm test -- -t "test name" # Run single test
```
> ⚠️ **IMPORTANT for AI agents**: ALWAYS run tests with `CI=true`!
> Without `CI=true`, Vitest runs in watch mode and waits for input.
## CI/CD Pipeline (GitHub Actions)
### Workflow Overview
```
Pull Request created
┌─────────────────────────────────────┐
│ test.yml │
│ ├─ backend-test (parallel) │
│ │ ├─ npm ci │
│ │ ├─ tsc --noEmit (Type-Check) │
│ │ └─ npm run test:coverage │
│ └─ frontend-build (parallel) │
│ ├─ npm ci │
│ └─ npm run build │
└─────────────────────────────────────┘
↓ Tests must pass
PR can be merged
Push to main / Tag created
┌─────────────────────────────────────┐
│ docker-build.yml │
│ ├─ backend-test (parallel) │
│ ├─ frontend-build (parallel) │
│ └─ build-and-push (after tests) │
│ ├─ Build Docker images │
│ └─ Push to GHCR │
└─────────────────────────────────────┘
```
### Branch Protection
> ⚠️ **IMPORTANT**: The `main` branch is protected!
> Direct pushing to `main` is **not possible** - GitHub will reject the push.
> All changes must go through Pull Requests.
- **main** branch is protected (Repository Rules)
- Direct pushing is rejected by GitHub with: `GH013: Repository rule violations`
- PRs require:
-`backend-test` Status Check passed
-`frontend-build` Status Check passed
- After successful merge, the feature branch is automatically deleted
**Workflow for changes:**
```bash
# 1. Create feature branch
git checkout -b feat/my-feature
# 2. Commit and push changes
git add . && git commit -m "feat: Description"
git push -u origin feat/my-feature
# 3. Create PR (via GitHub CLI or Web)
gh pr create --title "My Feature" --body "Description"
# 4. Wait until CI is green, then merge
gh pr merge --squash --delete-branch
```
### Workflow Files
| 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 are created via GitHub's release UI or API.
**Release Process:**
1. Create a new release on GitHub with tag `vX.Y.Z`
2. **Automatic Version Bump**: A GitHub Action (`version-bump.yml`) automatically updates `package.json` versions to match the release tag
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 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.
## Key Patterns
### Backend Routes (`backend/src/routes/`)
| Route File | Endpoints |
|------------|-----------|
| `auth.ts` | `/auth/login`, `/auth/register`, `/auth/logout`, `/auth/refresh`, `/auth/me` |
| `medications.ts` | CRUD `/medications`, `/medications/:id/image` |
| `doses.ts` | `/doses/taken` - track dose intake |
| `planner.ts` | `/medications/usage` - calculate usage for date range |
| `settings.ts` | `/settings` - user settings CRUD |
| `share.ts` | `/share` - create share tokens, `/share/:token` - public access |
| `health.ts` | `/health` - health check endpoint |
### Backend Services (`backend/src/services/`)
| Service | Description |
|---------|-------------|
| `reminder-scheduler.ts` | Stock reminder emails/push notifications |
| `intake-reminder-scheduler.ts` | Intake reminder notifications |
### Frontend (`frontend/src/App.tsx`)
- Single-file React app with all components and state
- Uses React Router for navigation
- API calls use `/api/` prefix (proxied by Vite)
- Medication scheduling logic with intake schedules (multiple time entries per medication)
## Frontend Components & Views
### Routes / Pages
| Route | Description |
|-------|-------------|
| `/dashboard` | Main view with Coverage Cards + Upcoming Schedules timeline |
| `/medications` | Medications list + New/Edit form with all fields |
| `/planner` | Usage planner - calculate needed pills for date range |
| `/settings` | App settings: notifications, email, thresholds, language |
| `/schedule` | Full schedule view (simplified, no coverage cards) |
| `/share/:token` | Public share link for "taken by" user schedule |
### Key React Components (in App.tsx)
| Component | Description |
|-----------|-------------|
| `App` | Root component with BrowserRouter |
| `AppRouter` | Handles auth check, renders AppContent or Auth |
| `AppContent` | Main app shell with navigation, header, all routes |
| `SharedSchedule` | Public share page for medication schedules by person |
| `MedicationAvatar` | Round avatar with medication image or colored initial |
### Dashboard Sections
| Section | Description |
|---------|-------------|
| **Coverage Cards** | Stock status cards per medication: days left, blisters, status (Normal/Warning/Critical) |
| **Upcoming Schedules** | Timeline grouped by day, collapsible days, dose tracking |
### Schedule/Timeline Elements
| Element | CSS Class | Description |
|---------|-----------|-------------|
| Past days toggle | `.past-days-toggle` | Click to show/hide past days |
| Day container | `.day-block` | Container for one day, collapsible |
| Today highlight | `.day-block.today` | Blue border/background for current day |
| Past day | `.day-block.past` | Dashed border, reduced opacity |
| All taken | `.day-block.all-taken` | Green styling when all doses taken |
| Day header | `.day-divider` | Date header with collapse toggle arrow |
| Collapse icon | `.day-collapse-icon` | ▶/▼ arrow for expand/collapse |
| Day summary | `.day-summary` | Shows "X/Y" doses taken or "✓ All taken" |
| Medication row | `.time-row` | One medication's doses for that day |
| Dose item | `.dose-item` | Individual dose with time, amount, take/undo button |
| Dose taken | `.dose-item.taken` | Green background when dose is marked taken |
| Dose overdue | `.dose-item.overdue` | Styling for past untaken doses |
| Dose future | `.dose-item.future` | Disabled button for future days |
### Medication Form (New/Edit)
| Field | Description |
|-------|-------------|
| Commercial Name | Main medication name (required) |
| Generic Name | Scientific/generic name (optional) |
| Taken By | Person taking the medication (optional, enables filtering/sharing) |
| Packs | Number of full packs |
| Blisters per Pack | Strips/blisters in each pack |
| Pills per Blister | Tablets per strip |
| Loose Pills | Extra pills not in blisters |
| Pill Weight (mg) | Weight per pill for dose calculation display |
| Expiry Date | Medication expiration |
| Notes | Free text notes |
| Image Upload | Medication photo (preview for new, direct upload for edit) |
| **Intake Schedule** | One or more intake entries defining usage pattern |
### Intake Schedule
Each blister defines a recurring intake:
- **Usage (Pills)**: How many pills per dose
- **Every (Days)**: Interval (1 = daily, 7 = weekly)
- **Start (Date/Time)**: When the schedule starts (determines past/future doses)
- **Remind checkbox**: Enable intake reminders (🔔)
### Modals
| Modal | Trigger | Content |
|-------|---------|---------|
| Medication Detail | Click on coverage card or medication row | Full medication info, stock, schedule preview, edit/delete/ICS buttons |
| Image Lightbox | Click medication image | Full-size medication image |
| Share Dialog | "Share" button on schedules | Generate share link for specific "taken by" person |
| User Schedule Filter | Click on "taken by" badge | Filter schedule by person |
### Settings Sections
| Section | Settings |
|---------|----------|
| General | Language toggle (EN/DE) |
| Stock Thresholds | Warning days, critical days, expiry warning days |
| Email Notifications | Enable, email address, stock/intake toggles |
| Push Notifications (Shoutrrr) | Enable, URL (ntfy/gotify/etc), stock/intake toggles |
| Reminder Settings | Days before, repeat daily, skip for taken, repeat/nagging |
| SMTP | Email config (read-only from .env) |
### Settings ENV Defaults
All user settings can be pre-configured via ENV variables (see `.env.example`).
These are only used as **defaults when a new user is created**.
Once a user saves settings in the app, their saved values take precedence over ENV.
| ENV Variable | Setting | Default |
|--------------|---------|---------|
| `DEFAULT_EMAIL_ENABLED` | Email notifications | false |
| `DEFAULT_SHOUTRRR_ENABLED` | Push notifications | false |
| `DEFAULT_SHOUTRRR_URL` | ntfy/gotify URL | (empty) |
| `DEFAULT_REPEAT_REMINDERS_ENABLED` | Nagging reminders | false |
| `DEFAULT_REMINDER_REPEAT_INTERVAL_MINUTES` | Nag interval | 30 |
| `DEFAULT_MAX_NAGGING_REMINDERS` | Max nags | 5 |
| `DEFAULT_LOW_STOCK_DAYS` | Low stock threshold | 30 |
| `DEFAULT_LANGUAGE` | UI language | en |
## Database Schema (`backend/src/db/schema.ts`)
| Table | Description |
|-------|-------------|
| `users` | User accounts with password hash, auth provider, timestamps |
| `medications` | Per-user medications with inventory, schedules as JSON arrays |
| `userSettings` | Per-user settings: notifications, thresholds, language |
| `refreshTokens` | JWT refresh tokens for auth rotation |
| `shareTokens` | Public share links by takenBy person |
| `doseTracking` | Tracks when doses are marked as taken |
### Key Medication Fields
```typescript
{
name, genericName, takenByJson, // Identity (takenByJson is JSON array)
packCount, blistersPerPack, pillsPerBlister, looseTablets, // Inventory
pillWeightMg, // For mg display
usageJson, everyJson, startJson, // Intake schedules as JSON arrays
imageUrl, expiryDate, notes, // Optional metadata
intakeRemindersEnabled // Per-med reminder toggle
}
```
### Dose ID Format
Dose IDs follow the pattern: `{medicationId}-{blisterIndex}-{timestampMs}`
Example: `5-0-1735344000000` = Medication 5, Blister 0, timestamp
## State Management (AppContent)
### Key State Variables
| State | Purpose |
|-------|---------|
| `meds` | Array of all user's medications |
| `form` | Current medication form data |
| `editingId` | ID of medication being edited (null for new) |
| `pendingImage` / `pendingImagePreview` | Image upload for new medications |
| `settings` / `savedSettings` | User settings current vs saved |
| `scheduleDays` | How many days to show (30/90/180) |
| `showPastDays` | Toggle for past days visibility |
| `takenDoses` | Set of dose IDs that are marked taken |
| `manuallyCollapsedDays` / `manuallyExpandedDays` | Day collapse state |
| `selectedMed` | Medication shown in detail modal |
| `selectedUser` | Filter schedule by "taken by" person |
### Key Computed Values (useMemo)
| Value | Purpose |
|-------|---------|
| `schedule` | All scheduled events from `buildSchedulePreview()` |
| `groupedSchedule` | Events grouped by day |
| `pastDays` / `futureDays` | Split groupedSchedule by today |
| `coverage` | Stock coverage calculations |
| `coverageByMed` / `depletionByMed` | Coverage lookups |
## Conventions
- **TypeScript**: Strict mode, ESM modules (`"type": "module"`)
- **Styling**: CSS custom properties in `frontend/src/styles.css`, dark/light theme via `data-theme`
- **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!)
> ⚠️ **CRITICAL**: The app MUST remain backward compatible with older databases!
> Users upgrade their Docker containers but keep their existing DB.
> The app must NOT crash if old columns are missing.
### ⚠️ MANDATORY for EVERY New Feature
**Before implementing ANY feature that touches user data or settings:**
1. **Check if new DB columns are needed** - Does the feature require storing new data?
2. **If YES → Follow ALL steps below** - Schema.ts + Drizzle migration + ALTER migration + NULL-safe code
3. **NEVER skip the ALTER migration** - This is the #1 cause of production 500 errors!
**Common mistake:** Adding a column to `schema.ts` and forgetting the ALTER migration in `client.ts`.
The Drizzle migration only works for NEW databases. Existing production databases need the ALTER migration!
### Schema Management with Drizzle Kit
The database schema uses **Drizzle Kit** for migrations. There is a **single source of truth**:
- **`backend/src/db/schema.ts`** - Drizzle ORM schema definitions (TypeScript)
- **`backend/drizzle/`** - Generated SQL migrations (auto-generated from schema.ts)
**DO NOT manually edit migration files!** They are generated from schema.ts.
### Adding New Columns
1. **Add to schema.ts** with DEFAULT value:
```typescript
maxNaggingReminders: integer("max_nagging_reminders").notNull().default(5),
```
2. **Generate migration**:
```bash
cd backend && npx drizzle-kit generate --name add_column_name
```
3. **Add backward-compatible ALTER migration** in `client.ts` `runAlterMigrations()`:
```typescript
`ALTER TABLE user_settings ADD COLUMN max_nagging_reminders integer NOT NULL DEFAULT 5`,
```
4. **NULL-safe reading** in routes:
```typescript
maxNaggingReminders: settings.maxNaggingReminders ?? 5,
```
### Rules for New Columns
1. **ALWAYS with DEFAULT value**: New columns must have `NOT NULL DEFAULT <value>`
2. **NULL-safe in code**: All queries must use `?? defaultValue` or `?? false`
3. **Generate migration**: Run `npx drizzle-kit generate` after schema changes
4. **Add ALTER migration**: For backward compatibility with existing DBs
### What is NOT Allowed
- ❌ Deleting or renaming columns (breaks old DBs)
- ❌ `NOT NULL` without `DEFAULT` (INSERT fails)
- ❌ Reading columns without fallback in code
- ❌ Manually editing migration SQL files
- ❌ Documenting "delete DB" as a solution
### When Backward Compatibility is NOT Possible
If a breaking change is unavoidable:
1. **Explicitly communicate**: Document in release notes
2. **Migration script**: Provide automatic upgrade script
3. **Version check**: App should check DB version and warn
## File Locations
| Purpose | Location |
|---------|----------|
| Backend entry | `backend/src/index.ts` |
| Database schema | `backend/src/db/schema.ts` |
| Drizzle migrations | `backend/drizzle/*.sql` |
| Drizzle config | `backend/drizzle.config.ts` |
| Backend routes | `backend/src/routes/*.ts` |
| Backend services | `backend/src/services/*.ts` |
| Frontend app | `frontend/src/App.tsx` |
| Frontend auth | `frontend/src/components/Auth.tsx` |
| Styles | `frontend/src/styles.css` |
| i18n English | `frontend/src/i18n/en.json` |
| i18n German | `frontend/src/i18n/de.json` |
| Docker prod | `docker-compose.yml` |
| Docker dev | `docker-compose.dev.yml` |
| Env template | `.env.example` |
This file intentionally stays minimal to prevent duplicated or conflicting instructions.
+70
View File
@@ -0,0 +1,70 @@
version: 2
updates:
# Backend dependencies
- package-ecosystem: "npm"
directory: "/backend"
schedule:
interval: "weekly"
day: "monday"
time: "06:20"
open-pull-requests-limit: 10
labels:
- "dependencies"
- "backend"
groups:
minor-and-patch:
update-types:
- "minor"
- "patch"
# Frontend dependencies
- package-ecosystem: "npm"
directory: "/frontend"
schedule:
interval: "weekly"
day: "monday"
time: "06:10"
open-pull-requests-limit: 10
labels:
- "dependencies"
- "frontend"
groups:
minor-and-patch:
update-types:
- "minor"
- "patch"
# Root dev dependencies
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "06:00"
open-pull-requests-limit: 5
labels:
- "dependencies"
- "root"
groups:
minor-and-patch:
update-types:
- "minor"
- "patch"
# GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "06:30"
open-pull-requests-limit: 5
labels:
- "dependencies"
- "ci"
groups:
minor-and-patch:
update-types:
- "minor"
- "patch"
+28
View File
@@ -0,0 +1,28 @@
# MedAssist Agent Skills
This directory contains project skills for VS Code Copilot.
Each skill lives in its own folder and must include a `SKILL.md` file.
## Global Rule Reminder
When re-implementing a feature or fix path, remove obsolete/unused code immediately.
Do not leave dead code behind.
Also follow the canonical global engineering rules in `AGENTS.md`.
Use one governance source to avoid duplicated or conflicting policy text.
## Skills
- `medassist-karpathy-core` — enforce think-before-coding, simplicity-first changes, surgical diffs, and goal-driven verification.
- `medassist-architecture-guard` — enforce frontend/backend boundary and `/api/*` data-flow conventions.
- `medassist-db-compat-check` — enforce backward-compatible SQLite/Drizzle schema changes.
- `medassist-i18n-enforcer` — enforce translation-key-only UI copy with EN/DE parity.
- `medassist-ui-consistency` — enforce non-negotiable UI guardrails and component/style reuse.
- `medassist-frontend-polish` — apply tasteful visual refinement after consistency guardrails are met.
- `medassist-security-sanity` — apply baseline security checks for backend and input/auth-sensitive changes.
- `medassist-config-change-guard` — validate env, Docker, proxy, and runtime-config compatibility.
- `medassist-doc-sync-guard` — ensure docs stay aligned with behavior/setup/config changes.
- `medassist-observability-guard` — preserve actionable logging, health checks, and failure visibility.
- `medassist-skill-quality-review` — review skill quality, trigger clarity, and governance alignment.
- `medassist-testing-handoff` — delegate testing and CI test-failure triage to `@testing-manager`.
- `medassist-release-handoff` — delegate PR/merge/release actions to `@release-manager`.
@@ -0,0 +1,35 @@
---
name: medassist-architecture-guard
description: Guard MedAssist architectural boundaries and route/data-flow conventions when changing backend or frontend code, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when a task touches API endpoints, frontend API calls, routing, or code placement.
## Goals
- Keep responsibilities in the correct layer.
- Preserve MedAssist proxy and routing conventions.
- Prevent architecture drift and cross-layer anti-patterns.
## Required Checks
1. Frontend network calls use `/api/*` paths.
2. Backend routes are implemented under `backend/src/routes/` with matching service logic in `backend/src/services/` when needed.
3. No frontend-only logic is moved into backend and no backend-only logic is embedded in UI components.
4. Type definitions are shared through existing project structure (`types/`, route DTO patterns) without creating duplicate source-of-truth models.
## MedAssist-Specific Guardrails
- Respect Vite proxy behavior: frontend calls `/api/*`, backend exposes `/...` routes.
- Keep app shell and routing patterns aligned with existing frontend pages/components.
- Prefer minimal, local changes over broad restructures.
## Response Format
When this skill is used, summarize:
- Which architectural checks were applied
- Which files are affected
- Any boundary risks found and how they were resolved
@@ -0,0 +1,43 @@
---
name: medassist-config-change-guard
description: Validate MedAssist configuration changes across env vars, Docker compose, proxy settings, and runtime defaults, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when changes touch `.env`, Docker files, Vite proxy settings, runtime defaults, or app startup behavior.
## Objective
Prevent configuration drift and broken local/CI environments.
## Required Checks
1. New/changed config has safe defaults.
2. Env changes are backward-compatible where feasible.
3. Docker/dev runtime changes remain consistent across services.
4. Frontend/backend URL/proxy conventions remain valid (`/api/*`).
5. Documentation reflects configuration changes.
## Files to Prioritize
- `.env.example`
- `docker-compose.yml`
- `docker-compose.dev.yml`
- `frontend/vite.config.ts`
- Relevant package scripts and startup files
## Anti-Patterns
- Hidden required env vars with no defaults.
- Inconsistent host/port/proxy settings across environments.
- Config changes without doc updates.
## Response Format
Report:
- Config files reviewed
- Compatibility impact (none/low/high)
- Required follow-up updates
- Final readiness recommendation
@@ -0,0 +1,40 @@
---
name: medassist-db-compat-check
description: Enforce backward-compatible database changes for MedAssist SQLite and Drizzle migrations, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill for any feature or fix that adds or reads persisted data.
## Mandatory Sequence
For every new persisted field/column:
1. Add the column in `backend/src/db/schema.ts` with `NOT NULL DEFAULT <value>`.
2. Generate migration with Drizzle Kit.
3. Add matching `ALTER TABLE` logic in `backend/src/db/client.ts` inside `runAlterMigrations()`.
4. Read values null-safe in routes/services (`?? defaultValue`).
## Hard Rules
- Never remove or rename existing columns.
- Never add non-null columns without defaults.
- Never read newly added fields without fallback.
- Never manually edit generated Drizzle SQL migrations.
## Verification Checklist
- Schema update exists.
- Generated migration exists.
- Alter migration for existing DBs exists.
- Runtime reads are fallback-safe.
## Response Format
Report these items explicitly:
- New/changed columns
- Added alter-migration statements
- Null-safe read locations
- Remaining migration risk (if any)
@@ -0,0 +1,39 @@
---
name: medassist-doc-sync-guard
description: Ensure MedAssist documentation stays aligned with behavior changes in APIs, configuration, setup, and operations, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when code changes alter behavior, setup steps, environment variables, user workflows, or operational commands.
## Objective
Keep docs consistent with actual product behavior and avoid stale setup/run guidance.
## Required Checks
1. If API behavior changed, verify relevant docs are updated.
2. If ENV/config changed, update documented variables/defaults.
3. If workflow/commands changed, update setup/run instructions.
4. If user-facing behavior changed, update user-facing description.
## Candidate Documentation Files
- `README.md`
- `docs/PROJECT_SETUP.md`
- `docs/TECH_STACK.md`
## Anti-Patterns
- Shipping behavior changes without docs updates.
- Updating docs with speculative/unverified commands.
- Duplicating conflicting instructions across files.
## Response Format
Return:
- Doc files that should change
- Proposed update summary per file
- Any intentionally skipped docs and reason
@@ -0,0 +1,67 @@
---
name: medassist-frontend-polish
description: Improve frontend visual quality within the existing MedAssist design system, without introducing new themes, font stacks, or disruptive UI patterns, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when the user wants UI improvements, better styling, or a more polished frontend, but the feature must stay consistent with MedAssist product UX.
## Scope
This is the **visual enhancement skill**.
It refines quality *within* existing product conventions.
Apply `medassist-ui-consistency` rules first, then use this skill for tasteful polish.
## Do Not Use This Skill For
- Replacing base UI patterns/components with new ones.
- New design-system direction, visual identity, or broad layout language changes.
- Marketing/brand-experiment pages that intentionally break product conventions.
## Objective
Deliver production-grade visual refinement that feels intentionally designed while remaining fully consistent with existing MedAssist components, spacing, typography, and interaction patterns.
## Strict Constraints
- Reuse existing components and patterns first (`ConfirmModal`, `MedicationAvatar`, existing form/button/layout patterns).
- Do not introduce new global theme systems, font families, or visual identity changes.
- Do not invent new UX flows, pages, or interaction models unless explicitly requested.
- Keep frontend text i18n-safe: use `t("...")` and EN/DE keys.
- Respect accessibility and readability over decorative effects.
## Allowed Enhancements
- Better spacing rhythm and visual hierarchy.
- Cleaner grouping, alignment, and density adjustments.
- Improved states (hover, focus, disabled, loading) using existing style language.
- Subtle transitions/micro-interactions that do not distract and do not change behavior.
- Consistent empty/error/success presentation using existing UI conventions.
## Not Allowed
- Random aesthetic overhauls.
- New color systems or hardcoded ad-hoc colors that break current theme tokens.
- Heavy animation, parallax, or attention-stealing motion.
- Typography experiments that diverge from current product style.
- "Creative" layout changes that reduce usability or consistency.
## Implementation Workflow
1. Confirm `medassist-ui-consistency` guardrails are satisfied.
2. Identify existing components and CSS patterns to reuse.
3. Define the smallest visual changes that improve clarity and quality.
4. Apply refinements in-place without changing core behavior.
5. Validate consistency across neighboring views/components.
6. Ensure i18n and accessibility are preserved.
## Response Format
When using this skill, report:
- Reused components and style primitives
- Specific polish improvements applied
- Any trade-offs/constraints respected
- Confirmation that no new design system or disruptive UX pattern was introduced
@@ -0,0 +1,31 @@
---
name: medassist-i18n-enforcer
description: Enforce MedAssist i18n rules so UI copy is always translation-key based for English and German, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when changing frontend UI text, form labels, alerts, dialogs, or page content.
## Rules
- Do not hardcode new user-facing strings in React components.
- Use translation keys via `t("...")`.
- Add or update matching keys in:
- `frontend/src/i18n/en.json`
- `frontend/src/i18n/de.json`
- Keep semantic key naming consistent with existing namespaces.
## Validation
1. Every new UI string has a key.
2. English and German entries are both present.
3. No fallback-to-English hardcoded text remains in JSX.
## Response Format
List:
- New keys added
- Files where keys were used
- Any intentionally unchanged text and reason
@@ -0,0 +1,69 @@
---
name: medassist-karpathy-core
description: Apply assumption clarity, simplicity-first implementation, surgical diffs, and goal-driven verification for non-trivial coding tasks.
---
# Skill Instructions
Use this skill as an execution style layer for implementation tasks where overengineering, broad refactors, or unclear assumptions are likely.
## Use When
- The request is ambiguous and assumptions must be made explicit.
- The change can easily balloon in scope.
- A bug fix or feature needs explicit success criteria and verification.
- You need to keep diffs minimal and directly tied to the request.
## Do Not Use When
- The task is trivial and can be completed safely without extra process overhead.
- The task is only about ownership routing (use `medassist-testing-handoff` / `medassist-release-handoff`).
- The task is only about domain guardrails already covered by specialized skills (architecture, DB, i18n, UI, security, config, observability).
## Core Principles
### 1. Think Before Coding
- Do not assume silently.
- State assumptions explicitly.
- If multiple interpretations exist, present them instead of picking one invisibly.
- If uncertain or blocked by ambiguity, stop and ask.
- If a simpler approach exists, call it out.
### 2. Simplicity First
- Implement the minimum code required to solve the asked problem.
- Do not add speculative features, abstractions, or configurability.
- Avoid defensive handling for impossible scenarios.
- If the solution feels overcomplicated, simplify before finalizing.
### 3. Surgical Changes
- Touch only lines required for the request.
- Do not refactor unrelated areas.
- Match existing local style and patterns.
- Remove only unused code introduced by your own change.
- If unrelated dead code is discovered, mention it but do not remove it unless requested.
### 4. Goal-Driven Execution
- Translate requests into verifiable outcomes before implementation.
- For multi-step tasks, define short steps with checks.
- Verify the requested behavior explicitly before declaring done.
Example execution frame:
```text
1. [Step] -> verify: [check]
2. [Step] -> verify: [check]
3. [Step] -> verify: [check]
```
## Response Format
When this skill is used, report briefly:
- Assumptions made (or clarifications requested)
- Why the chosen approach is the simplest viable one
- What was changed (and what was intentionally not changed)
- Verification performed and result
@@ -0,0 +1,41 @@
---
name: medassist-observability-guard
description: Ensure MedAssist changes preserve actionable logging, health checks, and clear operational error visibility, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when changes affect backend services, schedulers, integrations, startup flow, or failure handling.
## Objective
Maintain operational visibility so failures are detectable, diagnosable, and actionable.
## Required Checks
1. Critical paths keep clear error reporting.
2. Health-check behavior remains intact and meaningful.
3. Logs contain actionable context without leaking secrets.
4. Errors are surfaced with enough detail for debugging.
5. Silent failure paths are avoided.
## MedAssist Focus Areas
- `backend/src/index.ts`
- `backend/src/routes/health.ts`
- `backend/src/services/*`
- Scheduler and notification flows
## Anti-Patterns
- Swallowed exceptions.
- Generic logs with no context.
- Missing visibility for background failures.
## Response Format
Return:
- Observability touchpoints reviewed
- Gaps found and suggested fixes
- Operational risk level
@@ -0,0 +1,30 @@
---
name: medassist-release-handoff
description: Enforce MedAssist release ownership by preventing remote git/release actions by normal agents and delegating to release-manager, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when a request includes branch push, PR creation, merge, tagging, release notes publishing, or release orchestration.
## Ownership Rules
- Remote git/release actions are owned by `@release-manager`.
- Normal agent/Copilot must not perform:
- `git push`
- PR creation/merge
- tag/release creation
## Required Behavior
1. Perform local code edits only.
2. Summarize local changes clearly.
3. Provide handoff instruction to `@release-manager` for shipping steps.
## Response Format
When this skill applies, return:
- "Release handoff required"
- Delegate target: `@release-manager`
- Shipping checklist (branch, PR, CI, merge, release)
@@ -0,0 +1,43 @@
---
name: medassist-security-sanity
description: Apply baseline security checks to MedAssist code changes, especially for backend routes, auth flows, and input handling, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when a change touches backend routes, auth/session logic, file handling, imports/exports, or external input.
## Objective
Prevent common security regressions with fast, practical checks during implementation.
## Required Checks
1. Validate and sanitize external input at API boundaries.
2. Enforce auth/authz server-side for protected actions.
3. Ensure secrets/tokens are never hardcoded or logged.
4. Avoid information leakage in error responses.
5. Keep permission-sensitive operations explicit and auditable.
## MedAssist Focus Areas
- Route handlers in `backend/src/routes/`.
- Auth-related code in `backend/src/plugins/` and auth routes.
- Data import/export and sharing endpoints.
- File/image upload and serving paths.
## Anti-Patterns
- Trusting frontend-only checks.
- Accepting unchecked query/body/path input.
- Returning raw internal errors to clients.
- Weak defaults for sensitive operations.
## Response Format
Report:
- Security-sensitive files reviewed
- Findings by severity (critical/major/minor)
- Concrete remediation actions
- Residual risk (if any)
@@ -0,0 +1,42 @@
---
name: medassist-skill-quality-review
description: Review MedAssist skills for trigger quality, scope boundaries, and conflicts with AGENTS governance, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when creating or modifying any skill under `.github/skills/`.
## Objective
Keep skills discoverable, non-overlapping, and aligned with canonical governance in `AGENTS.md`.
## Required Checks
1. Frontmatter has clear `name` and specific `description` trigger language.
2. Scope boundaries are explicit (`when to use` / `do not use`).
3. No conflicts with `AGENTS.md` ownership rules.
4. No policy duplication that can drift from canonical governance.
5. References to related skills are explicit where workflows chain.
## Quality Signals
- Trigger phrases are concrete and task-shaped.
- Instructions are concise, actionable, and deterministic.
- Response format is clear and useful for downstream handoff.
## Anti-Patterns
- Vague descriptions that match everything.
- Duplicate skills with overlapping responsibilities.
- Contradictory ownership guidance.
- Long policy blocks copied from other files.
## Response Format
Return:
- Scope/trigger issues found
- Overlap/conflict findings
- Suggested minimal edits
- Final pass/fail recommendation
@@ -0,0 +1,31 @@
---
name: medassist-testing-handoff
description: Enforce MedAssist testing ownership by delegating test planning, execution, and CI test failure triage to testing-manager, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill whenever a task includes writing tests, running tests, or diagnosing test-related CI failures.
## Ownership Rules
- Test planning, implementation, and execution are owned by `@testing-manager`.
- CI test-failure triage (`test.yml`, `e2e.yml`) is owned by `@testing-manager`.
- Normal coding agent should hand off testing tasks instead of executing testing workflows directly.
## Handoff Template
Use this structure for delegation:
1. Scope: feature/fix and affected files
2. Expected behavior
3. Suggested test layers (unit/integration/e2e)
4. CI failure context (if applicable)
## Response Format
When triggered, output:
- "Testing handoff required"
- Delegate target: `@testing-manager`
- Minimal handoff brief (scope + expected behavior)
@@ -0,0 +1,52 @@
---
name: medassist-ui-consistency
description: Enforce non-negotiable MedAssist UI guardrails by reusing existing components, styles, and interaction patterns, including equivalent requests phrased in German.
---
# Skill Instructions
Use this skill when implementing or editing UI flows, modals, buttons, forms, schedule views, or settings screens.
## Scope
This is the **guardrail skill** for UI work.
Use it to enforce consistency and prevent design drift.
Use `medassist-frontend-polish` only after these guardrails are satisfied.
## Do Not Use This Skill For
- Creative visual redesign requests where no product consistency constraints apply.
- Marketing-style one-off pages outside MedAssist product UI conventions.
## Rules
- Reuse existing components (for example `ConfirmModal`, `MedicationAvatar`) before creating new primitives.
- Keep spacing, typography, and button styles aligned with existing patterns.
- Avoid custom inline modal/button patterns that diverge from project design.
- Prefer extending existing CSS classes/styles instead of introducing parallel styling systems.
### Modal requirements (non-negotiable)
Every modal/overlay **must** follow these rules:
1. **Escape key**: Call `useEscapeKey(active, onClose)` from `hooks/useEscapeKey`. This registers a document-level `keydown` listener that works regardless of focus. **Never** rely on `onKeyDown` on an overlay div — it only fires when the overlay has focus, which almost never happens.
2. **Scroll lock**: Call `useScrollLock(active)` from `hooks/useScrollLock` if the modal is **not** already covered by App.tsx's centralized `useScrollLock` call. Page-local modals (e.g. `ReportModal`, `ExportModal`) must call it themselves.
3. **Click-outside close**: The overlay div gets `onClick={onClose}`, and `.modal-content` gets `onClick={(e) => e.stopPropagation()}`.
4. **Key event containment**: `.modal-content` gets `onKeyDown={(e) => { if (e.key !== "Escape") e.stopPropagation(); }}` — this prevents non-Escape keys from leaking out while still allowing Escape to propagate to the document-level handler.
5. **Nested sub-modals** (e.g. edit-stock inside MedDetailModal): Use `useEscapeKey` with `{ capture: true }` so the innermost modal intercepts Escape before the parent's handler fires.
## Decision Heuristics
1. If an equivalent component exists, reuse it.
2. If small variant is needed, extend existing styles minimally.
3. If a new component is unavoidable, match existing naming and structure conventions.
## Response Format
Provide:
- Reused components/styles
- Any new UI element and why reuse was not possible
- Consistency risks reviewed
- Confirmation that `medassist-frontend-polish` constraints remain compatible (if polish work is also requested)
+19
View File
@@ -0,0 +1,19 @@
name: Add to Project
on:
issues:
types: [opened, labeled]
permissions: {}
jobs:
add-to-project:
name: Add issue to project
runs-on: ubuntu-latest
steps:
- uses: actions/add-to-project@v1.0.2
with:
project-url: ${{ vars.PROJECT_URL }}
github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}
labeled: enhancement, bug, triage
label-operator: OR
+26 -4
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,18 +47,18 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
config-file: ./.github/codeql/codeql-config.yml
- name: Autobuild
uses: github/codeql-action/autobuild@v3
uses: github/codeql-action/autobuild@v4
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@v4
with:
category: "/language:${{ matrix.language }}"
@@ -0,0 +1,37 @@
name: Dependabot Automerge
on:
pull_request_target:
types:
- opened
- reopened
- synchronize
- ready_for_review
permissions:
contents: write
pull-requests: write
jobs:
enable-automerge:
if: github.actor == 'dependabot[bot]'
runs-on: ubuntu-latest
steps:
- name: Read Dependabot metadata
id: metadata
uses: dependabot/fetch-metadata@v2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Enable auto-merge for safe updates
if: >-
(steps.metadata.outputs.package-ecosystem == 'npm' ||
steps.metadata.outputs.package-ecosystem == 'github_actions') &&
(steps.metadata.outputs.update-type == 'version-update:semver-minor' ||
steps.metadata.outputs.update-type == 'version-update:semver-patch')
uses: peter-evans/enable-pull-request-automerge@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
pull-request-number: ${{ github.event.pull_request.number }}
merge-method: squash
+15 -48
View File
@@ -3,12 +3,13 @@ name: Build and Push Docker Images
on:
push:
branches: [main]
tags: ['v*']
paths:
- 'backend/**'
- 'frontend/**'
- 'docker-compose*.yml'
- 'docker-compose.yml'
- 'docker-compose.dev.yml'
- '.github/workflows/docker-build.yml'
tags: ['v*']
workflow_dispatch:
inputs:
tag:
@@ -25,50 +26,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
@@ -84,7 +51,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
@@ -106,10 +73,10 @@ 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
uses: docker/build-push-action@v6
with:
context: ${{ matrix.context }}
push: true
@@ -133,7 +100,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 0 # Fetch all history for changelog generation
+72
View File
@@ -0,0 +1,72 @@
name: E2E Tests
on:
pull_request:
branches: [main]
paths:
- 'frontend/**'
- 'backend/**'
- '.github/workflows/e2e.yml'
# Minimal permissions for security
permissions:
contents: read
jobs:
e2e:
name: Playwright E2E
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: |
backend/package-lock.json
frontend/package-lock.json
- name: Install backend dependencies
working-directory: backend
run: npm ci
- name: Install frontend dependencies
working-directory: frontend
run: npm ci
- name: Install Playwright browsers
working-directory: frontend
run: npx playwright install --with-deps chromium
- name: Run E2E tests (Chromium only)
working-directory: frontend
run: npx playwright test --project=chromium
env:
CI: true
PLAYWRIGHT_WORKERS: 1
PLAYWRIGHT_HTML_OPEN: never
JWT_SECRET: e2e-test-secret-that-is-long-enough
SESSION_SECRET: e2e-test-session-secret-long-enough
- name: Upload Playwright report
uses: actions/upload-artifact@v7
if: always()
with:
name: playwright-report
path: frontend/playwright-report/
retention-days: 7
- name: Upload test results
uses: actions/upload-artifact@v7
if: always()
with:
name: playwright-results
path: frontend/test-results/
retention-days: 7
+105
View File
@@ -0,0 +1,105 @@
name: Move Done in Project
on:
issues:
types: [closed]
pull_request:
types: [closed]
permissions: {}
jobs:
move-to-done:
name: Move to Done
runs-on: ubuntu-latest
if: >-
(github.event_name == 'issues' && github.event.issue.state_reason == 'completed') ||
(github.event_name == 'pull_request' && github.event.pull_request.merged == true)
steps:
- name: Move project item to Done
uses: actions/github-script@v8
with:
github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}
script: |
const projectId = 'PVT_kwHOADH82s4BO2OT';
const statusFieldId = 'PVTSSF_lAHOADH82s4BO2OTzg9bdkE';
const doneOptionId = 'ca45af98';
// Determine content ID (issue or PR node ID)
const nodeId = context.payload.issue?.node_id || context.payload.pull_request?.node_id;
const number = context.payload.issue?.number || context.payload.pull_request?.number;
const type = context.payload.issue ? 'issue' : 'pull_request';
console.log(`Processing ${type} #${number} (${nodeId})`);
// Find the project item by content node ID
const result = await github.graphql(`
query($nodeId: ID!) {
node(id: $nodeId) {
... on Issue {
projectItems(first: 10) {
nodes {
id
project { id }
fieldValueByName(name: "Status") {
... on ProjectV2ItemFieldSingleSelectValue {
name
optionId
}
}
}
}
}
... on PullRequest {
projectItems(first: 10) {
nodes {
id
project { id }
fieldValueByName(name: "Status") {
... on ProjectV2ItemFieldSingleSelectValue {
name
optionId
}
}
}
}
}
}
}
`, { nodeId });
const items = result.node?.projectItems?.nodes || [];
const projectItem = items.find(item => item.project.id === projectId);
if (!projectItem) {
console.log(`${type} #${number} is not in the project board — skipping.`);
return;
}
const currentStatus = projectItem.fieldValueByName?.name || 'unknown';
if (currentStatus === 'Done') {
console.log(`${type} #${number} is already "Done" — skipping.`);
return;
}
console.log(`Moving ${type} #${number} from "${currentStatus}" to "Done"...`);
await github.graphql(`
mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
updateProjectV2ItemFieldValue(input: {
projectId: $projectId
itemId: $itemId
fieldId: $fieldId
value: { singleSelectOptionId: $optionId }
}) {
projectV2Item { id }
}
}
`, {
projectId,
itemId: projectItem.id,
fieldId: statusFieldId,
optionId: doneOptionId
});
console.log(`Successfully moved ${type} #${number} to "Done".`);
-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 }}
+48 -7
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
@@ -23,10 +51,10 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
@@ -45,7 +73,7 @@ jobs:
run: npm run test:coverage
- name: Upload coverage report
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
if: always()
with:
name: backend-coverage
@@ -53,10 +81,12 @@ jobs:
retention-days: 7
# =============================================================================
# Frontend Build Validation
# Frontend Tests & Build (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
@@ -66,10 +96,10 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
@@ -81,5 +111,16 @@ jobs:
- name: Lint
run: npm run lint
- name: Run tests with coverage
run: npm run test:coverage
- name: TypeScript type check & build
run: npm run build
- name: Upload coverage report
uses: actions/upload-artifact@v7
if: always()
with:
name: frontend-coverage
path: frontend/coverage/
retention-days: 7
+32 -24
View File
@@ -1,30 +1,35 @@
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
# Prevent parallel badge workflows from racing each other
concurrency:
group: update-test-badges
cancel-in-progress: true
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
uses: actions/checkout@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ secrets.BADGE_TOKEN || secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
@@ -47,8 +52,9 @@ jobs:
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
@@ -60,8 +66,9 @@ jobs:
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: Update README badges
@@ -88,16 +95,17 @@ 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]"
# Rebase on latest main to avoid push rejection when concurrent
# badge workflows or other [skip ci] commits land between checkout and push
git pull --rebase origin main
git push
fi
-57
View File
@@ -1,57 +0,0 @@
name: Version Bump on Release
on:
release:
types: [published]
permissions:
contents: write
jobs:
version-bump:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: main
token: ${{ secrets.GITHUB_TOKEN }}
- name: Get version from tag
id: version
run: |
# Extract version from tag (e.g., v1.6.0 -> 1.6.0)
VERSION="${GITHUB_REF_NAME#v}"
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "Extracted version: $VERSION"
- name: Update package.json versions
run: |
VERSION="${{ steps.version.outputs.version }}"
# Update backend/package.json
jq --arg v "$VERSION" '.version = $v' backend/package.json > backend/package.json.tmp
mv backend/package.json.tmp backend/package.json
# Update frontend/package.json
jq --arg v "$VERSION" '.version = $v' frontend/package.json > frontend/package.json.tmp
mv frontend/package.json.tmp frontend/package.json
echo "Updated versions to $VERSION"
cat backend/package.json | head -5
cat frontend/package.json | head -5
- name: Commit and push
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add backend/package.json frontend/package.json
# Only commit if there are changes
if git diff --staged --quiet; then
echo "No version changes needed"
else
git commit -m "chore: bump version to ${{ steps.version.outputs.version }} [skip ci]"
git push origin main
fi
+10 -1
View File
@@ -18,6 +18,12 @@ build/
coverage/
.nyc_output/
# Playwright
/frontend/playwright-report/
/frontend/test-results/
/frontend/e2e/.auth/
/frontend/blob-report/
# ===================
# Environment
# ===================
@@ -73,5 +79,8 @@ Thumbs.db
.turbo/
.roo/
.roomodes
.claude/
AGENTS.md
docs/TECH_STACK.md
docs/TECH_STACK.md
doku
plan
+4 -1
View File
@@ -1,5 +1,8 @@
{
"vitest.root": "backend",
"vitest.enable": true,
"vitest.commandLine": "npm test --"
"vitest.commandLine": "npm test --",
"chat.tools.terminal.autoApprove": {
"test": true
}
}
+49
View File
@@ -0,0 +1,49 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "E2E stable",
"type": "shell",
"command": "npm",
"args": ["run", "test:e2e"],
"options": {
"cwd": "${workspaceFolder}/frontend"
},
"group": "test",
"problemMatcher": []
},
{
"label": "E2E stable + merged video",
"type": "shell",
"command": "npm",
"args": ["run", "test:e2e:with-video"],
"options": {
"cwd": "${workspaceFolder}/frontend"
},
"group": "test",
"problemMatcher": []
},
{
"label": "E2E all browsers",
"type": "shell",
"command": "npm",
"args": ["run", "test:e2e:all"],
"options": {
"cwd": "${workspaceFolder}/frontend"
},
"group": "test",
"problemMatcher": []
},
{
"label": "E2E all browsers + merged video",
"type": "shell",
"command": "npm",
"args": ["run", "test:e2e:all:with-video"],
"options": {
"cwd": "${workspaceFolder}/frontend"
},
"group": "test",
"problemMatcher": []
}
]
}
+45 -8
View File
@@ -10,7 +10,7 @@
</p>
<p align="center">
<img src="https://img.shields.io/badge/React-18-61DAFB?logo=react" alt="React 18" />
<img src="https://img.shields.io/badge/React-19-61DAFB?logo=react" alt="React 19" />
<img src="https://img.shields.io/badge/TypeScript-5-3178C6?logo=typescript" alt="TypeScript" />
<img src="https://img.shields.io/badge/Fastify-5-000000?logo=fastify" alt="Fastify" />
<img src="https://img.shields.io/badge/SQLite-Database-003B57?logo=sqlite" alt="SQLite" />
@@ -18,13 +18,13 @@
</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-569%2F569-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
<img src="https://img.shields.io/badge/Frontend_Tests-769%2F769-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
</p>
### 🤖 AI-Generated Code
> This app was 100% coded with Claude Opus 4.5. Use at your own risk.
> This app was 100% coded with [Claude Opus 4.6](https://www.anthropic.com/claude) and [GPT-5.3 Codex](https://openai.com/index/gpt-5/). Use at your own risk.
### ⚠️ Disclaimer
@@ -120,9 +120,10 @@ 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
- Manual stock correction supports partial blisters and loose pills
### Medication Refill
- One-click refill with pack or loose pill options
@@ -132,6 +133,7 @@ Share your medication schedule with others via a public link.
### Flexible Schedules
- Daily, weekly, or custom intervals per medication
- Independent schedules for each medication
- Optional timeline filters for dashboard and shared schedule views
### Stock Alerts & Reminders
- Notifications before stock runs out
@@ -141,6 +143,11 @@ 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
### Reports
- Generate medication reports as PDF, Markdown, or plain text
- Include intake history, refill history, and prescription details
### Multi-Person Support
- Manage medications for multiple people
@@ -187,7 +194,7 @@ All configuration is done via environment variables in `.env`. Copy `.env.exampl
| `PGID` | `1000` | Group ID for container file permissions |
| `PORT` | `3000` | Backend API port |
| `CORS_ORIGINS` | `http://localhost:4174` | Allowed origins for CORS |
| `LOG_LEVEL` | `info` | Log verbosity (`debug`, `info`, `warn`, `error`) |
| `LOG_LEVEL` | `info` | Log verbosity (`debug`, `info`, `warn`, `error`, `silent`). At `info` (default), high-frequency polling endpoints are suppressed. Set `debug` to see all requests. |
| `TZ` | `Europe/Berlin` | Timezone for scheduled reminders |
### Authentication
@@ -212,7 +219,7 @@ Generate secrets with: `openssl rand -hex 32`
| `OIDC_ISSUER_URL` | — | OIDC provider URL |
| `OIDC_CLIENT_ID` | — | Client ID from OIDC provider |
| `OIDC_CLIENT_SECRET` | — | Client secret from OIDC provider |
| `OIDC_REDIRECT_URI` | — | Callback URL |
| `OIDC_REDIRECT_URI` | — | Full callback URL (e.g., `https://your-domain.com/api/auth/oidc/callback`) |
| `OIDC_SCOPES` | `openid profile email` | Scopes to request |
| `OIDC_USERNAME_CLAIM` | `preferred_username` | Claim for username |
| `OIDC_AUTO_CREATE_USERS` | `true` | Auto-create users on first SSO login |
@@ -243,7 +250,9 @@ Generate secrets with: `openssl rand -hex 32`
MedAssist uses [Shoutrrr](https://containrrr.dev/shoutrrr/) for push notifications, supporting many services with a single URL format.
**Supported services:** ntfy, Pushover, Gotify, Discord, Telegram, Slack, Matrix, and [many more](https://containrrr.dev/shoutrrr/v0.8/services/overview/).
**Implemented URL schemes in MedAssist:** `ntfy://`, `discord://`, `pushover://`, `gotify://`, `telegram://`, plus direct `https://` webhooks.
This covers common providers like ntfy, Discord, Pushover, Gotify, Telegram, Slack webhooks, and many others via webhook URLs.
Configure push notifications in Settings → Push, or set defaults via environment variables:
@@ -254,6 +263,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):
@@ -273,6 +290,7 @@ Get your keys at [pushover.net](https://pushover.net/):
**Gotify** (self-hosted):
```
gotify://your-server.com/TOKEN
gotify://your-server.com:443/path/to/gotify/TOKEN?priority=1
```
**Discord**:
@@ -283,6 +301,7 @@ discord://TOKEN@WEBHOOK_ID
**Telegram**:
```
telegram://TOKEN@telegram?chats=CHAT_ID
telegram://TOKEN@telegram?chats=@your_channel,-1001234567890
```
For all services and options, see the [Shoutrrr documentation](https://containrrr.dev/shoutrrr/v0.8/services/overview/).
@@ -296,6 +315,24 @@ docker compose -f docker-compose.dev.yml up
- Frontend: `http://localhost:5173` (hot reload)
- Backend: `http://localhost:3000`
Playwright E2E recommendations:
```bash
cd frontend
npm run test:e2e:local # local run with PLAYWRIGHT_WORKERS=4
npm run test:e2e:all:local # local all-browser run with PLAYWRIGHT_WORKERS=4
```
- CI stays at `PLAYWRIGHT_WORKERS=1` for stability.
- Data-heavy specs remain sequential via the `chromium-data` project config.
# Dependency Updates
- Dependabot checks dependencies weekly for `frontend`, `backend`, repository root tooling, and GitHub Actions.
- Minor and patch updates are grouped to reduce PR noise.
- Dependabot minor/patch PRs are configured for auto-merge after required CI checks pass.
- Major updates still require manual review before merge.
# Acknowledgements
This project was inspired by [MedAssist](https://github.com/njic/medassist) by njic.
+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 @@
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;
@@ -0,0 +1,2 @@
ALTER TABLE `medications` ADD `is_obsolete` integer DEFAULT false NOT NULL;
ALTER TABLE `medications` ADD `obsolete_at` integer;
@@ -0,0 +1,8 @@
ALTER TABLE `medications` ADD `prescription_enabled` integer NOT NULL DEFAULT 0;
ALTER TABLE `medications` ADD `prescription_authorized_refills` integer;
ALTER TABLE `medications` ADD `prescription_remaining_refills` integer;
ALTER TABLE `medications` ADD `prescription_low_refill_threshold` integer NOT NULL DEFAULT 1;
ALTER TABLE `medications` ADD `prescription_expiry_date` text;
ALTER TABLE `user_settings` ADD `email_prescription_reminders` integer NOT NULL DEFAULT 1;
ALTER TABLE `user_settings` ADD `shoutrrr_prescription_reminders` integer NOT NULL DEFAULT 1;
@@ -0,0 +1 @@
ALTER TABLE `medications` ADD `medication_start_date` text DEFAULT '' NOT NULL;
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `dose_tracking` ADD `taken_source` text DEFAULT 'manual' NOT NULL;
+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": {}
}
}
File diff suppressed because it is too large Load Diff
+35
View File
@@ -43,6 +43,41 @@
"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
},
{
"idx": 8,
"version": "6",
"when": 1771160400000,
"tag": "0008_add_obsolete_medications",
"breakpoints": true
},
{
"idx": 9,
"version": "6",
"when": 1771164000000,
"tag": "0009_add_medication_start_date",
"breakpoints": true
},
{
"idx": 10,
"version": "6",
"when": 1771694832866,
"tag": "0010_mean_spot",
"breakpoints": true
}
]
}
+1163 -2034
View File
File diff suppressed because it is too large Load Diff
+20 -18
View File
@@ -1,6 +1,6 @@
{
"name": "medassist-ng-backend",
"version": "1.7.1",
"version": "1.17.1",
"private": true,
"type": "module",
"scripts": {
@@ -17,31 +17,33 @@
"check": "npx biome check . && tsc --noEmit"
},
"dependencies": {
"@fastify/cookie": "^10.0.1",
"@fastify/cors": "^10.0.1",
"@fastify/cookie": "^11.0.2",
"@fastify/cors": "^11.2.0",
"@fastify/helmet": "^13.0.2",
"@fastify/jwt": "^10.0.0",
"@fastify/multipart": "^9.3.0",
"@fastify/multipart": "^9.4.0",
"@fastify/rate-limit": "^10.3.0",
"@fastify/sensible": "^6.0.4",
"@fastify/static": "^8.3.0",
"@libsql/client": "^0.10.0",
"argon2": "^0.40.0",
"dotenv": "^16.4.5",
"@fastify/static": "^9.0.0",
"@libsql/client": "^0.17.0",
"argon2": "^0.44.0",
"dotenv": "^17.3.1",
"drizzle-orm": "^0.45.1",
"fastify": "^5.0.0",
"nodemailer": "^7.0.11",
"openid-client": "^6.8.1",
"fastify": "^5.7.4",
"nodemailer": "^8.0.1",
"openid-client": "^6.8.2",
"sharp": "^0.34.5",
"zod": "^3.23.8"
},
"devDependencies": {
"@biomejs/biome": "^2.3.12",
"@types/node": "^22.7.4",
"@types/nodemailer": "^6.4.21",
"@types/supertest": "^6.0.2",
"@vitest/coverage-v8": "^4.0.16",
"drizzle-kit": "^0.31.8",
"supertest": "^7.0.0",
"@biomejs/biome": "^2.4.4",
"@types/node": "^25.3.2",
"@types/nodemailer": "^7.0.11",
"@types/supertest": "^7.2.0",
"@vitest/coverage-v8": "^4.0.18",
"drizzle-kit": "^0.31.9",
"pino-pretty": "^13.1.3",
"supertest": "^7.2.2",
"tsx": "^4.19.0",
"typescript": "^5.5.4",
"vitest": "^4.0.16"
+64 -177
View File
@@ -1,162 +1,35 @@
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 { 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,
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`,
// Added for package type support (blister vs bottle)
`ALTER TABLE medications ADD COLUMN package_type text NOT NULL DEFAULT 'blister'`,
`ALTER TABLE medications ADD COLUMN total_pills integer`,
// Added for dose unit selection (mg, g, mcg, ml, IU, etc.)
`ALTER TABLE medications ADD COLUMN dose_unit text DEFAULT 'mg'`,
// Added for intake-level takenBy: unified intakes structure
`ALTER TABLE medications ADD COLUMN intakes_json text NOT NULL DEFAULT '[]'`,
];
for (const sql of alterMigrations) {
try {
await client.execute(sql);
} catch (e: any) {
// Silently ignore "duplicate column" errors - column already exists
if (!e.message?.includes("duplicate column")) {
errors.push(e.message);
}
}
}
// Create tables that might be missing (silently fail if already exists)
const createTableMigrations = [
// Added in v1.3.x - refill history tracking
`CREATE TABLE IF NOT EXISTS refill_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
medication_id INTEGER NOT NULL REFERENCES medications(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
packs_added INTEGER NOT NULL DEFAULT 0,
loose_pills_added INTEGER NOT NULL DEFAULT 0,
refill_date INTEGER NOT NULL DEFAULT (strftime('%s','now'))
)`,
];
for (const sql of createTableMigrations) {
try {
await client.execute(sql);
} catch (e: any) {
// Silently ignore "table already exists" errors
if (!e.message?.includes("already exists")) {
errors.push(e.message);
}
}
}
return { success: errors.length === 0, errors };
}
/** 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)
@@ -165,34 +38,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`);
} catch (err: any) {
console.error(`[DB] ERROR: Failed to create database client: ${err.message}`);
console.error(`[DB] Database path: ${dbPath}`);
log.debug(`[DB] Database client created successfully`);
} catch (err: unknown) {
log.error(`[DB] ERROR: Failed to create database client: ${(err as Error).message}`);
log.error(`[DB] Database path: ${dbPath}`);
process.exit(1);
}
@@ -201,28 +74,42 @@ 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);
} else if (migrateResult.warning) {
console.log(`[DB] Migration warning:`, migrateResult.warning);
} else {
console.log(`[DB] Drizzle migrations completed`);
log.error(`[DB] Migration error: ${migrateResult.error}`);
}
// 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`);
}
}
+398
View File
@@ -0,0 +1,398 @@
/**
* 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: unknown) {
return { success: false, error: (err as Error).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: unknown) {
const msg = (err as Error).message ?? "";
// Duplicate column / already exists = DB is already up-to-date (expected for existing DBs)
if (msg.includes("duplicate column") || msg.includes("already exists")) {
return { success: true };
}
return { success: false, error: msg };
}
}
/** 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 for intake automation auditability (manual vs automatic taken)
`ALTER TABLE dose_tracking ADD COLUMN taken_source text NOT NULL DEFAULT 'manual'`,
// 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 soft-archiving medications (without deleting history)
`ALTER TABLE medications ADD COLUMN is_obsolete integer NOT NULL DEFAULT 0`,
`ALTER TABLE medications ADD COLUMN obsolete_at integer`,
// Added for explicit medication lifecycle start date
`ALTER TABLE medications ADD COLUMN medication_start_date text NOT NULL DEFAULT ''`,
// 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`,
// Added for timeline visibility toggles (dashboard + shared schedule)
`ALTER TABLE user_settings ADD COLUMN upcoming_today_only integer NOT NULL DEFAULT 0`,
`ALTER TABLE user_settings ADD COLUMN share_schedule_today_only integer NOT NULL DEFAULT 0`,
`ALTER TABLE user_settings ADD COLUMN swap_dashboard_main_sections integer NOT NULL DEFAULT 0`,
// Added for prescription refill tracking and reminders
`ALTER TABLE medications ADD COLUMN prescription_enabled integer NOT NULL DEFAULT 0`,
`ALTER TABLE medications ADD COLUMN prescription_authorized_refills integer`,
`ALTER TABLE medications ADD COLUMN prescription_remaining_refills integer`,
`ALTER TABLE medications ADD COLUMN prescription_low_refill_threshold integer NOT NULL DEFAULT 1`,
`ALTER TABLE medications ADD COLUMN prescription_expiry_date text`,
`ALTER TABLE user_settings ADD COLUMN email_prescription_reminders integer NOT NULL DEFAULT 1`,
`ALTER TABLE user_settings ADD COLUMN shoutrrr_prescription_reminders integer NOT NULL DEFAULT 1`,
`ALTER TABLE user_settings ADD COLUMN last_prescription_reminder_sent text`,
`ALTER TABLE user_settings ADD COLUMN last_prescription_reminder_channel text`,
`ALTER TABLE user_settings ADD COLUMN last_prescription_reminder_med_names text`,
// Added for refill history prescription tracking
`ALTER TABLE refill_history ADD COLUMN used_prescription integer NOT NULL DEFAULT 0`,
];
for (const sql of alterMigrations) {
try {
await client.execute(sql);
} catch (e: unknown) {
// Silently ignore "duplicate column" errors - column already exists
if (!(e as Error).message?.includes("duplicate column")) {
errors.push((e as Error).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: unknown) {
// Silently ignore "table already exists" errors
if (!(e as Error).message?.includes("already exists")) {
errors.push((e as Error).message);
}
}
}
// Create indexes that might be missing (silently fail if already exists)
const createIndexMigrations = [
// Added in v1.6.x - case-insensitive unique usernames
`CREATE UNIQUE INDEX IF NOT EXISTS users_username_lower_unique ON users(lower(username))`,
];
for (const sql of createIndexMigrations) {
try {
await client.execute(sql);
} catch (e: unknown) {
// Silently ignore "already exists" errors
if (!(e as Error).message?.includes("already exists")) {
errors.push((e as Error).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: unknown) {
console.error(`[DB] Error creating default user:`, (e as Error).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: unknown) {
errors.push(`Trailing-hyphen repair failed: ${(e as Error).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: unknown) {
errors.push(`Failed to repair dose ${dose.id}: ${(e as Error).message}`);
}
}
}
}
} catch (e: unknown) {
errors.push(`Repair failed: ${(e as Error).message}`);
}
return { repaired, errors };
}
+11 -8
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);
@@ -38,8 +41,8 @@ export async function executeMigration(
const executed = Number(tables.rows[0].count) || 0;
return { success: true, executed, errors };
} catch (err: any) {
errors.push(err.message);
} catch (err: unknown) {
errors.push((err as Error).message);
return { success: false, executed: 0, errors };
}
}
@@ -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);
}
+12
View File
@@ -65,9 +65,21 @@ export function getTableCreationSQL(): string[] {
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,
upcoming_today_only integer NOT NULL DEFAULT 0,
share_schedule_today_only integer NOT NULL DEFAULT 0,
swap_dashboard_main_sections integer NOT NULL DEFAULT 0,
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,
last_prescription_reminder_sent text,
last_prescription_reminder_channel text,
last_prescription_reminder_med_names text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
+29 -1
View File
@@ -47,6 +47,14 @@ export const medications = sqliteTable("medications", {
expiryDate: text("expiry_date"),
notes: text("notes"),
intakeRemindersEnabled: integer("intake_reminders_enabled", { mode: "boolean" }).notNull().default(false),
medicationStartDate: text("medication_start_date").notNull().default(""),
isObsolete: integer("is_obsolete", { mode: "boolean" }).notNull().default(false),
obsoleteAt: integer("obsolete_at", { mode: "timestamp" }),
prescriptionEnabled: integer("prescription_enabled", { mode: "boolean" }).notNull().default(false),
prescriptionAuthorizedRefills: integer("prescription_authorized_refills"),
prescriptionRemainingRefills: integer("prescription_remaining_refills"),
prescriptionLowRefillThreshold: integer("prescription_low_refill_threshold").notNull().default(1),
prescriptionExpiryDate: text("prescription_expiry_date"),
dismissedUntil: text("dismissed_until"), // ISO date string (e.g. "2026-01-23") - all past doses until this date are dismissed
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
});
@@ -65,11 +73,15 @@ export const userSettings = sqliteTable("user_settings", {
notificationEmail: text("notification_email"),
emailStockReminders: integer("email_stock_reminders", { mode: "boolean" }).notNull().default(true),
emailIntakeReminders: integer("email_intake_reminders", { mode: "boolean" }).notNull().default(true),
emailPrescriptionReminders: integer("email_prescription_reminders", { mode: "boolean" }).notNull().default(true),
// Push notifications (shoutrrr/ntfy)
shoutrrrEnabled: integer("shoutrrr_enabled", { mode: "boolean" }).notNull().default(false),
shoutrrrUrl: text("shoutrrr_url"),
shoutrrrStockReminders: integer("shoutrrr_stock_reminders", { mode: "boolean" }).notNull().default(true),
shoutrrrIntakeReminders: integer("shoutrrr_intake_reminders", { mode: "boolean" }).notNull().default(true),
shoutrrrPrescriptionReminders: integer("shoutrrr_prescription_reminders", { mode: "boolean" })
.notNull()
.default(true),
// Reminder settings
reminderDaysBefore: integer("reminder_days_before").notNull().default(7),
repeatDailyReminders: integer("repeat_daily_reminders", { mode: "boolean" }).notNull().default(false),
@@ -86,12 +98,26 @@ 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),
// UI timeline visibility preferences
upcomingTodayOnly: integer("upcoming_today_only", { mode: "boolean" }).notNull().default(false),
shareScheduleTodayOnly: integer("share_schedule_today_only", { mode: "boolean" }).notNull().default(false),
swapDashboardMainSections: integer("swap_dashboard_main_sections", { mode: "boolean" }).notNull().default(false),
// 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"),
// Last prescription reminder tracking (separate from stock/intake)
lastPrescriptionReminderSent: text("last_prescription_reminder_sent"),
lastPrescriptionReminderChannel: text("last_prescription_reminder_channel"),
lastPrescriptionReminderMedNames: text("last_prescription_reminder_med_names"),
// Timestamps
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
});
@@ -137,6 +163,7 @@ export const doseTracking = sqliteTable("dose_tracking", {
doseId: text("dose_id", { length: 255 }).notNull(), // e.g. "med-5-1-86400000-1735200000000"
takenAt: integer("taken_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s','now'))`),
markedBy: text("marked_by", { length: 100 }), // null = user, "Daniel" = via share link
takenSource: text("taken_source", { length: 20 }).notNull().default("manual"), // manual or automatic
dismissed: integer("dismissed", { mode: "boolean" }).notNull().default(false), // true = missed dose acknowledged without taking
});
@@ -153,5 +180,6 @@ export const refillHistory = sqliteTable("refill_history", {
.references(() => users.id, { onDelete: "cascade" }),
packsAdded: integer("packs_added").notNull().default(0),
loosePillsAdded: integer("loose_pills_added").notNull().default(0),
usedPrescription: integer("used_prescription", { mode: "boolean" }).notNull().default(false),
refillDate: integer("refill_date", { mode: "timestamp" }).notNull().default(sql`(strftime('%s','now'))`),
});
+263 -29
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,103 @@ type TranslationKeys = {
repeatDailyNote: string;
empty: string;
low: string;
critical: string;
lowStock: string;
reorderNow: string;
emptySection: string;
lowSection: string;
criticalSection: string;
lowStockSection: string;
};
// Prescription reminder (shared across email + push)
prescriptionReminder: {
subjectSingle: string;
subjectMultiple: string;
pushTitleLow: string;
pushTitleEmpty: string;
pushEmpty: string;
pushEmptySingle: string;
pushLow: string;
pushLowSingle: string;
pushRenewNow: string;
pushEmptySection: string;
pushLowSection: string;
pushRefillsLeft: string;
title: string;
titleEmpty: string;
descriptionLow: string;
descriptionEmpty: string;
alertLowSingle: string;
alertLowMultiple: string;
alertEmptySingle: string;
alertEmptyMultiple: string;
line: string;
lineEmpty: string;
expiresSuffix: string;
repeatDailyNote: string;
tableHeaders: {
medication: string;
refillsLeft: string;
reminderThreshold: string;
prescriptionExpires: string;
};
};
// Demand calculator email
demandCalculator: {
subject: string;
title: string;
description: string;
summaryOutOfStock: string;
summaryAllOk: string;
tableHeaders: {
medication: string;
usage: string;
needed: string;
prescriptionRefills: string;
available: string;
status: string;
};
statusEnough: string;
statusEmpty: string;
prescriptionNotApplicable: 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",
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!",
subject: "MedAssist-ng: ⚠️ {count} Medication{s} Running Critically Low",
title: "⚠️ MedAssist-ng: Automatic Reorder Reminder",
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 +227,109 @@ 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",
},
prescriptionReminder: {
subjectSingle: "MedAssist-ng: 🚨 Prescription Refill Reminder",
subjectMultiple: "MedAssist-ng: 🚨 {count} Prescriptions Need Renewal Soon",
pushTitleLow: "💊 MedAssist-ng: {count} prescriptions are running low",
pushTitleEmpty: "💊 MedAssist-ng: {count} prescriptions need renewal now",
pushEmpty: "prescriptions out of refills",
pushEmptySingle: "prescription out of refills",
pushLow: "prescriptions low on refills",
pushLowSingle: "prescription low on refills",
pushRenewNow: "Renew Now!",
pushEmptySection: "Prescriptions with no refills left",
pushLowSection: "Prescriptions running low on refills",
pushRefillsLeft: "{count} refill(s) remaining on this prescription",
title: "⚠️ MedAssist-ng - Prescription Reminder",
titleEmpty: "🚨 MedAssist-ng - Prescription Reminder",
descriptionLow: "Some prescriptions are low on remaining refills.",
descriptionEmpty: "Some prescriptions have no refills left. Contact your doctor for renewal.",
alertLowSingle: "⚠️ 1 prescription is low on refills",
alertLowMultiple: "⚠️ {count} prescriptions are low on refills",
alertEmptySingle: "🚨 1 prescription needs renewal now",
alertEmptyMultiple: "🚨 {count} prescriptions need renewal now",
line: "{name}: {refills} refill(s) remaining on this prescription{expirySuffix}",
lineEmpty: "{name}: no refills remaining on this prescription{expirySuffix}",
expiresSuffix: ", expires {date}",
repeatDailyNote: "You are receiving this daily reminder because 'Repeat Daily' is enabled in settings.",
tableHeaders: {
medication: "Medication",
refillsLeft: "Prescription refills left",
reminderThreshold: "Reminder threshold",
prescriptionExpires: "Prescription expires",
},
},
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",
prescriptionRefills: "Prescription refills",
available: "Available",
status: "Status",
},
statusEnough: "✓ Enough",
statusEmpty: "✗ Empty",
prescriptionNotApplicable: "",
},
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",
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!",
subject: "MedAssist-ng: ⚠️ {count} Medikament{e} kritisch niedrig",
title: "⚠️ MedAssist-ng: Automatische Nachbestell-Erinnerung",
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 +346,86 @@ 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",
},
prescriptionReminder: {
subjectSingle: "MedAssist-ng: 🚨 Rezept-Nachfüll-Erinnerung",
subjectMultiple: "MedAssist-ng: 🚨 {count} Rezepte müssen bald erneuert werden",
pushTitleLow: "💊 MedAssist-ng: {count} Rezept(e) haben nur noch wenige Nachfüllungen",
pushTitleEmpty: "💊 MedAssist-ng: {count} Rezept(e) müssen jetzt erneuert werden",
pushEmpty: "Rezepte ohne verbleibende Nachfüllung",
pushEmptySingle: "Rezept ohne verbleibende Nachfüllung",
pushLow: "Rezepte mit wenigen verbleibenden Nachfüllungen",
pushLowSingle: "Rezept mit wenigen verbleibenden Nachfüllungen",
pushRenewNow: "Jetzt erneuern!",
pushEmptySection: "Rezepte ohne Nachfüllungen",
pushLowSection: "Rezepte mit bald aufgebrauchten Nachfüllungen",
pushRefillsLeft: "{count} Nachfüllung(en) für dieses Rezept übrig",
title: "⚠️ MedAssist-ng - Rezept-Erinnerung",
titleEmpty: "🚨 MedAssist-ng - Rezept-Erinnerung",
descriptionLow: "Einige Rezepte haben nur noch wenige Nachfüllungen.",
descriptionEmpty:
"Einige Rezepte haben keine Nachfüllungen mehr. Bitte kontaktieren Sie Ihren Arzt für eine Erneuerung.",
alertLowSingle: "⚠️ 1 Rezept ist bei den Nachfüllungen niedrig",
alertLowMultiple: "⚠️ {count} Rezepte sind bei den Nachfüllungen niedrig",
alertEmptySingle: "🚨 1 Rezept muss jetzt erneuert werden",
alertEmptyMultiple: "🚨 {count} Rezepte müssen jetzt erneuert werden",
line: "{name}: {refills} Nachfüllung(en) für dieses Rezept übrig{expirySuffix}",
lineEmpty: "{name}: keine Nachfüllung mehr für dieses Rezept{expirySuffix}",
expiresSuffix: ", läuft ab {date}",
repeatDailyNote:
"Sie erhalten diese tägliche Erinnerung, weil 'Täglich wiederholen' in den Einstellungen aktiviert ist.",
tableHeaders: {
medication: "Medikament",
refillsLeft: "Rezept-Nachfüllungen übrig",
reminderThreshold: "Erinnerungsschwelle",
prescriptionExpires: "Rezeptablauf",
},
},
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",
prescriptionRefills: "Rezept-Nachfüllungen",
available: "Verfügbar",
status: "Status",
},
statusEnough: "✓ Ausreichend",
statusEmpty: "✗ Leer",
prescriptionNotApplicable: "",
},
common: {
pill: "Tablette",
pills: "Tabletten",
blister: "Blister",
blisters: "Blister",
day: "Tag",
days: "Tage",
soon: "bald",
footer: "🤖 Gesendet von MedAssist-ng",
},
},
};
@@ -264,3 +463,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;
}
+54 -7
View File
@@ -1,4 +1,6 @@
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import type { IncomingHttpHeaders } from "node:http";
import { resolve } from "node:path";
import cookie from "@fastify/cookie";
import cors from "@fastify/cors";
@@ -10,6 +12,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";
@@ -19,6 +22,7 @@ import { medicationRoutes } from "./routes/medications.js";
import { oidcRoutes } from "./routes/oidc.js";
import { plannerRoutes } from "./routes/planner.js";
import { refillRoutes } from "./routes/refills.js";
import { reportRoutes } from "./routes/report.js";
import { settingsRoutes } from "./routes/settings.js";
import { shareRoutes } from "./routes/share.js";
import { startIntakeReminderScheduler } from "./services/intake-reminder-scheduler.js";
@@ -43,6 +47,31 @@ import {
parseCorsOrigins,
} from "./utils/server-config.js";
function sanitizeCorrelationId(headers: IncomingHttpHeaders): string | null {
const rawHeader = headers["x-correlation-id"];
if (typeof rawHeader !== "string") return null;
const trimmed = rawHeader.trim();
if (!trimmed) return null;
if (trimmed.length > 128) return null;
if (!/^[A-Za-z0-9._:-]+$/.test(trimmed)) return null;
return trimmed;
}
function buildLoggerOptions(level: string) {
const base = {
level,
timestamp: () => `,"time":"${new Date().toISOString()}"`,
};
// Human-readable logs in development, structured JSON in production/test
if (process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "test") {
return {
...base,
transport: { target: "pino-pretty", options: { translateTime: "SYS:yyyy-mm-dd HH:MM:ss.l" } },
};
}
return base;
}
/** Create and configure Fastify app (without starting) */
export async function createApp(options?: {
logLevel?: string;
@@ -66,11 +95,18 @@ 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({
logger: { level: opts.logLevel },
logger: buildLoggerOptions(opts.logLevel),
genReqId: (request) => sanitizeCorrelationId(request.headers) ?? randomUUID(),
});
app.addHook("onRequest", (request, reply, done) => {
request.correlationId = request.id;
reply.header("x-correlation-id", request.id);
done();
});
// Build config
@@ -117,6 +153,7 @@ export async function createApp(options?: {
await app.register(doseRoutes);
await app.register(exportRoutes);
await app.register(refillRoutes);
await app.register(reportRoutes);
return app;
}
@@ -125,17 +162,24 @@ 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();
const app = Fastify({
logger: {
level: env.LOG_LEVEL,
},
logger: buildLoggerOptions(env.LOG_LEVEL),
genReqId: (request) => sanitizeCorrelationId(request.headers) ?? randomUUID(),
});
app.addHook("onRequest", (request, reply, done) => {
request.correlationId = request.id;
reply.header("x-correlation-id", request.id);
done();
});
const origins = parseCorsOrigins(env.CORS_ORIGINS);
@@ -161,7 +205,7 @@ await app.register(sensible);
await app.register(helmet);
await app.register(cors, { origin: origins, credentials: true });
await app.register(rateLimit, {
max: 100,
max: Number(process.env.RATE_LIMIT_MAX) || 100,
timeWindow: "1 minute",
});
await app.register(cookie, { secret: env.COOKIE_SECRET ?? "dev-cookie-secret" });
@@ -187,6 +231,7 @@ await app.register(shareRoutes);
await app.register(doseRoutes);
await app.register(exportRoutes);
await app.register(refillRoutes);
await app.register(reportRoutes);
const start = async () => {
try {
@@ -196,12 +241,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) {
+11 -6
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;
}
@@ -48,7 +47,7 @@ export async function getAnonymousUserId(): Promise<number> {
export interface AuthState {
authEnabled: boolean;
registrationEnabled: boolean;
localAuthEnabled: boolean;
formLoginEnabled: boolean;
oidcEnabled: boolean;
oidcProviderName: string;
hasUsers: boolean;
@@ -60,15 +59,18 @@ export async function getAuthState(): Promise<AuthState> {
const [result] = await db.select({ count: count() }).from(users).where(sql`${users.id} != ${ANONYMOUS_USER_ID}`);
const hasUsers = result.count > 0;
const needsSetup = env.AUTH_ENABLED && !hasUsers;
return {
authEnabled: env.AUTH_ENABLED,
// Registration: enabled via ENV OR no users exist (first-time setup)
registrationEnabled: env.REGISTRATION_ENABLED || !hasUsers,
localAuthEnabled: env.AUTH_ENABLED, // Password auth available when auth is enabled
// Form login: enabled when auth + form login are both on, or forced on for first-user setup
formLoginEnabled: needsSetup || (env.AUTH_ENABLED && env.FORM_LOGIN_ENABLED),
oidcEnabled: env.OIDC_ENABLED,
oidcProviderName: env.OIDC_PROVIDER_NAME,
hasUsers,
needsSetup: env.AUTH_ENABLED && !hasUsers,
needsSetup,
};
}
@@ -143,9 +145,12 @@ export async function requireAuth(request: FastifyRequest, reply: FastifyReply)
id: user.id,
username: user.username,
};
} catch (err: any) {
} catch (err: unknown) {
// Re-throw our own errors
if (err?.message === "AUTH_REQUIRED" || err?.message === "USER_NOT_FOUND" || err?.message === "ACCOUNT_DISABLED") {
if (
err instanceof Error &&
(err.message === "AUTH_REQUIRED" || err.message === "USER_NOT_FOUND" || err.message === "ACCOUNT_DISABLED")
) {
throw err;
}
// JWT verification failed
+31 -2
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"),
@@ -25,7 +28,11 @@ const EnvSchema = z.object({
.string()
.transform((v) => v === "true")
.default("false"),
// Disable local auth when using SSO only
// Disable username/password form login (useful for OIDC-only setups)
FORM_LOGIN_ENABLED: z
.string()
.transform((v) => v === "true")
.default("true"),
// JWT Secrets - only required when AUTH_ENABLED=true
JWT_SECRET: z.string().min(10).optional(),
@@ -125,4 +132,26 @@ if (parsed.OIDC_ENABLED) {
}
}
// Validate that at least one login method is available when auth is enabled
if (parsed.AUTH_ENABLED && !parsed.FORM_LOGIN_ENABLED && !parsed.OIDC_ENABLED) {
console.error("=".repeat(60));
console.error("AUTHENTICATION CONFIGURATION ERROR");
console.error("=".repeat(60));
console.error("AUTH_ENABLED=true but no login method is available.");
console.error("FORM_LOGIN_ENABLED=false and OIDC_ENABLED=false means users cannot log in.");
console.error("");
console.error("To fix this, either:");
console.error(" 1. Set FORM_LOGIN_ENABLED=true to allow username/password login");
console.error(" 2. Set OIDC_ENABLED=true to allow SSO login");
console.error("=".repeat(60));
process.exit(1);
}
// Warn about ineffective registration when form login is disabled
if (parsed.REGISTRATION_ENABLED && !parsed.FORM_LOGIN_ENABLED) {
console.warn(
"[config] REGISTRATION_ENABLED=true has no effect when FORM_LOGIN_ENABLED=false (no registration form available)"
);
}
export const env = parsed;
+40 -42
View File
@@ -1,12 +1,20 @@
import { randomBytes } from "node:crypto";
import { resolve } from "node:path";
import argon2 from "argon2";
import { eq } from "drizzle-orm";
import { eq, sql } 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";
import {
ALLOWED_IMAGE_MIME_TYPES,
removeImageFiles,
streamToBuffer,
writeOptimizedImageSet,
} from "../utils/image-upload.js";
// =============================================================================
// Argon2id Configuration - State of the Art Password Hashing
@@ -52,6 +60,7 @@ const sensitiveRateLimitConfig = {
const registerSchema = z.object({
username: z
.string()
.trim()
.min(3, "Username must be at least 3 characters")
.max(50, "Username must be at most 50 characters")
.regex(/^[a-zA-Z0-9_-]+$/, "Username can only contain letters, numbers, underscores, and hyphens"),
@@ -62,7 +71,7 @@ const registerSchema = z.object({
});
const loginSchema = z.object({
username: z.string().min(1, "Username is required"),
username: z.string().trim().min(1, "Username is required"),
password: z.string().min(1, "Password is required"),
rememberMe: z.boolean().optional().default(false),
});
@@ -80,6 +89,8 @@ const updateProfileSchema = z.object({
// Auth Routes
// =============================================================================
export async function authRoutes(app: FastifyInstance) {
const IMAGES_DIR = resolve(getDataDir(), "images");
// Token TTLs
const accessTtlMinutes = 15;
const refreshTtlDays = 14;
@@ -112,8 +123,8 @@ export async function authRoutes(app: FastifyInstance) {
return reply.status(400).send({ error: "Registration is disabled", code: "REGISTRATION_DISABLED" });
}
if (!state.localAuthEnabled) {
return reply.status(400).send({ error: "Local authentication is disabled", code: "LOCAL_AUTH_DISABLED" });
if (!state.formLoginEnabled) {
return reply.status(400).send({ error: "Form login is disabled", code: "FORM_LOGIN_DISABLED" });
}
// Validate input
@@ -128,7 +139,7 @@ export async function authRoutes(app: FastifyInstance) {
const { username, password } = parsed.data;
// Check if username already exists
const [existingUser] = await db.select().from(users).where(eq(users.username, username));
const [existingUser] = await db.select().from(users).where(sql`lower(${users.username}) = lower(${username})`);
if (existingUser) {
return reply.status(409).send({ error: "Username already taken", code: "USERNAME_EXISTS" });
}
@@ -174,8 +185,8 @@ export async function authRoutes(app: FastifyInstance) {
return reply.status(400).send({ error: "Authentication is disabled", code: "AUTH_DISABLED" });
}
if (!state.localAuthEnabled) {
return reply.status(400).send({ error: "Local authentication is disabled", code: "LOCAL_AUTH_DISABLED" });
if (!state.formLoginEnabled) {
return reply.status(400).send({ error: "Form login is disabled", code: "FORM_LOGIN_DISABLED" });
}
const parsed = loginSchema.safeParse(request.body);
@@ -189,7 +200,7 @@ export async function authRoutes(app: FastifyInstance) {
const { username, password, rememberMe } = parsed.data;
// Find user by username
const [user] = await db.select().from(users).where(eq(users.username, username));
const [user] = await db.select().from(users).where(sql`lower(${users.username}) = lower(${username})`);
// Generic error to prevent user enumeration
const invalidCredentialsError = () =>
@@ -460,36 +471,35 @@ export async function authRoutes(app: FastifyInstance) {
const data = await request.file();
if (!data) {
return reply.status(400).send({ error: "No file uploaded" });
return reply.status(400).send({ error: "No file uploaded", code: "NO_FILE" });
}
// Validate file type
const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
if (!allowedTypes.includes(data.mimetype)) {
return reply.status(400).send({ error: "Invalid file type. Allowed: JPEG, PNG, WebP, GIF" });
if (!ALLOWED_IMAGE_MIME_TYPES.includes(data.mimetype)) {
return reply.status(400).send({ error: "Invalid file type", code: "INVALID_TYPE" });
}
// Generate unique filename
const ext = data.filename.split(".").pop() || "jpg";
const filename = `avatar_${authUser.id}_${Date.now()}.${ext}`;
let uploadBuffer: Buffer;
try {
uploadBuffer = await streamToBuffer(data.file);
} catch (error) {
if (error instanceof Error && error.message === "IMAGE_TOO_LARGE") {
return reply.status(400).send({ error: "Image too large", code: "IMAGE_TOO_LARGE" });
}
throw error;
}
// Save file
const fs = await import("node:fs/promises");
const path = await import("node:path");
const imagesDir = path.join(process.cwd(), "data", "images");
await fs.mkdir(imagesDir, { recursive: true });
const buffer = await data.toBuffer();
await fs.writeFile(path.join(imagesDir, filename), buffer);
let filename: string;
try {
({ filename } = await writeOptimizedImageSet(IMAGES_DIR, `avatar_${authUser.id}`, uploadBuffer));
} catch {
return reply.status(400).send({ error: "Invalid image", code: "INVALID_IMAGE" });
}
// Delete old avatar if exists
const [user] = await db.select().from(users).where(eq(users.id, authUser.id));
if (user?.avatarUrl) {
try {
await fs.unlink(path.join(imagesDir, user.avatarUrl));
} catch {
// Ignore if file doesn't exist
}
removeImageFiles(IMAGES_DIR, user.avatarUrl);
}
// Update user
@@ -520,13 +530,7 @@ export async function authRoutes(app: FastifyInstance) {
}
// Delete file
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));
} catch {
// Ignore if file doesn't exist
}
removeImageFiles(IMAGES_DIR, user.avatarUrl);
// Update user
await db.update(users).set({ avatarUrl: null, updatedAt: new Date() }).where(eq(users.id, authUser.id));
@@ -553,13 +557,7 @@ export async function authRoutes(app: FastifyInstance) {
// 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(process.cwd(), "data", "images", user.avatarUrl));
} catch {
// Ignore if file doesn't exist
}
removeImageFiles(IMAGES_DIR, user.avatarUrl);
}
// Delete user - cascade delete handles all related data
+133 -9
View File
@@ -2,10 +2,11 @@ import { and, eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../db/client.js";
import { doseTracking, shareTokens } from "../db/schema.js";
import { doseTracking, medications, shareTokens } 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, personTakesMedication } from "../utils/scheduler-utils.js";
// =============================================================================
// Validation Schemas
@@ -22,6 +23,13 @@ const dismissDosesSchema = z.object({
doseIds: z.array(z.string().min(1)).min(1, "At least one doseId is required"),
});
const doseIdPattern = /^(\d+)-(\d+)-(\d+)(?:-(.+))?$/;
function maskToken(token: string): string {
if (token.length <= 8) return token;
return `${token.slice(0, 4)}...${token.slice(-4)}`;
}
// Helper to get user ID from request
// Returns anonymous user ID when auth is disabled
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
@@ -38,14 +46,100 @@ async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<
return authUser.id;
}
type ParsedDoseId = {
medicationId: number;
intakeIndex: number;
timestampMs: number;
personSuffix: string | null;
};
function parseDoseId(doseId: string): ParsedDoseId | null {
const match = doseIdPattern.exec(doseId);
if (!match) return null;
const medicationId = Number.parseInt(match[1], 10);
const intakeIndex = Number.parseInt(match[2], 10);
const timestampMs = Number.parseInt(match[3], 10);
const personSuffix = match[4] ? match[4].trim() : null;
if (Number.isNaN(medicationId) || Number.isNaN(intakeIndex) || Number.isNaN(timestampMs) || intakeIndex < 0) {
return null;
}
return {
medicationId,
intakeIndex,
timestampMs,
personSuffix,
};
}
async function getActiveShareToken(token: string): Promise<{
share: typeof shareTokens.$inferSelect | null;
reason: "not_found" | "expired" | "ok";
}> {
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
if (!share) return { share: null, reason: "not_found" };
if (share.expiresAt && share.expiresAt.getTime() < Date.now()) {
return { share: null, reason: "expired" };
}
return { share, reason: "ok" };
}
async function validateShareDoseId(share: typeof shareTokens.$inferSelect, doseId: string): Promise<boolean> {
const parsedDose = parseDoseId(doseId);
if (!parsedDose) {
return false;
}
const [medication] = await db
.select()
.from(medications)
.where(and(eq(medications.id, parsedDose.medicationId), eq(medications.userId, share.userId)));
if (!medication) {
return false;
}
const medTakenBy = parseTakenByJson(medication.takenByJson);
const intakes = parseIntakesJson(
medication.intakesJson,
{ usageJson: medication.usageJson, everyJson: medication.everyJson, startJson: medication.startJson },
medication.intakeRemindersEnabled ?? false
);
if (!personTakesMedication(share.takenBy, medTakenBy, intakes)) {
return false;
}
const intake = intakes[parsedDose.intakeIndex];
if (!intake) {
return false;
}
const expectedPersons = intake.takenBy ? [intake.takenBy] : medTakenBy;
if (expectedPersons.length === 0) {
return parsedDose.personSuffix === null;
}
if (!parsedDose.personSuffix) {
return true;
}
return expectedPersons.includes(parsedDose.personSuffix);
}
// =============================================================================
// Dose Tracking Routes
// =============================================================================
export async function doseRoutes(app: FastifyInstance) {
// ---------------------------------------------------------------------------
// GET /doses/taken - PROTECTED: Get all taken doses for the user
// Suppress request logs — polled every 5s by frontend
// ---------------------------------------------------------------------------
app.get("/doses/taken", { preHandler: requireAuth }, async (request, reply) => {
app.get("/doses/taken", { preHandler: requireAuth, logLevel: "warn" }, async (request, reply) => {
const userId = await getUserId(request, reply);
// Get all taken doses for this user (no time limit)
@@ -56,6 +150,7 @@ export async function doseRoutes(app: FastifyInstance) {
doseId: d.doseId,
takenAt: d.takenAt?.getTime() ?? Date.now(),
markedBy: d.markedBy,
takenSource: d.takenSource ?? "manual",
dismissed: d.dismissed ?? false,
})),
};
@@ -94,6 +189,7 @@ export async function doseRoutes(app: FastifyInstance) {
userId,
doseId,
markedBy: null, // Marked by the user themselves
takenSource: "manual",
});
return { success: true };
@@ -209,13 +305,14 @@ export async function doseRoutes(app: FastifyInstance) {
// ---------------------------------------------------------------------------
// GET /share/:token/doses - PUBLIC: Get taken doses for a share link
// Suppress request logs — polled every 5s by SharedSchedule
// ---------------------------------------------------------------------------
app.get<{ Params: { token: string } }>("/share/:token/doses", async (request, reply) => {
app.get<{ Params: { token: string } }>("/share/:token/doses", { logLevel: "warn" }, async (request, reply) => {
const { token } = request.params;
// Find share token
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
const { share, reason } = await getActiveShareToken(token);
if (!share) {
request.log.warn(`[ShareDose] Rejected read for token ${maskToken(token)} (reason=${reason})`);
return reply.notFound("Share link not found");
}
@@ -227,6 +324,7 @@ export async function doseRoutes(app: FastifyInstance) {
doseId: d.doseId,
takenAt: d.takenAt?.getTime() ?? Date.now(),
markedBy: d.markedBy,
takenSource: d.takenSource ?? "manual",
dismissed: d.dismissed ?? false,
})),
};
@@ -249,12 +347,20 @@ export async function doseRoutes(app: FastifyInstance) {
const { doseId } = parsed.data;
// Find share token
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
const { share, reason } = await getActiveShareToken(token);
if (!share) {
request.log.warn(`[ShareDose] Rejected mark for token ${maskToken(token)} (reason=${reason})`);
return reply.notFound("Share link not found");
}
const isValidShareDoseId = await validateShareDoseId(share, doseId);
if (!isValidShareDoseId) {
request.log.warn(
`[ShareDose] Rejected invalid doseId in mark request (owner=${share.userId}, takenBy=${share.takenBy}, doseId=${doseId})`
);
return reply.status(400).send({ error: "Invalid or unauthorized doseId" });
}
// Check if already marked
const [existing] = await db
.select()
@@ -262,6 +368,7 @@ export async function doseRoutes(app: FastifyInstance) {
.where(and(eq(doseTracking.userId, share.userId), eq(doseTracking.doseId, doseId)));
if (existing) {
request.log.debug(`[ShareDose] Duplicate mark ignored (owner=${share.userId}, doseId=${doseId})`);
return { success: true, message: "Already marked" };
}
@@ -270,8 +377,13 @@ export async function doseRoutes(app: FastifyInstance) {
userId: share.userId,
doseId,
markedBy: share.takenBy, // e.g. "Daniel"
takenSource: "manual",
});
request.log.info(
`[ShareDose] Dose marked via share link (owner=${share.userId}, takenBy=${share.takenBy}, doseId=${doseId})`
);
return { success: true };
}
);
@@ -282,12 +394,20 @@ export async function doseRoutes(app: FastifyInstance) {
app.delete<{ Params: { token: string; doseId: string } }>("/share/:token/doses/:doseId", async (request, reply) => {
const { token, doseId } = request.params;
// Find share token
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
const { share, reason } = await getActiveShareToken(token);
if (!share) {
request.log.warn(`[ShareDose] Rejected unmark for token ${maskToken(token)} (reason=${reason})`);
return reply.notFound("Share link not found");
}
const isValidShareDoseId = await validateShareDoseId(share, doseId);
if (!isValidShareDoseId) {
request.log.warn(
`[ShareDose] Rejected invalid doseId in unmark request (owner=${share.userId}, takenBy=${share.takenBy}, doseId=${doseId})`
);
return reply.status(400).send({ error: "Invalid or unauthorized doseId" });
}
// Check if this dose was dismissed
const [existing] = await db
.select()
@@ -296,9 +416,13 @@ export async function doseRoutes(app: FastifyInstance) {
if (existing?.dismissed) {
// Already dismissed - keep the record as-is
request.log.debug(`[ShareDose] Unmark ignored for dismissed dose (owner=${share.userId}, doseId=${doseId})`);
} else {
// Not dismissed - delete the record entirely
await db.delete(doseTracking).where(and(eq(doseTracking.userId, share.userId), eq(doseTracking.doseId, doseId)));
request.log.info(
`[ShareDose] Dose unmarked via share link (owner=${share.userId}, takenBy=${share.takenBy}, doseId=${doseId})`
);
}
return { success: true };
+120 -7
View File
@@ -2,21 +2,22 @@ import { randomBytes } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { extname, resolve } from "node:path";
import { eq } from "drizzle-orm";
import type { FastifyInstance } from "fastify";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../db/client.js";
import { doseTracking, medications, shareTokens, userSettings } from "../db/schema.js";
import { getDataDir } from "../db/db-utils.js";
import { doseTracking, medications, refillHistory, 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)
// =============================================================================
const EXPORT_VERSION = "1.0";
const EXPORT_VERSION = "1.1";
// =============================================================================
// Zod Schemas for Import Validation
@@ -34,8 +35,10 @@ const inventorySchema = z.object({
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().nullable().optional(), // For bottle type: total capacity
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({
@@ -47,9 +50,18 @@ const medicationExportSchema = z.object({
pillWeightMg: z.number().int().nullable().optional(),
doseUnit: z.enum(["mg", "g", "mcg", "ml", "IU", "units", "drops", "puffs"]).default("mg"),
schedules: z.array(scheduleSchema).default([]),
medicationStartDate: z.string().nullable().optional(),
expiryDate: z.string().nullable().optional(),
notes: z.string().nullable().optional(),
intakeRemindersEnabled: z.boolean().default(false),
isObsolete: z.boolean().default(false),
obsoleteAt: z.string().nullable().optional(),
prescriptionEnabled: z.boolean().default(false),
prescriptionAuthorizedRefills: z.number().int().min(0).nullable().optional(),
prescriptionRemainingRefills: z.number().int().min(0).nullable().optional(),
prescriptionLowRefillThreshold: z.number().int().min(0).default(1),
prescriptionExpiryDate: z.string().nullable().optional(),
dismissedUntil: z.string().nullable().optional(), // ISO date string for dismissed past doses
image: z.string().nullable().optional(), // base64 data URL or null
lastStockCorrectionAt: z.string().nullable().optional(), // ISO datetime of last stock correction
});
@@ -60,10 +72,19 @@ const doseHistorySchema = z.object({
scheduledTime: z.string(), // ISO datetime
takenAt: z.string(), // ISO datetime
markedBy: z.string().nullable().optional(),
takenSource: z.enum(["manual", "automatic"]).default("manual"),
dismissed: z.boolean().default(false),
takenByPerson: z.string().nullable().optional(), // Person suffix from dose ID (e.g., "Daniel")
});
const refillHistoryExportSchema = z.object({
medicationRef: z.string(), // References _exportId
packsAdded: z.number().int().min(0).default(0),
loosePillsAdded: z.number().int().min(0).default(0),
usedPrescription: z.boolean().default(false),
refillDate: z.string(), // ISO datetime
});
const shareLinkSchema = z.object({
takenBy: z.string().min(1),
scheduleDays: z.number().int().min(1).default(30),
@@ -78,11 +99,13 @@ const settingsExportSchema = z
notificationEmail: z.string().nullable().optional(),
emailStockReminders: z.boolean().default(true),
emailIntakeReminders: z.boolean().default(true),
emailPrescriptionReminders: z.boolean().default(true),
// Push notifications
shoutrrrEnabled: z.boolean().optional(),
shoutrrrUrl: z.string().nullable().optional(),
shoutrrrStockReminders: z.boolean().default(true),
shoutrrrIntakeReminders: z.boolean().default(true),
shoutrrrPrescriptionReminders: z.boolean().default(true),
// Reminder settings
reminderDaysBefore: z.number().int().default(7),
repeatDailyReminders: z.boolean().default(false),
@@ -94,9 +117,11 @@ const settingsExportSchema = z
lowStockDays: z.number().int().default(30),
normalStockDays: z.number().int().default(90),
highStockDays: z.number().int().default(180),
expiryWarningDays: z.number().int().default(90),
// UI preferences
language: z.string().default("en"),
stockCalculationMode: z.enum(["automatic", "manual"]).default("automatic"),
shareStockStatus: z.boolean().default(true),
})
.optional();
@@ -106,6 +131,7 @@ const importDataSchema = z.object({
includeSensitiveData: z.boolean().default(false),
medications: z.array(medicationExportSchema).default([]),
doseHistory: z.array(doseHistorySchema).default([]),
refillHistory: z.array(refillHistoryExportSchema).default([]),
settings: settingsExportSchema,
shareLinks: z.array(shareLinkSchema).default([]),
});
@@ -115,7 +141,7 @@ const importDataSchema = z.object({
// =============================================================================
// Helper to get user ID from request
async function getUserId(request: any, reply: any): Promise<number> {
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
if (!env.AUTH_ENABLED) {
return getAnonymousUserId();
}
@@ -273,15 +299,26 @@ export async function exportRoutes(app: FastifyInstance) {
packCount: med.packCount ?? 1,
blistersPerPack: med.blistersPerPack ?? 1,
pillsPerBlister: med.pillsPerBlister ?? 1,
totalPills: med.totalPills ?? null,
looseTablets: med.looseTablets ?? 0,
stockAdjustment: med.stockAdjustment ?? 0,
packageType: med.packageType ?? "blister",
},
pillWeightMg: med.pillWeightMg,
doseUnit: med.doseUnit ?? "mg",
schedules: parseIntakesForExport(med),
medicationStartDate: med.medicationStartDate || null,
expiryDate: med.expiryDate,
notes: med.notes,
intakeRemindersEnabled: med.intakeRemindersEnabled ?? false,
isObsolete: med.isObsolete ?? false,
obsoleteAt: med.obsoleteAt?.toISOString() ?? null,
prescriptionEnabled: med.prescriptionEnabled ?? false,
prescriptionAuthorizedRefills: med.prescriptionAuthorizedRefills ?? null,
prescriptionRemainingRefills: med.prescriptionRemainingRefills ?? null,
prescriptionLowRefillThreshold: med.prescriptionLowRefillThreshold ?? 1,
prescriptionExpiryDate: med.prescriptionExpiryDate ?? null,
dismissedUntil: med.dismissedUntil ?? null,
image: includeImages ? imageToBase64(med.imageUrl) : null,
lastStockCorrectionAt: lastStockCorrectionAtIso,
};
@@ -328,6 +365,7 @@ export async function exportRoutes(app: FastifyInstance) {
scheduledTime: scheduledTimeIso,
takenAt: takenAtIso,
markedBy: dose.markedBy,
takenSource: dose.takenSource === "automatic" ? "automatic" : "manual",
dismissed: dose.dismissed ?? false,
takenByPerson: parsed.person,
};
@@ -343,11 +381,13 @@ export async function exportRoutes(app: FastifyInstance) {
notificationEmail: settings.notificationEmail,
emailStockReminders: settings.emailStockReminders,
emailIntakeReminders: settings.emailIntakeReminders,
emailPrescriptionReminders: settings.emailPrescriptionReminders ?? true,
// Only include sensitive data if requested
shoutrrrEnabled: includeSensitive ? settings.shoutrrrEnabled : undefined,
shoutrrrUrl: includeSensitive ? settings.shoutrrrUrl : undefined,
shoutrrrStockReminders: settings.shoutrrrStockReminders,
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
shoutrrrPrescriptionReminders: settings.shoutrrrPrescriptionReminders ?? true,
reminderDaysBefore: settings.reminderDaysBefore,
repeatDailyReminders: settings.repeatDailyReminders,
skipRemindersForTakenDoses: settings.skipRemindersForTakenDoses,
@@ -357,8 +397,10 @@ export async function exportRoutes(app: FastifyInstance) {
lowStockDays: settings.lowStockDays,
normalStockDays: settings.normalStockDays,
highStockDays: settings.highStockDays,
expiryWarningDays: settings.expiryWarningDays,
language: settings.language,
stockCalculationMode: settings.stockCalculationMode,
shareStockStatus: settings.shareStockStatus,
}
: undefined;
@@ -389,6 +431,39 @@ export async function exportRoutes(app: FastifyInstance) {
};
});
// 5. Load refill history
const refills = await db.select().from(refillHistory).where(eq(refillHistory.userId, userId));
const exportRefillHistory = refills
.map((refill) => {
const exportId = medIdToExportId.get(refill.medicationId);
if (!exportId) return null; // Orphaned refill, skip
// Safely convert refillDate to ISO string
let refillDateIso: string;
try {
if (refill.refillDate instanceof Date && !Number.isNaN(refill.refillDate.getTime())) {
refillDateIso = refill.refillDate.toISOString();
} else if (typeof refill.refillDate === "number" || typeof refill.refillDate === "string") {
const d = new Date(refill.refillDate);
refillDateIso = !Number.isNaN(d.getTime()) ? d.toISOString() : new Date().toISOString();
} else {
refillDateIso = new Date().toISOString();
}
} catch {
refillDateIso = new Date().toISOString();
}
return {
medicationRef: exportId,
packsAdded: refill.packsAdded ?? 0,
loosePillsAdded: refill.loosePillsAdded ?? 0,
usedPrescription: refill.usedPrescription ?? false,
refillDate: refillDateIso,
};
})
.filter((r): r is NonNullable<typeof r> => r !== null);
// Build export object
const exportData = {
version: EXPORT_VERSION,
@@ -396,12 +471,17 @@ export async function exportRoutes(app: FastifyInstance) {
includeSensitiveData: includeSensitive,
medications: exportMedications,
doseHistory: exportDoseHistory,
refillHistory: exportRefillHistory,
settings: exportSettings,
shareLinks: exportShareLinks,
};
// Set download headers
const filename = `medassist-export-${new Date().toISOString().split("T")[0]}.json`;
const now = new Date();
const dateStr = now.toISOString().replace(/[-:]/g, "").replace(/T/, "-").slice(0, 13);
const authUser = env.AUTH_ENABLED ? (request.user as unknown as AuthUser | null) : null;
const userPart = authUser?.username ? `-${authUser.username}` : "";
const filename = `medassist-export${userPart}-${dateStr}.json`;
reply.header("Content-Type", "application/json");
reply.header("Content-Disposition", `attachment; filename="${filename}"`);
@@ -452,7 +532,8 @@ export async function exportRoutes(app: FastifyInstance) {
}
}
// Delete in order: doses, share tokens, medications, settings
// Delete in order: refill history, doses, share tokens, medications, settings
await db.delete(refillHistory).where(eq(refillHistory.userId, userId));
await db.delete(doseTracking).where(eq(doseTracking.userId, userId));
await db.delete(shareTokens).where(eq(shareTokens.userId, userId));
await db.delete(medications).where(eq(medications.userId, userId));
@@ -489,14 +570,17 @@ 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,
looseTablets: med.inventory.looseTablets,
totalPills: med.inventory.totalPills ?? null,
stockAdjustment: med.inventory.stockAdjustment ?? 0,
lastStockCorrectionAt: med.lastStockCorrectionAt ? new Date(med.lastStockCorrectionAt) : null,
pillWeightMg: med.pillWeightMg || null,
doseUnit: med.doseUnit ?? "mg",
medicationStartDate: med.medicationStartDate || "",
intakesJson,
usageJson,
everyJson,
@@ -504,6 +588,14 @@ export async function exportRoutes(app: FastifyInstance) {
expiryDate: med.expiryDate || null,
notes: med.notes || null,
intakeRemindersEnabled,
isObsolete: med.isObsolete ?? false,
obsoleteAt: med.obsoleteAt ? new Date(med.obsoleteAt) : null,
prescriptionEnabled: med.prescriptionEnabled ?? false,
prescriptionAuthorizedRefills: med.prescriptionEnabled ? (med.prescriptionAuthorizedRefills ?? null) : null,
prescriptionRemainingRefills: med.prescriptionEnabled ? (med.prescriptionRemainingRefills ?? null) : null,
prescriptionLowRefillThreshold: med.prescriptionLowRefillThreshold ?? 1,
prescriptionExpiryDate: med.prescriptionExpiryDate || null,
dismissedUntil: med.dismissedUntil || null,
imageUrl: null, // Will be set after image is saved
})
.returning();
@@ -535,6 +627,7 @@ export async function exportRoutes(app: FastifyInstance) {
doseId,
takenAt: new Date(dose.takenAt),
markedBy: dose.markedBy || null,
takenSource: dose.takenSource ?? "manual",
dismissed: dose.dismissed ?? false,
});
}
@@ -547,10 +640,12 @@ export async function exportRoutes(app: FastifyInstance) {
notificationEmail: importData.settings.notificationEmail || null,
emailStockReminders: importData.settings.emailStockReminders ?? true,
emailIntakeReminders: importData.settings.emailIntakeReminders ?? true,
emailPrescriptionReminders: importData.settings.emailPrescriptionReminders ?? true,
shoutrrrEnabled: importData.settings.shoutrrrEnabled ?? false,
shoutrrrUrl: importData.settings.shoutrrrUrl || null,
shoutrrrStockReminders: importData.settings.shoutrrrStockReminders ?? true,
shoutrrrIntakeReminders: importData.settings.shoutrrrIntakeReminders ?? true,
shoutrrrPrescriptionReminders: importData.settings.shoutrrrPrescriptionReminders ?? true,
reminderDaysBefore: importData.settings.reminderDaysBefore ?? 7,
repeatDailyReminders: importData.settings.repeatDailyReminders ?? false,
skipRemindersForTakenDoses: importData.settings.skipRemindersForTakenDoses ?? false,
@@ -560,8 +655,10 @@ export async function exportRoutes(app: FastifyInstance) {
lowStockDays: importData.settings.lowStockDays ?? 30,
normalStockDays: importData.settings.normalStockDays ?? 90,
highStockDays: importData.settings.highStockDays ?? 180,
expiryWarningDays: importData.settings.expiryWarningDays ?? 90,
language: importData.settings.language ?? "en",
stockCalculationMode: importData.settings.stockCalculationMode ?? "automatic",
shareStockStatus: importData.settings.shareStockStatus ?? true,
});
}
@@ -579,11 +676,27 @@ export async function exportRoutes(app: FastifyInstance) {
});
}
// 7. Import refill history with remapped medication IDs
for (const refill of importData.refillHistory) {
const newMedId = exportIdToNewId.get(refill.medicationRef);
if (!newMedId) continue; // Skip orphaned refill records
await db.insert(refillHistory).values({
medicationId: newMedId,
userId,
packsAdded: refill.packsAdded ?? 0,
loosePillsAdded: refill.loosePillsAdded ?? 0,
usedPrescription: refill.usedPrescription ?? false,
refillDate: new Date(refill.refillDate),
});
}
return {
success: true,
imported: {
medications: importData.medications.length,
doseHistory: importData.doseHistory.length,
refillHistory: importData.refillHistory.length,
settings: importData.settings ? 1 : 0,
shareLinks: importData.shareLinks.length,
},
+2 -3
View File
@@ -10,11 +10,10 @@ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
const backendVersion = packageJson.version || "unknown";
export async function healthRoutes(app: FastifyInstance) {
// Exempt from rate limit - lightweight health check
app.get("/health", { config: { rateLimit: false } }, async () => ({
// Exempt from rate limit + suppress request logs (called every 30s by Docker healthcheck)
app.get("/health", { config: { rateLimit: false }, logLevel: "warn" }, async () => ({
status: "ok",
version: backendVersion,
smtpConfigured: Boolean(process.env.SMTP_HOST),
shoutrrrConfigured: Boolean(process.env.SHOUTRRR_URL),
}));
}
+556 -87
View File
@@ -1,17 +1,22 @@
import { createWriteStream, existsSync, unlinkSync } from "node:fs";
import { extname, resolve } from "node:path";
import { pipeline } from "node:stream/promises";
import { resolve } from "node:path";
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 { doseTracking, medications } from "../db/schema.js";
import { getDataDir } from "../db/db-utils.js";
import { doseTracking, medications, 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 {
ALLOWED_IMAGE_MIME_TYPES,
removeImageFiles,
streamToBuffer,
writeOptimizedImageSet,
} from "../utils/image-upload.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({
@@ -31,10 +36,13 @@ const blisterSchema = z.object({
const packageTypeSchema = z.enum(["blister", "bottle"]).default("blister");
const doseUnitSchema = z.enum(["mg", "g", "mcg", "ml", "IU", "units", "drops", "puffs"]).default("mg");
const medicationStartDateSchema = z
.union([z.string().regex(/^\d{4}-\d{2}-\d{2}$/), z.literal(""), z.null()])
.optional();
const medicationSchema = z
.object({
name: z.string().trim().min(1).max(100),
name: z.string().trim().max(100).default(""),
genericName: z.string().trim().max(100).nullable().optional(),
takenBy: z.array(z.string().trim().max(100)).default([]), // Medication-level takenBy (fallback)
packageType: packageTypeSchema,
@@ -45,14 +53,59 @@ const medicationSchema = z
looseTablets: z.number().int().min(0).default(0),
pillWeightMg: z.number().nonnegative().nullable().optional(),
doseUnit: doseUnitSchema,
medicationStartDate: medicationStartDateSchema,
expiryDate: z.string().nullable().optional(),
notes: z.string().max(2000).nullable().optional(),
prescriptionEnabled: z.boolean().default(false),
prescriptionAuthorizedRefills: z.number().int().min(0).nullable().optional(),
prescriptionRemainingRefills: z.number().int().min(0).nullable().optional(),
prescriptionLowRefillThreshold: z.number().int().min(0).default(1),
prescriptionExpiryDate: z.string().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" });
.refine((data) => (data.name && data.name.length > 0) || (data.genericName && data.genericName.length > 0), {
message: "Either 'name' or 'genericName' must be provided",
path: ["name"],
})
.refine((data) => data.intakes || data.blisters, { message: "Either 'intakes' or 'blisters' must be provided" })
.refine(
(data) => {
const startDate = data.medicationStartDate ?? "";
if (!startDate) return true;
const scheduleStarts = data.intakes?.map((i) => i.start) ?? data.blisters?.map((b) => b.start) ?? [];
return scheduleStarts.every((scheduleStart) => scheduleStart.slice(0, 10) >= startDate);
},
{
message: "Medication start date must be on or before all intake dates",
path: ["medicationStartDate"],
}
)
.refine(
(data) => {
if (!data.prescriptionEnabled) return true;
if (data.prescriptionAuthorizedRefills == null || data.prescriptionRemainingRefills == null) return false;
return data.prescriptionRemainingRefills <= data.prescriptionAuthorizedRefills;
},
{
message: "When prescription is enabled, remaining refills must be <= authorized refills",
path: ["prescriptionRemainingRefills"],
}
)
.refine(
(data) => {
if (!data.prescriptionEnabled) return true;
if (data.prescriptionAuthorizedRefills == null) return false;
return data.prescriptionLowRefillThreshold <= data.prescriptionAuthorizedRefills;
},
{
message: "When prescription is enabled, low refill threshold must be <= authorized refills",
path: ["prescriptionLowRefillThreshold"],
}
);
export async function medicationRoutes(app: FastifyInstance) {
// All medication routes require auth
@@ -75,9 +128,13 @@ export async function medicationRoutes(app: FastifyInstance) {
return authUser.id;
}
app.get("/medications", async (request, reply) => {
app.get<{ Querystring: { includeObsolete?: string } }>("/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);
const includeObsolete = request.query.includeObsolete === "true";
const whereClause = includeObsolete
? eq(medications.userId, userId)
: and(eq(medications.userId, userId), eq(medications.isObsolete, false));
const rows = await db.select().from(medications).where(whereClause).orderBy(medications.id);
return rows.map((row) => {
// Parse intakes from new format, falling back to legacy
const intakes = parseIntakesJson(
@@ -101,6 +158,7 @@ export async function medicationRoutes(app: FastifyInstance) {
lastStockCorrectionAt: row.lastStockCorrectionAt?.toISOString() ?? null,
pillWeightMg: row.pillWeightMg,
doseUnit: row.doseUnit ?? "mg",
medicationStartDate: row.medicationStartDate || null,
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 })),
@@ -108,6 +166,13 @@ export async function medicationRoutes(app: FastifyInstance) {
expiryDate: row.expiryDate,
notes: row.notes,
intakeRemindersEnabled: row.intakeRemindersEnabled ?? false,
isObsolete: row.isObsolete ?? false,
obsoleteAt: row.obsoleteAt?.toISOString() ?? null,
prescriptionEnabled: row.prescriptionEnabled ?? false,
prescriptionAuthorizedRefills: row.prescriptionAuthorizedRefills ?? null,
prescriptionRemainingRefills: row.prescriptionRemainingRefills ?? null,
prescriptionLowRefillThreshold: row.prescriptionLowRefillThreshold ?? 1,
prescriptionExpiryDate: row.prescriptionExpiryDate ?? null,
dismissedUntil: row.dismissedUntil ?? null,
updatedAt: row.updatedAt,
};
@@ -131,8 +196,14 @@ export async function medicationRoutes(app: FastifyInstance) {
looseTablets,
pillWeightMg,
doseUnit,
medicationStartDate,
expiryDate,
notes,
prescriptionEnabled,
prescriptionAuthorizedRefills,
prescriptionRemainingRefills,
prescriptionLowRefillThreshold,
prescriptionExpiryDate,
intakeRemindersEnabled,
intakes: inputIntakes,
blisters: inputBlisters,
@@ -184,8 +255,14 @@ export async function medicationRoutes(app: FastifyInstance) {
looseTablets,
pillWeightMg: pillWeightMg || null,
doseUnit: doseUnit ?? "mg",
medicationStartDate: medicationStartDate ?? "",
expiryDate: expiryDate || null,
notes: notes || null,
prescriptionEnabled: prescriptionEnabled ?? false,
prescriptionAuthorizedRefills: prescriptionEnabled ? (prescriptionAuthorizedRefills ?? null) : null,
prescriptionRemainingRefills: prescriptionEnabled ? (prescriptionRemainingRefills ?? null) : null,
prescriptionLowRefillThreshold: prescriptionLowRefillThreshold ?? 1,
prescriptionExpiryDate: prescriptionExpiryDate || null,
intakeRemindersEnabled: intakeRemindersEnabled ?? false,
intakesJson,
usageJson,
@@ -209,12 +286,20 @@ export async function medicationRoutes(app: FastifyInstance) {
lastStockCorrectionAt: inserted.lastStockCorrectionAt?.toISOString() ?? null,
pillWeightMg: inserted.pillWeightMg,
doseUnit: inserted.doseUnit ?? "mg",
medicationStartDate: inserted.medicationStartDate || null,
intakes,
blisters: intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start })),
imageUrl: inserted.imageUrl,
expiryDate: inserted.expiryDate,
notes: inserted.notes,
intakeRemindersEnabled: inserted.intakeRemindersEnabled,
isObsolete: inserted.isObsolete ?? false,
obsoleteAt: inserted.obsoleteAt?.toISOString() ?? null,
prescriptionEnabled: inserted.prescriptionEnabled ?? false,
prescriptionAuthorizedRefills: inserted.prescriptionAuthorizedRefills ?? null,
prescriptionRemainingRefills: inserted.prescriptionRemainingRefills ?? null,
prescriptionLowRefillThreshold: inserted.prescriptionLowRefillThreshold ?? 1,
prescriptionExpiryDate: inserted.prescriptionExpiryDate ?? null,
updatedAt: inserted.updatedAt,
};
});
@@ -246,8 +331,14 @@ export async function medicationRoutes(app: FastifyInstance) {
looseTablets,
pillWeightMg,
doseUnit,
medicationStartDate,
expiryDate,
notes,
prescriptionEnabled,
prescriptionAuthorizedRefills,
prescriptionRemainingRefills,
prescriptionLowRefillThreshold,
prescriptionExpiryDate,
intakeRemindersEnabled,
intakes: inputIntakes,
blisters: inputBlisters,
@@ -284,6 +375,17 @@ export async function medicationRoutes(app: FastifyInstance) {
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({
@@ -298,43 +400,143 @@ export async function medicationRoutes(app: FastifyInstance) {
looseTablets,
pillWeightMg: pillWeightMg || null,
doseUnit: doseUnit ?? "mg",
medicationStartDate: medicationStartDate ?? "",
expiryDate: expiryDate || null,
notes: notes || null,
prescriptionEnabled: prescriptionEnabled ?? false,
prescriptionAuthorizedRefills: prescriptionEnabled ? (prescriptionAuthorizedRefills ?? null) : null,
prescriptionRemainingRefills: prescriptionEnabled ? (prescriptionRemainingRefills ?? null) : null,
prescriptionLowRefillThreshold: prescriptionLowRefillThreshold ?? 1,
prescriptionExpiryDate: prescriptionExpiryDate || 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(...intakes.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));
}
}
}
@@ -353,19 +555,85 @@ export async function medicationRoutes(app: FastifyInstance) {
lastStockCorrectionAt: result[0].lastStockCorrectionAt?.toISOString() ?? null,
pillWeightMg: result[0].pillWeightMg,
doseUnit: result[0].doseUnit ?? "mg",
medicationStartDate: result[0].medicationStartDate || null,
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,
intakeRemindersEnabled: result[0].intakeRemindersEnabled,
isObsolete: result[0].isObsolete ?? false,
obsoleteAt: result[0].obsoleteAt?.toISOString() ?? null,
prescriptionEnabled: result[0].prescriptionEnabled ?? false,
prescriptionAuthorizedRefills: result[0].prescriptionAuthorizedRefills ?? null,
prescriptionRemainingRefills: result[0].prescriptionRemainingRefills ?? null,
prescriptionLowRefillThreshold: result[0].prescriptionLowRefillThreshold ?? 1,
prescriptionExpiryDate: result[0].prescriptionExpiryDate ?? null,
updatedAt: result[0].updatedAt,
};
});
// Stock correction endpoint - only updates stockAdjustment, preserves looseTablets
app.post<{ Params: { id: string } }>("/medications/:id/obsolete", async (req, reply) => {
const idNum = Number(req.params.id);
if (Number.isNaN(idNum)) return reply.badRequest("Invalid id");
const userId = await getUserId(req, reply);
const [existing] = await db
.select()
.from(medications)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound();
const [updated] = await db
.update(medications)
.set({
isObsolete: true,
obsoleteAt: new Date(),
updatedAt: new Date(),
})
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
.returning();
return {
id: updated.id,
isObsolete: updated.isObsolete ?? false,
obsoleteAt: updated.obsoleteAt?.toISOString() ?? null,
updatedAt: updated.updatedAt,
};
});
app.post<{ Params: { id: string } }>("/medications/:id/reactivate", async (req, reply) => {
const idNum = Number(req.params.id);
if (Number.isNaN(idNum)) return reply.badRequest("Invalid id");
const userId = await getUserId(req, reply);
const [existing] = await db
.select()
.from(medications)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound();
const [updated] = await db
.update(medications)
.set({
isObsolete: false,
obsoleteAt: null,
updatedAt: new Date(),
})
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
.returning();
return {
id: updated.id,
isObsolete: updated.isObsolete ?? false,
obsoleteAt: updated.obsoleteAt?.toISOString() ?? null,
updatedAt: updated.updatedAt,
};
});
// Stock correction endpoint - updates stockAdjustment and optionally looseTablets (for blister type)
// Also sets lastStockCorrectionAt so consumed doses before this point don't count
app.patch<{ Params: { id: string }; Body: { stockAdjustment: number } }>(
app.patch<{ Params: { id: string }; Body: { stockAdjustment: number; looseTablets?: number } }>(
"/medications/:id/stock-adjustment",
async (req, reply) => {
const idNum = Number(req.params.id);
@@ -380,16 +648,32 @@ export async function medicationRoutes(app: FastifyInstance) {
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound();
const { stockAdjustment } = req.body as { stockAdjustment: number };
const { stockAdjustment, looseTablets } = req.body as { stockAdjustment: number; looseTablets?: number };
if (typeof stockAdjustment !== "number") return reply.badRequest("stockAdjustment must be a number");
if (
looseTablets !== undefined &&
(typeof looseTablets !== "number" || !Number.isInteger(looseTablets) || looseTablets < 0)
) {
return reply.badRequest("looseTablets must be a non-negative integer");
}
const updateFields: {
stockAdjustment: number;
lastStockCorrectionAt: Date;
updatedAt: Date;
looseTablets?: number;
} = {
stockAdjustment,
lastStockCorrectionAt: new Date(),
updatedAt: new Date(),
};
if (looseTablets !== undefined) {
updateFields.looseTablets = looseTablets;
}
const result = await db
.update(medications)
.set({
stockAdjustment,
lastStockCorrectionAt: new Date(), // Mark when correction was made
updatedAt: new Date(),
})
.set(updateFields)
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
.returning();
@@ -417,10 +701,7 @@ export async function medicationRoutes(app: FastifyInstance) {
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound();
if (existing.imageUrl) {
const imagePath = resolve(IMAGES_DIR, existing.imageUrl);
if (existsSync(imagePath)) unlinkSync(imagePath);
}
if (existing.imageUrl) removeImageFiles(IMAGES_DIR, existing.imageUrl);
const deleted = await db
.delete(medications)
@@ -443,24 +724,31 @@ export async function medicationRoutes(app: FastifyInstance) {
if (!existing) return reply.notFound();
const data = await req.file();
if (!data) return reply.badRequest("No file uploaded");
if (!data) return reply.status(400).send({ error: "No file uploaded", code: "NO_FILE" });
const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
if (!allowedTypes.includes(data.mimetype)) {
return reply.badRequest("Invalid file type. Allowed: JPEG, PNG, WebP, GIF");
if (!ALLOWED_IMAGE_MIME_TYPES.includes(data.mimetype)) {
return reply.status(400).send({ error: "Invalid file type", code: "INVALID_TYPE" });
}
const ext = extname(data.filename) || ".jpg";
const filename = `med-${idNum}-${Date.now()}${ext}`;
const filepath = resolve(IMAGES_DIR, filename);
let uploadBuffer: Buffer;
try {
uploadBuffer = await streamToBuffer(data.file);
} catch (error) {
if (error instanceof Error && error.message === "IMAGE_TOO_LARGE") {
return reply.status(400).send({ error: "Image too large", code: "IMAGE_TOO_LARGE" });
}
throw error;
}
await pipeline(data.file, createWriteStream(filepath));
let filename: string;
try {
({ filename } = await writeOptimizedImageSet(IMAGES_DIR, `med-${idNum}`, uploadBuffer));
} catch {
return reply.status(400).send({ error: "Invalid image", code: "INVALID_IMAGE" });
}
// Delete old image if exists
if (existing.imageUrl) {
const oldPath = resolve(IMAGES_DIR, existing.imageUrl);
if (existsSync(oldPath)) unlinkSync(oldPath);
}
if (existing.imageUrl) removeImageFiles(IMAGES_DIR, existing.imageUrl);
await db
.update(medications)
@@ -482,10 +770,7 @@ export async function medicationRoutes(app: FastifyInstance) {
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
if (!existing) return reply.notFound();
if (existing.imageUrl) {
const filepath = resolve(IMAGES_DIR, existing.imageUrl);
if (existsSync(filepath)) unlinkSync(filepath);
}
if (existing.imageUrl) removeImageFiles(IMAGES_DIR, existing.imageUrl);
await db
.update(medications)
@@ -495,10 +780,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) {
@@ -506,7 +795,47 @@ 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);
const rows = await db
.select()
.from(medications)
.where(and(eq(medications.userId, userId), eq(medications.isObsolete, false)))
.orderBy(medications.id);
const [settingsRow] = await db
.select({ stockCalculationMode: userSettings.stockCalculationMode })
.from(userSettings)
.where(eq(userSettings.userId, userId));
const stockCalculationMode = settingsRow?.stockCalculationMode === "manual" ? "manual" : "automatic";
// 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)));
const takenDoseIdsByMed = new Map<number, Set<string>>();
const takenDoseTimestamps = new Map<string, number>();
takenDoses.forEach((dose) => {
const parts = dose.doseId.split("-");
if (parts.length < 3) return;
const medId = parseInt(parts[0], 10);
if (Number.isNaN(medId)) return;
if (!takenDoseIdsByMed.has(medId)) {
takenDoseIdsByMed.set(medId, new Set());
}
takenDoseIdsByMed.get(medId)!.add(dose.doseId);
const rawTakenAt = Number(dose.takenAt);
let takenAtMs: number;
if (Number.isFinite(rawTakenAt)) {
takenAtMs = rawTakenAt < 1_000_000_000_000 ? rawTakenAt * 1000 : rawTakenAt;
} else {
takenAtMs = new Date(dose.takenAt).getTime();
}
takenDoseTimestamps.set(dose.doseId, takenAtMs);
});
// Use current time as the reference point for "available" stock
const now = new Date();
const payload = rows.map((row) => {
@@ -517,51 +846,175 @@ export async function medicationRoutes(app: FastifyInstance) {
row.intakeRemindersEnabled ?? false
);
const blisters = intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start }));
const usageTotal = calculateUsageInRange(blisters, start, end);
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 with the same automatic/manual behavior as frontend coverage.
const stockCorrectionCutoff = row.lastStockCorrectionAt ? new Date(row.lastStockCorrectionAt).getTime() : 0;
const takenDoseIds = takenDoseIdsByMed.get(row.id) ?? new Set<string>();
// Count consumed pills by generating expected doses and checking if they're taken
let consumedUntilNow = 0;
blisters.forEach((blister) => {
const blisterStart = parseLocalDateTime(blister.start);
if (Number.isNaN(blisterStart.getTime()) || blisterStart > now) return;
const msPerDay = 86400000;
const period = Math.max(1, blister.every) * msPerDay;
const occurrences = Math.floor((now.getTime() - blisterStart.getTime()) / period) + 1;
consumedUntilNow += occurrences * blister.usage;
});
const msPerDay = 86400000;
if (stockCalculationMode === "automatic") {
blisters.forEach((blister, blisterIdx) => {
const blisterStart = parseLocalDateTime(blister.start).getTime();
if (Number.isNaN(blisterStart)) return;
const period = Math.max(1, blister.every) * msPerDay;
let effectiveStart: number;
if (stockCorrectionCutoff > 0 && stockCorrectionCutoff >= blisterStart) {
const elapsedSinceStart = stockCorrectionCutoff - blisterStart;
const periodsElapsed = Math.floor(elapsedSinceStart / period);
effectiveStart = blisterStart + (periodsElapsed + 1) * period;
} else {
effectiveStart = blisterStart;
}
const intake = intakes[blisterIdx];
const intakePerson = intake?.takenBy;
const fallbackPeople = parseTakenByJson(row.takenByJson);
let peopleForThisIntake: Array<string | null>;
if (intakePerson) {
peopleForThisIntake = [intakePerson];
} else if (fallbackPeople.length > 0) {
peopleForThisIntake = fallbackPeople;
} else {
peopleForThisIntake = [null];
}
let timeBasedConsumed = 0;
let lastAutoConsumedDateMs = 0;
if (effectiveStart <= now.getTime()) {
const occurrences = Math.floor((now.getTime() - effectiveStart) / period) + 1;
timeBasedConsumed = occurrences * blister.usage * peopleForThisIntake.length;
const lastDoseTime = new Date(effectiveStart + (occurrences - 1) * period);
lastAutoConsumedDateMs = new Date(
lastDoseTime.getFullYear(),
lastDoseTime.getMonth(),
lastDoseTime.getDate()
).getTime();
}
const stockCorrectionDateOnly =
stockCorrectionCutoff > 0
? new Date(
new Date(stockCorrectionCutoff).getFullYear(),
new Date(stockCorrectionCutoff).getMonth(),
new Date(stockCorrectionCutoff).getDate()
).getTime()
: 0;
const earlyCutoff = Math.max(lastAutoConsumedDateMs, stockCorrectionDateOnly);
let earlyTakenConsumed = 0;
for (const doseId of takenDoseIds) {
const parts = doseId.split("-");
if (parts.length < 3) continue;
const bIdx = parseInt(parts[1], 10);
const timestamp = parseInt(parts[2], 10);
if (!Number.isNaN(bIdx) && !Number.isNaN(timestamp) && bIdx === blisterIdx && timestamp > earlyCutoff) {
earlyTakenConsumed += blister.usage;
}
}
consumedUntilNow += timeBasedConsumed + earlyTakenConsumed;
});
} else {
blisters.forEach((blister, blisterIdx) => {
const blisterStart = parseLocalDateTime(blister.start);
const blisterStartDateOnly = new Date(
blisterStart.getFullYear(),
blisterStart.getMonth(),
blisterStart.getDate()
).getTime();
if (Number.isNaN(blisterStartDateOnly)) return;
for (const doseId of takenDoseIds) {
const parts = doseId.split("-");
if (parts.length < 3) continue;
const parsedBlisterIdx = parseInt(parts[1], 10);
const doseTimestamp = parseInt(parts[2], 10);
if (Number.isNaN(parsedBlisterIdx) || Number.isNaN(doseTimestamp) || parsedBlisterIdx !== blisterIdx) {
continue;
}
const takenAt = takenDoseTimestamps.get(doseId) ?? 0;
const afterCorrectionOrNoCorrection = stockCorrectionCutoff === 0 || takenAt > stockCorrectionCutoff;
if (doseTimestamp >= blisterStartDateOnly && afterCorrectionOrNoCorrection) {
consumedUntilNow += blister.usage;
}
}
});
}
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 currentPills = Math.max(0, originalTotalPills - consumedUntilNow);
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,
currentPills: currentStock,
plannerUsage: usageTotal,
blisterSize: pillsPerBlister,
blistersNeeded,
fullBlisters,
loosePills,
enough,
packageType,
};
});
@@ -627,12 +1080,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));
+33 -27
View File
@@ -1,5 +1,5 @@
import { createHash, randomBytes } from "node:crypto";
import { eq } from "drizzle-orm";
import { eq, sql } from "drizzle-orm";
import type { FastifyInstance, FastifyReply } from "fastify";
import * as client from "openid-client";
import { db } from "../db/client.js";
@@ -63,7 +63,7 @@ export async function oidcRoutes(app: FastifyInstance) {
// ---------------------------------------------------------------------------
// GET /auth/oidc/login - Initiates OIDC flow
// ---------------------------------------------------------------------------
app.get("/auth/oidc/login", async (_request, reply) => {
app.get("/auth/oidc/login", async (request, reply) => {
try {
const config = await getOIDCConfig();
@@ -104,8 +104,8 @@ export async function oidcRoutes(app: FastifyInstance) {
});
return reply.redirect(authUrl.href);
} catch (err: any) {
console.error("[OIDC] Login error:", err);
} catch (err: unknown) {
request.log.error({ err }, "[OIDC] Login initialization failed");
return reply.redirect(`${getFrontendUrl()}/?error=oidc_init_failed`);
}
});
@@ -120,7 +120,7 @@ export async function oidcRoutes(app: FastifyInstance) {
// Handle OIDC provider errors
if (error) {
console.error(`[OIDC] Provider error: ${error} - ${error_description}`);
app.log.warn({ error, errorDescription: error_description }, "[OIDC] Provider returned error");
return reply.redirect(`${getFrontendUrl()}/?error=oidc_${error}`);
}
@@ -131,35 +131,35 @@ export async function oidcRoutes(app: FastifyInstance) {
// Verify state
const storedState = request.unsignCookie(request.cookies.oidc_state || "");
if (!storedState.valid || storedState.value !== state) {
console.error("[OIDC] State mismatch");
request.log.warn("[OIDC] State mismatch during callback validation");
return reply.redirect(`${getFrontendUrl()}/?error=oidc_state_mismatch`);
}
// Get code verifier
const storedVerifier = request.unsignCookie(request.cookies.oidc_code_verifier || "");
if (!storedVerifier.valid || !storedVerifier.value) {
console.error("[OIDC] Missing code verifier");
request.log.warn("[OIDC] Missing/invalid code verifier cookie");
return reply.redirect(`${getFrontendUrl()}/?error=oidc_missing_verifier`);
}
try {
const config = await getOIDCConfig();
const _redirectUri = env.OIDC_REDIRECT_URI!;
const redirectUri = env.OIDC_REDIRECT_URI!;
// Exchange code for tokens
const tokens = await client.authorizationCodeGrant(
config,
new URL(request.url, `http://${request.headers.host}`),
{
pkceCodeVerifier: storedVerifier.value,
expectedState: state,
}
);
// Build complete callback URL with query parameters for validation
const callbackUrl = new URL(redirectUri);
callbackUrl.search = new URLSearchParams(request.query as Record<string, string>).toString();
const tokens = await client.authorizationCodeGrant(config, callbackUrl, {
pkceCodeVerifier: storedVerifier.value,
expectedState: state,
});
// Get user info
const sub = tokens.claims()?.sub;
if (!sub) {
console.error("[OIDC] Missing sub claim in token");
request.log.error("[OIDC] Missing sub claim in token response");
return reply.redirect(`${getFrontendUrl()}/?error=oidc_missing_sub`);
}
const userInfo = await client.fetchUserInfo(config, tokens.access_token, sub);
@@ -167,11 +167,17 @@ export async function oidcRoutes(app: FastifyInstance) {
// Extract username from configured claim
const usernameClaim = env.OIDC_USERNAME_CLAIM;
const username =
(userInfo as any)[usernameClaim] || userInfo.preferred_username || userInfo.email || userInfo.sub;
(userInfo as Record<string, string>)[usernameClaim] ||
userInfo.preferred_username ||
userInfo.email ||
userInfo.sub;
const oidcSubject = userInfo.sub;
if (!username || !oidcSubject) {
console.error("[OIDC] Missing required user info:", { username, oidcSubject });
request.log.error(
{ hasUsername: Boolean(username), hasOidcSubject: Boolean(oidcSubject) },
"[OIDC] Missing required user info"
);
return reply.redirect(`${getFrontendUrl()}/?error=oidc_missing_user_info`);
}
@@ -201,7 +207,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);
@@ -210,8 +216,8 @@ export async function oidcRoutes(app: FastifyInstance) {
// In dev: CORS_ORIGINS contains the frontend URL
const frontendUrl = env.CORS_ORIGINS.split(",")[0] || "http://localhost:5173";
return reply.redirect(`${frontendUrl}/dashboard`);
} catch (err: any) {
console.error("[OIDC] Callback error:", err);
} catch (err: unknown) {
request.log.error({ err }, "[OIDC] Callback processing failed");
return reply.redirect(`${getFrontendUrl()}/?error=oidc_callback_failed`);
}
}
@@ -234,25 +240,25 @@ async function findOrCreateOIDCUser(
}
// Check if username already exists (potential collision)
const [existingByUsername] = await db.select().from(users).where(eq(users.username, username));
const [existingByUsername] = await db.select().from(users).where(sql`lower(${users.username}) = lower(${username})`);
if (existingByUsername) {
// Username collision! Check if it's a local user without OIDC linked
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
}
}
// Check if auto-create is enabled
if (!env.OIDC_AUTO_CREATE_USERS) {
console.error(`[OIDC] User creation disabled and user not found: ${username}`);
// No logger is available in this helper, route-level logs already capture callback failures.
return null;
}
@@ -268,7 +274,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;
}
File diff suppressed because it is too large Load Diff
+58 -13
View File
@@ -11,6 +11,7 @@ const refillSchema = z
.object({
packsAdded: z.number().int().min(0).default(0),
loosePillsAdded: z.number().int().min(0).default(0),
usePrescription: z.boolean().default(false),
})
.refine((data) => data.packsAdded > 0 || data.loosePillsAdded > 0, {
message: "Must add at least one pack or some loose pills",
@@ -50,17 +51,46 @@ export async function refillRoutes(app: FastifyInstance) {
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
if (!med) return reply.notFound("Medication not found");
const { packsAdded, loosePillsAdded } = parsed.data;
const { packsAdded, loosePillsAdded, usePrescription } = parsed.data;
const isBottle = (med.packageType ?? "blister") === "bottle";
const effectivePacksAdded = isBottle ? 0 : packsAdded;
const effectiveLoosePillsAdded = loosePillsAdded;
const remainingPrescriptionRefills = med.prescriptionRemainingRefills ?? 0;
if (effectivePacksAdded < 1 && effectiveLoosePillsAdded < 1) {
return reply.status(400).send({ error: "Must add at least one pack or some loose pills" });
}
if (usePrescription) {
if (!(med.prescriptionEnabled ?? false)) {
return reply.status(400).send({ error: "Prescription refill is not enabled for this medication" });
}
if (remainingPrescriptionRefills <= 0) {
return reply.status(409).send({ error: "No remaining prescription refills" });
}
if (!isBottle && effectivePacksAdded > remainingPrescriptionRefills) {
return reply.status(409).send({ error: "Packs to add exceed remaining prescription refills" });
}
}
// Update medication stock
const newPackCount = med.packCount + packsAdded;
const newLooseTablets = med.looseTablets + loosePillsAdded;
const newPackCount = med.packCount + effectivePacksAdded;
const newLooseTablets = med.looseTablets + effectiveLoosePillsAdded;
let consumedRefills = 0;
if (usePrescription) {
consumedRefills = isBottle ? 1 : effectivePacksAdded;
}
const newRemainingRefills = usePrescription
? Math.max(0, remainingPrescriptionRefills - consumedRefills)
: (med.prescriptionRemainingRefills ?? null);
await db
.update(medications)
.set({
packCount: newPackCount,
looseTablets: newLooseTablets,
prescriptionRemainingRefills: newRemainingRefills,
updatedAt: new Date(),
})
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
@@ -71,28 +101,41 @@ export async function refillRoutes(app: FastifyInstance) {
.values({
medicationId: medId,
userId,
packsAdded,
loosePillsAdded,
packsAdded: effectivePacksAdded,
loosePillsAdded: effectiveLoosePillsAdded,
usedPrescription: usePrescription,
})
.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 pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
const totalPillsAdded = isBottle
? effectiveLoosePillsAdded
: effectivePacksAdded * pillsPerPack + effectiveLoosePillsAdded;
const newTotalPills = isBottle
? newLooseTablets + (med.stockAdjustment ?? 0)
: newPackCount * pillsPerPack + newLooseTablets + (med.stockAdjustment ?? 0);
return {
success: true,
refill: {
id: refill.id,
packsAdded,
loosePillsAdded,
packsAdded: effectivePacksAdded,
loosePillsAdded: effectiveLoosePillsAdded,
totalPillsAdded,
refillDate: refill.refillDate,
},
newStock: {
packCount: newPackCount,
looseTablets: newLooseTablets,
totalPills: newPackCount * pillsPerPack + newLooseTablets,
totalPills: newTotalPills,
},
prescription: {
used: usePrescription,
remainingRefills: newRemainingRefills,
authorizedRefills: med.prescriptionAuthorizedRefills ?? null,
lowRefillThreshold: med.prescriptionLowRefillThreshold ?? 1,
enabled: med.prescriptionEnabled ?? false,
},
};
});
@@ -118,13 +161,15 @@ 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,
usedPrescription: r.usedPrescription ?? false,
refillDate: r.refillDate,
}));
});
+113
View File
@@ -0,0 +1,113 @@
import { eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../db/client.js";
import { doseTracking, medications, refillHistory } from "../db/schema.js";
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js";
const reportDataSchema = z.object({
medicationIds: z.array(z.number().int().positive()).min(1).max(100),
});
export async function reportRoutes(app: FastifyInstance) {
app.addHook("preHandler", requireAuth);
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
if (!env.AUTH_ENABLED) {
return getAnonymousUserId();
}
const authUser = request.user as unknown as AuthUser | null;
if (!authUser) {
reply.status(401).send({ error: "User not authenticated", code: "AUTH_REQUIRED" });
throw new Error("AUTH_REQUIRED");
}
return authUser.id;
}
// POST /medications/report-data - Get aggregated dose/refill data for report generation
app.post("/medications/report-data", async (req, reply) => {
const parsed = reportDataSchema.safeParse(req.body);
if (!parsed.success) return reply.status(400).send(parsed.error.format());
const userId = await getUserId(req, reply);
const { medicationIds } = parsed.data;
// Verify all medications belong to this user
const userMeds = await db.select({ id: medications.id }).from(medications).where(eq(medications.userId, userId));
const userMedIds = new Set(userMeds.map((m) => m.id));
for (const id of medicationIds) {
if (!userMedIds.has(id)) {
return reply.status(403).send({ error: "Access denied to medication" });
}
}
// Fetch dose tracking for all requested medications
// doseId format: "{medicationId}-{blisterIndex}-{dateMs}" or "{medicationId}-{blisterIndex}-{dateMs}-{takenBy}"
const allDoses = await db
.select({
doseId: doseTracking.doseId,
takenAt: doseTracking.takenAt,
dismissed: doseTracking.dismissed,
takenSource: doseTracking.takenSource,
})
.from(doseTracking)
.where(eq(doseTracking.userId, userId));
// Group doses by medication ID
const dosesByMed = new Map<number, { takenAt: Date; dismissed: boolean; takenSource: string }[]>();
for (const dose of allDoses) {
const medId = Number.parseInt(dose.doseId.split("-")[0], 10);
if (Number.isNaN(medId) || !medicationIds.includes(medId)) continue;
if (!dosesByMed.has(medId)) dosesByMed.set(medId, []);
dosesByMed.get(medId)!.push({
takenAt: dose.takenAt,
dismissed: dose.dismissed,
takenSource: dose.takenSource ?? "manual",
});
}
// Fetch refill history for requested medications
const result: Record<
number,
{
dosesTaken: number;
automaticDosesTaken: number;
dosesDismissed: number;
firstDoseAt: string | null;
lastDoseAt: string | null;
refills: { packsAdded: number; loosePillsAdded: number; usedPrescription: boolean; refillDate: string }[];
}
> = {};
for (const medId of medicationIds) {
const doses = dosesByMed.get(medId) ?? [];
const takenDoses = doses.filter((d) => !d.dismissed);
const automaticTakenDoses = takenDoses.filter((d) => d.takenSource === "automatic");
const dismissedDoses = doses.filter((d) => d.dismissed);
const sortedTaken = takenDoses.map((d) => d.takenAt.getTime()).sort((a, b) => a - b);
// Get refills for this medication
const refills = await db.select().from(refillHistory).where(eq(refillHistory.medicationId, medId));
result[medId] = {
dosesTaken: takenDoses.length,
automaticDosesTaken: automaticTakenDoses.length,
dosesDismissed: dismissedDoses.length,
firstDoseAt: sortedTaken.length > 0 ? new Date(sortedTaken[0]).toISOString() : null,
lastDoseAt: sortedTaken.length > 0 ? new Date(sortedTaken[sortedTaken.length - 1]).toISOString() : null,
refills: refills.map((r) => ({
packsAdded: r.packsAdded,
loosePillsAdded: r.loosePillsAdded,
usedPrescription: r.usedPrescription ?? false,
refillDate: r.refillDate instanceof Date ? r.refillDate.toISOString() : String(r.refillDate),
})),
};
}
return result;
});
}
+343 -40
View File
@@ -1,5 +1,5 @@
import { eq } from "drizzle-orm";
import type { FastifyInstance } from "fastify";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import nodemailer from "nodemailer";
import { db } from "../db/client.js";
import { userSettings } from "../db/schema.js";
@@ -15,10 +15,12 @@ export type UserSettings = {
notificationEmail: string | null;
emailStockReminders: boolean;
emailIntakeReminders: boolean;
emailPrescriptionReminders: boolean;
shoutrrrEnabled: boolean;
shoutrrrUrl: string | null;
shoutrrrStockReminders: boolean;
shoutrrrIntakeReminders: boolean;
shoutrrrPrescriptionReminders: boolean;
reminderDaysBefore: number;
repeatDailyReminders: boolean;
skipRemindersForTakenDoses: boolean;
@@ -30,11 +32,21 @@ export type UserSettings = {
highStockDays: number;
language: Language;
stockCalculationMode: "automatic" | "manual";
shareStockStatus: boolean;
upcomingTodayOnly: boolean;
shareScheduleTodayOnly: boolean;
swapDashboardMainSections: 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;
lastPrescriptionReminderSent: string | null;
lastPrescriptionReminderChannel: string | null;
lastPrescriptionReminderMedNames: string | null;
};
type SettingsBody = {
@@ -49,14 +61,20 @@ type SettingsBody = {
shoutrrrUrl: string;
emailStockReminders: boolean;
emailIntakeReminders: boolean;
emailPrescriptionReminders: boolean;
shoutrrrStockReminders: boolean;
shoutrrrIntakeReminders: boolean;
shoutrrrPrescriptionReminders: boolean;
skipRemindersForTakenDoses: boolean;
repeatRemindersEnabled: boolean;
reminderRepeatIntervalMinutes: number;
maxNaggingReminders: number;
language: string;
stockCalculationMode: "automatic" | "manual";
shareStockStatus: boolean;
upcomingTodayOnly: boolean;
shareScheduleTodayOnly: boolean;
swapDashboardMainSections: boolean;
};
type TestEmailBody = {
@@ -67,6 +85,21 @@ type TestShoutrrrBody = {
url: string;
};
function getNotificationProvider(url: string): string {
if (url.startsWith("discord://")) return "discord";
if (url.startsWith("telegram://")) return "telegram";
if (url.startsWith("gotify://")) return "gotify";
if (url.startsWith("pushover://")) return "pushover";
if (url.startsWith("ntfy://")) return "ntfy";
try {
const parsed = new URL(url);
return parsed.hostname || "https";
} catch {
return "unknown";
}
}
// Helper to parse boolean env vars
function envBool(key: string, defaultVal: boolean): boolean {
const val = process.env[key];
@@ -89,10 +122,12 @@ function getDefaultSettings() {
notificationEmail: process.env.DEFAULT_NOTIFICATION_EMAIL || null,
emailStockReminders: envBool("DEFAULT_EMAIL_STOCK_REMINDERS", true),
emailIntakeReminders: envBool("DEFAULT_EMAIL_INTAKE_REMINDERS", true),
emailPrescriptionReminders: envBool("DEFAULT_EMAIL_PRESCRIPTION_REMINDERS", true),
shoutrrrEnabled: envBool("DEFAULT_SHOUTRRR_ENABLED", false),
shoutrrrUrl: process.env.DEFAULT_SHOUTRRR_URL || null,
shoutrrrStockReminders: envBool("DEFAULT_SHOUTRRR_STOCK_REMINDERS", true),
shoutrrrIntakeReminders: envBool("DEFAULT_SHOUTRRR_INTAKE_REMINDERS", true),
shoutrrrPrescriptionReminders: envBool("DEFAULT_SHOUTRRR_PRESCRIPTION_REMINDERS", true),
reminderDaysBefore: envInt("REMINDER_DAYS_BEFORE", 7),
repeatDailyReminders: envBool("DEFAULT_REPEAT_DAILY_REMINDERS", false),
skipRemindersForTakenDoses: envBool("DEFAULT_SKIP_REMINDERS_FOR_TAKEN_DOSES", false),
@@ -104,11 +139,21 @@ 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),
upcomingTodayOnly: envBool("DEFAULT_UPCOMING_TODAY_ONLY", false),
shareScheduleTodayOnly: envBool("DEFAULT_SHARE_SCHEDULE_TODAY_ONLY", false),
swapDashboardMainSections: false,
lastAutoEmailSent: null,
lastNotificationType: null,
lastNotificationChannel: null,
lastReminderMedName: null,
lastReminderTakenBy: null,
lastStockReminderSent: null,
lastStockReminderChannel: null,
lastStockReminderMedNames: null,
lastPrescriptionReminderSent: null,
lastPrescriptionReminderChannel: null,
lastPrescriptionReminderMedNames: null,
};
}
@@ -139,10 +184,12 @@ export async function loadUserSettings(userId: number): Promise<UserSettings> {
notificationEmail: settings.notificationEmail,
emailStockReminders: settings.emailStockReminders,
emailIntakeReminders: settings.emailIntakeReminders,
emailPrescriptionReminders: settings.emailPrescriptionReminders ?? true,
shoutrrrEnabled: settings.shoutrrrEnabled,
shoutrrrUrl: settings.shoutrrrUrl,
shoutrrrStockReminders: settings.shoutrrrStockReminders,
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
shoutrrrPrescriptionReminders: settings.shoutrrrPrescriptionReminders ?? true,
reminderDaysBefore: settings.reminderDaysBefore,
repeatDailyReminders: settings.repeatDailyReminders,
skipRemindersForTakenDoses: settings.skipRemindersForTakenDoses ?? false,
@@ -154,11 +201,21 @@ 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,
upcomingTodayOnly: settings.upcomingTodayOnly ?? false,
shareScheduleTodayOnly: settings.shareScheduleTodayOnly ?? false,
swapDashboardMainSections: settings.swapDashboardMainSections ?? false,
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,
lastPrescriptionReminderSent: settings.lastPrescriptionReminderSent ?? null,
lastPrescriptionReminderChannel: settings.lastPrescriptionReminderChannel ?? null,
lastPrescriptionReminderMedNames: settings.lastPrescriptionReminderMedNames ?? null,
};
}
@@ -171,10 +228,12 @@ export async function getAllUserSettings(): Promise<UserSettings[]> {
notificationEmail: settings.notificationEmail,
emailStockReminders: settings.emailStockReminders,
emailIntakeReminders: settings.emailIntakeReminders,
emailPrescriptionReminders: settings.emailPrescriptionReminders ?? true,
shoutrrrEnabled: settings.shoutrrrEnabled,
shoutrrrUrl: settings.shoutrrrUrl,
shoutrrrStockReminders: settings.shoutrrrStockReminders,
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
shoutrrrPrescriptionReminders: settings.shoutrrrPrescriptionReminders ?? true,
reminderDaysBefore: settings.reminderDaysBefore,
repeatDailyReminders: settings.repeatDailyReminders,
skipRemindersForTakenDoses: settings.skipRemindersForTakenDoses ?? false,
@@ -186,11 +245,21 @@ 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,
upcomingTodayOnly: settings.upcomingTodayOnly ?? false,
shareScheduleTodayOnly: settings.shareScheduleTodayOnly ?? false,
swapDashboardMainSections: settings.swapDashboardMainSections ?? false,
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,
lastPrescriptionReminderSent: settings.lastPrescriptionReminderSent ?? null,
lastPrescriptionReminderChannel: settings.lastPrescriptionReminderChannel ?? null,
lastPrescriptionReminderMedNames: settings.lastPrescriptionReminderMedNames ?? null,
}));
}
@@ -200,7 +269,7 @@ export async function settingsRoutes(app: FastifyInstance) {
// Helper to get user ID from request
// Returns anonymous user ID when auth is disabled
async function getUserId(request: any, reply: any): Promise<number> {
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
// If auth is disabled, use the anonymous user
if (!env.AUTH_ENABLED) {
return getAnonymousUserId();
@@ -215,7 +284,8 @@ export async function settingsRoutes(app: FastifyInstance) {
}
// Get settings for current user
app.get("/settings", async (request, reply) => {
// Suppress request logs — polled every 30s for reminder status refresh
app.get("/settings", { logLevel: "warn" }, async (request, reply) => {
const userId = await getUserId(request, reply);
const settings = await getOrCreateUserSettings(userId);
@@ -233,14 +303,20 @@ export async function settingsRoutes(app: FastifyInstance) {
shoutrrrUrl: settings.shoutrrrUrl ?? "",
emailStockReminders: settings.emailStockReminders,
emailIntakeReminders: settings.emailIntakeReminders,
emailPrescriptionReminders: settings.emailPrescriptionReminders ?? true,
shoutrrrStockReminders: settings.shoutrrrStockReminders,
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
shoutrrrPrescriptionReminders: settings.shoutrrrPrescriptionReminders ?? true,
skipRemindersForTakenDoses: settings.skipRemindersForTakenDoses,
repeatRemindersEnabled: settings.repeatRemindersEnabled ?? false,
reminderRepeatIntervalMinutes: settings.reminderRepeatIntervalMinutes ?? 30,
maxNaggingReminders: settings.maxNaggingReminders ?? 5,
language: settings.language,
stockCalculationMode: settings.stockCalculationMode ?? "automatic",
shareStockStatus: settings.shareStockStatus ?? true,
upcomingTodayOnly: settings.upcomingTodayOnly ?? false,
shareScheduleTodayOnly: settings.shareScheduleTodayOnly ?? false,
swapDashboardMainSections: settings.swapDashboardMainSections ?? false,
// SMTP settings (from .env - shared/server-configured)
smtpHost: process.env.SMTP_HOST ?? "",
smtpPort: parseInt(process.env.SMTP_PORT ?? "587", 10),
@@ -254,6 +330,14 @@ 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,
// Prescription reminder tracking (separate from stock/intake)
lastPrescriptionReminderSent: settings.lastPrescriptionReminderSent ?? null,
lastPrescriptionReminderChannel: settings.lastPrescriptionReminderChannel ?? null,
lastPrescriptionReminderMedNames: settings.lastPrescriptionReminderMedNames ?? null,
// Server settings (from .env, read-only)
expiryWarningDays: parseInt(process.env.EXPIRY_WARNING_DAYS ?? "30", 10),
});
@@ -281,10 +365,12 @@ export async function settingsRoutes(app: FastifyInstance) {
notificationEmail: body.notificationEmail || null,
emailStockReminders: body.emailStockReminders ?? true,
emailIntakeReminders: body.emailIntakeReminders ?? true,
emailPrescriptionReminders: body.emailPrescriptionReminders ?? true,
shoutrrrEnabled: body.shoutrrrEnabled ?? false,
shoutrrrUrl: body.shoutrrrUrl || null,
shoutrrrStockReminders: body.shoutrrrStockReminders ?? true,
shoutrrrIntakeReminders: body.shoutrrrIntakeReminders ?? true,
shoutrrrPrescriptionReminders: body.shoutrrrPrescriptionReminders ?? true,
reminderDaysBefore: body.reminderDaysBefore,
repeatDailyReminders,
skipRemindersForTakenDoses: body.skipRemindersForTakenDoses ?? false,
@@ -296,6 +382,10 @@ export async function settingsRoutes(app: FastifyInstance) {
highStockDays: body.highStockDays ?? 180,
language: body.language ?? "en",
stockCalculationMode: body.stockCalculationMode ?? "automatic",
shareStockStatus: body.shareStockStatus ?? true,
upcomingTodayOnly: body.upcomingTodayOnly ?? false,
shareScheduleTodayOnly: body.shareScheduleTodayOnly ?? false,
swapDashboardMainSections: body.swapDashboardMainSections ?? false,
updatedAt: new Date(),
};
@@ -311,6 +401,30 @@ export async function settingsRoutes(app: FastifyInstance) {
return reply.send({ success: true });
});
// Update only the language setting (lightweight, called on dropdown change)
app.put<{ Body: { language: string } }>("/settings/language", async (request, reply) => {
const userId = await getUserId(request, reply);
const { language } = request.body;
if (!language || !["en", "de"].includes(language)) {
return reply.status(400).send({ error: "Invalid language" });
}
const existingSettings = await db.select().from(userSettings).where(eq(userSettings.userId, userId));
if (existingSettings.length > 0) {
await db.update(userSettings).set({ language, updatedAt: new Date() }).where(eq(userSettings.userId, userId));
} else {
await db.insert(userSettings).values({
userId,
...getDefaultSettings(),
language,
});
}
return reply.send({ success: true });
});
// Test email - use SMTP settings from process.env
app.post<{ Body: TestEmailBody }>("/settings/test-email", async (request, reply) => {
const { email } = request.body;
@@ -369,6 +483,7 @@ export async function settingsRoutes(app: FastifyInstance) {
}
try {
const provider = getNotificationProvider(url);
const result = await sendShoutrrrNotification(
url,
"MedAssist-ng Test",
@@ -376,11 +491,17 @@ export async function settingsRoutes(app: FastifyInstance) {
);
if (result.success) {
request.log.info({ provider }, "[Settings] Test push notification sent");
return reply.send({ success: true, message: "Test notification sent successfully" });
} else {
request.log.warn({ provider, error: result.error ?? "unknown" }, "[Settings] Test push notification failed");
return reply.status(500).send({ error: result.error });
}
} catch (error) {
request.log.error(
{ provider: getNotificationProvider(url), error },
"[Settings] Unexpected error while sending test push notification"
);
const errorMessage = error instanceof Error ? error.message : "Unknown error";
return reply.status(500).send({ error: `Failed to send notification: ${errorMessage}` });
}
@@ -393,6 +514,28 @@ function sanitizeNotificationUrl(
urlStr: string
): { url: string; isNtfy: boolean; auth?: { user: string; pass: string } } | { error: string } {
try {
// Support Shoutrrr Discord format: discord://TOKEN@WEBHOOK_ID
if (urlStr.startsWith("discord://")) {
const parsedDiscord = new URL(urlStr);
const webhookId = parsedDiscord.hostname;
const webhookToken = parsedDiscord.username;
if (!webhookId || !webhookToken) {
return { error: "Invalid Discord URL format" };
}
if (!/^\d+$/.test(webhookId)) {
return { error: "Invalid Discord webhook ID" };
}
if (!/^[A-Za-z0-9._-]+$/.test(webhookToken)) {
return { error: "Invalid Discord webhook token" };
}
const discordWebhookUrl = `https://discord.com/api/webhooks/${webhookId}/${webhookToken}`;
return { url: discordWebhookUrl, isNtfy: false };
}
// Convert ntfy:// to https:// for parsing, track if it was ntfy
const isNtfy = urlStr.startsWith("ntfy://");
const normalizedUrl = isNtfy ? urlStr.replace("ntfy://", "https://") : urlStr;
@@ -404,38 +547,9 @@ function sanitizeNotificationUrl(
return { error: "Only HTTP/HTTPS protocols are allowed" };
}
// Block private/internal IP addresses
const hostname = parsed.hostname.toLowerCase();
// Block localhost
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") {
return { error: "Localhost URLs are not allowed" };
}
// Block private IP ranges (basic check)
const ipMatch = hostname.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if (ipMatch) {
const [, a, b] = ipMatch.map(Number);
// 10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x (link-local)
if (
a === 10 ||
a === 127 ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 169 && b === 254)
) {
return { error: "Private IP addresses are not allowed" };
}
}
// Block common internal hostnames
if (
hostname.endsWith(".local") ||
hostname.endsWith(".internal") ||
hostname.endsWith(".lan") ||
hostname === "metadata.google.internal"
) {
return { error: "Internal hostnames are not allowed" };
const hostValidationError = validateNotificationHostname(parsed.hostname);
if (hostValidationError) {
return { error: hostValidationError };
}
// Reconstruct URL from validated components - this breaks taint tracking
@@ -452,6 +566,39 @@ function sanitizeNotificationUrl(
}
}
function validateNotificationHostname(hostnameRaw: string): string | null {
const hostname = hostnameRaw.toLowerCase();
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") {
return "Localhost URLs are not allowed";
}
const ipMatch = hostname.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if (ipMatch) {
const [, a, b] = ipMatch.map(Number);
if (
a === 10 ||
a === 127 ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 169 && b === 254)
) {
return "Private IP addresses are not allowed";
}
}
if (
hostname.endsWith(".local") ||
hostname.endsWith(".internal") ||
hostname.endsWith(".lan") ||
hostname === "metadata.google.internal"
) {
return "Internal hostnames are not allowed";
}
return null;
}
// Send notification via Shoutrrr-compatible URL (supports ntfy, Discord, Telegram, etc.)
export async function sendShoutrrrNotification(
urlStr: string,
@@ -459,6 +606,149 @@ export async function sendShoutrrrNotification(
message: string
): Promise<{ success: boolean; error?: string }> {
try {
if (urlStr.startsWith("pushover://")) {
const pushoverAuthority = urlStr.slice("pushover://".length).split("/")[0] ?? "";
const atIndex = pushoverAuthority.lastIndexOf("@");
const credentialPart = atIndex >= 0 ? pushoverAuthority.slice(0, atIndex) : "";
const userKey = atIndex >= 0 ? pushoverAuthority.slice(atIndex + 1) : "";
const tokenSeparatorIndex = credentialPart.indexOf(":");
const apiToken = tokenSeparatorIndex >= 0 ? credentialPart.slice(tokenSeparatorIndex + 1) : "";
const parsedPushover = new URL(urlStr);
if (!apiToken || !userKey) {
return { success: false, error: "Invalid Pushover URL format" };
}
const pushoverBody = new URLSearchParams({
token: apiToken,
user: userKey,
title,
message,
});
const devices = parsedPushover.searchParams.get("devices");
if (devices) {
pushoverBody.set("device", devices);
}
const priority = parsedPushover.searchParams.get("priority");
if (priority && /^-?\d+$/.test(priority)) {
pushoverBody.set("priority", priority);
}
const response = await fetch("https://api.pushover.net/1/messages.json", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: pushoverBody.toString(),
redirect: "error",
});
if (response.ok) return { success: true };
const errorText = await response.text();
return { success: false, error: `HTTP ${response.status}: ${errorText}` };
}
if (urlStr.startsWith("telegram://")) {
const parsedTelegram = new URL(urlStr);
const token = parsedTelegram.username;
if (!token || parsedTelegram.hostname !== "telegram") {
return { success: false, error: "Invalid Telegram URL format" };
}
const chatsRaw = parsedTelegram.searchParams.get("chats") ?? parsedTelegram.searchParams.get("channels") ?? "";
const chats = chatsRaw
.split(",")
.map((chat) => chat.trim())
.filter(Boolean);
if (chats.length === 0) {
return { success: false, error: "Telegram URL requires chats parameter" };
}
const parseModeRaw = parsedTelegram.searchParams.get("parseMode")?.toLowerCase();
let parseMode: "HTML" | "Markdown" | "MarkdownV2" | undefined;
if (parseModeRaw === "html") {
parseMode = "HTML";
} else if (parseModeRaw === "markdown") {
parseMode = "Markdown";
} else if (parseModeRaw === "markdownv2") {
parseMode = "MarkdownV2";
}
const notificationRaw = parsedTelegram.searchParams.get("notification")?.toLowerCase();
const disableNotification = notificationRaw === "no" || notificationRaw === "false";
const previewRaw = parsedTelegram.searchParams.get("preview")?.toLowerCase();
const disablePreview = previewRaw === "no" || previewRaw === "false";
if (!/^\d+:[A-Za-z0-9_-]+$/.test(token)) {
return { success: false, error: "Invalid Telegram token format" };
}
const telegramSendMessageUrl = new URL("/bot/sendMessage", "https://api.telegram.org");
telegramSendMessageUrl.pathname = `/bot${token}/sendMessage`;
for (const chatId of chats) {
const payload: Record<string, string | boolean> = {
chat_id: chatId,
text: `${title}\n\n${message}`,
disable_notification: disableNotification,
disable_web_page_preview: disablePreview,
};
if (parseMode) {
payload.parse_mode = parseMode;
}
// codeql[js/request-forgery]: host is fixed to api.telegram.org and token is pattern-validated.
const response = await fetch(telegramSendMessageUrl.toString(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
redirect: "error",
});
if (!response.ok) {
const errorText = await response.text();
return { success: false, error: `HTTP ${response.status}: ${errorText}` };
}
}
return { success: true };
}
if (urlStr.startsWith("gotify://")) {
const parsedGotify = new URL(urlStr);
const hostValidationError = validateNotificationHostname(parsedGotify.hostname);
if (hostValidationError) {
return { success: false, error: hostValidationError };
}
const pathParts = parsedGotify.pathname
.split("/")
.map((part) => part.trim())
.filter(Boolean);
if (pathParts.length === 0) {
return { success: false, error: "Invalid Gotify URL format" };
}
const token = pathParts[pathParts.length - 1];
const basePath = pathParts.slice(0, -1).join("/");
const disableTlsRaw = parsedGotify.searchParams.get("disabletls")?.toLowerCase();
const protocol = disableTlsRaw === "yes" || disableTlsRaw === "true" || disableTlsRaw === "1" ? "http" : "https";
const gotifyWebhookUrl = `${protocol}://${parsedGotify.host}${basePath ? `/${basePath}` : ""}/message?token=${encodeURIComponent(token)}`;
const gotifyPriority = parsedGotify.searchParams.get("priority");
const gotifyMessage = gotifyPriority ? `${message}\n\n(priority=${gotifyPriority})` : message;
// Reuse validated https webhook path to keep a single outbound request sink.
return sendShoutrrrNotification(gotifyWebhookUrl, title, gotifyMessage);
}
// Validate and sanitize URL to prevent SSRF - this reconstructs the URL
// from validated components, breaking taint tracking
const validation = sanitizeNotificationUrl(urlStr);
@@ -467,7 +757,7 @@ export async function sendShoutrrrNotification(
}
// Use ONLY the reconstructed URL from validation - never the original urlStr
const { url: sanitizedUrl, isNtfy, auth } = validation;
const { url: sanitizedUrl, isNtfy: _isNtfy, auth } = validation;
let targetUrl: string;
const method = "POST";
@@ -486,14 +776,17 @@ export async function sendShoutrrrNotification(
// 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;
let isDiscordWebhook = false;
try {
const parsedUrl = new URL(sanitizedUrl);
const hostname = parsedUrl.hostname.toLowerCase();
const pathname = parsedUrl.pathname.toLowerCase();
isDiscordWebhook =
(hostname === "discord.com" || hostname === "discordapp.com") && pathname.startsWith("/api/webhooks");
isJsonWebhook =
// Discord webhooks
((hostname === "discord.com" || hostname === "discordapp.com") && pathname.startsWith("/api/webhooks")) ||
isDiscordWebhook ||
// Slack webhooks
hostname === "hooks.slack.com" ||
hostname.endsWith(".hooks.slack.com") ||
@@ -510,7 +803,10 @@ export async function sendShoutrrrNotification(
// This works for ntfy, Apprise, and most simple push services
if (!isJsonWebhook) {
targetUrl = sanitizedUrl;
headers = { Title: cleanTitle, Tags: "pill" };
// Use RFC 2047 Base64 encoding for Title header to safely pass non-ASCII
// characters (umlauts, accents, etc.) through HTTP headers
const encodedTitle = `=?UTF-8?B?${Buffer.from(cleanTitle, "utf-8").toString("base64")}?=`;
headers = { Title: encodedTitle, Tags: "pill" };
body = message;
// Add auth if present (extracted during sanitization)
@@ -520,9 +816,16 @@ export async function sendShoutrrrNotification(
} else if (sanitizedUrl.startsWith("http://") || sanitizedUrl.startsWith("https://")) {
targetUrl = sanitizedUrl;
headers = { "Content-Type": "application/json" };
body = JSON.stringify({ title, message, text: `${title}\n\n${message}` });
if (isDiscordWebhook) {
body = JSON.stringify({ content: `${title}\n\n${message}` });
} else {
body = JSON.stringify({ title, message, text: `${title}\n\n${message}` });
}
} else {
return { success: false, error: "Unsupported URL format. Use ntfy:// or https:// URL" };
return {
success: false,
error: "Unsupported URL format. Use ntfy://, discord://, pushover://, gotify://, telegram://, or https:// URL",
};
}
// SSRF protection: targetUrl is reconstructed from sanitizeNotificationUrl() which validates:
+54 -13
View File
@@ -1,5 +1,5 @@
import { randomBytes } from "node:crypto";
import { eq } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../db/client.js";
@@ -14,9 +14,6 @@ import {
personTakesMedication,
} from "../utils/scheduler-utils.js";
// Share token validity: 1 year in milliseconds
const SHARE_TOKEN_VALIDITY_MS = 365 * 24 * 60 * 60 * 1000;
// =============================================================================
// Validation Schemas
// =============================================================================
@@ -25,6 +22,11 @@ const createShareSchema = z.object({
scheduleDays: z.number().int().min(1).max(365).default(30),
});
function maskToken(token: string): string {
if (token.length <= 8) return token;
return `${token.slice(0, 4)}...${token.slice(-4)}`;
}
// Helper to get user ID from request
// Returns anonymous user ID when auth is disabled
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
@@ -54,6 +56,7 @@ export async function shareRoutes(app: FastifyInstance) {
// Find share token
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
if (!share) {
request.log.warn(`[Share] Invalid share token requested: ${maskToken(token)}`);
return reply.status(404).send({
error: "Share link not found",
code: "NOT_FOUND",
@@ -62,6 +65,9 @@ export async function shareRoutes(app: FastifyInstance) {
// Check if token has expired
if (share.expiresAt && share.expiresAt.getTime() < Date.now()) {
request.log.warn(
`[Share] Expired token requested: ${maskToken(token)} (owner=${share.userId}, takenBy=${share.takenBy})`
);
// Get the username of the owner to show in the expired message
const [owner] = await db.select({ username: users.username }).from(users).where(eq(users.id, share.userId));
return reply.status(410).send({
@@ -114,7 +120,9 @@ export async function shareRoutes(app: FastifyInstance) {
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,
@@ -123,6 +131,7 @@ export async function shareRoutes(app: FastifyInstance) {
doseUnit: med.doseUnit ?? "mg",
imageUrl: med.imageUrl,
totalPills,
packageType: med.packageType ?? "blister",
packCount: med.packCount,
blistersPerPack: med.blistersPerPack,
looseTablets: med.looseTablets,
@@ -132,6 +141,8 @@ export async function shareRoutes(app: FastifyInstance) {
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,
};
});
@@ -142,7 +153,15 @@ 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,
upcomingTodayOnly: settings?.upcomingTodayOnly ?? false,
shareScheduleTodayOnly: settings?.shareScheduleTodayOnly ?? false,
};
});
@@ -184,25 +203,47 @@ export async function shareRoutes(app: FastifyInstance) {
});
}
// Generate unique token (8 bytes = 16 hex chars)
// Keep exactly one active share link per person/user.
// If a link already exists, return the same token and only update settings.
const [existingShare] = await db
.select()
.from(shareTokens)
.where(and(eq(shareTokens.userId, userId), eq(shareTokens.takenBy, takenBy)));
if (existingShare) {
await db.update(shareTokens).set({ scheduleDays, expiresAt: null }).where(eq(shareTokens.id, existingShare.id));
request.log.info(
`[Share] Reused existing share token (owner=${userId}, takenBy=${takenBy}, scheduleDays=${scheduleDays})`
);
return {
reused: true,
token: existingShare.token,
shareUrl: `/share/${existingShare.token}`,
expiresAt: null,
};
}
const token = randomBytes(8).toString("hex");
// Set expiration date (1 year from now)
const expiresAt = new Date(Date.now() + SHARE_TOKEN_VALIDITY_MS);
// Create share token
await db.insert(shareTokens).values({
userId: userId,
userId,
token,
takenBy,
scheduleDays,
expiresAt,
expiresAt: null,
});
request.log.info(
`[Share] Created new share token (owner=${userId}, takenBy=${takenBy}, scheduleDays=${scheduleDays})`
);
return {
reused: false,
token,
shareUrl: `/share/${token}`,
expiresAt: expiresAt.toISOString(),
expiresAt: null,
};
}
);
+197 -57
View File
@@ -3,9 +3,18 @@ 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 {
cleanOldIntakeReminders,
@@ -13,7 +22,6 @@ import {
getTimezone,
getTodaysIntakes,
getUpcomingIntakes,
type Intake,
type IntakeReminderState,
parseIntakeReminderState,
parseIntakesJson,
@@ -25,7 +33,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,6 +50,114 @@ function saveIntakeReminderState(state: IntakeReminderState): void {
writeFileSync(intakeReminderStateFile, JSON.stringify(state, null, 2));
}
function buildDoseIdForIntake(intake: UpcomingIntake & { medicationId: number; blisterIndex: number }): string {
const intakeDate = intake.intakeTime;
const dateOnlyMs = new Date(intakeDate.getFullYear(), intakeDate.getMonth(), intakeDate.getDate()).getTime();
if (intake.takenBy) {
return `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}-${intake.takenBy}`;
}
return `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}`;
}
async function autoMarkDueIntakesAsTaken(
settings: UserSettings & { userId: number },
rows: (typeof medications.$inferSelect)[],
locale: string,
tz: string,
logger: ServiceLogger
): Promise<number> {
if (settings.stockCalculationMode !== "automatic") {
return 0;
}
const now = new Date();
const nowInTimezone = new Date(now.toLocaleString("en-US", { timeZone: tz }));
const todayStart = new Date(now.toLocaleString("en-US", { timeZone: tz }));
todayStart.setHours(0, 0, 0, 0);
const todayEnd = new Date(now.toLocaleString("en-US", { timeZone: tz }));
todayEnd.setHours(23, 59, 59, 999);
const existingToday = await db
.select({ doseId: doseTracking.doseId })
.from(doseTracking)
.where(
and(
eq(doseTracking.userId, settings.userId),
gte(doseTracking.takenAt, todayStart),
lte(doseTracking.takenAt, todayEnd)
)
);
const existingDoseIds = new Set(existingToday.map((d) => d.doseId));
let inserted = 0;
for (const med of rows) {
if (med.isObsolete) {
continue;
}
const intakes = parseIntakesJson(
med.intakesJson,
{ usageJson: med.usageJson, everyJson: med.everyJson, startJson: med.startJson },
med.intakeRemindersEnabled ?? false
);
if (intakes.length === 0) {
continue;
}
const medicationTakenBy = parseTakenByJson(med.takenByJson);
const medDisplayName = med.name || med.genericName || "";
const todaysIntakes = getTodaysIntakes(
medDisplayName,
intakes,
medicationTakenBy,
med.pillWeightMg,
locale,
tz,
med.id,
med.doseUnit ?? "mg"
);
for (const intake of todaysIntakes) {
const intakeTimeInTimezone = new Date(intake.intakeTime.toLocaleString("en-US", { timeZone: tz }));
if (intakeTimeInTimezone.getTime() > nowInTimezone.getTime()) {
continue;
}
if (intake.medicationId === undefined || intake.blisterIndex === undefined) {
continue;
}
const doseId = buildDoseIdForIntake({
...intake,
medicationId: intake.medicationId,
blisterIndex: intake.blisterIndex,
});
if (existingDoseIds.has(doseId)) {
continue;
}
await db.insert(doseTracking).values({
userId: settings.userId,
doseId,
takenAt: intake.intakeTime,
markedBy: null,
takenSource: "automatic",
dismissed: false,
});
existingDoseIds.add(doseId);
inserted++;
}
}
if (inserted > 0) {
logger.info(`[IntakeReminder] User ${settings.userId}: Auto-marked ${inserted} due intake dose(s) as taken`);
}
return inserted;
}
async function sendIntakeReminderEmail(
email: string,
intakes: UpcomingIntake[],
@@ -148,7 +264,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>
@@ -177,7 +293,7 @@ ${intakes
.join("\n")}
---
${tr.intakeReminder.footer}`;
${getFooterPlain(language)}`;
const subject = isRepeat
? `[Reminder] ${t(tr.intakeReminder.subject, { medications: intakes.map((i) => i.medName).join(", ") })}`
@@ -209,21 +325,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);
@@ -232,50 +345,55 @@ 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}`
);
const rows = await db
.select()
.from(medications)
.where(eq(medications.userId, settings.userId))
.orderBy(medications.id);
const locale = getDateLocale(language);
const tz = getTimezone();
await autoMarkDueIntakesAsTaken(settings, rows, locale, tz, logger);
// Check if any intake reminder notifications are enabled (granular check)
const emailEnabled = settings.emailEnabled && settings.notificationEmail && settings.emailIntakeReminders;
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})`
);
// Get all medications with intake reminders enabled for this user
const rows = await db
.select()
.from(medications)
.where(eq(medications.userId, settings.userId))
.orderBy(medications.id);
const 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 })[] = [];
const locale = getDateLocale(language);
const tz = getTimezone();
// Get start and end of today in user's timezone (for filtering today's doses only)
const now = new Date();
const todayStart = new Date(now.toLocaleString("en-US", { timeZone: tz }));
@@ -284,7 +402,7 @@ 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()}`
);
@@ -298,30 +416,31 @@ async function checkAndSendIntakeRemindersForUser(
);
// Medication-level takenBy (for fallback/display purposes)
const medicationTakenBy = parseTakenByJson(med.takenByJson);
const medDisplayName = med.name || med.genericName || "";
logger.info(
`[IntakeReminder] User ${settings.userId}: Processing medication "${med.name}" with ${intakes.length} intakes`
logger.debug(
`[IntakeReminder] User ${settings.userId}: Processing medication "${medDisplayName}" with ${intakes.length} intakes`
);
// 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.info(`[IntakeReminder] User ${settings.userId}: Intake ${idx} has reminders disabled, skipping`);
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) => {
intakesWithReminders.forEach((intake, _blisterIndex) => {
const actualIndex = intakes.indexOf(intake); // Get the actual index in original array
logger.info(
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,
medDisplayName,
[intake],
REMINDER_MINUTES_BEFORE,
medicationTakenBy,
@@ -332,7 +451,7 @@ async function checkAndSendIntakeRemindersForUser(
med.id,
med.doseUnit ?? "mg"
);
logger.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Intake ${actualIndex} found ${upcomingIntakes.length} upcoming intakes (reminder window)`
);
@@ -348,7 +467,7 @@ async function checkAndSendIntakeRemindersForUser(
// If repeat reminders enabled, also check for missed intakes (past the intake time)
if (settings.repeatRemindersEnabled) {
const allTodaysIntakes = getTodaysIntakes(
med.name,
medDisplayName,
[intake],
medicationTakenBy,
med.pillWeightMg,
@@ -357,13 +476,13 @@ async function checkAndSendIntakeRemindersForUser(
med.id,
med.doseUnit ?? "mg"
);
logger.info(
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.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Intake ${actualIndex} found ${missedIntakes.length} missed intakes (past intake time)`
);
@@ -382,10 +501,10 @@ async function checkAndSendIntakeRemindersForUser(
});
}
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
}
@@ -408,15 +527,33 @@ 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. Check how recently it was missed.
const minutesSinceIntake = (nowMs - intakeTimeMs) / 60000;
const gracePeriodMinutes = (settings.reminderRepeatIntervalMinutes ?? 30) + REMINDER_MINUTES_BEFORE;
if (minutesSinceIntake <= gracePeriodMinutes) {
// Recently missed — scheduler likely recovered from sleep/restart.
// Send a catch-up reminder (counts as first nagging reminder).
remindersToSend.push({ ...intake, currentSendCount: 1, maxReminders, isAdvanceReminder: false });
logger.info(
`[IntakeReminder] User ${settings.userId}: Catch-up reminder for recently missed "${intake.medName}" at ${intake.intakeTimeStr} (${Math.round(minutesSinceIntake)} min ago)`
);
} else {
// Long ago — seed state without notification (user likely already noticed)
state.reminders[key] = {
firstSentAt: nowMs,
lastSentAt: nowMs,
sendCount: 0,
advanceSent: false,
};
logger.debug(
`[IntakeReminder] User ${settings.userId}: Seeding state for old past "${intake.medName}" at ${intake.intakeTimeStr} (no notification — ${Math.round(minutesSinceIntake)} min ago)`
);
}
} 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}`
);
}
@@ -431,13 +568,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})`
);
}
@@ -477,7 +614,7 @@ async function checkAndSendIntakeRemindersForUser(
const doseId = `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}-${intake.takenBy}`;
const isTaken = takenDoseIds.has(doseId);
if (isTaken) {
logger.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Skipping "${intake.medName}" - dose ${doseId} already taken`
);
}
@@ -487,7 +624,7 @@ async function checkAndSendIntakeRemindersForUser(
const doseId = `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}`;
const isTaken = takenDoseIds.has(doseId);
if (isTaken) {
logger.info(
logger.debug(
`[IntakeReminder] User ${settings.userId}: Skipping "${intake.medName}" - dose ${doseId} already taken`
);
}
@@ -496,7 +633,7 @@ async function checkAndSendIntakeRemindersForUser(
});
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;
}
}
@@ -550,7 +687,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 });
@@ -589,7 +729,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;
@@ -653,7 +795,8 @@ async function checkAndSendIntakeRemindersForUser(
saveIntakeReminderState(state);
// Update global reminder state for UI display
const channel = emailSuccess && shoutrrrSuccess ? "both" : emailSuccess ? "email" : "push";
const singleChannel = emailSuccess ? "email" : "push";
const channel = emailSuccess && shoutrrrSuccess ? "both" : singleChannel;
updateReminderSentTime("intake", channel);
// Also update user settings in database so frontend can display the info
@@ -667,10 +810,7 @@ async function checkAndSendIntakeRemindersForUser(
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
File diff suppressed because it is too large Load Diff
+129 -11
View File
@@ -28,7 +28,7 @@ vi.mock("../db/client.js", () => ({
vi.mock("../plugins/env.js", () => ({
env: {
AUTH_ENABLED: true,
LOCAL_AUTH_ENABLED: true,
FORM_LOGIN_ENABLED: true,
REGISTRATION_ENABLED: true,
OIDC_ENABLED: false,
NODE_ENV: "test",
@@ -144,7 +144,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
const data = response.json();
expect(data.authEnabled).toBe(true);
expect(data.registrationEnabled).toBe(true);
expect(data.localAuthEnabled).toBe(true);
expect(data.formLoginEnabled).toBe(true);
});
});
@@ -194,6 +194,29 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
expect(response.json().code).toBe("USERNAME_EXISTS");
});
it("should reject duplicate username regardless of case", async () => {
await app.inject({
method: "POST",
url: "/auth/register",
payload: {
username: "CaseUser",
password: "TestPassword123",
},
});
const response = await app.inject({
method: "POST",
url: "/auth/register",
payload: {
username: "caseuser",
password: "AnotherPassword123",
},
});
expect(response.statusCode).toBe(409);
expect(response.json().code).toBe("USERNAME_EXISTS");
});
it("should reject short password", async () => {
const response = await app.inject({
method: "POST",
@@ -222,6 +245,57 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
expect(response.json().code).toBe("VALIDATION_ERROR");
});
it("should register with trimmed username when input has whitespace", async () => {
const response = await app.inject({
method: "POST",
url: "/auth/register",
payload: {
username: " trimuser ",
password: "TestPassword123",
},
});
expect(response.statusCode).toBe(201);
expect(response.json().user.username).toBe("trimuser");
});
it("should reject whitespace-only username on registration", async () => {
const response = await app.inject({
method: "POST",
url: "/auth/register",
payload: {
username: " ",
password: "TestPassword123",
},
});
expect(response.statusCode).toBe(400);
expect(response.json().code).toBe("VALIDATION_ERROR");
});
it("should reject duplicate username even with surrounding whitespace", async () => {
await app.inject({
method: "POST",
url: "/auth/register",
payload: {
username: "spacedupe",
password: "TestPassword123",
},
});
const response = await app.inject({
method: "POST",
url: "/auth/register",
payload: {
username: " spacedupe ",
password: "AnotherPassword123",
},
});
expect(response.statusCode).toBe(409);
expect(response.json().code).toBe("USERNAME_EXISTS");
});
it("should reject invalid username characters", async () => {
const response = await app.inject({
method: "POST",
@@ -271,8 +345,23 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
// Should set cookies
const cookies = response.cookies;
expect(cookies.find((c: any) => c.name === "access_token")).toBeDefined();
expect(cookies.find((c: any) => c.name === "refresh_token")).toBeDefined();
expect(cookies.find((c: { name: string }) => c.name === "access_token")).toBeDefined();
expect(cookies.find((c: { name: string }) => c.name === "refresh_token")).toBeDefined();
});
it("should login case-insensitively with different username casing", async () => {
const response = await app.inject({
method: "POST",
url: "/auth/login",
payload: {
username: "LOGINUSER",
password: "TestPassword123",
},
});
expect(response.statusCode).toBe(200);
expect(response.json().ok).toBe(true);
expect(response.json().user.username).toBe("loginuser");
});
it("should reject invalid password", async () => {
@@ -303,6 +392,35 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
expect(response.json().code).toBe("INVALID_CREDENTIALS");
});
it("should login successfully when username has leading/trailing whitespace", async () => {
const response = await app.inject({
method: "POST",
url: "/auth/login",
payload: {
username: " loginuser ",
password: "TestPassword123",
},
});
expect(response.statusCode).toBe(200);
expect(response.json().ok).toBe(true);
expect(response.json().user.username).toBe("loginuser");
});
it("should reject whitespace-only username on login", async () => {
const response = await app.inject({
method: "POST",
url: "/auth/login",
payload: {
username: " ",
password: "TestPassword123",
},
});
expect(response.statusCode).toBe(400);
expect(response.json().code).toBe("VALIDATION_ERROR");
});
it("should support rememberMe option", async () => {
const response = await app.inject({
method: "POST",
@@ -355,7 +473,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
},
});
const refreshToken = login.cookies.find((c: any) => c.name === "refresh_token");
const refreshToken = login.cookies.find((c: { name: string }) => c.name === "refresh_token");
const response = await app.inject({
method: "POST",
@@ -418,7 +536,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
},
});
const refreshToken = login.cookies.find((c: any) => c.name === "refresh_token");
const refreshToken = login.cookies.find((c: { name: string }) => c.name === "refresh_token");
const response = await app.inject({
method: "POST",
@@ -468,7 +586,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
},
});
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
const response = await app.inject({
method: "GET",
@@ -566,7 +684,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
},
});
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
const response = await app.inject({
method: "PUT",
@@ -615,7 +733,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
},
});
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
const response = await app.inject({
method: "PUT",
@@ -651,7 +769,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
},
});
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
const response = await app.inject({
method: "PUT",
@@ -704,7 +822,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
},
});
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
// Delete account
const response = await app.inject({
+438 -3
View File
@@ -7,15 +7,18 @@ import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator";
import { afterEach, beforeEach, describe, expect, it } 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);
});
});
});
+125
View File
@@ -0,0 +1,125 @@
import { afterEach, describe, expect, it, vi } from "vitest";
type ClientTestOptions = {
dirWritable?: boolean;
authEnabled?: boolean;
};
async function loadDbClientModule(options: ClientTestOptions = {}) {
const { dirWritable = true, authEnabled = false } = options;
vi.resetModules();
vi.restoreAllMocks();
process.env.AUTH_ENABLED = authEnabled ? "true" : "false";
process.env.DOTENV_PATH = "/tmp/medassist-nonexistent.env";
const existsSync = vi.fn().mockReturnValue(false);
const statSync = vi.fn().mockReturnValue({ mode: 0o40755, uid: 1000, gid: 1000 });
vi.doMock("node:fs", () => ({ existsSync, statSync }));
const dotenvConfig = vi.fn();
vi.doMock("dotenv", () => ({ default: { config: dotenvConfig } }));
const createClient = vi.fn().mockReturnValue({ execute: vi.fn() });
vi.doMock("@libsql/client", () => ({ createClient }));
const drizzle = vi.fn().mockReturnValue({ __db: true });
vi.doMock("drizzle-orm/libsql", () => ({ drizzle }));
const ensureDataDirectory = vi
.fn()
.mockReturnValue(dirWritable ? { success: true } : { success: false, error: "permission denied" });
const getDbPaths = vi.fn().mockReturnValue({
dataDir: "/tmp/medassist-data",
dbPath: "/tmp/medassist-data/medassist.db",
url: "file:/tmp/medassist-data/medassist.db",
});
const runDrizzleMigrations = vi.fn().mockResolvedValue({ success: true });
const runAlterMigrations = vi.fn().mockResolvedValue({ errors: [] });
const repairTrailingHyphenDoseIds = vi.fn().mockResolvedValue({ repaired: 0, errors: [] });
const repairOrphanedDoseIds = vi.fn().mockResolvedValue({ repaired: 0, errors: [] });
const ensureDefaultUser = vi.fn().mockResolvedValue(false);
vi.doMock("../db/db-utils.js", () => ({
buildDbUrl: vi.fn(),
getDataDir: vi.fn(),
ensureDataDirectory,
getDbPaths,
runDrizzleMigrations,
runAlterMigrations,
repairTrailingHyphenDoseIds,
repairOrphanedDoseIds,
ensureDefaultUser,
}));
const log = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
vi.doMock("../utils/logger.js", () => ({ log }));
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit:${code ?? 0}`);
}) as never);
const modulePromise = import("../db/client.js");
return {
modulePromise,
mocks: {
existsSync,
statSync,
dotenvConfig,
createClient,
drizzle,
ensureDataDirectory,
getDbPaths,
runDrizzleMigrations,
runAlterMigrations,
repairTrailingHyphenDoseIds,
repairOrphanedDoseIds,
ensureDefaultUser,
log,
exitSpy,
},
};
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("db/client bootstrap", () => {
it("initializes db and runs migrations when directory is writable", async () => {
const { modulePromise, mocks } = await loadDbClientModule({ dirWritable: true, authEnabled: false });
const mod = await modulePromise;
expect(mod.db).toBeTruthy();
expect(mod.migrationsReady).toBeInstanceOf(Promise);
await mod.migrationsReady;
expect(mocks.ensureDataDirectory).toHaveBeenCalledWith("/tmp/medassist-data");
expect(mocks.createClient).toHaveBeenCalledWith({ url: "file:/tmp/medassist-data/medassist.db" });
expect(mocks.runDrizzleMigrations).toHaveBeenCalledTimes(1);
expect(mocks.runAlterMigrations).toHaveBeenCalledTimes(1);
expect(mocks.repairTrailingHyphenDoseIds).toHaveBeenCalledTimes(1);
expect(mocks.repairOrphanedDoseIds).toHaveBeenCalledTimes(1);
expect(mocks.ensureDefaultUser).toHaveBeenCalledWith(expect.anything(), false);
});
it("passes auth-enabled flag to ensureDefaultUser", async () => {
const { modulePromise, mocks } = await loadDbClientModule({ dirWritable: true, authEnabled: true });
const mod = await modulePromise;
await mod.migrationsReady;
expect(mocks.ensureDefaultUser).toHaveBeenCalledWith(expect.anything(), true);
});
it("exits when data directory is not writable", async () => {
const { modulePromise } = await loadDbClientModule({ dirWritable: false });
await expect(modulePromise).rejects.toThrow("process.exit:1");
});
});
+1 -1
View File
@@ -271,7 +271,7 @@ describe("Dose Tracking API", () => {
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data.doses).toHaveLength(2);
expect(data.doses.map((d: any) => d.doseId).sort()).toEqual([doseId1, doseId2].sort());
expect(data.doses.map((d: { doseId: string }) => d.doseId).sort()).toEqual([doseId1, doseId2].sort());
// Each dose should have a takenAt timestamp
for (const dose of data.doses) {
expect(dose.takenAt).toBeTypeOf("number");
+831 -4
View File
@@ -55,6 +55,7 @@ const { medicationRoutes } = await import("../routes/medications.js");
const { settingsRoutes } = await import("../routes/settings.js");
const { healthRoutes } = await import("../routes/health.js");
const { refillRoutes } = await import("../routes/refills.js");
const { reportRoutes } = await import("../routes/report.js");
const { exportRoutes } = await import("../routes/export.js");
// =============================================================================
@@ -99,6 +100,14 @@ async function createSchema(client: Client) {
expiry_date text,
notes text,
intake_reminders_enabled integer NOT NULL DEFAULT 0,
medication_start_date text NOT NULL DEFAULT '',
is_obsolete integer NOT NULL DEFAULT 0,
obsolete_at integer,
prescription_enabled integer NOT NULL DEFAULT 0,
prescription_authorized_refills integer,
prescription_remaining_refills integer,
prescription_low_refill_threshold integer NOT NULL DEFAULT 1,
prescription_expiry_date text,
dismissed_until text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
@@ -110,10 +119,12 @@ async function createSchema(client: Client) {
notification_email text,
email_stock_reminders integer NOT NULL DEFAULT 1,
email_intake_reminders integer NOT NULL DEFAULT 1,
email_prescription_reminders integer NOT NULL DEFAULT 1,
shoutrrr_enabled integer NOT NULL DEFAULT 0,
shoutrrr_url text,
shoutrrr_stock_reminders integer NOT NULL DEFAULT 1,
shoutrrr_intake_reminders integer NOT NULL DEFAULT 1,
shoutrrr_prescription_reminders integer NOT NULL DEFAULT 1,
reminder_days_before integer NOT NULL DEFAULT 7,
repeat_daily_reminders integer NOT NULL DEFAULT 0,
skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0,
@@ -126,11 +137,21 @@ 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,
upcoming_today_only integer NOT NULL DEFAULT 0,
share_schedule_today_only integer NOT NULL DEFAULT 0,
swap_dashboard_main_sections integer NOT NULL DEFAULT 0,
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,
last_prescription_reminder_sent text,
last_prescription_reminder_channel text,
last_prescription_reminder_med_names text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
@@ -150,6 +171,7 @@ async function createSchema(client: Client) {
dose_id text NOT NULL,
taken_at integer NOT NULL DEFAULT (strftime('%s','now')),
marked_by text,
taken_source text NOT NULL DEFAULT 'manual',
dismissed integer NOT NULL DEFAULT 0,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
@@ -159,6 +181,7 @@ async function createSchema(client: Client) {
user_id integer NOT NULL,
packs_added integer NOT NULL DEFAULT 0,
loose_pills_added integer NOT NULL DEFAULT 0,
used_prescription integer NOT NULL DEFAULT 0,
refill_date integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (medication_id) REFERENCES medications(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
@@ -243,11 +266,80 @@ describe("E2E Tests with Real Routes", () => {
await app.register(settingsRoutes);
await app.register(healthRoutes);
await app.register(refillRoutes);
await app.register(reportRoutes);
await app.register(exportRoutes);
await app.ready();
});
// ---------------------------------------------------------------------------
// Report Routes
// ---------------------------------------------------------------------------
describe("Real /medications/report-data route", () => {
it("should return 400 for invalid payload", async () => {
const response = await app.inject({
method: "POST",
url: "/medications/report-data",
payload: { medicationIds: [] },
});
expect(response.statusCode).toBe(400);
});
it("should return 403 when requested medication is not owned by user", async () => {
const response = await app.inject({
method: "POST",
url: "/medications/report-data",
payload: { medicationIds: [999999] },
});
expect(response.statusCode).toBe(403);
expect(response.json().error).toBe("Access denied to medication");
});
it("should aggregate taken/dismissed doses and refill history", async () => {
const medId = await createMedication(testClient, userId, "Report Med", ["Daniel"]);
// One taken dose and one dismissed dose for the same medication
await testClient.execute({
sql: `INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed)
VALUES (?, ?, ?, 0)`,
args: [userId, `${medId}-0-1735344000000`, 1735344000],
});
await testClient.execute({
sql: `INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed)
VALUES (?, ?, ?, 1)`,
args: [userId, `${medId}-0-1735430400000-Daniel`, 1735430400],
});
await testClient.execute({
sql: `INSERT INTO refill_history (medication_id, user_id, packs_added, loose_pills_added, used_prescription, refill_date)
VALUES (?, ?, ?, ?, ?, ?)`,
args: [medId, userId, 2, 5, 1, 1735516800],
});
const response = await app.inject({
method: "POST",
url: "/medications/report-data",
payload: { medicationIds: [medId] },
});
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data[medId].dosesTaken).toBe(1);
expect(data[medId].dosesDismissed).toBe(1);
expect(data[medId].firstDoseAt).toBe(new Date(1735344000 * 1000).toISOString());
expect(data[medId].lastDoseAt).toBe(new Date(1735344000 * 1000).toISOString());
expect(data[medId].refills).toHaveLength(1);
expect(data[medId].refills[0]).toMatchObject({
packsAdded: 2,
loosePillsAdded: 5,
usedPrescription: true,
});
});
});
afterAll(async () => {
await app.close();
testClient.close();
@@ -726,6 +818,39 @@ describe("E2E Tests with Real Routes", () => {
const data = getResponse.json();
expect(data.repeatDailyReminders).toBe(false);
});
it("should reject invalid language in lightweight language endpoint", async () => {
const response = await app.inject({
method: "PUT",
url: "/settings/language",
payload: { language: "fr" },
});
expect(response.statusCode).toBe(400);
expect(response.json().error).toBe("Invalid language");
});
it("should create and update language via lightweight language endpoint", async () => {
let response = await app.inject({
method: "PUT",
url: "/settings/language",
payload: { language: "de" },
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ success: true });
response = await app.inject({
method: "PUT",
url: "/settings/language",
payload: { language: "en" },
});
expect(response.statusCode).toBe(200);
const getResponse = await app.inject({ method: "GET", url: "/settings" });
expect(getResponse.json().language).toBe("en");
});
});
// ---------------------------------------------------------------------------
@@ -743,7 +868,6 @@ describe("E2E Tests with Real Routes", () => {
const json = response.json();
expect(json.status).toBe("ok");
expect(typeof json.smtpConfigured).toBe("boolean");
expect(typeof json.shoutrrrConfigured).toBe("boolean");
});
});
@@ -1164,7 +1288,6 @@ describe("E2E Tests with Real Routes", () => {
const json = response.json();
expect(json.status).toBe("ok");
expect(typeof json.smtpConfigured).toBe("boolean");
expect(typeof json.shoutrrrConfigured).toBe("boolean");
});
});
@@ -1617,6 +1740,83 @@ describe("E2E Tests with Real Routes", () => {
expect(data.newStock.looseTablets).toBe(15); // 5 + 10
});
it("should decrement remaining refills and mark history when using prescription refill", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Prescription Refill Med",
packCount: 1,
blistersPerPack: 2,
pillsPerBlister: 10,
looseTablets: 0,
prescriptionEnabled: true,
prescriptionAuthorizedRefills: 3,
prescriptionRemainingRefills: 2,
prescriptionLowRefillThreshold: 1,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
expect(createResponse.statusCode).toBe(200);
const medId = createResponse.json().id;
const refillResponse = await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 1, loosePillsAdded: 0, usePrescription: true },
});
expect(refillResponse.statusCode).toBe(200);
const refillData = refillResponse.json();
expect(refillData.prescription.used).toBe(true);
expect(refillData.prescription.remainingRefills).toBe(1);
const medsResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(medsResponse.statusCode).toBe(200);
const med = medsResponse.json().find((m: Record<string, unknown>) => m.id === medId);
expect(med.prescriptionRemainingRefills).toBe(1);
const historyResponse = await app.inject({
method: "GET",
url: `/medications/${medId}/refills`,
});
expect(historyResponse.statusCode).toBe(200);
expect(historyResponse.json()[0].usedPrescription).toBe(true);
});
it("should reject prescription refill when no remaining prescription refills are available", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Prescription Empty Med",
packCount: 1,
blistersPerPack: 2,
pillsPerBlister: 10,
looseTablets: 0,
prescriptionEnabled: true,
prescriptionAuthorizedRefills: 2,
prescriptionRemainingRefills: 0,
prescriptionLowRefillThreshold: 1,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
expect(createResponse.statusCode).toBe(200);
const medId = createResponse.json().id;
const refillResponse = await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 1, loosePillsAdded: 0, usePrescription: true },
});
expect(refillResponse.statusCode).toBe(409);
expect(refillResponse.json().error).toContain("No remaining prescription refills");
});
it("should return 400 when no packs or pills added", async () => {
const createResponse = await app.inject({
method: "POST",
@@ -1714,8 +1914,10 @@ describe("E2E Tests with Real Routes", () => {
const refills = response.json();
expect(refills).toHaveLength(2);
// Check both refills exist (order may vary)
const hasPackRefill = refills.some((r: any) => r.packsAdded === 1 && r.loosePillsAdded === 0);
const hasLooseRefill = refills.some((r: any) => r.packsAdded === 0 && r.loosePillsAdded === 5);
const hasPackRefill = refills.some((r: Record<string, unknown>) => r.packsAdded === 1 && r.loosePillsAdded === 0);
const hasLooseRefill = refills.some(
(r: Record<string, unknown>) => r.packsAdded === 0 && r.loosePillsAdded === 5
);
expect(hasPackRefill).toBe(true);
expect(hasLooseRefill).toBe(true);
});
@@ -1730,6 +1932,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: Record<string, unknown>) => 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: Record<string, unknown>) => 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: Record<string, unknown>) => 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: Record<string, unknown>) => 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: Record<string, unknown>) => 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: Record<string, unknown>) => 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
// ---------------------------------------------------------------------------
@@ -1808,6 +2308,87 @@ describe("E2E Tests with Real Routes", () => {
expect(data.settings).toBeDefined();
expect(data.settings.emailEnabled).toBe(true);
});
it("should include sensitive settings when requested", async () => {
await app.inject({
method: "PUT",
url: "/settings",
payload: {
emailEnabled: false,
notificationEmail: "",
reminderDaysBefore: 7,
repeatDailyReminders: false,
lowStockDays: 30,
normalStockDays: 90,
highStockDays: 180,
shoutrrrEnabled: true,
shoutrrrUrl: "https://example.com/topic",
emailStockReminders: false,
emailIntakeReminders: false,
emailPrescriptionReminders: false,
shoutrrrStockReminders: true,
shoutrrrIntakeReminders: true,
shoutrrrPrescriptionReminders: true,
skipRemindersForTakenDoses: false,
repeatRemindersEnabled: false,
reminderRepeatIntervalMinutes: 30,
maxNaggingReminders: 5,
language: "en",
stockCalculationMode: "automatic",
shareStockStatus: true,
upcomingTodayOnly: false,
shareScheduleTodayOnly: false,
swapDashboardMainSections: false,
},
});
const response = await app.inject({
method: "GET",
url: "/export?includeSensitive=true",
});
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data.settings.shoutrrrEnabled).toBe(true);
expect(data.settings.shoutrrrUrl).toBe("https://example.com/topic");
});
it("should gracefully export malformed date-like DB values", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Date Edge Med",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id as number;
await testClient.execute({
sql: `INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed) VALUES (?, ?, ?, 0)`,
args: [userId, `${medId}-0-1735344000000`, "not-a-date"],
});
await testClient.execute({
sql: `INSERT INTO refill_history (medication_id, user_id, packs_added, loose_pills_added, used_prescription, refill_date)
VALUES (?, ?, ?, ?, ?, ?)`,
args: [medId, userId, 1, 0, 0, "still-not-a-date"],
});
await testClient.execute({
sql: `INSERT INTO share_tokens (user_id, token, taken_by, schedule_days, expires_at) VALUES (?, ?, ?, ?, ?)`,
args: [userId, "date-edge-token", "Daniel", 30, "broken-date"],
});
const response = await app.inject({ method: "GET", url: "/export" });
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data.doseHistory).toHaveLength(1);
expect(Number.isNaN(Date.parse(data.doseHistory[0].takenAt))).toBe(false);
expect(data.refillHistory).toHaveLength(1);
expect(Number.isNaN(Date.parse(data.refillHistory[0].refillDate))).toBe(false);
expect(data.shareLinks).toHaveLength(1);
expect(data.shareLinks[0].expiresAt).toBeNull();
});
});
describe("Real /import routes", () => {
@@ -1916,4 +2497,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");
});
});
});
+76
View File
@@ -0,0 +1,76 @@
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
const ORIGINAL_ENV = { ...process.env };
describe("plugins/env runtime validation", () => {
beforeEach(() => {
vi.resetModules();
vi.restoreAllMocks();
process.env = {
...ORIGINAL_ENV,
DOTENV_PATH: "/tmp/medassist-nonexistent.env",
};
});
afterAll(() => {
process.env = ORIGINAL_ENV;
});
it("loads with defaults when auth and oidc are disabled", async () => {
delete process.env.AUTH_ENABLED;
delete process.env.OIDC_ENABLED;
delete process.env.JWT_SECRET;
delete process.env.REFRESH_SECRET;
delete process.env.COOKIE_SECRET;
const mod = await import("../plugins/env.js");
expect(mod.env.AUTH_ENABLED).toBe(false);
expect(mod.env.OIDC_ENABLED).toBe(false);
expect(mod.env.PORT).toBe(3000);
});
it("exits when auth is enabled but secrets are missing", async () => {
process.env.AUTH_ENABLED = "true";
delete process.env.JWT_SECRET;
delete process.env.REFRESH_SECRET;
delete process.env.COOKIE_SECRET;
vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit:${code ?? 0}`);
}) as never);
await expect(import("../plugins/env.js")).rejects.toThrow("process.exit:1");
});
it("exits when oidc is enabled but required settings are missing", async () => {
process.env.AUTH_ENABLED = "false";
process.env.OIDC_ENABLED = "true";
delete process.env.OIDC_ISSUER_URL;
delete process.env.OIDC_CLIENT_ID;
delete process.env.OIDC_CLIENT_SECRET;
delete process.env.OIDC_REDIRECT_URI;
vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit:${code ?? 0}`);
}) as never);
await expect(import("../plugins/env.js")).rejects.toThrow("process.exit:1");
});
it("loads when auth and oidc settings are complete", async () => {
process.env.AUTH_ENABLED = "true";
process.env.JWT_SECRET = "jwt-secret-for-runtime-test";
process.env.REFRESH_SECRET = "refresh-secret-runtime-test";
process.env.COOKIE_SECRET = "cookie-secret-runtime-test";
process.env.OIDC_ENABLED = "true";
process.env.OIDC_ISSUER_URL = "https://auth.example.com";
process.env.OIDC_CLIENT_ID = "medassist";
process.env.OIDC_CLIENT_SECRET = "super-secret-client";
process.env.OIDC_REDIRECT_URI = "https://app.example.com/api/auth/oidc/callback";
const mod = await import("../plugins/env.js");
expect(mod.env.AUTH_ENABLED).toBe(true);
expect(mod.env.OIDC_ENABLED).toBe(true);
expect(mod.env.OIDC_CLIENT_ID).toBe("medassist");
});
});
+1 -1
View File
@@ -3,7 +3,7 @@ import { z } from "zod";
// Mock process.exit to prevent tests from exiting
const mockExit = vi.fn();
vi.spyOn(process, "exit").mockImplementation(mockExit as any);
vi.spyOn(process, "exit").mockImplementation(mockExit as unknown as (...args: unknown[]) => never);
// Re-create the schema from env.ts for testing
const EnvSchema = z.object({
+18 -9
View File
@@ -23,10 +23,12 @@ async function registerExportRoutes(ctx: TestContext) {
const userId = 1; // Test user ID
// Helper to parse blisters from DB
function parseBlisters(row: any): Array<{ usage: number; every: number; start: string; remind: boolean }> {
const usage = JSON.parse(row.usage_json || "[]") as number[];
const every = JSON.parse(row.every_json || "[]") as number[];
const start = JSON.parse(row.start_json || "[]") as string[];
function parseBlisters(
row: Record<string, unknown>
): Array<{ usage: number; every: number; start: string; remind: boolean }> {
const usage = JSON.parse((row.usage_json as string) || "[]") as number[];
const every = JSON.parse((row.every_json as string) || "[]") as number[];
const start = JSON.parse((row.start_json as string) || "[]") as string[];
const len = Math.min(usage.length, every.length, start.length);
return Array.from({ length: len }, (_, i) => ({
usage: usage[i],
@@ -99,7 +101,7 @@ async function registerExportRoutes(ctx: TestContext) {
args: [userId],
});
let settings;
let settings: Record<string, unknown> | undefined;
if (settingsResult.rows.length > 0) {
const s = settingsResult.rows[0];
settings = {
@@ -150,7 +152,8 @@ async function registerExportRoutes(ctx: TestContext) {
});
// POST /import
app.post<{ Body: any }>("/import", async (request, reply) => {
app.post("/import", async (request, reply) => {
// biome-ignore lint/suspicious/noExplicitAny: test helper with dynamic import data shape
const importData = request.body as any;
// Basic validation
@@ -167,9 +170,15 @@ async function registerExportRoutes(ctx: TestContext) {
// Import medications
const exportIdToNewId = new Map<string, number>();
for (const med of importData.medications || []) {
const usageJson = JSON.stringify((med.schedules || []).map((s: any) => s.usage));
const everyJson = JSON.stringify((med.schedules || []).map((s: any) => s.every));
const startJson = JSON.stringify((med.schedules || []).map((s: any) => s.start));
const usageJson = JSON.stringify(
((med.schedules as Array<Record<string, unknown>>) || []).map((s: Record<string, unknown>) => s.usage)
);
const everyJson = JSON.stringify(
((med.schedules as Array<Record<string, unknown>>) || []).map((s: Record<string, unknown>) => s.every)
);
const startJson = JSON.stringify(
((med.schedules as Array<Record<string, unknown>>) || []).map((s: Record<string, unknown>) => s.start)
);
const takenByJson = JSON.stringify(med.takenBy || []);
const result = await client.execute({
+375 -29
View File
@@ -94,6 +94,14 @@ async function createSchema(client: Client) {
expiry_date text,
notes text,
intake_reminders_enabled integer NOT NULL DEFAULT 0,
medication_start_date text NOT NULL DEFAULT '',
is_obsolete integer NOT NULL DEFAULT 0,
obsolete_at integer,
prescription_enabled integer NOT NULL DEFAULT 0,
prescription_authorized_refills integer,
prescription_remaining_refills integer,
prescription_low_refill_threshold integer NOT NULL DEFAULT 1,
prescription_expiry_date text,
dismissed_until text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
@@ -105,10 +113,12 @@ async function createSchema(client: Client) {
notification_email text,
email_stock_reminders integer NOT NULL DEFAULT 1,
email_intake_reminders integer NOT NULL DEFAULT 1,
email_prescription_reminders integer NOT NULL DEFAULT 1,
shoutrrr_enabled integer NOT NULL DEFAULT 0,
shoutrrr_url text,
shoutrrr_stock_reminders integer NOT NULL DEFAULT 1,
shoutrrr_intake_reminders integer NOT NULL DEFAULT 1,
shoutrrr_prescription_reminders integer NOT NULL DEFAULT 1,
reminder_days_before integer NOT NULL DEFAULT 7,
repeat_daily_reminders integer NOT NULL DEFAULT 0,
skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0,
@@ -121,11 +131,21 @@ 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,
upcoming_today_only integer NOT NULL DEFAULT 0,
share_schedule_today_only integer NOT NULL DEFAULT 0,
swap_dashboard_main_sections integer NOT NULL DEFAULT 0,
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,
last_prescription_reminder_sent text,
last_prescription_reminder_channel text,
last_prescription_reminder_med_names text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
@@ -145,6 +165,7 @@ async function createSchema(client: Client) {
dose_id text NOT NULL,
taken_at integer NOT NULL DEFAULT (strftime('%s','now')),
marked_by text,
taken_source text NOT NULL DEFAULT 'manual',
dismissed integer NOT NULL DEFAULT 0,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
@@ -365,6 +386,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
// ---------------------------------------------------------------------------
@@ -706,7 +917,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",
@@ -716,17 +936,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
},
});
@@ -735,13 +955,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",
@@ -751,17 +980,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,
},
});
@@ -773,7 +1002,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",
@@ -782,29 +1020,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",
@@ -814,8 +1065,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
],
},
});
@@ -825,8 +1076,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,
},
});
@@ -838,6 +1089,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",
@@ -846,7 +1106,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 }],
},
});
@@ -855,8 +1115,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,
},
});
@@ -942,6 +1202,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
});
});
// ---------------------------------------------------------------------------
@@ -991,8 +1337,8 @@ describe("Integration Tests", () => {
url: "/medications",
});
const meds = medsRes.json();
const med1 = meds.find((m: any) => m.id === med1Id);
const med2 = meds.find((m: any) => m.id === med2Id);
const med1 = meds.find((m: Record<string, unknown>) => m.id === med1Id);
const med2 = meds.find((m: Record<string, unknown>) => m.id === med2Id);
expect(med1.dismissedUntil).toBe("2025-01-15");
expect(med2.dismissedUntil).toBe("2025-01-15");
@@ -1034,7 +1380,7 @@ describe("Integration Tests", () => {
method: "GET",
url: "/medications",
});
const med = medsRes.json().find((m: any) => m.id === medId);
const med = medsRes.json().find((m: Record<string, unknown>) => m.id === medId);
expect(med.dismissedUntil).toBeNull();
});
@@ -1104,7 +1450,7 @@ describe("Integration Tests", () => {
method: "GET",
url: "/medications",
});
const med = medsRes.json().find((m: any) => m.id === medId);
const med = medsRes.json().find((m: Record<string, unknown>) => m.id === medId);
expect(med.dismissedUntil).toBeNull();
});
});
+151
View File
@@ -0,0 +1,151 @@
import cookie from "@fastify/cookie";
import Fastify from "fastify";
import { afterEach, describe, expect, it, vi } from "vitest";
type OidcMocks = {
discovery: ReturnType<typeof vi.fn>;
buildAuthorizationUrl: ReturnType<typeof vi.fn>;
};
async function buildOidcApp(envOverrides: Record<string, unknown>) {
vi.resetModules();
const env = {
OIDC_ENABLED: true,
OIDC_ISSUER_URL: "https://issuer.example.com",
OIDC_CLIENT_ID: "medassist-client",
OIDC_CLIENT_SECRET: "medassist-client-secret",
OIDC_REDIRECT_URI: "https://app.example.com/api/auth/oidc/callback",
OIDC_SCOPES: "openid profile email",
OIDC_AUTO_CREATE_USERS: true,
OIDC_USERNAME_CLAIM: "preferred_username",
OIDC_PROVIDER_NAME: "SSO",
NODE_ENV: "test",
CORS_ORIGINS: "http://localhost:5173",
ACCESS_TOKEN_TTL_MINUTES: 15,
REFRESH_TOKEN_TTL_DAYS: 7,
...envOverrides,
};
vi.doMock("../plugins/env.js", () => ({ env }));
vi.doMock("../db/client.js", () => ({
db: {
select: vi.fn(() => ({ from: vi.fn(() => ({ where: vi.fn().mockResolvedValue([]) })) })),
insert: vi.fn(() => ({
values: vi.fn(() => ({ returning: vi.fn().mockResolvedValue([{ id: 1, username: "sso-user" }]) })),
})),
update: vi.fn(() => ({ set: vi.fn(() => ({ where: vi.fn().mockResolvedValue(undefined) })) })),
},
}));
const discovery = vi.fn().mockResolvedValue({ issuer: "https://issuer.example.com" });
const buildAuthorizationUrl = vi.fn().mockImplementation((_cfg, params) => {
const state = typeof params?.state === "string" ? params.state : "state";
return new URL(`https://issuer.example.com/authorize?state=${state}`);
});
vi.doMock("openid-client", () => ({
discovery,
buildAuthorizationUrl,
authorizationCodeGrant: vi.fn(),
fetchUserInfo: vi.fn(),
}));
const { oidcRoutes } = await import("../routes/oidc.js");
const app = Fastify({ logger: false });
await app.register(cookie, { secret: "test-cookie-secret" });
app.decorate("config", {
accessSecret: "test-jwt-secret-12345",
refreshSecret: "test-refresh-secret-12345",
accessTtl: 15 * 60,
refreshTtl: 7 * 24 * 60 * 60,
cookieOptions: { httpOnly: true, sameSite: "lax", secure: false, path: "/" },
refreshCookieOptions: { httpOnly: true, sameSite: "lax", secure: false, path: "/auth" },
});
await app.register(oidcRoutes);
await app.ready();
return {
app,
mocks: { discovery, buildAuthorizationUrl } as OidcMocks,
};
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("OIDC routes", () => {
it("returns 400 on login and callback when oidc is disabled", async () => {
const { app } = await buildOidcApp({ OIDC_ENABLED: false });
try {
const login = await app.inject({ method: "GET", url: "/auth/oidc/login" });
const callback = await app.inject({ method: "GET", url: "/auth/oidc/callback" });
expect(login.statusCode).toBe(400);
expect(callback.statusCode).toBe(400);
} finally {
await app.close();
}
});
it("redirects to provider and sets PKCE cookies on /auth/oidc/login", async () => {
const { app, mocks } = await buildOidcApp({ OIDC_ENABLED: true });
try {
const res = await app.inject({ method: "GET", url: "/auth/oidc/login" });
expect(res.statusCode).toBe(302);
expect(res.headers.location).toContain("https://issuer.example.com/authorize");
expect(res.cookies.some((c) => c.name === "oidc_code_verifier")).toBe(true);
expect(res.cookies.some((c) => c.name === "oidc_state")).toBe(true);
expect(mocks.discovery).toHaveBeenCalledTimes(1);
expect(mocks.buildAuthorizationUrl).toHaveBeenCalledTimes(1);
} finally {
await app.close();
}
});
it("redirects with provider error when callback contains error params", async () => {
const { app } = await buildOidcApp({ OIDC_ENABLED: true });
try {
const res = await app.inject({
method: "GET",
url: "/auth/oidc/callback?error=access_denied&error_description=user_cancelled",
});
expect(res.statusCode).toBe(302);
expect(res.headers.location).toBe("http://localhost:5173/?error=oidc_access_denied");
} finally {
await app.close();
}
});
it("redirects when callback is missing required params", async () => {
const { app } = await buildOidcApp({ OIDC_ENABLED: true });
try {
const res = await app.inject({ method: "GET", url: "/auth/oidc/callback" });
expect(res.statusCode).toBe(302);
expect(res.headers.location).toBe("http://localhost:5173/?error=oidc_missing_params");
} finally {
await app.close();
}
});
it("redirects when callback state validation fails", async () => {
const { app } = await buildOidcApp({ OIDC_ENABLED: true });
try {
const res = await app.inject({
method: "GET",
url: "/auth/oidc/callback?code=abc123&state=state123",
});
expect(res.statusCode).toBe(302);
expect(res.headers.location).toBe("http://localhost:5173/?error=oidc_state_mismatch");
} finally {
await app.close();
}
});
});
+466 -26
View File
@@ -63,7 +63,7 @@ vi.mock("../services/reminder-scheduler.js", () => ({
// Mock sendShoutrrrNotification from settings
vi.mock("../routes/settings.js", async (importOriginal) => {
const original = (await importOriginal()) as any;
const original = (await importOriginal()) as Record<string, unknown>;
return {
...original,
sendShoutrrrNotification: mockSendShoutrrr,
@@ -86,6 +86,42 @@ async function createSchema(client: Client) {
is_active integer NOT NULL DEFAULT 1,
created_at integer NOT NULL DEFAULT (strftime('%s','now')),
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 '[]',
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,
medication_start_date text NOT NULL DEFAULT '',
is_obsolete integer NOT NULL DEFAULT 0,
obsolete_at integer,
prescription_enabled integer NOT NULL DEFAULT 0,
prescription_authorized_refills integer,
prescription_remaining_refills integer,
prescription_low_refill_threshold integer NOT NULL DEFAULT 1,
prescription_expiry_date text,
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,
@@ -94,10 +130,12 @@ async function createSchema(client: Client) {
notification_email text,
email_stock_reminders integer NOT NULL DEFAULT 1,
email_intake_reminders integer NOT NULL DEFAULT 1,
email_prescription_reminders integer NOT NULL DEFAULT 1,
shoutrrr_enabled integer NOT NULL DEFAULT 0,
shoutrrr_url text,
shoutrrr_stock_reminders integer NOT NULL DEFAULT 1,
shoutrrr_intake_reminders integer NOT NULL DEFAULT 1,
shoutrrr_prescription_reminders integer NOT NULL DEFAULT 1,
reminder_days_before integer NOT NULL DEFAULT 7,
repeat_daily_reminders integer NOT NULL DEFAULT 0,
skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0,
@@ -110,11 +148,21 @@ 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,
upcoming_today_only integer NOT NULL DEFAULT 0,
share_schedule_today_only integer NOT NULL DEFAULT 0,
swap_dashboard_main_sections integer NOT NULL DEFAULT 0,
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,
last_prescription_reminder_sent text,
last_prescription_reminder_channel text,
last_prescription_reminder_med_names text,
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
@@ -126,6 +174,7 @@ async function createSchema(client: Client) {
}
async function clearData(client: Client) {
await client.execute("DELETE FROM medications");
await client.execute("DELETE FROM user_settings");
await client.execute("DELETE FROM users");
await client.execute("DELETE FROM sqlite_sequence");
@@ -146,6 +195,18 @@ describe("Planner Routes", () => {
"INSERT INTO users (id, username, auth_provider) VALUES (999999999, '__anonymous__', 'anonymous')"
);
// Insert test medications so active-medication filters pass
await testClient.execute({
sql: `INSERT INTO medications (id, user_id, name, taken_by_json, usage_json, every_json, start_json)
VALUES (1, 999999999, 'Aspirin', '["Daniel"]', '[1]', '[1]', '["2025-01-01T08:00:00.000Z"]')`,
args: [],
});
await testClient.execute({
sql: `INSERT INTO medications (id, user_id, name, taken_by_json, usage_json, every_json, start_json)
VALUES (2, 999999999, 'Ibuprofen', '["Daniel"]', '[1]', '[1]', '["2025-01-01T08:00:00.000Z"]')`,
args: [],
});
app = Fastify({ logger: false });
await app.register(plannerRoutes);
await app.ready();
@@ -161,21 +222,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 +235,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 +269,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 +278,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 +311,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 +325,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 +371,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 +384,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 +415,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 +428,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 +464,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 +743,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 +781,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 +938,205 @@ 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");
});
});
describe("POST /reminder/send-prescription", () => {
it("should reject request with missing prescription data", async () => {
const response = await app.inject({
method: "POST",
url: "/reminder/send-prescription",
payload: {
email: "test@example.com",
prescriptionLow: [],
},
});
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error: "Missing prescription reminder data" });
});
it("should return error when no notification channels configured", async () => {
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: "/reminder/send-prescription",
payload: {
email: "test@example.com",
prescriptionLow: [{ name: "Aspirin", remainingRefills: 0, threshold: 1, expiryDate: "2026-01-01" }],
},
});
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error: "No notification channels configured" });
});
it("should send prescription email reminder when email is 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, language) VALUES (?, 1, 0, 'en')`,
args: [999999999],
});
mockSendMail.mockResolvedValueOnce({ messageId: "123" });
const response = await app.inject({
method: "POST",
url: "/reminder/send-prescription",
payload: {
email: "test@example.com",
prescriptionLow: [
{ name: "Aspirin", remainingRefills: 0, threshold: 1, expiryDate: "2026-01-01" },
{ name: "Ibuprofen", remainingRefills: 1, threshold: 2, expiryDate: null },
],
},
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ success: true, message: "Prescription reminder sent via email" });
expect(mockSendMail).toHaveBeenCalledTimes(1);
expect(mockUpdateReminderSentTime).toHaveBeenCalledWith("prescription", "email");
expect(mockUpdateUserReminderSentTime).toHaveBeenCalledWith(
999999999,
"prescription",
"email",
"Aspirin, Ibuprofen"
);
delete process.env.SMTP_HOST;
delete process.env.SMTP_USER;
delete process.env.SMTP_PASS;
});
it("should send prescription push reminder 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: "/reminder/send-prescription",
payload: {
email: "test@example.com",
prescriptionLow: [{ name: "Aspirin", remainingRefills: 1, threshold: 2, expiryDate: "2026-01-01" }],
},
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ success: true, message: "Prescription reminder sent via push" });
expect(mockSendShoutrrr).toHaveBeenCalledTimes(1);
const [_url, title, message] = mockSendShoutrrr.mock.calls[0];
expect(title).toContain("Renew Now");
expect(message).toContain("Aspirin");
expect(mockUpdateReminderSentTime).toHaveBeenCalledWith("prescription", "push");
expect(mockUpdateUserReminderSentTime).toHaveBeenCalledWith(999999999, "prescription", "push", "Aspirin");
});
});
});
+422
View File
@@ -0,0 +1,422 @@
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { migrate } from "drizzle-orm/libsql/migrator";
import Fastify, { type FastifyInstance } from "fastify";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { runAlterMigrations } from "../db/db-utils.js";
const { testClient, testDb, mockedEnv, nodemailerSendMail, fetchMock } = vi.hoisted(() => {
const { createClient } = require("@libsql/client");
const { drizzle } = require("drizzle-orm/libsql");
const client = createClient({ url: ":memory:" });
const db = drizzle(client);
const env = {
AUTH_ENABLED: false,
OIDC_ENABLED: false,
OIDC_PROVIDER_NAME: "SSO",
NODE_ENV: "test",
};
return {
testClient: client,
testDb: db,
mockedEnv: env,
nodemailerSendMail: vi.fn(),
fetchMock: vi.fn(),
};
});
vi.mock("../db/client.js", () => ({
db: testDb,
migrationsReady: Promise.resolve(),
}));
vi.mock("../plugins/env.js", () => ({ env: mockedEnv }));
vi.mock("../plugins/auth.js", () => ({
requireAuth: async () => {},
getAnonymousUserId: async () => 1,
}));
vi.mock("nodemailer", () => ({
default: {
createTransport: () => ({
sendMail: nodemailerSendMail,
}),
},
}));
const { settingsRoutes, sendShoutrrrNotification } = await import("../routes/settings.js");
const { exportRoutes } = await import("../routes/export.js");
const { reportRoutes } = await import("../routes/report.js");
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const migrationsFolder = resolve(__dirname, "../../drizzle");
async function clearTables() {
await testClient.execute("DELETE FROM refill_history");
await testClient.execute("DELETE FROM dose_tracking");
await testClient.execute("DELETE FROM share_tokens");
await testClient.execute("DELETE FROM user_settings");
await testClient.execute("DELETE FROM medications");
await testClient.execute("DELETE FROM users");
}
async function seedAnonymousUser() {
await testClient.execute({
sql: "INSERT INTO users (id, username, auth_provider, is_active) VALUES (?, ?, ?, 1)",
args: [1, "anon", "anonymous"],
});
}
async function seedMedication(name = "Aspirin") {
const result = await testClient.execute({
sql: `INSERT INTO medications (
user_id, name, generic_name, taken_by_json, package_type,
pack_count, blisters_per_pack, pills_per_blister, loose_tablets,
usage_json, every_json, start_json, intakes_json,
stock_adjustment, intake_reminders_enabled
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id`,
args: [
1,
name,
"Acetylsalicylic acid",
JSON.stringify(["Daniel"]),
"blister",
2,
2,
10,
3,
JSON.stringify([1]),
JSON.stringify([1]),
JSON.stringify(["2026-01-01T08:00:00.000Z"]),
JSON.stringify([
{ usage: 1, every: 1, start: "2026-01-01T08:00:00.000Z", takenBy: "Daniel", intakeRemindersEnabled: true },
]),
0,
1,
],
});
return result.rows[0].id as number;
}
describe("Real route coverage: settings/export/report", () => {
let app: FastifyInstance;
beforeAll(async () => {
await migrate(testDb, { migrationsFolder });
await runAlterMigrations(testClient);
app = Fastify({ logger: false });
await app.register(settingsRoutes);
await app.register(exportRoutes);
await app.register(reportRoutes);
await app.ready();
});
afterAll(async () => {
await app.close();
testClient.close();
});
beforeEach(async () => {
vi.clearAllMocks();
vi.stubGlobal("fetch", fetchMock);
await clearTables();
await seedAnonymousUser();
delete process.env.SMTP_HOST;
delete process.env.SMTP_USER;
delete process.env.SMTP_TOKEN;
delete process.env.SMTP_PASS;
delete process.env.SMTP_FROM;
delete process.env.SMTP_PORT;
delete process.env.SMTP_SECURE;
});
it("GET /settings creates defaults for anonymous user", async () => {
const response = await app.inject({ method: "GET", url: "/settings" });
expect(response.statusCode).toBe(200);
const body = response.json();
expect(body.language).toBe("en");
expect(body.shareStockStatus).toBe(true);
expect(body.upcomingTodayOnly).toBe(false);
expect(body.shareScheduleTodayOnly).toBe(false);
});
it("PUT /settings disables repeatDailyReminders when no stock reminder channel exists", async () => {
const response = await app.inject({
method: "PUT",
url: "/settings",
payload: {
emailEnabled: false,
notificationEmail: "",
reminderDaysBefore: 7,
repeatDailyReminders: true,
lowStockDays: 30,
normalStockDays: 90,
highStockDays: 180,
shoutrrrEnabled: false,
shoutrrrUrl: "",
emailStockReminders: true,
emailIntakeReminders: true,
emailPrescriptionReminders: true,
shoutrrrStockReminders: true,
shoutrrrIntakeReminders: true,
shoutrrrPrescriptionReminders: true,
skipRemindersForTakenDoses: false,
repeatRemindersEnabled: false,
reminderRepeatIntervalMinutes: 30,
maxNaggingReminders: 5,
language: "en",
stockCalculationMode: "automatic",
shareStockStatus: true,
upcomingTodayOnly: false,
shareScheduleTodayOnly: false,
swapDashboardMainSections: false,
},
});
expect(response.statusCode).toBe(200);
const stored = await testClient.execute({
sql: "SELECT repeat_daily_reminders FROM user_settings WHERE user_id = 1",
});
expect(stored.rows[0].repeat_daily_reminders).toBe(0);
});
it("PUT /settings/language validates supported language", async () => {
const response = await app.inject({
method: "PUT",
url: "/settings/language",
payload: { language: "fr" },
});
expect(response.statusCode).toBe(400);
expect(response.json().error).toBe("Invalid language");
});
it("POST /settings/test-email fails when SMTP is not configured", async () => {
const response = await app.inject({
method: "POST",
url: "/settings/test-email",
payload: { email: "person@example.com" },
});
expect(response.statusCode).toBe(400);
expect(response.json().error).toBe("SMTP not configured");
});
it("POST /settings/test-email sends email when SMTP is configured", async () => {
process.env.SMTP_HOST = "smtp.example.com";
process.env.SMTP_USER = "mailer@example.com";
process.env.SMTP_TOKEN = "secret";
nodemailerSendMail.mockResolvedValue(undefined);
const response = await app.inject({
method: "POST",
url: "/settings/test-email",
payload: { email: "person@example.com" },
});
expect(response.statusCode).toBe(200);
expect(nodemailerSendMail).toHaveBeenCalledTimes(1);
});
it("POST /settings/test-shoutrrr validates URL presence", async () => {
const response = await app.inject({
method: "POST",
url: "/settings/test-shoutrrr",
payload: { url: "" },
});
expect(response.statusCode).toBe(400);
});
it("sendShoutrrrNotification blocks localhost/private targets", async () => {
const result = await sendShoutrrrNotification("http://127.0.0.1/hook", "test", "message");
expect(result.success).toBe(false);
expect(result.error).toContain("not allowed");
});
it("sendShoutrrrNotification handles ntfy auth and safe URL reconstruction", async () => {
fetchMock.mockResolvedValue({ ok: true });
const result = await sendShoutrrrNotification("ntfy://user:pass@ntfy.sh/mytopic", "Title ä", "Message");
expect(result.success).toBe(true);
expect(fetchMock).toHaveBeenCalledWith(
"https://ntfy.sh/mytopic",
expect.objectContaining({
headers: expect.objectContaining({
Authorization: expect.stringMatching(/^Basic /),
}),
method: "POST",
redirect: "error",
})
);
});
it("sendShoutrrrNotification uses JSON payload for webhook URLs", async () => {
fetchMock.mockResolvedValue({ ok: true });
const result = await sendShoutrrrNotification("https://hooks.slack.com/services/a/b/c", "Title", "Body");
expect(result.success).toBe(true);
const call = fetchMock.mock.calls[0];
expect(call[1].headers["Content-Type"]).toBe("application/json");
expect(JSON.parse(call[1].body)).toMatchObject({ title: "Title", message: "Body" });
});
it("POST /medications/report-data returns 403 for meds not owned by user", async () => {
await seedMedication("Owned Med");
const response = await app.inject({
method: "POST",
url: "/medications/report-data",
payload: { medicationIds: [9999] },
});
expect(response.statusCode).toBe(403);
});
it("POST /medications/report-data aggregates doses and refills", async () => {
const medId = await seedMedication("Report Med");
await testClient.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed) VALUES (?, ?, ?, ?)",
args: [1, `${medId}-0-1700000000000-Daniel`, 1700000000, 0],
});
await testClient.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed) VALUES (?, ?, ?, ?)",
args: [1, `${medId}-0-1700000600000-Daniel`, 1700000600, 1],
});
await testClient.execute({
sql: "INSERT INTO refill_history (medication_id, user_id, packs_added, loose_pills_added, used_prescription, refill_date) VALUES (?, ?, ?, ?, ?, ?)",
args: [medId, 1, 1, 2, 1, 1700001200],
});
const response = await app.inject({
method: "POST",
url: "/medications/report-data",
payload: { medicationIds: [medId] },
});
expect(response.statusCode).toBe(200);
const body = response.json();
expect(body[medId].dosesTaken).toBe(1);
expect(body[medId].dosesDismissed).toBe(1);
expect(body[medId].refills).toHaveLength(1);
});
it("GET /export includes medications, settings, doseHistory and refillHistory", async () => {
const medId = await seedMedication("Export Med");
await testClient.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id, taken_at, marked_by) VALUES (?, ?, ?, ?)",
args: [1, `${medId}-0-1700000000000-Daniel`, 1700000000, "Daniel"],
});
await testClient.execute({
sql: "INSERT INTO refill_history (medication_id, user_id, packs_added, loose_pills_added, used_prescription, refill_date) VALUES (?, ?, ?, ?, ?, ?)",
args: [medId, 1, 1, 3, 0, 1700000000],
});
await testClient.execute({
sql: "INSERT INTO user_settings (user_id, email_enabled, notification_email, share_stock_status, language) VALUES (?, ?, ?, ?, ?)",
args: [1, 1, "x@example.com", 1, "de"],
});
await testClient.execute({
sql: "INSERT INTO share_tokens (user_id, token, taken_by, schedule_days) VALUES (?, ?, ?, ?)",
args: [1, "abc123", "Daniel", 30],
});
const response = await app.inject({
method: "GET",
url: "/export?includeSensitive=true&includeImages=false",
});
expect(response.statusCode).toBe(200);
const body = response.json();
expect(body.medications).toHaveLength(1);
expect(body.doseHistory).toHaveLength(1);
expect(body.refillHistory).toHaveLength(1);
expect(body.settings.language).toBe("de");
expect(body.shareLinks).toHaveLength(1);
});
it("POST /import validates payload and imports minimal valid structure", async () => {
const invalid = await app.inject({
method: "POST",
url: "/import",
payload: { foo: "bar" },
});
expect(invalid.statusCode).toBe(400);
const validImport = {
version: "1.1",
exportedAt: new Date().toISOString(),
includeSensitiveData: false,
medications: [
{
_exportId: "med-1",
name: "Imported Med",
genericName: null,
takenBy: ["Daniel"],
inventory: {
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
totalPills: null,
looseTablets: 0,
stockAdjustment: 0,
packageType: "blister",
},
pillWeightMg: null,
doseUnit: "mg",
schedules: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00.000Z", remind: false, takenBy: "Daniel" }],
medicationStartDate: "",
expiryDate: null,
notes: null,
intakeRemindersEnabled: false,
isObsolete: false,
obsoleteAt: null,
prescriptionEnabled: false,
prescriptionAuthorizedRefills: null,
prescriptionRemainingRefills: null,
prescriptionLowRefillThreshold: 1,
prescriptionExpiryDate: null,
dismissedUntil: null,
image: null,
lastStockCorrectionAt: null,
},
],
doseHistory: [],
refillHistory: [],
settings: {
emailEnabled: false,
notificationEmail: null,
emailStockReminders: true,
emailIntakeReminders: true,
emailPrescriptionReminders: true,
shoutrrrEnabled: false,
shoutrrrUrl: null,
shoutrrrStockReminders: true,
shoutrrrIntakeReminders: true,
shoutrrrPrescriptionReminders: true,
reminderDaysBefore: 7,
repeatDailyReminders: false,
skipRemindersForTakenDoses: false,
repeatRemindersEnabled: false,
reminderRepeatIntervalMinutes: 30,
maxNaggingReminders: 5,
lowStockDays: 30,
normalStockDays: 90,
highStockDays: 180,
expiryWarningDays: 30,
language: "en",
stockCalculationMode: "automatic",
shareStockStatus: true,
},
shareLinks: [],
};
const valid = await app.inject({
method: "POST",
url: "/import",
payload: validImport,
});
expect(valid.statusCode).toBe(200);
expect(valid.json().imported.medications).toBe(1);
const rows = await testClient.execute({
sql: "SELECT name FROM medications WHERE user_id = 1",
});
expect(rows.rows[0].name).toBe("Imported Med");
});
});
+16 -8
View File
@@ -4,7 +4,7 @@ import { resolve } from "node:path";
import cookie from "@fastify/cookie";
import cors from "@fastify/cors";
import sensible from "@fastify/sensible";
import Fastify from "fastify";
import Fastify, { type FastifyInstance } from "fastify";
import { afterEach, describe, expect, it } from "vitest";
// Import from utils to avoid index.ts import side effects (server start)
@@ -294,10 +294,18 @@ describe("Server Bootstrap", () => {
refreshCookieOptions,
});
expect((app as any).config.accessTtl).toBe(15);
expect((app as any).config.refreshTtl).toBe(7);
expect((app as any).config.cookieOptions.httpOnly).toBe(true);
expect((app as any).config.refreshCookieOptions.maxAge).toBe(7 * 24 * 60 * 60);
const appWithConfig = app as unknown as {
config: {
accessTtl: number;
refreshTtl: number;
cookieOptions: { httpOnly: boolean };
refreshCookieOptions: { maxAge: number };
};
};
expect(appWithConfig.config.accessTtl).toBe(15);
expect(appWithConfig.config.refreshTtl).toBe(7);
expect(appWithConfig.config.cookieOptions.httpOnly).toBe(true);
expect(appWithConfig.config.refreshCookieOptions.maxAge).toBe(7 * 24 * 60 * 60);
await app.close();
});
@@ -364,15 +372,15 @@ describe("Server Bootstrap", () => {
const app = Fastify({ logger: false });
// Mock route plugins
const healthRoutes = async (app: any) => {
const healthRoutes = async (app: FastifyInstance) => {
app.get("/health", async () => ({ status: "ok" }));
};
const authRoutes = async (app: any) => {
const authRoutes = async (app: FastifyInstance) => {
app.post("/auth/login", async () => ({ token: "mock" }));
};
const medicationRoutes = async (app: any) => {
const medicationRoutes = async (app: FastifyInstance) => {
app.get("/medications", async () => []);
};
+50
View File
@@ -388,6 +388,56 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
// Both should be found as they're within the window
expect(result.length).toBeGreaterThanOrEqual(1);
});
it("should catch up missed advance reminder when notify window passed but intake still future", () => {
// Intake at 15:57, reminder 15 min before = 15:42
// Scheduler was down at 15:42, now running at 15:50 (intake still in future)
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T15:57:00" })];
// "now" = 15:50 local time on the same day — past the 15:42 notify window, but before 15:57 intake
const now = new Date(2025, 0, 1, 15, 50, 0).getTime();
const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
// Should still return the intake as a catch-up advance reminder
expect(result).toHaveLength(1);
expect(result[0].medName).toBe("TestMed");
expect(result[0].usage).toBe(1);
});
it("should catch up missed advance reminder even 1 minute before intake", () => {
// Intake at 08:00, reminder at 07:45. Scheduler catches up at 07:59.
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00" })];
const now = new Date(2025, 0, 1, 7, 59, 30).getTime();
const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
expect(result).toHaveLength(1);
});
it("should not catch up for intakes already in the past", () => {
// Intake at 08:00, reminder at 07:45. Now = 08:05 (intake already past).
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00" })];
const now = new Date(2025, 0, 1, 8, 5, 0).getTime();
const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
// Should NOT return — intake is past, handled by getTodaysIntakes instead
expect(result).toHaveLength(0);
});
it("should catch up for recurring intake on later day", () => {
// Intake started Jan 1 at 10:00, every 1 day. Now = Jan 3 at 09:50 (past notify, before intake)
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T10:00:00" })];
const now = new Date(2025, 0, 3, 9, 50, 0).getTime();
const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
// Should return today's occurrence via catch-up
expect(result).toHaveLength(1);
// The intake time should be Jan 3 at 10:00
expect(result[0].intakeTime.getHours()).toBe(10);
expect(result[0].intakeTime.getDate()).toBe(3);
});
});
describe("getTodaysIntakes", () => {
+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 () => {
+2 -2
View File
@@ -612,8 +612,8 @@ describe("Stock Calculation API", () => {
const data = response.json();
expect(data).toHaveLength(2);
const medA = data.find((d: any) => d.medicationName === "Med A");
const medB = data.find((d: any) => d.medicationName === "Med B");
const medA = data.find((d: Record<string, unknown>) => d.medicationName === "Med A");
const medB = data.find((d: Record<string, unknown>) => d.medicationName === "Med B");
expect(medA.plannerUsage).toBe(10); // 10 days × 1 pill
expect(medB.plannerUsage).toBe(10); // 5 doses × 2 pills
@@ -0,0 +1,350 @@
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { migrate } from "drizzle-orm/libsql/migrator";
import Fastify, { type FastifyInstance } from "fastify";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { runAlterMigrations } from "../db/db-utils.js";
const { testClient, testDb, mockedEnv } = vi.hoisted(() => {
const { createClient } = require("@libsql/client");
const { drizzle } = require("drizzle-orm/libsql");
const client = createClient({ url: ":memory:" });
const db = drizzle(client);
return {
testClient: client,
testDb: db,
mockedEnv: {
AUTH_ENABLED: false,
OIDC_ENABLED: false,
OIDC_PROVIDER_NAME: "SSO",
NODE_ENV: "test",
},
};
});
vi.mock("../db/client.js", () => ({
db: testDb,
migrationsReady: Promise.resolve(),
}));
vi.mock("../plugins/env.js", () => ({ env: mockedEnv }));
vi.mock("../plugins/auth.js", () => ({
requireAuth: async () => {},
getAnonymousUserId: async () => 1,
}));
const { medicationRoutes } = await import("../routes/medications.js");
const { getMedicationsNeedingReminderForTests } = await import("../services/reminder-scheduler.js");
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const migrationsFolder = resolve(__dirname, "../../drizzle");
async function clearTables() {
await testClient.execute("DELETE FROM refill_history");
await testClient.execute("DELETE FROM dose_tracking");
await testClient.execute("DELETE FROM share_tokens");
await testClient.execute("DELETE FROM user_settings");
await testClient.execute("DELETE FROM medications");
await testClient.execute("DELETE FROM users");
}
async function seedAnonymousUser() {
await testClient.execute({
sql: "INSERT INTO users (id, username, auth_provider, is_active) VALUES (?, ?, ?, 1)",
args: [1, "anon", "anonymous"],
});
}
async function setStockMode(mode: "automatic" | "manual") {
await testClient.execute({
sql: `INSERT INTO user_settings (user_id, stock_calculation_mode, reminder_days_before, low_stock_days, language)
VALUES (?, ?, 7, 365, 'en')`,
args: [1, mode],
});
}
async function createMedication(options: {
name: string;
packCount?: number;
blistersPerPack?: number;
pillsPerBlister?: number;
looseTablets?: number;
stockAdjustment?: number;
lastStockCorrectionAt?: number | null;
isObsolete?: boolean;
takenBy?: string[];
intakes: Array<{ usage: number; every: number; start: string; takenBy?: string | null }>;
}) {
const {
name,
packCount = 1,
blistersPerPack = 1,
pillsPerBlister = 10,
looseTablets = 0,
stockAdjustment = 0,
lastStockCorrectionAt = null,
isObsolete = false,
takenBy = [],
intakes,
} = options;
const usageJson = JSON.stringify(intakes.map((i) => i.usage));
const everyJson = JSON.stringify(intakes.map((i) => i.every));
const startJson = JSON.stringify(intakes.map((i) => i.start));
const intakesJson = JSON.stringify(
intakes.map((i) => ({
usage: i.usage,
every: i.every,
start: i.start,
takenBy: i.takenBy ?? null,
intakeRemindersEnabled: false,
}))
);
const result = await testClient.execute({
sql: `INSERT INTO medications (
user_id, name, taken_by_json, package_type,
pack_count, blisters_per_pack, pills_per_blister, loose_tablets,
stock_adjustment, last_stock_correction_at,
usage_json, every_json, start_json, intakes_json,
is_obsolete, intake_reminders_enabled
) VALUES (?, ?, ?, 'blister', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
RETURNING id`,
args: [
1,
name,
JSON.stringify(takenBy),
packCount,
blistersPerPack,
pillsPerBlister,
looseTablets,
stockAdjustment,
lastStockCorrectionAt,
usageJson,
everyJson,
startJson,
intakesJson,
isObsolete ? 1 : 0,
],
});
return Number(result.rows[0].id);
}
async function markDoseTaken(options: {
medicationId: number;
blisterIdx: number;
doseDateOnlyMs: number;
takenAtMs: number;
personSuffix?: string;
}) {
const { medicationId, blisterIdx, doseDateOnlyMs, takenAtMs, personSuffix } = options;
const baseId = `${medicationId}-${blisterIdx}-${doseDateOnlyMs}`;
const doseId = personSuffix ? `${baseId}-${personSuffix}` : baseId;
await testClient.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed) VALUES (?, ?, ?, 0)",
args: [1, doseId, Math.floor(takenAtMs / 1000)],
});
}
async function getUsageRow(app: FastifyInstance, startDate: string, endDate: string, medicationName: string) {
const response = await app.inject({
method: "POST",
url: "/medications/usage",
payload: { startDate, endDate },
});
expect(response.statusCode).toBe(200);
const rows = response.json();
const row = rows.find((r: { medicationName: string }) => r.medicationName === medicationName);
expect(row).toBeDefined();
return row;
}
function toDateOnlyMs(date: Date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
}
describe("Stock semantics parity (planner usage vs scheduler)", () => {
let app: FastifyInstance;
beforeAll(async () => {
await migrate(testDb, { migrationsFolder });
await runAlterMigrations(testClient);
app = Fastify({ logger: false });
await app.register(medicationRoutes);
await app.ready();
});
afterAll(async () => {
await app.close();
testClient.close();
});
beforeEach(async () => {
await clearTables();
await seedAnonymousUser();
});
it("keeps automatic mode current stock in sync", async () => {
await setStockMode("automatic");
const medName = "Auto Sync";
await createMedication({
name: medName,
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
intakes: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00" }],
});
const usageRow = await getUsageRow(app, "2026-01-01T00:00:00.000Z", "2026-01-31T23:59:59.999Z", medName);
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "automatic");
const schedulerRow = lowStock.find((r) => r.name === medName);
expect(schedulerRow).toBeDefined();
expect(usageRow.currentPills).toBe(usageRow.totalPills);
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
});
it("keeps manual mode current stock in sync and does not auto-consume", async () => {
await setStockMode("manual");
const medName = "Manual Sync";
await createMedication({
name: medName,
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
intakes: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00" }],
});
const usageRow = await getUsageRow(app, "2026-01-01T00:00:00.000Z", "2026-01-31T23:59:59.999Z", medName);
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "manual");
const schedulerRow = lowStock.find((r) => r.name === medName);
expect(schedulerRow).toBeDefined();
expect(usageRow.currentPills).toBe(10);
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
});
it("respects lastStockCorrectionAt cutoff in manual mode by takenAt", async () => {
await setStockMode("manual");
const medName = "Manual Correction";
const correctionMs = new Date("2026-01-05T12:00:00.000Z").getTime();
const medicationId = await createMedication({
name: medName,
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
lastStockCorrectionAt: correctionMs,
intakes: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00" }],
});
const jan5DateOnly = toDateOnlyMs(new Date("2026-01-05T00:00:00.000Z"));
const jan6DateOnly = toDateOnlyMs(new Date("2026-01-06T00:00:00.000Z"));
await markDoseTaken({
medicationId,
blisterIdx: 0,
doseDateOnlyMs: jan5DateOnly,
takenAtMs: new Date("2026-01-05T10:00:00.000Z").getTime(),
});
await markDoseTaken({
medicationId,
blisterIdx: 0,
doseDateOnlyMs: jan6DateOnly,
takenAtMs: new Date("2026-01-06T10:00:00.000Z").getTime(),
});
const usageRow = await getUsageRow(app, "2026-01-01T00:00:00.000Z", "2026-01-31T23:59:59.999Z", medName);
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "manual");
const schedulerRow = lowStock.find((r) => r.name === medName);
expect(schedulerRow).toBeDefined();
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
});
it("counts early taken dose in automatic mode without drift", async () => {
await setStockMode("automatic");
const medName = "Early Taken";
const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1);
tomorrow.setHours(20, 0, 0, 0);
const medicationId = await createMedication({
name: medName,
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
intakes: [{ usage: 1, every: 1, start: tomorrow.toISOString().slice(0, 19) }],
});
const tomorrowDateOnly = toDateOnlyMs(tomorrow);
await markDoseTaken({
medicationId,
blisterIdx: 0,
doseDateOnlyMs: tomorrowDateOnly,
takenAtMs: now.getTime(),
});
const rangeStart = new Date(now);
rangeStart.setDate(now.getDate() - 1);
const rangeEnd = new Date(now);
rangeEnd.setDate(now.getDate() + 7);
const usageRow = await getUsageRow(app, rangeStart.toISOString(), rangeEnd.toISOString(), medName);
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "automatic");
const schedulerRow = lowStock.find((r) => r.name === medName);
expect(schedulerRow).toBeDefined();
expect(usageRow.currentPills).toBe(9);
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
});
it("handles mixed intake-level and fallback takenBy consistently", async () => {
await setStockMode("automatic");
const medName = "Mixed TakenBy";
await createMedication({
name: medName,
packCount: 2,
blistersPerPack: 1,
pillsPerBlister: 10,
takenBy: ["Alice", "Bob"],
intakes: [
{ usage: 1, every: 1, start: "2026-01-01T08:00:00", takenBy: "Alice" },
{ usage: 1, every: 1, start: "2026-01-01T20:00:00", takenBy: null },
],
});
const usageRow = await getUsageRow(app, "2026-01-01T00:00:00.000Z", "2026-01-31T23:59:59.999Z", medName);
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "automatic");
const schedulerRow = lowStock.find((r) => r.name === medName);
expect(schedulerRow).toBeDefined();
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
expect(usageRow.currentPills).toBeLessThan(20);
});
it("excludes obsolete medications from planner usage and scheduler", async () => {
await setStockMode("automatic");
await createMedication({
name: "Obsolete Med",
isObsolete: true,
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
intakes: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00" }],
});
const response = await app.inject({
method: "POST",
url: "/medications/usage",
payload: { startDate: "2026-01-01T00:00:00.000Z", endDate: "2026-01-31T23:59:59.999Z" },
});
expect(response.statusCode).toBe(200);
expect(response.json().some((r: { medicationName: string }) => r.medicationName === "Obsolete Med")).toBe(false);
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "automatic");
expect(lowStock.some((r) => r.name === "Obsolete Med")).toBe(false);
});
});
+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: ⚠️ 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: ⚠️ 2 Medikamente kritisch niedrig");
const takenBy = t(translations.intakeReminder.takenBy, { name: "Daniel" });
expect(takenBy).toBe("für Daniel");
+1
View File
@@ -22,6 +22,7 @@ declare module "fastify" {
interface FastifyRequest {
user?: AuthUser | null;
correlationId?: string;
}
}
+80
View File
@@ -0,0 +1,80 @@
import { existsSync, unlinkSync } from "node:fs";
import { writeFile } from "node:fs/promises";
import { extname, resolve } from "node:path";
import sharp from "sharp";
export const ALLOWED_IMAGE_MIME_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
export const MAX_IMAGE_UPLOAD_BYTES = 10 * 1024 * 1024;
export function getThumbFilename(imageFilename: string): string {
const ext = extname(imageFilename);
const base = ext ? imageFilename.slice(0, -ext.length) : imageFilename;
return `${base}-thumb.webp`;
}
export function removeImageFiles(imagesDir: string, imageFilename: string): void {
const fullPath = resolve(imagesDir, imageFilename);
if (existsSync(fullPath)) unlinkSync(fullPath);
const thumbFilename = getThumbFilename(imageFilename);
if (thumbFilename !== imageFilename) {
const thumbPath = resolve(imagesDir, thumbFilename);
if (existsSync(thumbPath)) unlinkSync(thumbPath);
}
}
export async function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer> {
const chunks: Buffer[] = [];
let totalSize = 0;
for await (const chunk of stream) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
totalSize += buffer.length;
if (totalSize > MAX_IMAGE_UPLOAD_BYTES) {
throw new Error("IMAGE_TOO_LARGE");
}
chunks.push(buffer);
}
return Buffer.concat(chunks);
}
export async function writeOptimizedImageSet(
imagesDir: string,
filePrefix: string,
uploadBuffer: Buffer,
options?: {
maxEdgePx?: number;
thumbSizePx?: number;
fullQuality?: number;
thumbQuality?: number;
}
): Promise<{ filename: string; thumbFilename: string }> {
const maxEdgePx = options?.maxEdgePx ?? 1600;
const thumbSizePx = options?.thumbSizePx ?? 96;
const fullQuality = options?.fullQuality ?? 82;
const thumbQuality = options?.thumbQuality ?? 76;
const filename = `${filePrefix}-${Date.now()}.webp`;
const thumbFilename = getThumbFilename(filename);
const filepath = resolve(imagesDir, filename);
const thumbFilepath = resolve(imagesDir, thumbFilename);
const optimizedBuffer = await sharp(uploadBuffer, { failOn: "error" })
.rotate()
.resize({ width: maxEdgePx, height: maxEdgePx, fit: "inside", withoutEnlargement: true })
.webp({ quality: fullQuality })
.toBuffer();
const thumbBuffer = await sharp(uploadBuffer, { failOn: "error" })
.rotate()
.resize({ width: thumbSizePx, height: thumbSizePx, fit: "cover", position: "attention" })
.webp({ quality: thumbQuality })
.toBuffer();
await writeFile(filepath, optimizedBuffer);
await writeFile(thumbFilepath, thumbBuffer);
return { filename, thumbFilename };
}
+50
View File
@@ -0,0 +1,50 @@
/**
* 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();
}
function ts(): string {
return new Date().toISOString();
}
export const log = {
debug(msg: string): void {
if (shouldLog("debug")) console.log(`[${ts()}] [DEBUG] ${msg}`);
},
info(msg: string): void {
if (shouldLog("info")) console.log(`[${ts()}] [INFO] ${msg}`);
},
warn(msg: string): void {
if (shouldLog("warn")) console.warn(`[${ts()}] [WARN] ${msg}`);
},
error(msg: string): void {
if (shouldLog("error")) console.error(`[${ts()}] [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;
};
+26 -7
View File
@@ -122,7 +122,11 @@ export function getNextScheduledTime(reminderHour: number, tz?: string): Date {
/** Calculate milliseconds until next check at the given reminder hour */
export function getMsUntilNextCheck(reminderHour: number, tz?: string): number {
const next = getNextScheduledTime(reminderHour, tz);
return next.getTime() - Date.now();
const msUntilNext = next.getTime() - Date.now();
if (msUntilNext <= 0) {
return msUntilNext + 24 * 60 * 60 * 1000;
}
return msUntilNext;
}
// =============================================================================
@@ -191,7 +195,7 @@ export function parseIntakesJson(
try {
const parsed = JSON.parse(intakesJson);
if (Array.isArray(parsed) && parsed.length > 0) {
return parsed.map((intake: any) => ({
return parsed.map((intake: Record<string, unknown>) => ({
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(),
@@ -312,7 +316,7 @@ export type UpcomingIntake = {
export function getTodaysIntakes(
medName: string,
intakes: Intake[],
medicationTakenBy: string[], // Medication-level takenBy as fallback
_medicationTakenBy: string[], // Medication-level takenBy as fallback
pillWeightMg: number | null,
locale: string,
tz?: string,
@@ -388,7 +392,7 @@ export function getUpcomingIntakes(
medName: string,
intakes: Intake[],
minutesBefore: number,
medicationTakenBy: string[], // Medication-level takenBy as fallback
_medicationTakenBy: string[], // Medication-level takenBy as fallback
pillWeightMg: number | null,
locale: string,
tz?: string,
@@ -432,6 +436,11 @@ export function getUpcomingIntakes(
const currentNotifyTime = currentOccurrence - minutesBefore * 60 * 1000;
if (currentNotifyTime >= currentMinuteStart && currentOccurrence > now) {
nextTime = currentOccurrence;
} else if (currentNotifyTime < currentMinuteStart && currentOccurrence > now) {
// CATCH-UP: The notify window was missed (e.g. due to system sleep/restart)
// but the intake time is still in the future — include it so the advance
// reminder can still be sent rather than falling into a dead zone.
nextTime = currentOccurrence;
} else {
nextTime = nextOccurrence;
}
@@ -440,8 +449,15 @@ export function getUpcomingIntakes(
// Calculate when we should notify for this intake
const notifyTime = nextTime - minutesBefore * 60 * 1000;
// Check if notifyTime falls within the current minute (precise matching)
if (notifyTime >= currentMinuteStart && notifyTime < currentMinuteEnd) {
// Match if:
// 1. notifyTime falls within the current minute (normal case), OR
// 2. notifyTime is in the past but intakeTime is still in the future (catch-up
// for missed advance reminder window — e.g. scheduler was down during the
// exact notification minute due to system sleep, restart, or heavy load)
const isInCurrentMinute = notifyTime >= currentMinuteStart && notifyTime < currentMinuteEnd;
const isMissedButStillUpcoming = notifyTime < currentMinuteStart && nextTime > now;
if (isInCurrentMinute || isMissedButStillUpcoming) {
const intakeDate = new Date(nextTime);
upcoming.push({
medName,
@@ -471,9 +487,10 @@ export function getUpcomingIntakes(
export type ReminderState = {
lastAutoEmailSent: string | null;
lastAutoEmailDate: string | null;
lastStockSchedulerCheckDate: string | null;
notifiedMedications: string[];
nextScheduledCheck: string | null;
lastNotificationType: "stock" | "intake" | null;
lastNotificationType: "stock" | "intake" | "prescription" | null;
lastNotificationChannel: "email" | "push" | "both" | null;
};
@@ -493,6 +510,7 @@ export function createDefaultReminderState(): ReminderState {
return {
lastAutoEmailSent: null,
lastAutoEmailDate: null,
lastStockSchedulerCheckDate: null,
notifiedMedications: [],
nextScheduledCheck: null,
lastNotificationType: null,
@@ -512,6 +530,7 @@ export function parseReminderState(json: string): ReminderState {
return {
lastAutoEmailSent: saved.lastAutoEmailSent ?? null,
lastAutoEmailDate: saved.lastAutoEmailDate ?? null,
lastStockSchedulerCheckDate: saved.lastStockSchedulerCheckDate ?? null,
notifiedMedications: saved.notifiedMedications ?? [],
nextScheduledCheck: saved.nextScheduledCheck ?? null,
lastNotificationType: saved.lastNotificationType ?? null,
+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 });
}
+20
View File
@@ -14,5 +14,25 @@ export default defineConfig({
},
// Timeout for longer integration tests
testTimeout: 10000,
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
include: ["src/**/*.ts"],
exclude: [
"src/test/**",
"src/**/*.d.ts",
"src/**/index.ts",
"src/services/**",
"src/utils/logger.ts",
],
thresholds: {
global: {
lines: 60,
functions: 65,
branches: 50,
statements: 60,
},
},
},
},
});
+12 -3
View File
@@ -2,14 +2,22 @@
"$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,
"rules": {
"recommended": true,
"complexity": {
"noForEach": "off"
"noForEach": "off",
"noImportantStyles": "off"
},
"suspicious": {
"noExplicitAny": "warn",
@@ -21,7 +29,8 @@
"style": {
"noNonNullAssertion": "off",
"useConst": "error",
"noParameterAssign": "off"
"noParameterAssign": "off",
"noNestedTernary": "warn"
},
"correctness": {
"noUnusedVariables": "warn",
+7
View File
@@ -9,6 +9,9 @@ services:
- ./data:/app/data
env_file:
- .env
environment:
- DATA_DIR=/app/data
- RATE_LIMIT_MAX=1000
ports:
- "3000:3000"
security_opt:
@@ -27,6 +30,10 @@ services:
volumes:
- ./frontend:/app
- frontend_node_modules:/app/node_modules
env_file:
- .env
environment:
- BACKEND_URL=http://backend-dev:3000
ports:
- "5173:5173"
security_opt:
+5
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,10 @@ services:
frontend:
image: ghcr.io/danielvolz/medassist-ng-frontend:latest
container_name: medassist-ng-frontend
env_file:
- .env
environment:
- BACKEND_URL=backend:3000
ports:
- "4174:8080"
networks:
+365
View File
@@ -0,0 +1,365 @@
# Agent Memory Notes
Purpose: persistent agent work memory to survive context loss.
## Usage Rules
- Update this file during and after meaningful work.
- Record decisions, touched files, constraints, and unresolved follow-ups.
- Keep entries concise and chronological.
## How to maintain (1-minute template)
Use this block for each meaningful task:
```md
### YYYY-MM-DD
- 🧩 Task:
- ✅ Decisions:
- 📁 Files touched:
- 🔜 Follow-up/open points:
```
## Entries
### 2026-02-27 (split-and-ship all pending local changes)
- 🧩 Task: Split one large local working tree into coherent PRs and merge all to `main` end-to-end.
- ✅ Decisions:
- Created and merged 4 PRs to keep scopes reviewable while ensuring all pending changes were shipped.
- PR mapping:
- #334 `feat/form-login-enabled` (Issue #309)
- #336 `chore/improve-logging` (Issue #335)
- #339 `fix/typescript-strictness-react19` (Issue #337)
- #341 `chore/dependabot-agent-governance` (Issue #340)
- For PR #341, required checks were initially skipped by path filtering; added minimal no-op backend/frontend comment touches so required checks executed and merge satisfied ruleset.
- Verified linked project items for issues `#309`, `#335`, `#337`, `#340` are `Done`.
- 📁 Files touched:
- All changed files were fully distributed across PRs and merged.
- Mandatory reporting updated: `doku/memory_notes.md`, `doku/report.md`.
- 🔜 Follow-up/open points:
- None pending from this split/merge task.
### 2026-02-27 (pre-PR gate validation for `chore/dependabot-agent-governance`)
- 🧩 Task: Validate minimal relevant local non-interactive checks for governance/config/docs changes.
- ✅ Decisions:
- Confirmed changed scope with `git status --short` and validated only listed files.
- Ran repo-defined lint gate (`npm run lint`) to satisfy local pre-PR lint requirement.
- Ran parser-level YAML/frontmatter checks for changed `.yml` and agent markdown files.
- Ran a targeted `markdownlint-cli2` check; it reported many style errors, but this linter is not part of this repository's configured gate.
- 📁 Files touched:
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Local pre-PR gate for this scope is satisfied by configured checks (lint + syntax validation); optional markdown style cleanup can be handled in a separate docs-formatting pass.
### 2026-02-27 (PR3 local gate rerun after MedDetailModal test fix)
- 🧩 Task: Re-run PR3 local gate on `fix/typescript-strictness-react19` after `MedDetailModal` assertion fix.
- ✅ Decisions:
- Re-ran `frontend check` via `CI=true npm --prefix /Users/danielvolz/git/medassist/frontend run check`.
- Re-ran the same focused Vitest subset from prior gate run (12 files including `MedDetailModal.test.tsx`).
- Treated React `act(...)` warnings and JSDOM `scrollTo()` notices as non-blocking because all tests passed.
- 📁 Files touched:
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Pre-PR local gate for the requested frontend scope is now satisfied.
### 2026-02-27 (pre-PR gate validation for `fix/typescript-strictness-react19`)
- 🧩 Task: Validate minimal relevant local non-interactive frontend lint/tests for React 19 + TS strictness scope.
- ✅ Decisions:
- Ran only frontend checks relevant to the changed scope: `check` (Biome + `tsc --noEmit`) and targeted Vitest on changed test files.
- Treated React `act(...)` warnings and JSDOM `scrollTo` notices as non-blocking because they did not fail tests.
- 📁 Files touched:
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Gate is blocked by one failing test assertion in `src/test/components/MedDetailModal.test.tsx` expecting `undefined` where implementation currently passes `false` as second arg to `onSubmitRefill`.
### 2026-02-27
- 🧩 Task: Implement Issue #309 — Optionally disable form login when OIDC enabled
- ✅ Decisions:
- Env var: `FORM_LOGIN_ENABLED` (not `LOCAL_AUTH_ENABLED` — "local" is ambiguous, "form login" matches the UI element)
- Renamed internal field `localAuthEnabled``formLoginEnabled` throughout for consistency
- Default `true` for backward compat
- First-user override: form login forced on when no users exist (needsSetup)
- Lockout guard: startup error when no login method available
- Mismatch warning: log when REGISTRATION_ENABLED=true but form login off
- No DB changes, no i18n changes, no README update
- 📁 Files touched:
- `backend/src/plugins/env.ts` — added FORM_LOGIN_ENABLED + validation
- `backend/src/plugins/auth.ts` — renamed field + wired to env var + first-user override
- `backend/src/routes/auth.ts` — renamed guard references + error code
- `frontend/src/components/Auth.tsx` — renamed interface + conditionals
- `frontend/src/test/components/Auth.test.tsx` — renamed in mocks
- `frontend/src/test/components/AppHeader.test.tsx` — renamed in mocks
- `backend/src/test/auth.test.ts` — renamed env mock + assertion
- `.env.example` — documented new var
- 🔜 Follow-up: E2E tests for OIDC-only mode (delegate to @testing-manager)
### 2026-02-27 (pre-PR gate validation for chore/improve-logging)
- 🧩 Task: Validate local lint/tests for branch `chore/improve-logging` on changed logging/nginx/backend-route files.
- ✅ Decisions:
- Ran minimal relevant non-interactive checks only: backend lint, frontend lint, and targeted backend route test file (`e2e-routes.test.ts`).
- No additional broad suites were executed to keep scope minimal.
- 📁 Files touched:
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Frontend lint still reports one warning in `frontend/src/components/MedicationAvatar.tsx` (`useExhaustiveDependencies`, extra dependency `imageUrl`).
- Pre-PR gate is not clean until this lint warning is resolved.
### 2026-02-26
- Added mandatory memory/report persistence rules to `.github/copilot-instructions.md` and `AGENTS.md`.
- Removed obsolete mandatory persistence rule for `doku/APP_BEHAVIOR.md` from `AGENTS.md`.
- Created `doku/memory_notes.md` and `doku/report.md` as the new required persistence/reporting files.
### 2026-02-26 — Logging Implementation Plan
- 🧩 Task: Create implementation plan to fix noisy logging (nginx 5s polling spam, missing timestamps, unfilterable levels).
- ✅ Decisions:
- Use Fastify per-route `logLevel` option (not `disableRequestLogging`) to suppress health/polling request logs.
- Suppress `GET /doses/taken` and `GET /health` at `info` level (visible at `debug`).
- Add separate nginx location blocks for polling paths with `access_log off` at `info` level.
- Add ISO timestamps to startup logger (`backend/src/utils/logger.ts`).
- Add `pino-pretty` as devDependency for human-readable dev logs.
- Use nginx `log_format timed` with `$time_iso8601`.
- 📁 Files touched: `plan/feature-structured-logging-1.md` (created).
- 🔜 Follow-up: Implement the plan (5 phases, 18 tasks).
### 2026-02-26 — Logging Plan Implementation (complete)
- 🧩 Task: Implement all 5 phases of the structured logging plan.
- ✅ Decisions:
- Phase 1: Added `logLevel: 'warn'` to `GET /health`, `logLevel: 'debug'` to `GET /doses/taken` and `GET /share/:token/doses` — suppresses Pino automatic request logs at `info` level.
- Phase 2: Updated startup logger (`backend/src/utils/logger.ts`) to prepend `[ISO timestamp] [LEVEL]` prefix. Added `pino-pretty` devDependency with transport config active only when `NODE_ENV !== 'production' && !== 'test'`.
- Phase 3+4: nginx.conf now has dedicated location blocks for polling endpoints using `${NGINX_POLLING_LOG}` variable. `nginx-entrypoint.sh` differentiates `debug` (all logs) / `info` (polling suppressed) / `warn+` (all suppressed). Added `log_format timed` with ISO timestamps.
- Phase 5: Updated `.env.example` and `README.md` with detailed LOG_LEVEL behavior descriptions.
- 📁 Files touched:
- `backend/src/routes/health.ts` — logLevel: 'warn'
- `backend/src/routes/doses.ts` — logLevel: 'debug' on GET /doses/taken and GET /share/:token/doses
- `backend/src/utils/logger.ts` — ISO timestamps on all startup log messages
- `backend/src/index.ts` — pino-pretty transport for dev mode
- `backend/package.json` — added pino-pretty devDependency
- `frontend/nginx.conf` — polling location blocks, log_format timed
- `frontend/nginx-entrypoint.sh` — 3-tier LOG_LEVEL logic (debug/info/warn+)
- `.env.example` — expanded LOG_LEVEL docs
- `README.md` — expanded LOG_LEVEL description
- 🔜 Follow-up: Docker build + manual verification (TEST-004 through TEST-008). Hand off to @testing-manager for any automated test coverage.
### 2026-02-26 (follow-up)
- Added a short "How to maintain" template section to this file and to `doku/report.md`.
- Updated report entry so this follow-up is documented for user review.
### 2026-02-26 (emoji template follow-up)
- Added emoji-based label conventions for faster scanning in this file template.
- Updated `doku/report.md` template to match the same emoji convention.
### 2026-02-26 (testing-manager instruction hardening)
- 🧩 Task: Strengthen `testing-manager` agent instructions for lint gates, real/reliable tests, and current test setup commands.
- ✅ Decisions:
- Added hard lint gate: all errors and simple/fixable warnings must be resolved before PR-ready handoff.
- Added explicit anti-fake-test rules and validity checklist to enforce real functional verification and regression safety.
- Updated backend/frontend Vitest commands to non-watch CI-safe `test:run` usage and aligned Playwright examples.
- 📁 Files touched:
- `.github/agents/testing-manager.agent.md`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Keep this instruction set mirrored if additional testing policy docs are introduced later.
### 2026-02-26 (pre-PR local quality gate clarification)
- 🧩 Task: Clarify that PRs must not be created before local lint/tests are green.
- ✅ Decisions:
- Added explicit rule: before PR creation, all lint errors and relevant tests must pass locally.
- Added explicit rule: no CI-first failures; broken behavior must reproduce and be fixed locally before handoff.
- 📁 Files touched:
- `.github/agents/testing-manager.agent.md`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Apply same wording to other governance docs only if requested.
### 2026-02-26 (release-manager local gate alignment)
- 🧩 Task: Apply the same pre-PR local lint/test gate policy to `release-manager` instructions.
- ✅ Decisions:
- Added explicit pre-PR local quality gate requirement to `release-manager` critical rules.
- Added explicit no CI-first-failure policy for release orchestration.
- Updated PR workflow steps to require local gate confirmation before push/PR creation.
- 📁 Files touched:
- `.github/agents/release-manager.agent.md`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Keep both manager agents (`testing-manager`, `release-manager`) aligned on this gate language.
### 2026-02-26 (React 19 upgrade best-practice clarification)
- 🧩 Task: Validate and refine the React 19 upgrade plan with official guidance.
- ✅ Decisions:
- Keep `@types/react` and `@types/react-dom`, but bump both to `^19.x` during the React upgrade.
- Do not force `useContext` to `use()` migration in the upgrade PR; only fix what is required for compatibility.
- Keep strict scope boundary: version upgrade only; adopt new React 19 features in separate follow-up PRs.
- 📁 Files touched:
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- When implementation starts, apply the same scope boundary in commit and PR structure.
### 2026-02-26 (React 19 implementation)
- 🧩 Task: Implement the scoped React 19 dependency upgrade.
- ✅ Decisions:
- Upgraded `react`/`react-dom` to `^19.2.0`.
- Kept `@types/react` and `@types/react-dom` and upgraded both to `^19.2.2`.
- Did not include optional API migrations (`useContext` to `use()`, Actions APIs, RSC changes).
- 📁 Files touched:
- `frontend/package.json`
- `frontend/package-lock.json`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Run local install/lint/check in a dedicated testing handoff to validate full dependency tree behavior.
### 2026-02-26 (testing handoff run for React 19 upgrade)
- 🧩 Task: Execute frontend lint/check/relevant tests and apply only mandatory compatibility fixes.
- ✅ Decisions:
- Fixed only strict compatibility/type issues in touched tests (`ics`, `schedule`, `MobileEditModal`) without feature migration.
- Did not expand scope into broad unrelated test refactors.
- 📁 Files touched:
- `frontend/src/test/utils/ics.test.ts`
- `frontend/src/test/utils/schedule.test.ts`
- `frontend/src/test/components/MobileEditModal.test.tsx`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- `frontend check` still blocked by unrelated `MedDetailModal.test.tsx` prop-shape mismatches (`usePrescriptionRefill`, `onUsePrescriptionRefillChange`, and `RefillEntry` field changes).
- Existing lint warning remains in `frontend/src/components/MedicationAvatar.tsx` (`useExhaustiveDependencies`).
### 2026-02-26 (blocker follow-up: lint fix + testing-manager handoff)
- 🧩 Task: Remove remaining lint warning and prepare formal handoff for out-of-scope MedDetailModal test drift.
- ✅ Decisions:
- Fixed `MedicationAvatar` warning by tracking previous `imageUrl` via ref in effect logic.
- Kept `MedDetailModal.test.tsx` changes out of this implementation due testing ownership boundary and prepared explicit handoff content instead.
- 📁 Files touched:
- `frontend/src/components/MedicationAvatar.tsx`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- `@testing-manager` should align `MedDetailModal` tests with current `MedDetailModalProps` (`usePrescriptionRefill`, `onUsePrescriptionRefillChange`) and `RefillEntry` shape (`refillDate`, `loosePillsAdded`).
### 2026-02-26 (automatic delegation preference applied)
- 🧩 Task: Apply user preference to delegate testing work automatically without additional confirmation prompts.
- ✅ Decisions:
- Hand off residual test/type drift work to `@testing-manager` immediately when detected.
- Do not pause for approval before delegation unless there is a blocking ambiguity.
- 📁 Files touched:
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Keep this delegation style for future testing ownership boundaries.
### 2026-02-26 (continued type-fix sweep to green frontend check)
- 🧩 Task: Continue and clear remaining `frontend check` blockers after delegated MedDetailModal fixes.
- ✅ Decisions:
- Applied minimal compatibility fixes in production files only where type/lint failed (`MobileEditModal`, `SharedSchedule`, `AppContext`, `dashboard-helpers`, `DashboardPage`, `stock.ts`).
- Applied fixture-only updates in tests for new required `Medication`/`StockThresholds` shapes and minor mock typing issues.
- Kept scope to type/lint compatibility; no feature behavior migration.
- 📁 Files touched:
- `frontend/src/components/MobileEditModal.tsx`
- `frontend/src/components/SharedSchedule.tsx`
- `frontend/src/context/AppContext.tsx`
- `frontend/src/pages/dashboard-helpers.ts`
- `frontend/src/pages/DashboardPage.tsx`
- `frontend/src/utils/stock.ts`
- `frontend/src/test/setup.ts`
- `frontend/src/test/components/Lightbox.test.tsx`
- `frontend/src/test/components/UserFilterModal.test.tsx`
- `frontend/src/test/context/AppContext.test.tsx`
- `frontend/src/test/hooks/useMedications.test.ts`
- `frontend/src/test/hooks/useRefill.test.ts`
- `frontend/src/test/hooks/useSettings.test.ts`
- `frontend/src/test/hooks/useShare.test.ts`
- `frontend/src/test/utils/formatters.test.ts`
- `frontend/src/test/utils/schedule.test.ts`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- `frontend check` is now green.
- Focused tests pass; remaining broader suite execution can be done as separate validation step if requested.
### 2026-02-26 (npm EINTEGRITY fix)
- 🧩 Task: Resolve npm tarball corruption/integrity install failure after React 19 lockfile update.
- ✅ Decisions:
- Verified official registry integrity values with `npm view` and corrected lockfile hashes.
- Did not change versions; only fixed integrity metadata for `@types/react@19.2.2` and `@types/react-dom@19.2.2`.
### 2026-02-26 (dependency update automation)
- 🧩 Task: Implement automatic dependency update flow with safe merge policy.
- ✅ Decisions:
- Extended existing `.github/dependabot.yml` instead of replacing it.
- Added grouped minor/patch updates for root npm and GitHub Actions, plus scoped labels (`frontend`, `backend`, `root`).
- Added `.github/workflows/dependabot-automerge.yml` to enable auto-merge only for Dependabot npm/GitHub Actions patch+minor updates.
- Kept major updates manual by design.
- Synced docs in `README.md` and updated React badge to 19.
- 📁 Files touched:
- `.github/dependabot.yml`
- `.github/workflows/dependabot-automerge.yml`
- `README.md`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- If branch protection requires specific checks, ensure required status checks are set so auto-merge waits correctly.
- 📁 Files touched:
- `frontend/package-lock.json`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- `npm ci` now succeeds cleanly.
### 2026-02-26 (npm deprecation warnings assessment)
- 🧩 Task: Assess reported npm deprecation warnings and identify real source/package owners.
- ✅ Decisions:
- Warnings are not from `frontend`; they originate in `backend` transitive dependencies.
- `@esbuild-kit/*` comes from `drizzle-kit@0.31.9` (currently latest).
- `node-domexception` comes via `@libsql/client -> node-fetch -> fetch-blob` (currently latest published chain).
- Treat as non-blocking upstream warnings for now (no local secure/functional regression).
- 📁 Files touched:
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- Re-check on future dependency releases; warnings can be removed once upstream chains migrate.
### 2026-02-26 (MedDetailModal test type drift fix)
- 🧩 Task: Unblock the targeted `MedDetailModal` test type drift after React 19 changes.
- ✅ Decisions:
- Kept scope minimal and test-only: updated `frontend/src/test/components/MedDetailModal.test.tsx` only.
- Added missing required props in `defaultProps`: `usePrescriptionRefill`, `onUsePrescriptionRefillChange`.
- Updated `RefillEntry` fixtures to current shape by replacing legacy fields with `refillDate` and `loosePillsAdded`.
- Did not run the targeted test command because the requested precondition (`npm run check` passing) is not met.
- 📁 Files touched:
- `frontend/src/test/components/MedDetailModal.test.tsx`
- `doku/memory_notes.md`
- `doku/report.md`
- 🔜 Follow-up/open points:
- `frontend check` remains blocked by unrelated TypeScript errors in other files (outside MedDetailModal test scope).

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