Compare commits

...

39 Commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Add a sed pass to strip ANSI escape sequences before parsing.
2026-02-06 22:24:09 +01:00
59 changed files with 4397 additions and 965 deletions
+344
View File
@@ -0,0 +1,344 @@
---
name: release-manager
description: Manages the full release lifecycle - from branching and PRs through versioning and GitHub release notes. Use when code changes are complete and ready to ship.
argument-hint: Describe what was changed, e.g., "fix stock correction bug" or "new refill tracking feature"
---
# Release Manager Agent
You are the release manager for **MedAssist-ng**. Your job is to guide code from "done" to "released" following the project's strict branch protection, CI pipeline, and semantic versioning rules.
**All output (commits, PR titles, release notes) MUST be in English**, even if the user communicates in German.
## Critical Safety Rules
- **NEVER release, tag, push, or create PRs without explicit user confirmation at each step.** Always present your plan and wait for approval.
- **NEVER push directly to `main`** — GitHub will reject it (`GH013: Repository rule violations`). All changes go through Pull Requests.
- **NEVER skip CI checks.** Wait for all status checks to pass before merging.
---
## Task 1: Branch, PR, and Merge Workflow
When code changes (features or bug fixes) are complete and tested locally:
### Step 1: Verify Readiness
1. Check for uncommitted changes: `git status`
2. Ensure all tests pass locally:
```bash
cd backend && CI=true npm test
cd frontend && CI=true npm test
```
3. If tests fail, stop and fix them first.
### Step 2: Create Feature Branch
1. Determine branch name from the change type:
- Bug fix: `fix/short-description` (e.g., `fix/stock-correction-consumption`)
- Feature: `feat/short-description` (e.g., `feat/refill-tracking`)
- Chore: `chore/short-description`
2. Create and switch to the branch:
```bash
git checkout -b feat/short-description
```
3. Stage and commit changes with a conventional commit message:
```bash
git add .
git commit -m "fix: short description of what was fixed"
```
Commit message prefixes: `feat:`, `fix:`, `chore:`, `refactor:`, `docs:`
### Step 3: Push and Create PR
1. Push the branch:
```bash
git push -u origin feat/short-description
```
2. Create a Pull Request via GitHub CLI:
```bash
gh pr create --title "fix: short description" --body "Description of charges"
```
3. **Present the PR URL to the user and wait for confirmation.**
### Step 4: Wait for CI and Merge
1. Monitor CI status:
```bash
gh pr checks <PR_NUMBER> --watch
```
Required checks:
- ✅ `backend-test` (TypeScript type-check + vitest coverage)
- ✅ `frontend-build` (npm build)
2. If CI fails: analyze the failure, fix it, push again, and re-check.
3. Once CI is green, **ask the user for merge confirmation**, then:
```bash
gh pr merge <PR_NUMBER> --squash --delete-branch
```
4. Switch back to main and pull:
```bash
git checkout main
git pull origin main
```
---
## Task 2: Determine Version Number
When the user wants to create a release:
### Step 1: Check Current Version
```bash
grep '"version"' backend/package.json
```
Also check the latest git tag:
```bash
git tag --sort=-v:refname | head -5
```
### Step 2: Analyze Changes Since Last Release
```bash
git log $(git describe --tags --abbrev=0)..HEAD --oneline
```
Read through the commits to understand what changed.
### Step 3: Select SemVer Level
Apply these rules strictly:
| Change Type | Version Bump | Example |
|------------|-------------|---------|
| Bug fixes only, no new features | **patch** | `1.4.2` → `1.4.3` |
| New features (backward compatible) | **minor** | `1.4.2` → `1.5.0` |
| Breaking changes (DB schema without migration, removed ENV vars, changed API) | **major** | `1.4.2` → `2.0.0` |
**Guidelines:**
- When in doubt between patch and minor, prefer **minor** if any user-visible behavior is new.
- Bug fixes that also introduce small UX improvements = **patch**.
- Multiple bug fixes in one release = still **patch**.
- New UI sections, new API endpoints, new settings = **minor**.
- If a user can run `docker compose pull && docker compose up -d` without changing anything → NOT a breaking change.
**Present your version recommendation to the user with reasoning and wait for confirmation.**
---
## Task 3: Execute Release
Use the release script — it is **fully non-interactive** (no y/N prompts) and handles the entire flow automatically:
```bash
./scripts/release.sh <patch|minor|major|x.y.z>
```
The script performs these steps in order:
1. Checks out and updates `main`
2. Creates release branch `chore/release-X.Y.Z`
3. Bumps version in `backend/package.json` and `frontend/package.json`
4. Commits, pushes, and creates a PR
5. Waits for CI checks (with retry logic — polls every 15s, waits up to 10 minutes)
6. Merges the PR (squash + delete branch)
7. Creates a signed tag `vX.Y.Z` and pushes it
**The script auto-detects the git remote** (`origin` or `github`) and uses it consistently.
**CI wait behavior:** GitHub Actions can take 10-30 seconds before checks appear on a new PR. The script waits 20 seconds initially, then polls every 15 seconds until checks are registered, then watches them to completion. Maximum wait is 10 minutes.
**On failure:** If CI fails, the script exits with an error. The release branch and PR remain open for inspection. Fix the issue, push to the branch, and the PR will re-run CI. Then merge manually or re-run the script.
### Version Files (MANDATORY)
The version number is displayed in the **About modal** (Settings → About) as a single unified app version. This version is a **clickable link** pointing to the corresponding GitHub release (`https://github.com/DanielVolz/medassist-ng/releases/tag/vX.Y.Z`). The version is read from:
- **`backend/package.json`** → Backend version, returned by `/health` endpoint
- **`frontend/package.json`** → Frontend version, injected at build time via Vite's `__APP_VERSION__` define and used to construct the release link
**Both files MUST be updated to the new version before tagging a release.** If forgotten:
- The About modal will show the old version
- The version link will point to a non-existent GitHub release page
### Manual Release (if script is not available)
1. Create release branch:
```bash
git checkout main && git pull origin main
git checkout -b chore/release-X.Y.Z
```
2. Update versions in **both** `backend/package.json` and `frontend/package.json` to `X.Y.Z`
3. Commit, push, create PR, wait for CI, merge (same as Task 1)
4. Create signed tag:
```bash
git checkout main && git pull origin main
git tag -s "vX.Y.Z" -m "Release vX.Y.Z"
git push origin "vX.Y.Z"
```
### After Tagging
- The `docker-build.yml` workflow automatically builds and pushes Docker images to GHCR with both versioned tags (`1.8.7`, `1.8`) and `latest`.
- The `update-test-badges.yml` workflow runs automatically after a successful Docker build to update test count badges in the README.
- Track progress: `https://github.com/DanielVolz/medassist-ng/actions`
---
## Task 4: Write Release Notes
When the user asks to write release notes (MANDATORY for minor/major releases):
### Step 1: Gather Changes
```bash
git log vPREVIOUS..vNEW --oneline
```
Read the actual code changes (not just commit messages) to understand what was added or fixed.
### Step 2: Write Release Notes
**Release title:** Use just `vX.Y.Z` (e.g., `v1.4.1`), NOT "Release vX.Y.Z".
**Required structure:**
1. **"What's New"** (1-2 sentences): Brief intro explaining the main change
2. **"New Features" / "Bug Fixes" / "Improvements"**: Grouped bullet points with **bold feature names** and descriptions
3. **"Where to Find It"**: Tell users where they can access the new feature or see the fix
4. **Breaking Changes Warning** (if applicable): See below
**Style guidelines:**
- Use `### Heading` for sections
- Use **bold** for feature names in bullet points
- Keep descriptions on the same line as the feature name
- **No emojis** — do not use emoji in headings or bullet points
- **Include commit references** — each bullet point must end with the PR number (e.g., `(#136)`) or short commit hash (e.g., `(ab12cd3)`) linking to the commit/PR. Use PR numbers when available.
- Always end with "Where to Find It" section
- End with: `**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/vPREV...vNEW`
**ONLY include user-relevant changes.** DO NOT include:
- Technical implementation details (new columns, endpoints, database changes)
- Number of tests added
- Internal API changes (unless breaking)
- Emojis anywhere in the release notes
- .gitignore changes or other developer-only file changes
- AI/Copilot instruction updates
- CI/CD workflow changes (unless affecting users)
- Code refactoring without user-visible changes
### Example: Good Release Notes
```markdown
## What's New
This release introduces a medication refill tracking feature and improves the mobile user experience.
### New Features
- **Medication Refill**: Track when you refill your medications with a single click. Add full packs or individual pills and view complete refill history. (#120)
- **Automatic Stock Updates**: Stock levels are automatically recalculated after each refill. (#120)
- **Refill History**: Each medication shows a complete history of all refills with timestamps. (#122)
### Improvements
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability. (#125)
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices. (#125)
### Where to Find It
The refill button appears in the medication detail modal and in the edit form for each medication.
**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/v1.2.3...v1.3.0
```
### Breaking Changes Warning
If the update breaks existing configurations or stored data, it MUST be prominently warned:
**Breaking Changes include:**
- Database schema changes without automatic migration
- Removed or renamed ENV variables
- Changed API endpoints
- Incompatible `.env` format changes
- Loss of stored data after update
**Format:**
```markdown
## ⚠️ BREAKING CHANGES - Please read before updating!
**Database migration required**: This update changes the database schema.
Existing installations need to:
1. Create backup of `data/` folder
2. Stop containers
3. Perform update
4. If issues occur: Rollback using backup
**ENV variables changed**:
- `OLD_VAR` was renamed to `NEW_VAR`
- `REMOVED_VAR` is no longer supported
```
**What is NOT a Breaking Change:**
- ✅ New optional columns with DEFAULT values
- ✅ New ENV variables (with sensible defaults)
- ✅ New features that don't affect existing data
- ✅ Bug fixes that correct behavior
### Step 3: Publish
Present the release notes to the user. They will copy them to the GitHub release page or ask you to publish via:
```bash
gh release create vX.Y.Z --title "vX.Y.Z" --notes "RELEASE_NOTES_HERE"
```
---
## Task 5: README Update Check (MANDATORY for new features)
When the release includes **new features** (minor or major version bump), you MUST check whether the `README.md` needs to be updated **before** executing the release.
### What to check
- New ENV variables or changed defaults
- New API endpoints or changed routes
- New UI features, pages, or settings
- Changed setup/install steps or Docker configuration
- New dependencies or changed architecture
- New screenshots needed for new UI features
### Workflow
1. Review the changes included in the release
2. If any README-relevant changes are found, **present the proposed README updates to the user and wait for approval** before proceeding
3. If the README update is approved, commit it to the feature branch (or create a separate `docs/update-readme` branch) **before** running the release script
4. Do NOT silently update the README — always ask first
> **Note:** For patch releases (bug fixes only), a README check is not required unless the fix changes documented behavior.
---
## Complete Workflow Summary
```
Code complete & tests pass locally
1. Create feature branch (fix/... or feat/...)
2. Commit, push, create PR
3. Wait for CI (backend-test + frontend-build)
4. Merge PR to main (squash + delete branch)
Ready for release?
5. Check current version (git tag + package.json)
6. Analyze changes → determine SemVer level
7. If minor/major: check README.md for needed updates (Task 5)
8. Run ./scripts/release.sh <patch|minor|major>
(or manually: branch → version bump → PR → CI → merge → tag)
9. Write release notes (mandatory for minor/major)
10. Publish GitHub release
Docker images built automatically via CI
```
+13 -140
View File
@@ -4,12 +4,13 @@
- **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English. - **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English.
- **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action. - **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action.
- **NEVER create PRs without explicit permission**: Do NOT create Pull Requests, push branches, or merge code unless the user explicitly asks for it. Always present changes and wait for the user to confirm before any git operations that affect the remote repository. - **NEVER create PRs, push, or merge**: Only the **release-manager agent** (`@release-manager`) is allowed to create Pull Requests, push branches to the remote, or merge code. Regular agents and Copilot MUST NOT perform any git operations that affect the remote repository (no `git push`, no `gh pr create`, no `gh pr merge`). Present your local changes and tell the user to invoke `@release-manager` when ready to ship.
- **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository. - **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository.
- **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done. - **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done.
- **Remove old code when re-implementing**: When fixing a bug or re-implementing a feature that didn't work, ALWAYS remove the old/broken code completely. Never leave dead code, unused functions, or obsolete implementations in the codebase. - **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. - **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests. When modifying existing features, update or add tests accordingly. If old tests become obsolete due to code changes, remove or update them.
- **Fix bugs, don't test around them**: If you discover incorrect behavior in the code while writing tests, ALWAYS fix the buggy code first, then write tests that verify the correct behavior. NEVER write tests that mimic or assert broken behavior. The user's time is finite and irreplaceable — every bug left unfixed wastes it. - **Fix bugs, don't test around them**: If you discover incorrect behavior in the code while writing tests, ALWAYS fix the buggy code first, then write tests that verify the correct behavior. NEVER write tests that mimic or assert broken behavior. The user's time is finite and irreplaceable — every bug left unfixed wastes it.
- **Keep README.md up to date**: After implementing code changes, check whether the `README.md` needs to be updated (e.g., new features, changed ENV variables, new commands, changed architecture, new endpoints, updated screenshots). If changes are relevant to the README, **ask the user for confirmation** before updating it. Do NOT silently update the README — always present the proposed README changes and wait for approval. Examples of README-relevant changes: new ENV variables, new API endpoints, new UI features, changed setup/install steps, new dependencies, changed Docker configuration.
## Architecture Overview ## Architecture Overview
@@ -137,11 +138,16 @@ Push to main / Tag created
┌─────────────────────────────────────┐ ┌─────────────────────────────────────┐
│ docker-build.yml │ │ docker-build.yml │
─ backend-test (parallel) ─ build-and-push
│ ├─ frontend-build (parallel) │
│ └─ build-and-push (after tests) │
│ ├─ Build Docker images │ │ ├─ Build Docker images │
│ └─ Push to GHCR │ │ └─ Push to GHCR │
│ (Tag builds also set "latest") │
└─────────────────────────────────────┘
↓ After successful build
┌─────────────────────────────────────┐
│ update-test-badges.yml │
│ (workflow_run after docker-build) │
│ └─ Run tests, update badge counts │
└─────────────────────────────────────┘ └─────────────────────────────────────┘
``` ```
@@ -178,142 +184,9 @@ gh pr merge --squash --delete-branch
| File | Trigger | Purpose | | File | Trigger | Purpose |
|------|---------|--------| |------|---------|--------|
| `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures | | `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures |
| `.github/workflows/docker-build.yml` | Push to main, Tags | Tests + Build and push Docker images | | `.github/workflows/docker-build.yml` | Push to main, Tags | Build and push Docker images (+ create GitHub release on tags) |
| `.github/workflows/update-test-badges.yml` | After successful docker-build | Update test count badges in README |
### Adding New Code - Checklist | `.github/workflows/codeql.yml` | Push to main, PRs, Weekly | Security analysis |
1. ✅ Implement feature
2. ✅ Write tests for the feature
3. ✅ Run `npm run test:coverage` locally
4. ✅ Coverage must not decrease
5. ✅ Create and push feature branch
6. ✅ Create Pull Request
7. ✅ Wait until CI is green
8. ✅ Merge PR (branch is automatically deleted)
## GitHub Releases
> ⚠️ **IMPORTANT**: All GitHub Releases must be written in **English**!
### Release Workflow (MANDATORY for minor/major releases)
The `main` branch is protected - releases 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 ## Key Patterns
+22
View File
@@ -3,8 +3,30 @@ name: "CodeQL"
on: on:
push: push:
branches: [main] branches: [main]
paths:
- '**.js'
- '**.ts'
- '**.tsx'
- '**.jsx'
- 'backend/package.json'
- 'backend/package-lock.json'
- 'frontend/package.json'
- 'frontend/package-lock.json'
- '.github/codeql/**'
- '.github/workflows/codeql.yml'
pull_request: pull_request:
branches: [main] branches: [main]
paths:
- '**.js'
- '**.ts'
- '**.tsx'
- '**.jsx'
- 'backend/package.json'
- 'backend/package-lock.json'
- 'frontend/package.json'
- 'frontend/package-lock.json'
- '.github/codeql/**'
- '.github/workflows/codeql.yml'
schedule: schedule:
- cron: "0 6 * * 1" # Weekly on Monday at 6am UTC - cron: "0 6 * * 1" # Weekly on Monday at 6am UTC
workflow_dispatch: # Allow manual trigger workflow_dispatch: # Allow manual trigger
+8 -43
View File
@@ -25,50 +25,15 @@ env:
jobs: jobs:
# ============================================================================= # =============================================================================
# Run Tests First # Build and Push Docker Images
# ============================================================================= # Tests are NOT run here — branch protection on main requires all PR checks
backend-test: # (backend-test + frontend-build from test.yml) to pass before merge.
name: Backend Tests # Tags are created from main, so code is already tested.
runs-on: ubuntu-latest #
permissions: # Tag builds (v*) always set "latest" in addition to the semver tags.
contents: read # This ensures "latest" always points to the most recent release.
defaults:
run:
working-directory: backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: backend/package-lock.json
- run: npm ci
- run: npx tsc --noEmit
- run: npm run test:run
frontend-build:
name: Frontend Build
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- run: npm ci
- run: npm run build
# =============================================================================
# Build and Push Docker Images (only after tests pass)
# ============================================================================= # =============================================================================
build-and-push: build-and-push:
needs: [backend-test, frontend-build]
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: read contents: read
@@ -106,7 +71,7 @@ jobs:
type=semver,pattern={{version}} type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}} type=semver,pattern={{major}}.{{minor}}
type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }} type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
- name: Build and push - name: Build and push
uses: docker/build-push-action@v5 uses: docker/build-push-action@v5
-78
View File
@@ -1,78 +0,0 @@
name: Create Release
on:
push:
tags: ['v*']
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get version info
id: version
run: |
CURRENT_TAG=${GITHUB_REF#refs/tags/}
VERSION=${CURRENT_TAG#v}
echo "tag=$CURRENT_TAG" >> $GITHUB_OUTPUT
echo "version=$VERSION" >> $GITHUB_OUTPUT
# Get previous tag
PREV_TAG=$(git tag --sort=-v:refname | grep -A1 "^${CURRENT_TAG}$" | tail -1)
if [ "$PREV_TAG" = "$CURRENT_TAG" ]; then
PREV_TAG=""
fi
echo "previous_tag=$PREV_TAG" >> $GITHUB_OUTPUT
- name: Generate release template
run: |
cat > release_notes.md << 'EOF'
## What's New
<!--
Write 1-2 sentences describing the main changes in this release.
Example: This release introduces a medication refill tracking feature and improves the mobile user experience.
-->
### New Features
<!-- List new features with **bold** names and descriptions -->
- **Feature Name**: Description of the feature
### Improvements
<!-- List improvements and fixes -->
- **Improvement**: Description
### Where to Find It
<!-- Tell users where they can access new features -->
---
## Docker Images
```bash
docker pull ghcr.io/danielvolz/medassist-ng-backend:${{ steps.version.outputs.version }}
docker pull ghcr.io/danielvolz/medassist-ng-frontend:${{ steps.version.outputs.version }}
```
**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/${{ steps.version.outputs.previous_tag }}...${{ steps.version.outputs.tag }}
EOF
- name: Create Draft Release
uses: softprops/action-gh-release@v1
with:
body_path: release_notes.md
draft: true
generate_release_notes: false
name: "Release ${{ steps.version.outputs.tag }}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+32 -2
View File
@@ -10,10 +10,38 @@ permissions:
jobs: jobs:
# ============================================================================= # =============================================================================
# Backend Tests # Detect which paths changed to skip unnecessary jobs
# =============================================================================
changes:
name: Detect Changes
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
outputs:
backend: ${{ steps.filter.outputs.backend }}
frontend: ${{ steps.filter.outputs.frontend }}
steps:
- uses: dorny/paths-filter@v3
id: filter
with:
filters: |
backend:
- 'backend/**'
- 'biome.json'
- '.github/workflows/test.yml'
frontend:
- 'frontend/**'
- 'biome.json'
- '.github/workflows/test.yml'
# =============================================================================
# Backend Tests (skipped if no backend-related files changed)
# ============================================================================= # =============================================================================
backend-test: backend-test:
name: Backend Tests name: Backend Tests
needs: changes
if: needs.changes.outputs.backend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: read contents: read
@@ -53,10 +81,12 @@ jobs:
retention-days: 7 retention-days: 7
# ============================================================================= # =============================================================================
# Frontend Build Validation # Frontend Build Validation (skipped if no frontend-related files changed)
# ============================================================================= # =============================================================================
frontend-build: frontend-build:
name: Frontend Build name: Frontend Build
needs: changes
if: needs.changes.outputs.frontend == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: read contents: read
+22 -22
View File
@@ -1,13 +1,11 @@
name: Update Test Badges name: Update Test Badges
on: on:
push: workflow_dispatch:
workflow_run:
workflows: ["Build and Push Docker Images"]
types: [completed]
branches: [main] branches: [main]
paths:
- 'backend/src/**'
- 'frontend/src/**'
- 'backend/package.json'
- 'frontend/package.json'
permissions: permissions:
contents: write contents: write
@@ -16,12 +14,14 @@ jobs:
update-badges: update-badges:
name: Update Test Count Badges name: Update Test Count Badges
runs-on: ubuntu-latest 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: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.BADGE_TOKEN || secrets.GITHUB_TOKEN }}
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@v4 uses: actions/setup-node@v4
@@ -47,8 +47,9 @@ jobs:
run: | run: |
OUTPUT=$(npm run test:run 2>&1) || true OUTPUT=$(npm run test:run 2>&1) || true
echo "$OUTPUT" echo "$OUTPUT"
# Extract "Tests X passed" from output # Strip ANSI escape codes, then extract "Tests X passed" from output
PASSED=$(echo "$OUTPUT" | grep -oP 'Tests\s+\K\d+(?=\s+passed)' | tail -1) 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 echo "count=$PASSED" >> $GITHUB_OUTPUT
- name: Run frontend tests and capture count - name: Run frontend tests and capture count
@@ -60,8 +61,9 @@ jobs:
run: | run: |
OUTPUT=$(npm run test:run 2>&1) || true OUTPUT=$(npm run test:run 2>&1) || true
echo "$OUTPUT" echo "$OUTPUT"
# Extract "Tests X passed" from output # Strip ANSI escape codes, then extract "Tests X passed" from output
PASSED=$(echo "$OUTPUT" | grep -oP 'Tests\s+\K\d+(?=\s+passed)' | tail -1) 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 echo "count=$PASSED" >> $GITHUB_OUTPUT
- name: Update README badges - name: Update README badges
@@ -88,16 +90,14 @@ jobs:
exit 0 exit 0
fi fi
- name: Check for changes - name: Commit and push badge updates
id: git-check
run: | run: |
git diff --quiet README.md || echo "changed=true" >> $GITHUB_OUTPUT git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
- 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 add README.md git add README.md
git commit -m "chore: update test count badges [skip ci]" if git diff --cached --quiet; then
git push echo "No badge changes to commit"
else
git commit -m "chore: update test count badges [skip ci]"
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
+2 -2
View File
@@ -18,8 +18,8 @@
</p> </p>
<p align="center"> <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/Backend_Tests-494%2F494-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/Frontend_Tests-653%2F653-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
</p> </p>
### 🤖 AI-Generated Code ### 🤖 AI-Generated Code
+1 -1
View File
@@ -5,6 +5,6 @@ export default defineConfig({
out: "./drizzle", out: "./drizzle",
dialect: "sqlite", dialect: "sqlite",
dbCredentials: { dbCredentials: {
url: process.env.DATABASE_URL || "./data/medassist.db", url: process.env.DATABASE_URL || "./data/medassist-ng.db",
}, },
}); });
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "medassist-ng-backend", "name": "medassist-ng-backend",
"version": "1.7.1", "version": "1.8.8",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "medassist-ng-backend", "name": "medassist-ng-backend",
"version": "1.7.1", "version": "1.8.8",
"dependencies": { "dependencies": {
"@fastify/cookie": "^10.0.1", "@fastify/cookie": "^10.0.1",
"@fastify/cors": "^10.0.1", "@fastify/cors": "^10.0.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "medassist-ng-backend", "name": "medassist-ng-backend",
"version": "1.7.1", "version": "1.8.8",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
+47 -154
View File
@@ -1,162 +1,37 @@
import { accessSync, constants, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs"; import { existsSync, statSync } from "node:fs";
import { dirname, resolve } from "node:path"; import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { type Client, createClient } from "@libsql/client"; import { type Client, createClient } from "@libsql/client";
import dotenv from "dotenv"; import dotenv from "dotenv";
import { drizzle } from "drizzle-orm/libsql"; import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator";
dotenv.config({ path: process.env.DOTENV_PATH || ".env" }); // Import utilities from db-utils (side-effect-free)
import {
ensureDataDirectory,
ensureDefaultUser,
getDataDir,
getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations,
runDrizzleMigrations,
} from "./db-utils.js";
// Get migrations folder path (relative to this file's location) // Re-export all utilities so existing imports from client.ts keep working
const __filename = fileURLToPath(import.meta.url); export {
const __dirname = dirname(__filename); buildDbUrl,
const migrationsFolder = resolve(__dirname, "../../drizzle"); ensureDataDirectory,
ensureDefaultUser,
getDataDir,
getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations,
runDrizzleMigrations,
} from "./db-utils.js";
// ============================================================================= // Load .env: try cwd first, then parent dir (for local dev running from backend/)
// Exported utility functions for testing const envPath = process.env.DOTENV_PATH || (existsSync(".env") ? ".env" : "../.env");
// ============================================================================= dotenv.config({ path: envPath });
/** Build the database URL from a path */
export function buildDbUrl(dbPath: string): string {
return `file:${dbPath}`;
}
/** Get data directory and database path */
export function getDbPaths(cwd: string = process.cwd()): { dataDir: string; dbPath: string; url: string } {
const dataDir = resolve(cwd, "data");
const dbPath = resolve(dataDir, "medassist-ng.db");
const url = buildDbUrl(dbPath);
return { dataDir, dbPath, url };
}
/** Ensure data directory exists and is writable */
export function ensureDataDirectory(dataDir: string): { success: boolean; error?: string } {
try {
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true });
}
// Check if directory is writable
accessSync(dataDir, constants.W_OK);
// Try to create a test file to verify write access
const testFile = resolve(dataDir, ".write-test");
writeFileSync(testFile, "test");
return { success: true };
} catch (err: any) {
return { success: false, error: err.message };
}
}
/** Run drizzle-kit migrations on the database */
export async function runDrizzleMigrations(
database: ReturnType<typeof drizzle>
): Promise<{ success: boolean; error?: string; 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;
}
}
// ============================================================================= // =============================================================================
// Database initialization (runs on import) // Database initialization (runs on import)
@@ -201,7 +76,7 @@ export const db = drizzle(client);
// Auto-run migrations (self-healing database) // Auto-run migrations (self-healing database)
async function runMigrations() { async function runMigrations() {
// Run drizzle-kit generated migrations // Run drizzle-kit generated migrations
console.log(`[DB] Running drizzle migrations from: ${migrationsFolder}`); console.log(`[DB] Running drizzle migrations...`);
const migrateResult = await runDrizzleMigrations(db); const migrateResult = await runDrizzleMigrations(db);
if (!migrateResult.success) { if (!migrateResult.success) {
console.error(`[DB] Migration error:`, migrateResult.error); console.error(`[DB] Migration error:`, migrateResult.error);
@@ -218,6 +93,24 @@ async function runMigrations() {
} }
console.log(`[DB] Tables verified/created`); console.log(`[DB] Tables verified/created`);
// Repair dose IDs with trailing hyphens (from frontend takenBy bug)
const trailingResult = await repairTrailingHyphenDoseIds(client);
if (trailingResult.repaired > 0) {
console.log(`[DB] Repaired ${trailingResult.repaired} dose IDs with trailing hyphens`);
}
if (trailingResult.errors.length > 0) {
trailingResult.errors.forEach((err) => console.error(`[DB] Trailing-hyphen repair error:`, err));
}
// Repair orphaned dose tracking IDs from past schedule changes
const repairResult = await repairOrphanedDoseIds(client);
if (repairResult.repaired > 0) {
console.log(`[DB] Repaired ${repairResult.repaired} orphaned dose tracking IDs`);
}
if (repairResult.errors.length > 0) {
repairResult.errors.forEach((err) => console.error(`[DB] Dose repair error:`, err));
}
// If auth is disabled, ensure a default user exists (ID=1) // If auth is disabled, ensure a default user exists (ID=1)
const authEnabled = process.env.AUTH_ENABLED === "true"; const authEnabled = process.env.AUTH_ENABLED === "true";
const created = await ensureDefaultUser(client, authEnabled); const created = await ensureDefaultUser(client, authEnabled);
+352
View File
@@ -0,0 +1,352 @@
/**
* Pure utility functions for database operations.
* Separated from client.ts to allow importing without triggering
* top-level database initialization side effects.
*/
import { accessSync, constants, existsSync, mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import type { Client } from "@libsql/client";
import type { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator";
import { parseIntakesJson, parseLocalDateTime } from "../utils/scheduler-utils.js";
// Get migrations folder path (relative to this file's location)
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const migrationsFolder = resolve(__dirname, "../../drizzle");
// =============================================================================
// Path & Directory utilities
// =============================================================================
/**
* Get the data directory path.
*
* Resolution order:
* 1. DATA_DIR env var (set by docker-compose for containers)
* 2. Monorepo detection: if ../docker-compose.yml exists, we're in backend/
* subdirectory → use ../data (project root's data folder)
* 3. Fallback: resolve(cwd, "data") (running from project root or standalone)
*/
export function getDataDir(cwd: string = process.cwd()): string {
// Docker containers set DATA_DIR explicitly
if (process.env.DATA_DIR) return resolve(process.env.DATA_DIR);
// Local dev: detect if we're in backend/ subdirectory of the monorepo
if (existsSync(resolve(cwd, "..", "docker-compose.yml"))) {
return resolve(cwd, "..", "data");
}
// Default: data/ relative to cwd (running from project root)
return resolve(cwd, "data");
}
/** Build the database URL from a path */
export function buildDbUrl(dbPath: string): string {
return `file:${dbPath}`;
}
/** Get data directory and database path */
export function getDbPaths(cwd: string = process.cwd()): { dataDir: string; dbPath: string; url: string } {
const dataDir = getDataDir(cwd);
const dbPath = resolve(dataDir, "medassist-ng.db");
const url = buildDbUrl(dbPath);
return { dataDir, dbPath, url };
}
/** Ensure data directory exists and is writable */
export function ensureDataDirectory(dataDir: string): { success: boolean; error?: string } {
try {
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true });
}
// Check if directory is writable
accessSync(dataDir, constants.W_OK);
// Try to create a test file to verify write access
const testFile = resolve(dataDir, ".write-test");
writeFileSync(testFile, "test");
return { success: true };
} catch (err: any) {
return { success: false, error: err.message };
}
}
// =============================================================================
// Migration utilities
// =============================================================================
/** Run drizzle-kit migrations on the database */
export async function runDrizzleMigrations(
database: ReturnType<typeof drizzle>
): Promise<{ success: boolean; error?: string; warning?: string }> {
try {
await migrate(database, { migrationsFolder });
return { success: true };
} catch (err: any) {
// If the error is "duplicate column", it means the schema is already up-to-date
// This happens when ALTER migrations in client.ts have already added the columns
// We consider this a success with a warning, not a failure
if (err.message?.includes("duplicate column")) {
return { success: true, warning: `Schema already up-to-date: ${err.message}` };
}
return { success: false, error: err.message };
}
}
/** Run ALTER TABLE migrations for backward compatibility with older databases */
export async function runAlterMigrations(client: Client): Promise<{ success: boolean; errors: string[] }> {
const errors: string[] = [];
// These add new columns to existing tables (silently fail if column already exists)
const alterMigrations = [
// Added in v1.x - repeat reminders and nagging settings
`ALTER TABLE user_settings ADD COLUMN skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0`,
`ALTER TABLE user_settings ADD COLUMN repeat_reminders_enabled integer NOT NULL DEFAULT 0`,
`ALTER TABLE user_settings ADD COLUMN reminder_repeat_interval_minutes integer NOT NULL DEFAULT 30`,
`ALTER TABLE user_settings ADD COLUMN max_nagging_reminders integer NOT NULL DEFAULT 5`,
// Added in v1.2.3 - dismiss missed doses without deducting stock
`ALTER TABLE dose_tracking ADD COLUMN dismissed integer NOT NULL DEFAULT 0`,
// Added in v1.3.x - stock calculation mode (automatic/manual)
`ALTER TABLE user_settings ADD COLUMN stock_calculation_mode text NOT NULL DEFAULT 'automatic'`,
// Added for stock correction - hidden offset that doesn't affect looseTablets
`ALTER TABLE medications ADD COLUMN stock_adjustment integer NOT NULL DEFAULT 0`,
// Added for stock correction - timestamp to ignore consumed doses before correction
`ALTER TABLE medications ADD COLUMN last_stock_correction_at integer`,
// Added in v1.5.1 - dismiss past doses until date (robust against timestamp changes)
`ALTER TABLE medications ADD COLUMN dismissed_until text`,
// Added for more detailed reminder info display
`ALTER TABLE user_settings ADD COLUMN last_reminder_med_name text`,
`ALTER TABLE user_settings ADD COLUMN last_reminder_taken_by text`,
// Added for package type support (blister vs bottle)
`ALTER TABLE medications ADD COLUMN package_type text NOT NULL DEFAULT 'blister'`,
`ALTER TABLE medications ADD COLUMN total_pills integer`,
// Added for dose unit selection (mg, g, mcg, ml, IU, etc.)
`ALTER TABLE medications ADD COLUMN dose_unit text DEFAULT 'mg'`,
// Added for intake-level takenBy: unified intakes structure
`ALTER TABLE medications ADD COLUMN intakes_json text NOT NULL DEFAULT '[]'`,
];
for (const sql of alterMigrations) {
try {
await client.execute(sql);
} catch (e: any) {
// Silently ignore "duplicate column" errors - column already exists
if (!e.message?.includes("duplicate column")) {
errors.push(e.message);
}
}
}
// Create tables that might be missing (silently fail if already exists)
const createTableMigrations = [
// Added in v1.3.x - refill history tracking
`CREATE TABLE IF NOT EXISTS refill_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
medication_id INTEGER NOT NULL REFERENCES medications(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
packs_added INTEGER NOT NULL DEFAULT 0,
loose_pills_added INTEGER NOT NULL DEFAULT 0,
refill_date INTEGER NOT NULL DEFAULT (strftime('%s','now'))
)`,
];
for (const sql of createTableMigrations) {
try {
await client.execute(sql);
} catch (e: any) {
// Silently ignore "table already exists" errors
if (!e.message?.includes("already exists")) {
errors.push(e.message);
}
}
}
return { success: errors.length === 0, errors };
}
// =============================================================================
// User utilities
// =============================================================================
/** Ensure default user exists for auth-disabled mode */
export async function ensureDefaultUser(client: Client, authEnabled: boolean): Promise<boolean> {
if (authEnabled) {
return false; // No default user needed
}
try {
const result = await client.execute("SELECT id FROM users WHERE id = 1");
if (result.rows.length === 0) {
await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'default', 'local')");
return true; // Created
}
return false; // Already exists
} catch (e: any) {
console.error(`[DB] Error creating default user:`, e.message);
return false;
}
}
// =============================================================================
// Startup repair: fix orphaned dose tracking IDs from past schedule changes
// =============================================================================
const MS_PER_DAY = 86_400_000;
/**
* Repair dose IDs that have a trailing hyphen caused by a frontend bug where
* `[].toString()` produced an empty string, resulting in IDs like "5-0-1729123200000-"
* instead of "5-0-1729123200000". This strips trailing hyphens from all dose IDs.
*
* This function is idempotent - safe to run on every startup.
*/
export async function repairTrailingHyphenDoseIds(client: Client): Promise<{ repaired: number; errors: string[] }> {
const errors: string[] = [];
let repaired = 0;
try {
const result = await client.execute(
"UPDATE dose_tracking SET dose_id = RTRIM(dose_id, '-') WHERE dose_id LIKE '%-'"
);
repaired = result.rowsAffected;
} catch (e: any) {
errors.push(`Trailing-hyphen repair failed: ${e.message}`);
}
return { repaired, errors };
}
/**
* Repair orphaned dose tracking IDs that no longer match the current intake schedule.
* This fixes dose IDs that became invalid when a medication's schedule was changed
* BEFORE the on-edit migration (PR #103) was introduced.
*
* For each medication, generates all valid schedule dateOnlyMs values from each intake's
* start date up to today, then checks all dose_tracking entries. Any dose whose timestamp
* doesn't match a valid schedule date is remapped to the nearest valid date.
*
* This function is idempotent - safe to run on every startup.
*/
export async function repairOrphanedDoseIds(client: Client): Promise<{ repaired: number; errors: string[] }> {
const errors: string[] = [];
let repaired = 0;
try {
// Get all medications
const medsResult = await client.execute(
"SELECT id, intakes_json, usage_json, every_json, start_json, intake_reminders_enabled FROM medications"
);
if (medsResult.rows.length === 0) return { repaired, errors };
// Get all dose tracking entries
const dosesResult = await client.execute("SELECT id, dose_id FROM dose_tracking");
if (dosesResult.rows.length === 0) return { repaired, errors };
// Build a map of medId → dose entries for quick lookup
const dosesByMed = new Map<number, Array<{ id: number; doseId: string }>>();
for (const row of dosesResult.rows) {
const doseId = row.dose_id as string;
const parts = doseId.split("-");
if (parts.length < 3) continue;
const medId = parseInt(parts[0], 10);
if (Number.isNaN(medId)) continue;
if (!dosesByMed.has(medId)) dosesByMed.set(medId, []);
dosesByMed.get(medId)!.push({ id: row.id as number, doseId });
}
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
for (const med of medsResult.rows) {
const medId = med.id as number;
const medDoses = dosesByMed.get(medId);
if (!medDoses || medDoses.length === 0) continue;
// Parse intakes
const intakes = parseIntakesJson(
med.intakes_json as string | null,
{
usageJson: (med.usage_json as string) || "[]",
everyJson: (med.every_json as string) || "[]",
startJson: (med.start_json as string) || "[]",
},
(med.intake_reminders_enabled as number) === 1
);
if (intakes.length === 0) continue;
// For each intake index, build the set of valid dateOnlyMs values
const validDatesByIntake = new Map<number, Set<number>>();
for (let idx = 0; idx < intakes.length; idx++) {
const intake = intakes[idx];
const start = parseLocalDateTime(intake.start);
const every = intake.every;
if (every <= 0 || Number.isNaN(start.getTime())) continue;
const validDates = new Set<number>();
for (let d = new Date(start); d <= today; d.setDate(d.getDate() + every)) {
validDates.add(new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime());
}
validDatesByIntake.set(idx, validDates);
}
// Check each dose entry
for (const dose of medDoses) {
const parts = dose.doseId.split("-");
if (parts.length < 3) continue;
const intakeIdx = parseInt(parts[1], 10);
const dateOnlyMs = parseInt(parts[2], 10);
if (Number.isNaN(intakeIdx) || Number.isNaN(dateOnlyMs)) continue;
const validDates = validDatesByIntake.get(intakeIdx);
if (!validDates) continue; // Unknown intake index - skip
// Check if this dose's timestamp is valid
if (validDates.has(dateOnlyMs)) continue; // Already valid - nothing to do
// Orphaned dose - find the nearest valid schedule date
const intake = intakes[intakeIdx];
if (!intake) continue;
const halfInterval = (intake.every * MS_PER_DAY) / 2;
let bestMatch: number | null = null;
let bestDist = Infinity;
for (const validDate of validDates) {
const dist = Math.abs(validDate - dateOnlyMs);
if (dist < bestDist && dist <= halfInterval) {
bestDist = dist;
bestMatch = validDate;
}
}
if (bestMatch !== null) {
// Rebuild dose ID with new timestamp, preserving person suffix
const personSuffix = parts.length > 3 ? `-${parts.slice(3).join("-")}` : "";
const newDoseId = `${medId}-${intakeIdx}-${bestMatch}${personSuffix}`;
try {
await client.execute({
sql: "UPDATE dose_tracking SET dose_id = ? WHERE id = ?",
args: [newDoseId, dose.id],
});
repaired++;
} catch (e: any) {
errors.push(`Failed to repair dose ${dose.id}: ${e.message}`);
}
}
}
}
} catch (e: any) {
errors.push(`Repair failed: ${e.message}`);
}
return { repaired, errors };
}
+4 -1
View File
@@ -1,3 +1,4 @@
import { existsSync } from "node:fs";
import { dirname, resolve } from "node:path"; import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { type Client, createClient } from "@libsql/client"; import { type Client, createClient } from "@libsql/client";
@@ -5,7 +6,9 @@ import dotenv from "dotenv";
import { drizzle } from "drizzle-orm/libsql"; import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator"; import { migrate } from "drizzle-orm/libsql/migrator";
dotenv.config({ path: process.env.DOTENV_PATH || ".env" }); // Load .env: try cwd first, then parent dir (for local dev running from backend/)
const envPath = process.env.DOTENV_PATH || (existsSync(".env") ? ".env" : "../.env");
dotenv.config({ path: envPath });
// Get migrations folder path (relative to this file's location) // Get migrations folder path (relative to this file's location)
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
+2 -2
View File
@@ -156,7 +156,7 @@ const translations: Record<Language, TranslationKeys> = {
push: { push: {
stockTitle: "MedAssist-ng: 1 Medication Running Low", stockTitle: "MedAssist-ng: 1 Medication Running Low",
stockTitleMultiple: "MedAssist-ng: {count} Medications Running Low", stockTitleMultiple: "MedAssist-ng: {count} Medications Running Low",
intakeTitle: "💊 Medication Reminder in {minutes} min", intakeTitle: "💊 Reminder: Medication intake in {minutes} min",
pillsLeft: "{count} pills", pillsLeft: "{count} pills",
daysLeft: "{count} days left", daysLeft: "{count} days left",
pillsAt: "{count} pills at {time}", pillsAt: "{count} pills at {time}",
@@ -210,7 +210,7 @@ const translations: Record<Language, TranslationKeys> = {
push: { push: {
stockTitle: "MedAssist-ng: 1 Medikament wird knapp", stockTitle: "MedAssist-ng: 1 Medikament wird knapp",
stockTitleMultiple: "MedAssist-ng: {count} Medikamente werden knapp", stockTitleMultiple: "MedAssist-ng: {count} Medikamente werden knapp",
intakeTitle: "💊 Einnahme-Erinnerung in {minutes} Min.", intakeTitle: "💊 Erinnerung: Medikamenteneinnahme in {minutes} Min.",
pillsLeft: "{count} Tabletten", pillsLeft: "{count} Tabletten",
daysLeft: "{count} Tage übrig", daysLeft: "{count} Tage übrig",
pillsAt: "{count} Tabletten um {time}", pillsAt: "{count} Tabletten um {time}",
+2 -1
View File
@@ -10,6 +10,7 @@ import sensible from "@fastify/sensible";
import fastifyStatic from "@fastify/static"; import fastifyStatic from "@fastify/static";
import Fastify, { type FastifyInstance } from "fastify"; import Fastify, { type FastifyInstance } from "fastify";
import { migrationsReady } from "./db/client.js"; import { migrationsReady } from "./db/client.js";
import { getDataDir } from "./db/db-utils.js";
import { env } from "./plugins/env.js"; import { env } from "./plugins/env.js";
import { authRoutes } from "./routes/auth.js"; import { authRoutes } from "./routes/auth.js";
import { doseRoutes } from "./routes/doses.js"; import { doseRoutes } from "./routes/doses.js";
@@ -66,7 +67,7 @@ export async function createApp(options?: {
accessTtlMinutes: options?.accessTtlMinutes ?? 15, accessTtlMinutes: options?.accessTtlMinutes ?? 15,
refreshTtlDays: options?.refreshTtlDays ?? 7, refreshTtlDays: options?.refreshTtlDays ?? 7,
isProduction: options?.isProduction ?? false, isProduction: options?.isProduction ?? false,
imagesDir: options?.imagesDir ?? resolve(process.cwd(), "data/images"), imagesDir: options?.imagesDir ?? resolve(getDataDir(), "images"),
}; };
const app = Fastify({ const app = Fastify({
+4 -1
View File
@@ -1,7 +1,10 @@
import { existsSync } from "node:fs";
import dotenv from "dotenv"; import dotenv from "dotenv";
import { z } from "zod"; import { z } from "zod";
dotenv.config({ path: process.env.DOTENV_PATH || ".env" }); // Load .env: try cwd first, then parent dir (for local dev running from backend/)
const envPath = process.env.DOTENV_PATH || (existsSync(".env") ? ".env" : "../.env");
dotenv.config({ path: envPath });
const EnvSchema = z.object({ const EnvSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("production"), NODE_ENV: z.enum(["development", "production", "test"]).default("production"),
+4 -3
View File
@@ -4,6 +4,7 @@ import { eq } from "drizzle-orm";
import type { FastifyInstance } from "fastify"; import type { FastifyInstance } from "fastify";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { refreshTokens, users } from "../db/schema.js"; import { refreshTokens, users } from "../db/schema.js";
import { getAuthState, requireAuth } from "../plugins/auth.js"; import { getAuthState, requireAuth } from "../plugins/auth.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
@@ -476,7 +477,7 @@ export async function authRoutes(app: FastifyInstance) {
// Save file // Save file
const fs = await import("node:fs/promises"); const fs = await import("node:fs/promises");
const path = await import("node:path"); const path = await import("node:path");
const imagesDir = path.join(process.cwd(), "data", "images"); const imagesDir = path.join(getDataDir(), "images");
await fs.mkdir(imagesDir, { recursive: true }); await fs.mkdir(imagesDir, { recursive: true });
const buffer = await data.toBuffer(); const buffer = await data.toBuffer();
@@ -523,7 +524,7 @@ export async function authRoutes(app: FastifyInstance) {
const fs = await import("node:fs/promises"); const fs = await import("node:fs/promises");
const path = await import("node:path"); const path = await import("node:path");
try { try {
await fs.unlink(path.join(process.cwd(), "data", "images", user.avatarUrl)); await fs.unlink(path.join(getDataDir(), "images", user.avatarUrl));
} catch { } catch {
// Ignore if file doesn't exist // Ignore if file doesn't exist
} }
@@ -556,7 +557,7 @@ export async function authRoutes(app: FastifyInstance) {
const fs = await import("node:fs/promises"); const fs = await import("node:fs/promises");
const path = await import("node:path"); const path = await import("node:path");
try { try {
await fs.unlink(path.join(process.cwd(), "data", "images", user.avatarUrl)); await fs.unlink(path.join(getDataDir(), "images", user.avatarUrl));
} catch { } catch {
// Ignore if file doesn't exist // Ignore if file doesn't exist
} }
+5 -1
View File
@@ -5,13 +5,14 @@ import { eq } from "drizzle-orm";
import type { FastifyInstance } from "fastify"; import type { FastifyInstance } from "fastify";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { doseTracking, medications, shareTokens, userSettings } from "../db/schema.js"; import { doseTracking, medications, shareTokens, userSettings } from "../db/schema.js";
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js"; import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
import { parseIntakesJson, parseTakenByJson } from "../utils/scheduler-utils.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) // Export Format Version (bump this when format changes)
@@ -36,6 +37,7 @@ const inventorySchema = z.object({
pillsPerBlister: z.number().int().min(1).default(1), pillsPerBlister: z.number().int().min(1).default(1),
looseTablets: z.number().int().min(0).default(0), looseTablets: z.number().int().min(0).default(0),
stockAdjustment: z.number().int().default(0), // Manual stock correction stockAdjustment: z.number().int().default(0), // Manual stock correction
packageType: z.enum(["blister", "bottle"]).default("blister"),
}); });
const medicationExportSchema = z.object({ const medicationExportSchema = z.object({
@@ -275,6 +277,7 @@ export async function exportRoutes(app: FastifyInstance) {
pillsPerBlister: med.pillsPerBlister ?? 1, pillsPerBlister: med.pillsPerBlister ?? 1,
looseTablets: med.looseTablets ?? 0, looseTablets: med.looseTablets ?? 0,
stockAdjustment: med.stockAdjustment ?? 0, stockAdjustment: med.stockAdjustment ?? 0,
packageType: med.packageType ?? "blister",
}, },
pillWeightMg: med.pillWeightMg, pillWeightMg: med.pillWeightMg,
doseUnit: med.doseUnit ?? "mg", doseUnit: med.doseUnit ?? "mg",
@@ -489,6 +492,7 @@ export async function exportRoutes(app: FastifyInstance) {
name: med.name, name: med.name,
genericName: med.genericName || null, genericName: med.genericName || null,
takenByJson, takenByJson,
packageType: med.inventory.packageType ?? "blister",
packCount: med.inventory.packCount, packCount: med.inventory.packCount,
blistersPerPack: med.inventory.blistersPerPack, blistersPerPack: med.inventory.blistersPerPack,
pillsPerBlister: med.inventory.pillsPerBlister, pillsPerBlister: med.inventory.pillsPerBlister,
+166 -35
View File
@@ -5,13 +5,14 @@ import { and, eq, like } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { doseTracking, medications } from "../db/schema.js"; import { doseTracking, medications } from "../db/schema.js";
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js"; import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js"; import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js"; import type { AuthUser } from "../types/fastify.js";
import { type Intake, parseIntakesJson, parseLocalDateTime, parseTakenByJson } from "../utils/scheduler-utils.js"; import { type Intake, parseIntakesJson, parseLocalDateTime, parseTakenByJson } from "../utils/scheduler-utils.js";
const IMAGES_DIR = resolve(process.cwd(), "data/images"); const IMAGES_DIR = resolve(getDataDir(), "images");
// New intake schema with per-intake takenBy // New intake schema with per-intake takenBy
const intakeSchema = z.object({ const intakeSchema = z.object({
@@ -284,6 +285,17 @@ export async function medicationRoutes(app: FastifyInstance) {
const startJson = JSON.stringify(intakes.map((s) => s.start)); const startJson = JSON.stringify(intakes.map((s) => s.start));
const takenByJson = JSON.stringify(takenBy || []); const takenByJson = JSON.stringify(takenBy || []);
// If stock-defining fields changed, reset stockAdjustment so the new
// base stock reflects actual inventory. This prevents the old
// correction offset from skewing the total after an edit.
const stockFieldsChanged =
existing.packCount !== packCount ||
existing.blistersPerPack !== blistersPerPack ||
existing.pillsPerBlister !== pillsPerBlister ||
(existing.looseTablets ?? 0) !== (looseTablets ?? 0);
const stockResetFields = stockFieldsChanged ? { stockAdjustment: 0, lastStockCorrectionAt: new Date() } : {};
const result = await db const result = await db
.update(medications) .update(medications)
.set({ .set({
@@ -306,35 +318,129 @@ export async function medicationRoutes(app: FastifyInstance) {
everyJson, everyJson,
startJson, startJson,
updatedAt: new Date(), updatedAt: new Date(),
...stockResetFields,
}) })
.where(and(eq(medications.id, idNum), eq(medications.userId, userId))) .where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
.returning(); .returning();
if (!result.length) return reply.notFound(); if (!result.length) return reply.notFound();
// Clean up dose tracking entries that are before the earliest start date // ---------------------------------------------------------------
// This ensures consistency when the user changes the start date // Migrate dose tracking IDs when intake schedule changes
const earliestStart = Math.min(...intakes.map((b) => parseLocalDateTime(b.start).getTime())); // ---------------------------------------------------------------
if (!Number.isNaN(earliestStart)) { // Parse old intakes from the existing medication row
// Get all dose tracking entries for this medication and filter out invalid ones const oldIntakes = parseIntakesJson(
const allDoses = await db existing.intakesJson,
.select() { usageJson: existing.usageJson, everyJson: existing.everyJson, startJson: existing.startJson },
.from(doseTracking) existing.intakeRemindersEnabled
.where(and(eq(doseTracking.userId, userId), like(doseTracking.doseId, `${idNum}-%`))); );
// Find doses with timestamps before the earliest start date // Get all dose tracking entries for this medication
const dosesToDelete = allDoses.filter((dose) => { const allDoses = await db
const parts = dose.doseId.split("-"); .select()
if (parts.length >= 3) { .from(doseTracking)
const timestamp = parseInt(parts[2], 10); .where(and(eq(doseTracking.userId, userId), like(doseTracking.doseId, `${idNum}-%`)));
return !Number.isNaN(timestamp) && timestamp < earliestStart;
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 // Build set of new valid dateOnlyMs values for this intake
for (const dose of dosesToDelete) { const newDates = new Set<number>();
await db.delete(doseTracking).where(eq(doseTracking.id, dose.id)); 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));
}
} }
} }
@@ -550,7 +656,13 @@ export async function medicationRoutes(app: FastifyInstance) {
const blistersPerPack = row.blistersPerPack ?? 1; const blistersPerPack = row.blistersPerPack ?? 1;
const looseTablets = row.looseTablets ?? 0; const looseTablets = row.looseTablets ?? 0;
const stockAdjustment = row.stockAdjustment ?? 0; const stockAdjustment = row.stockAdjustment ?? 0;
const originalTotalPills = packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment; const packageType = row.packageType ?? "blister";
// For bottle type, looseTablets IS the current stock (no blister math)
const originalTotalPills =
packageType === "bottle"
? looseTablets + stockAdjustment
: packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
// Calculate consumption based on ACTUAL taken doses from dose_tracking // Calculate consumption based on ACTUAL taken doses from dose_tracking
// This ensures Planner shows the same "current stock" as the Dashboard/Modal // This ensures Planner shows the same "current stock" as the Dashboard/Modal
@@ -575,10 +687,19 @@ export async function medicationRoutes(app: FastifyInstance) {
const blisterStart = parseLocalDateTime(blister.start); const blisterStart = parseLocalDateTime(blister.start);
if (Number.isNaN(blisterStart.getTime())) return; if (Number.isNaN(blisterStart.getTime())) return;
const effectiveStart = Math.max(blisterStart.getTime(), stockCorrectionCutoff); const period = Math.max(1, blister.every) * msPerDay;
// After a stock correction, start counting from the NEXT scheduled
// dose, because the user's pill count already reflects all
// consumption up to the correction time.
let effectiveStart: number;
if (stockCorrectionCutoff > 0 && stockCorrectionCutoff >= blisterStart.getTime()) {
effectiveStart = stockCorrectionCutoff + period;
} else {
effectiveStart = blisterStart.getTime();
}
if (effectiveStart > now.getTime()) return; if (effectiveStart > now.getTime()) return;
const period = Math.max(1, blister.every) * msPerDay;
const occurrences = Math.floor((now.getTime() - effectiveStart) / period) + 1; const occurrences = Math.floor((now.getTime() - effectiveStart) / period) + 1;
// Get the people for this intake (from intakes array or medication takenBy) // Get the people for this intake (from intakes array or medication takenBy)
@@ -620,18 +741,27 @@ export async function medicationRoutes(app: FastifyInstance) {
// Calculate AVAILABLE = stock AFTER the planned period (currentStock - usageTotal) // Calculate AVAILABLE = stock AFTER the planned period (currentStock - usageTotal)
const availableAfterPeriod = Math.max(0, currentStock - usageTotal); const availableAfterPeriod = Math.max(0, currentStock - usageTotal);
// Calculate stock breakdown for availableAfterPeriod let fullBlisters: number;
// Consumption order: loose pills first, then from blisters let loosePills: number;
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);
const fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0; if (packageType === "bottle") {
const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0; // Bottle type: no blisters, everything is loose pills
const loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose 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; const enough = currentStock >= usageTotal;
return { return {
@@ -644,6 +774,7 @@ export async function medicationRoutes(app: FastifyInstance) {
fullBlisters, fullBlisters,
loosePills, loosePills,
enough, enough,
packageType,
}; };
}); });
+11 -6
View File
@@ -78,9 +78,13 @@ export async function refillRoutes(app: FastifyInstance) {
}) })
.returning(); .returning();
// Calculate pills added for response // Calculate pills added for response (packageType-aware)
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister; const isBottle = (med.packageType ?? "blister") === "bottle";
const totalPillsAdded = packsAdded * pillsPerPack + loosePillsAdded; const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
const totalPillsAdded = isBottle ? loosePillsAdded : packsAdded * pillsPerPack + loosePillsAdded;
const newTotalPills = isBottle
? newLooseTablets + (med.stockAdjustment ?? 0)
: newPackCount * pillsPerPack + newLooseTablets + (med.stockAdjustment ?? 0);
return { return {
success: true, success: true,
@@ -94,7 +98,7 @@ export async function refillRoutes(app: FastifyInstance) {
newStock: { newStock: {
packCount: newPackCount, packCount: newPackCount,
looseTablets: newLooseTablets, looseTablets: newLooseTablets,
totalPills: newPackCount * pillsPerPack + newLooseTablets, totalPills: newTotalPills,
}, },
}; };
}); });
@@ -120,13 +124,14 @@ export async function refillRoutes(app: FastifyInstance) {
.where(eq(refillHistory.medicationId, medId)) .where(eq(refillHistory.medicationId, medId))
.orderBy(desc(refillHistory.refillDate)); .orderBy(desc(refillHistory.refillDate));
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister; const isBottle = (med.packageType ?? "blister") === "bottle";
const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
return refills.map((r) => ({ return refills.map((r) => ({
id: r.id, id: r.id,
packsAdded: r.packsAdded, packsAdded: r.packsAdded,
loosePillsAdded: r.loosePillsAdded, loosePillsAdded: r.loosePillsAdded,
totalPillsAdded: r.packsAdded * pillsPerPack + r.loosePillsAdded, totalPillsAdded: isBottle ? r.loosePillsAdded : r.packsAdded * pillsPerPack + r.loosePillsAdded,
refillDate: r.refillDate, refillDate: r.refillDate,
})); }));
}); });
+4 -1
View File
@@ -114,7 +114,9 @@ export async function shareRoutes(app: FastifyInstance) {
const takenByArray = parseTakenByJson(med.takenByJson); const takenByArray = parseTakenByJson(med.takenByJson);
const totalPills = 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 { return {
id: med.id, id: med.id,
name: med.name, name: med.name,
@@ -123,6 +125,7 @@ export async function shareRoutes(app: FastifyInstance) {
doseUnit: med.doseUnit ?? "mg", doseUnit: med.doseUnit ?? "mg",
imageUrl: med.imageUrl, imageUrl: med.imageUrl,
totalPills, totalPills,
packageType: med.packageType ?? "blister",
packCount: med.packCount, packCount: med.packCount,
blistersPerPack: med.blistersPerPack, blistersPerPack: med.blistersPerPack,
looseTablets: med.looseTablets, looseTablets: med.looseTablets,
@@ -3,6 +3,7 @@ import { resolve } from "node:path";
import { and, eq, gte, lte } from "drizzle-orm"; import { and, eq, gte, lte } from "drizzle-orm";
import nodemailer from "nodemailer"; import nodemailer from "nodemailer";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { doseTracking, medications } from "../db/schema.js"; import { doseTracking, medications } from "../db/schema.js";
import { getDateLocale, getTranslations, type Language, t } from "../i18n/translations.js"; import { getDateLocale, getTranslations, type Language, t } from "../i18n/translations.js";
import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js"; import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js";
@@ -25,7 +26,7 @@ import { updateReminderSentTime, updateUserReminderSentTime } from "./reminder-s
const REMINDER_MINUTES_BEFORE = parseInt(process.env.REMINDER_MINUTES_BEFORE ?? "15", 10); const REMINDER_MINUTES_BEFORE = parseInt(process.env.REMINDER_MINUTES_BEFORE ?? "15", 10);
const CHECK_INTERVAL_MS = 60 * 1000; // Check every 1 minute const CHECK_INTERVAL_MS = 60 * 1000; // Check every 1 minute
const intakeReminderStateFile = resolve(process.cwd(), "data", "intake-reminder-state.json"); const intakeReminderStateFile = resolve(getDataDir(), "intake-reminder-state.json");
function loadIntakeReminderState(): IntakeReminderState { function loadIntakeReminderState(): IntakeReminderState {
try { try {
@@ -408,10 +409,18 @@ async function checkAndSendIntakeRemindersForUser(
if (!existingEntry) { if (!existingEntry) {
// New dose - send first reminder // New dose - send first reminder
if (isIntakePast) { if (isIntakePast) {
// Already missed - this is first nagging reminder (count=1) // Intake time already passed and we have no state entry — this means the scheduler
remindersToSend.push({ ...intake, currentSendCount: 1, maxReminders, isAdvanceReminder: false }); // was not aware of this intake before it happened (e.g., user just enabled reminders).
// Seed the state as already handled so repeat reminders can track from here,
// but do NOT send a notification for intakes that were missed before tracking started.
state.reminders[key] = {
firstSentAt: nowMs,
lastSentAt: nowMs,
sendCount: 0,
advanceSent: false,
};
logger.info( logger.info(
`[IntakeReminder] User ${settings.userId}: First nagging for missed "${intake.medName}" at ${intake.intakeTimeStr} (1/${maxReminders})` `[IntakeReminder] User ${settings.userId}: Seeding state for past "${intake.medName}" at ${intake.intakeTimeStr} (no notification — first detection)`
); );
} else { } else {
// Upcoming - this is advance reminder (no counter) // Upcoming - this is advance reminder (no counter)
@@ -550,7 +559,10 @@ async function checkAndSendIntakeRemindersForUser(
if (hasNaggingReminder && highestSendCount > 0) { if (hasNaggingReminder && highestSendCount > 0) {
// Nagging reminder - show counter // Nagging reminder - show counter
const counterStr = `(${highestSendCount}/${maxReminderCount})`; const counterStr = `(${highestSendCount}/${maxReminderCount})`;
title = language === "de" ? `⚠️ Medikamenten-Erinnerung ${counterStr}` : `⚠️ Medication Reminder ${counterStr}`; title =
language === "de"
? `⚠️ Erinnerung: Medikamenteneinnahme ${counterStr}`
: `⚠️ Reminder: Medication intake ${counterStr}`;
} else { } else {
// Advance reminder - no counter // Advance reminder - no counter
title = t(tr.push.intakeTitle, { minutes: REMINDER_MINUTES_BEFORE }); title = t(tr.push.intakeTitle, { minutes: REMINDER_MINUTES_BEFORE });
+5 -2
View File
@@ -3,6 +3,7 @@ import { resolve } from "node:path";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import nodemailer from "nodemailer"; import nodemailer from "nodemailer";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { getDataDir } from "../db/db-utils.js";
import { medications, userSettings } from "../db/schema.js"; import { medications, userSettings } from "../db/schema.js";
import { getTranslations, type Language, t } from "../i18n/translations.js"; import { getTranslations, type Language, t } from "../i18n/translations.js";
import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js"; import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js";
@@ -25,7 +26,7 @@ import {
const REMINDER_HOUR = parseInt(process.env.REMINDER_HOUR ?? "6", 10); // Default 6:00 AM local time const REMINDER_HOUR = parseInt(process.env.REMINDER_HOUR ?? "6", 10); // Default 6:00 AM local time
const reminderStateFile = resolve(process.cwd(), "data", "reminder-state.json"); const reminderStateFile = resolve(getDataDir(), "reminder-state.json");
function loadReminderState(): ReminderState { function loadReminderState(): ReminderState {
try { try {
@@ -105,7 +106,9 @@ async function getMedicationsNeedingReminder(
for (const row of rows) { for (const row of rows) {
const blisters = parseBlistersFromRow(row); const blisters = parseBlistersFromRow(row);
const totalPills = const totalPills =
row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0); (row.packageType ?? "blister") === "bottle"
? row.looseTablets + (row.stockAdjustment ?? 0)
: row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
const { daysLeft, depletionDate } = calculateDepletionInfo({ count: totalPills, blisters }, language); const { daysLeft, depletionDate } = calculateDepletionInfo({ count: totalPills, blisters }, language);
// Check if medication runs out within reminderDaysBefore days // Check if medication runs out within reminderDaysBefore days
+439 -4
View File
@@ -5,17 +5,20 @@ import { fileURLToPath } from "node:url";
import { createClient } from "@libsql/client"; import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql"; import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator"; import { migrate } from "drizzle-orm/libsql/migrator";
import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// Import the exported utility functions from client.ts // Import utility functions from db-utils (no side effects, unlike client.ts which initializes the DB)
import { import {
buildDbUrl, buildDbUrl,
ensureDataDirectory, ensureDataDirectory,
ensureDefaultUser, ensureDefaultUser,
getDataDir,
getDbPaths, getDbPaths,
repairOrphanedDoseIds,
repairTrailingHyphenDoseIds,
runAlterMigrations, runAlterMigrations,
runDrizzleMigrations, runDrizzleMigrations,
} from "../db/client.js"; } from "../db/db-utils.js";
// Import the exported utility functions from migrate.ts // Import the exported utility functions from migrate.ts
import { executeMigration, getStatementPreview, splitSQLStatements } from "../db/migrate.js"; 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", () => { describe("getDbPaths", () => {
it("should return correct paths based on cwd", () => { const originalDataDir = process.env.DATA_DIR;
afterEach(() => {
if (originalDataDir === undefined) {
delete process.env.DATA_DIR;
} else {
process.env.DATA_DIR = originalDataDir;
}
});
it("should return correct paths with DATA_DIR set", () => {
process.env.DATA_DIR = "/app/data";
const paths = getDbPaths("/app"); const paths = getDbPaths("/app");
expect(paths.dataDir).toBe("/app/data"); expect(paths.dataDir).toBe("/app/data");
expect(paths.dbPath).toBe("/app/data/medassist-ng.db"); expect(paths.dbPath).toBe("/app/data/medassist-ng.db");
expect(paths.url).toBe("file:/app/data/medassist-ng.db"); expect(paths.url).toBe("file:/app/data/medassist-ng.db");
}); });
it("should return correct paths without DATA_DIR in non-monorepo dir", () => {
delete process.env.DATA_DIR;
const paths = getDbPaths("/tmp");
expect(paths.dataDir).toBe("/tmp/data");
expect(paths.dbPath).toBe("/tmp/data/medassist-ng.db");
});
it("should use process.cwd() by default", () => { it("should use process.cwd() by default", () => {
delete process.env.DATA_DIR;
const paths = getDbPaths(); const paths = getDbPaths();
expect(paths.dataDir).toContain("data"); expect(paths.dataDir).toContain("data");
expect(paths.dbPath).toContain("medassist-ng.db"); expect(paths.dbPath).toContain("medassist-ng.db");
@@ -620,4 +686,373 @@ describe("Database Client", () => {
expect(users.rows).toHaveLength(1); expect(users.rows).toHaveLength(1);
}); });
}); });
describe("repairOrphanedDoseIds", () => {
let client: ReturnType<typeof createClient>;
beforeEach(async () => {
client = createClient({ url: ":memory:" });
const db = drizzle(client);
await migrate(db, { migrationsFolder });
// Create a test user
await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'testuser', 'local')");
});
it("should return 0 repairs when no data exists", async () => {
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(0);
expect(result.errors).toHaveLength(0);
});
it("should not modify dose IDs that already match the current schedule", async () => {
// Create weekly medication starting Oct 17 (Friday)
const intakes = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-17T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Weekly Med', ?, '[1]', '[7]', '["2025-10-17T08:00:00"]')`,
args: [intakes],
});
// Insert dose IDs that match the schedule (Fridays)
const fri17 = new Date(2025, 9, 17).getTime();
const fri24 = new Date(2025, 9, 24).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri24}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(0);
// Verify IDs unchanged
const doses = await client.execute("SELECT dose_id FROM dose_tracking ORDER BY dose_id");
expect(doses.rows[0].dose_id).toBe(`1-0-${fri17}`);
expect(doses.rows[1].dose_id).toBe(`1-0-${fri24}`);
});
it("should repair orphaned dose IDs when schedule shifted by 1 day", async () => {
// Current schedule: Saturdays (Oct 18)
const intakes = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Weekly Med', ?, '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [intakes],
});
// Insert orphaned dose IDs from OLD schedule (Fridays)
const fri17 = new Date(2025, 9, 17).getTime();
const fri24 = new Date(2025, 9, 24).getTime();
const fri31 = new Date(2025, 9, 31).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri24}`],
});
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri31}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(3);
expect(result.errors).toHaveLength(0);
// Verify dose IDs are now Saturdays
const sat18 = new Date(2025, 9, 18).getTime();
const sat25 = new Date(2025, 9, 25).getTime();
const nov1 = new Date(2025, 10, 1).getTime();
const doses = await client.execute("SELECT dose_id FROM dose_tracking ORDER BY dose_id");
const ids = doses.rows.map((r) => r.dose_id);
expect(ids).toContain(`1-0-${sat18}`);
expect(ids).toContain(`1-0-${sat25}`);
expect(ids).toContain(`1-0-${nov1}`);
});
it("should preserve person suffix when repairing dose IDs", async () => {
// Current schedule: Saturdays
const intakes = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: "Alice", intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Person Med', ?, '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [intakes],
});
// Orphaned dose with person suffix (from old Friday schedule)
const fri17 = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}-Alice`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(1);
// Verify person suffix preserved
const sat18 = new Date(2025, 9, 18).getTime();
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${sat18}-Alice`);
});
it("should not repair doses that are too far from any valid schedule date", async () => {
// Current schedule: biweekly (every 14 days) starting Oct 18
// halfInterval = 7 days, so doses more than 7 days from any valid date won't match
const intakes = JSON.stringify([
{ usage: 1, every: 14, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Biweekly Med', ?, '[1]', '[14]', '["2025-10-18T08:00:00"]')`,
args: [intakes],
});
// Insert dose on Oct 27 (9 days away from Oct 18, 4 days away from Nov 1)
// halfInterval = 7 days. Oct 27 is 9 days from Oct 18 (too far) and 4 days from Nov 1 (within range)
// Actually use Oct 26 which is 8 days from both (Oct 18 and Nov 1) - exactly at halfInterval + 1
// Wait: biweekly = Oct 18, Nov 1. Oct 26 is 8 days from Oct 18, 6 days from Nov 1 → 6 < 7, matches Nov 1
// Use Oct 25: 7 days from Oct 18, 7 days from Nov 1 → exactly at boundary. Use Oct 25 and check.
// The condition is dist <= halfInterval, so 7 <= 7 is true. Need dist > 7.
// Use a 28-day schedule instead: Oct 18, Nov 15. Midpoint is Nov 1-2. Nov 2 is 15 days from Oct 18, 13 from Nov 15. Both > 14. No match.
const intakes28 = JSON.stringify([
{ usage: 1, every: 28, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `UPDATE medications SET intakes_json = ?, every_json = '[28]' WHERE id = 1`,
args: [intakes28],
});
// Insert dose on Nov 2 (15 days from Oct 18, 13 days from Nov 15)
// halfInterval = 14 days. Both 15 > 14 and 13 < 14, so Nov 2 actually WOULD map to Nov 15.
// Use Nov 4: 17 days from Oct 18, 11 days from Nov 15 → 11 < 14, maps to Nov 15.
// For a 28-day interval, halfInterval = 14. A date must be > 14 days from ALL schedule dates.
// Between Oct 18 and Nov 15 (28 days), the only date > 14 from both is impossible.
// So lets use a gap: Oct 18 is the only past date for a monthly schedule.
// If we pick a date before Oct 18, like Oct 1 (17 days before Oct 18) → 17 > 14 → no match!
const oct1 = new Date(2025, 9, 1).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${oct1}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(0);
// Dose should remain unchanged
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${oct1}`);
});
it("should be idempotent - running twice produces same result", async () => {
// Current schedule: Saturdays
const intakes = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Weekly Med', ?, '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [intakes],
});
// Insert orphaned dose from Friday
const fri17 = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
// First run
const result1 = await repairOrphanedDoseIds(client);
expect(result1.repaired).toBe(1);
// Second run - should find 0 repairs (already fixed)
const result2 = await repairOrphanedDoseIds(client);
expect(result2.repaired).toBe(0);
// Verify final state
const sat18 = new Date(2025, 9, 18).getTime();
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows).toHaveLength(1);
expect(doses.rows[0].dose_id).toBe(`1-0-${sat18}`);
});
it("should handle multiple medications independently", async () => {
// Med 1: weekly Saturdays
const intakes1 = JSON.stringify([
{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Med 1', ?, '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [intakes1],
});
// Med 2: daily starting Oct 20 (valid IDs, no repair needed)
const intakes2 = JSON.stringify([
{ usage: 1, every: 1, start: "2025-10-20T08:00:00", takenBy: null, intakeRemindersEnabled: false },
]);
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (2, 1, 'Med 2', ?, '[1]', '[1]', '["2025-10-20T08:00:00"]')`,
args: [intakes2],
});
// Med 1: orphaned Friday dose
const fri17 = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
// Med 2: valid daily dose
const oct20 = new Date(2025, 9, 20).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`2-0-${oct20}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(1); // Only med 1 dose repaired
// Med 2 dose should be unchanged
const med2Doses = await client.execute("SELECT dose_id FROM dose_tracking WHERE dose_id LIKE '2-%'");
expect(med2Doses.rows[0].dose_id).toBe(`2-0-${oct20}`);
});
it("should handle legacy format (no intakes_json, uses usage/every/start arrays)", async () => {
// Medication with only legacy fields (intakes_json is '[]')
await client.execute({
sql: `INSERT INTO medications (id, user_id, name, intakes_json, usage_json, every_json, start_json)
VALUES (1, 1, 'Legacy Med', '[]', '[1]', '[7]', '["2025-10-18T08:00:00"]')`,
args: [],
});
// Orphaned Friday dose
const fri17 = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${fri17}`],
});
const result = await repairOrphanedDoseIds(client);
expect(result.repaired).toBe(1);
// Verify mapped to Saturday
const sat18 = new Date(2025, 9, 18).getTime();
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${sat18}`);
});
});
describe("repairTrailingHyphenDoseIds", () => {
let client: ReturnType<typeof createClient>;
beforeEach(async () => {
client = createClient({ url: ":memory:" });
const db = drizzle(client);
await migrate(db, { migrationsFolder });
await client.execute("INSERT INTO users (id, username, auth_provider) VALUES (1, 'testuser', 'local')");
});
it("should return 0 repairs when no dose IDs have trailing hyphens", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(0);
expect(result.errors).toHaveLength(0);
});
it("should strip trailing hyphen from dose IDs", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}-`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(1);
expect(result.errors).toHaveLength(0);
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${ts}`);
});
it("should not modify dose IDs with valid person suffixes", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}-Alice`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(0);
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${ts}-Alice`);
});
it("should handle multiple trailing hyphens", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}--`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(1);
const doses = await client.execute("SELECT dose_id FROM dose_tracking");
expect(doses.rows[0].dose_id).toBe(`1-0-${ts}`);
});
it("should repair multiple affected rows at once", async () => {
const ts1 = new Date(2025, 9, 17).getTime();
const ts2 = new Date(2025, 9, 24).getTime();
const ts3 = new Date(2025, 9, 31).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?), (1, ?), (1, ?)",
args: [`1-0-${ts1}-`, `2-0-${ts2}-`, `1-0-${ts3}`],
});
const result = await repairTrailingHyphenDoseIds(client);
expect(result.repaired).toBe(2); // Only 2 had trailing hyphens
expect(result.errors).toHaveLength(0);
const doses = await client.execute("SELECT dose_id FROM dose_tracking ORDER BY dose_id");
const ids = doses.rows.map((r) => r.dose_id);
expect(ids).toContain(`1-0-${ts1}`);
expect(ids).toContain(`2-0-${ts2}`);
expect(ids).toContain(`1-0-${ts3}`);
});
it("should be idempotent - running twice has no effect the second time", async () => {
const ts = new Date(2025, 9, 17).getTime();
await client.execute({
sql: "INSERT INTO dose_tracking (user_id, dose_id) VALUES (1, ?)",
args: [`1-0-${ts}-`],
});
const result1 = await repairTrailingHyphenDoseIds(client);
expect(result1.repaired).toBe(1);
const result2 = await repairTrailingHyphenDoseIds(client);
expect(result2.repaired).toBe(0);
});
});
}); });
+544
View File
@@ -1730,6 +1730,304 @@ describe("E2E Tests with Real Routes", () => {
}); });
}); });
// ---------------------------------------------------------------------------
// Real Stock Correction (PATCH /medications/:id/stock-adjustment) Tests
// ---------------------------------------------------------------------------
describe("Real /medications/:id/stock-adjustment routes", () => {
it("should update stockAdjustment and lastStockCorrectionAt", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Stock Correction Med",
packCount: 1,
blistersPerPack: 14,
pillsPerBlister: 14,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
expect(createResponse.statusCode).toBe(200);
const medId = createResponse.json().id;
// Correct stock: set adjustment to -83 (196 base - 83 = 113 pills)
const response = await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -83 },
});
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data.stockAdjustment).toBe(-83);
expect(data.lastStockCorrectionAt).toBeTruthy();
expect(data.updatedAt).toBeTruthy();
});
it("should persist stockAdjustment in GET /medications", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Persist Stock Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
// Apply stock correction
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -7 },
});
// Verify via GET
const getResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(getResponse.statusCode).toBe(200);
const meds = getResponse.json();
const med = meds.find((m: any) => m.id === medId);
expect(med).toBeDefined();
expect(med.stockAdjustment).toBe(-7);
expect(med.lastStockCorrectionAt).toBeTruthy();
});
it("should not reset stockAdjustment when editing medication via PUT", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Keep Adjustment Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
// Set stock adjustment
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -5 },
});
// Edit the medication (change name) - should preserve stockAdjustment
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Renamed Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
// Verify stockAdjustment is preserved
const getResponse = await app.inject({
method: "GET",
url: "/medications",
});
const med = getResponse.json().find((m: any) => m.id === medId);
expect(med.name).toBe("Renamed Med");
expect(med.stockAdjustment).toBe(-5);
});
it("should return 400 for non-numeric stockAdjustment", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Bad Adjustment Med",
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
const response = await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: "not-a-number" },
});
expect(response.statusCode).toBe(400);
});
it("should return 404 for non-existent medication", async () => {
const response = await app.inject({
method: "PATCH",
url: "/medications/99999/stock-adjustment",
payload: { stockAdjustment: 5 },
});
expect(response.statusCode).toBe(404);
});
it("should return 400 for invalid medication id", async () => {
const response = await app.inject({
method: "PATCH",
url: "/medications/invalid/stock-adjustment",
payload: { stockAdjustment: 5 },
});
expect(response.statusCode).toBe(400);
});
it("should reset stockAdjustment when stock fields change via PUT", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Reset Adj Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
// Set stock adjustment to -10
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -10 },
});
// Verify adjustment is set
let getMeds = await app.inject({ method: "GET", url: "/medications" });
let med = getMeds.json().find((m: any) => m.id === medId);
expect(med.stockAdjustment).toBe(-10);
// Edit medication with CHANGED stock fields (packCount 1 → 2)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Reset Adj Med",
packCount: 2,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
// stockAdjustment should be reset to 0
getMeds = await app.inject({ method: "GET", url: "/medications" });
med = getMeds.json().find((m: any) => m.id === medId);
expect(med.stockAdjustment).toBe(0);
expect(med.lastStockCorrectionAt).toBeTruthy();
});
it("should preserve stockAdjustment when only non-stock fields change via PUT", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Preserve Adj Med",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
const medId = createResponse.json().id;
// Set stock adjustment
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -5 },
});
// Edit only non-stock fields (name, notes)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Renamed Preserve Med",
notes: "Updated notes",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 30,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
});
// stockAdjustment should be preserved
const getMeds = await app.inject({ method: "GET", url: "/medications" });
const med = getMeds.json().find((m: any) => m.id === medId);
expect(med.name).toBe("Renamed Preserve Med");
expect(med.stockAdjustment).toBe(-5);
});
it("should not count phantom consumption in planner after stock correction", async () => {
// Create medication: 1 pack × 14 blisters × 14 pills = 196 pills total
// Schedule: 1 pill daily starting far in the past
const farPast = new Date("2024-01-01T08:00:00.000Z");
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Planner Phantom Med",
packCount: 1,
blistersPerPack: 14,
pillsPerBlister: 14,
looseTablets: 0,
blisters: [{ usage: 1, every: 1, start: farPast.toISOString() }],
},
});
const medId = createResponse.json().id;
// Correct stock to 113 pills (196 base - 83 = 113)
await app.inject({
method: "PATCH",
url: `/medications/${medId}/stock-adjustment`,
payload: { stockAdjustment: -83 },
});
// Query planner immediately - stock should be ~113 (not reduced by phantom dose)
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const nextWeek = new Date();
nextWeek.setDate(nextWeek.getDate() + 7);
const response = await app.inject({
method: "POST",
url: "/medications/usage",
payload: {
startDate: tomorrow.toISOString(),
endDate: nextWeek.toISOString(),
},
});
expect(response.statusCode).toBe(200);
const data = response.json();
const med = data.find((m: any) => m.medicationId === medId);
expect(med).toBeDefined();
// Total should be very close to 113 (not 112 or lower from phantom consumption)
// Allow up to 1 pill of natural consumption (test runs fast, but at most 1 day could pass)
expect(med.totalPills).toBeGreaterThanOrEqual(112);
expect(med.totalPills).toBeLessThanOrEqual(113);
});
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Real Export/Import Routes Tests // Real Export/Import Routes Tests
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -1916,4 +2214,250 @@ describe("E2E Tests with Real Routes", () => {
expect(medsResponse.json()[0].packCount).toBe(10); expect(medsResponse.json()[0].packCount).toBe(10);
}); });
}); });
// ---------------------------------------------------------------------------
// Package Type (bottle vs blister) Tests
// ---------------------------------------------------------------------------
describe("Package type handling (bottle vs blister)", () => {
const bottleMedication = {
name: "Vitamin D Drops",
packageType: "bottle",
packCount: 0,
blistersPerPack: 1,
pillsPerBlister: 1,
looseTablets: 120,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
};
const blisterMedication = {
name: "Aspirin Blister",
packageType: "blister",
packCount: 2,
blistersPerPack: 3,
pillsPerBlister: 10,
looseTablets: 5,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
};
it("should create and return bottle type medication", async () => {
const response = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data.packageType).toBe("bottle");
expect(data.looseTablets).toBe(120);
});
it("should return packageType in shared schedule for bottle type", async () => {
// Create bottle medication with takenBy
await app.inject({
method: "POST",
url: "/medications",
payload: { ...bottleMedication, takenBy: ["Daniel"] },
});
// Create share token
const shareResponse = await app.inject({
method: "POST",
url: "/share",
payload: { takenBy: "Daniel", scheduleDays: 30 },
});
expect(shareResponse.statusCode).toBe(200);
const { token } = shareResponse.json();
// Get shared schedule
const scheduleResponse = await app.inject({
method: "GET",
url: `/share/${token}`,
});
expect(scheduleResponse.statusCode).toBe(200);
const data = scheduleResponse.json();
expect(data.medications).toHaveLength(1);
expect(data.medications[0].packageType).toBe("bottle");
// Bottle totalPills = looseTablets + stockAdjustment (no blister math)
expect(data.medications[0].totalPills).toBe(120);
});
it("should calculate correct totalPills for shared blister medication", async () => {
await app.inject({
method: "POST",
url: "/medications",
payload: { ...blisterMedication, takenBy: ["Daniel"] },
});
const shareResponse = await app.inject({
method: "POST",
url: "/share",
payload: { takenBy: "Daniel", scheduleDays: 30 },
});
const { token } = shareResponse.json();
const scheduleResponse = await app.inject({
method: "GET",
url: `/share/${token}`,
});
expect(scheduleResponse.statusCode).toBe(200);
const data = scheduleResponse.json();
expect(data.medications).toHaveLength(1);
expect(data.medications[0].packageType).toBe("blister");
// Blister totalPills = 2 * 3 * 10 + 5 = 65
expect(data.medications[0].totalPills).toBe(65);
});
it("should calculate correct refill totalPillsAdded for bottle type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
const medId = createResponse.json().id;
// Refill bottle: only loosePillsAdded matters, packs should add 0 pills
const refillResponse = await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 0, loosePillsAdded: 30 },
});
expect(refillResponse.statusCode).toBe(200);
const data = refillResponse.json();
expect(data.refill.totalPillsAdded).toBe(30);
// newStock.totalPills should be looseTablets only (no blister math)
expect(data.newStock.totalPills).toBe(150); // 120 + 30
});
it("should calculate correct refill totalPillsAdded for blister type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: blisterMedication,
});
const medId = createResponse.json().id;
// Refill blister: 1 pack = 3 blisters * 10 pills = 30 pills + 5 loose
const refillResponse = await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 1, loosePillsAdded: 5 },
});
expect(refillResponse.statusCode).toBe(200);
const data = refillResponse.json();
expect(data.refill.totalPillsAdded).toBe(35); // 1*30 + 5
});
it("should return correct totalPillsAdded in refill history for bottle type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
const medId = createResponse.json().id;
// Add refill
await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 0, loosePillsAdded: 25 },
});
// Get refill history
const historyResponse = await app.inject({
method: "GET",
url: `/medications/${medId}/refills`,
});
expect(historyResponse.statusCode).toBe(200);
const refills = historyResponse.json();
expect(refills).toHaveLength(1);
// For bottle type, totalPillsAdded = loosePillsAdded only
expect(refills[0].totalPillsAdded).toBe(25);
});
it("should export and import bottle type medication correctly", async () => {
// Create bottle medication
await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
// Export
const exportResponse = await app.inject({
method: "GET",
url: "/export",
});
expect(exportResponse.statusCode).toBe(200);
const exportData = exportResponse.json();
expect(exportData.medications).toHaveLength(1);
expect(exportData.medications[0].inventory.packageType).toBe("bottle");
expect(exportData.medications[0].inventory.looseTablets).toBe(120);
// Clear and re-import
await clearData(testClient);
await testClient.execute(
"INSERT INTO users (id, username, auth_provider) VALUES (999999999, '__anonymous__', 'anonymous')"
);
const importResponse = await app.inject({
method: "POST",
url: "/import",
payload: exportData,
});
expect(importResponse.statusCode).toBe(200);
expect(importResponse.json().success).toBe(true);
// Verify imported medication has correct packageType
const medsResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(medsResponse.json()).toHaveLength(1);
const med = medsResponse.json()[0];
expect(med.name).toBe("Vitamin D Drops");
expect(med.packageType).toBe("bottle");
expect(med.looseTablets).toBe(120);
});
it("should default to blister when importing without packageType", async () => {
const importData = {
version: "1.0",
exportedAt: new Date().toISOString(),
medications: [
{
_exportId: "med-1",
name: "Old Export Med",
inventory: { packCount: 2, blistersPerPack: 3, pillsPerBlister: 10, looseTablets: 0 },
schedules: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
],
};
const importResponse = await app.inject({
method: "POST",
url: "/import",
payload: importData,
});
expect(importResponse.statusCode).toBe(200);
const medsResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(medsResponse.json()).toHaveLength(1);
expect(medsResponse.json()[0].packageType).toBe("blister");
});
});
}); });
+190
View File
@@ -365,6 +365,196 @@ describe("Integration Tests", () => {
}); });
}); });
// ---------------------------------------------------------------------------
// Dose ID Migration on Schedule Changes
// ---------------------------------------------------------------------------
describe("Dose ID migration when schedule changes", () => {
it("should migrate dose IDs when weekly start day changes", async () => {
// Create a weekly medication starting Friday Oct 17
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Weekly Med",
blisters: [{ usage: 1, every: 7, start: "2025-10-17T08:00:00" }],
},
});
const medId = createRes.json().id;
// Mark doses for Fridays (Oct 17, Oct 24, Oct 31)
const fri17 = new Date(2025, 9, 17).getTime(); // Oct 17
const fri24 = new Date(2025, 9, 24).getTime(); // Oct 24
const fri31 = new Date(2025, 9, 31).getTime(); // Oct 31
for (const ts of [fri17, fri24, fri31]) {
await app.inject({
method: "POST",
url: "/doses/taken",
payload: { doseId: `${medId}-0-${ts}` },
});
}
// Verify 3 doses exist
const before = await testClient.execute({
sql: `SELECT COUNT(*) as count FROM dose_tracking WHERE dose_id LIKE ?`,
args: [`${medId}-%`],
});
expect(before.rows[0].count).toBe(3);
// Change start to Saturday Oct 18 (shifts all future and past IDs)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Weekly Med",
blisters: [{ usage: 1, every: 7, start: "2025-10-18T08:00:00" }],
},
});
// Doses should be migrated to Saturday dates
const sat18 = new Date(2025, 9, 18).getTime(); // Oct 18
const sat25 = new Date(2025, 9, 25).getTime(); // Oct 25
const nov1 = new Date(2025, 10, 1).getTime(); // Nov 1
const after = await testClient.execute({
sql: `SELECT dose_id FROM dose_tracking WHERE dose_id LIKE ? ORDER BY dose_id`,
args: [`${medId}-%`],
});
expect(after.rows.length).toBe(3);
const ids = after.rows.map((r: { dose_id: string }) => r.dose_id);
expect(ids).toContain(`${medId}-0-${sat18}`);
expect(ids).toContain(`${medId}-0-${sat25}`);
expect(ids).toContain(`${medId}-0-${nov1}`);
});
it("should migrate dose IDs with person suffix when schedule changes", async () => {
// Create weekly medication with takenBy person
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Person Med",
intakes: [{ usage: 1, every: 7, start: "2025-10-17T08:00:00", takenBy: "Alice" }],
},
});
const medId = createRes.json().id;
// Mark dose with person suffix
const fri17 = new Date(2025, 9, 17).getTime();
await app.inject({
method: "POST",
url: "/doses/taken",
payload: { doseId: `${medId}-0-${fri17}-Alice` },
});
// Change start day
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Person Med",
intakes: [{ usage: 1, every: 7, start: "2025-10-18T08:00:00", takenBy: "Alice" }],
},
});
// Dose should be migrated with person suffix preserved
const sat18 = new Date(2025, 9, 18).getTime();
const after = await testClient.execute({
sql: `SELECT dose_id FROM dose_tracking WHERE dose_id LIKE ?`,
args: [`${medId}-%`],
});
expect(after.rows.length).toBe(1);
expect(after.rows[0].dose_id).toBe(`${medId}-0-${sat18}-Alice`);
});
it("should not migrate dose IDs when only time-of-day changes", async () => {
// Create daily medication at 08:00
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Daily Med",
blisters: [{ usage: 1, every: 1, start: "2025-10-17T08:00:00" }],
},
});
const medId = createRes.json().id;
// Mark dose
const oct17 = new Date(2025, 9, 17).getTime();
await app.inject({
method: "POST",
url: "/doses/taken",
payload: { doseId: `${medId}-0-${oct17}` },
});
// Change only time from 08:00 to 20:00 (same date)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Daily Med",
blisters: [{ usage: 1, every: 1, start: "2025-10-17T20:00:00" }],
},
});
// Dose ID should remain unchanged (dateOnlyMs is the same)
const after = await testClient.execute({
sql: `SELECT dose_id FROM dose_tracking WHERE dose_id LIKE ?`,
args: [`${medId}-%`],
});
expect(after.rows.length).toBe(1);
expect(after.rows[0].dose_id).toBe(`${medId}-0-${oct17}`);
});
it("should migrate dose IDs when interval changes from daily to every-other-day", async () => {
// Create daily medication starting Oct 17
const createRes = await app.inject({
method: "POST",
url: "/medications",
payload: {
name: "Interval Med",
blisters: [{ usage: 1, every: 1, start: "2025-10-17T08:00:00" }],
},
});
const medId = createRes.json().id;
// Mark doses for Oct 17, 18, 19
const oct17 = new Date(2025, 9, 17).getTime();
const oct18 = new Date(2025, 9, 18).getTime();
const oct19 = new Date(2025, 9, 19).getTime();
for (const ts of [oct17, oct18, oct19]) {
await app.inject({
method: "POST",
url: "/doses/taken",
payload: { doseId: `${medId}-0-${ts}` },
});
}
// Change to every 2 days (Oct 17, 19, 21, ...)
await app.inject({
method: "PUT",
url: `/medications/${medId}`,
payload: {
name: "Interval Med",
blisters: [{ usage: 1, every: 2, start: "2025-10-17T08:00:00" }],
},
});
// Oct 17 stays (matches), Oct 18 → Oct 19 (nearest), Oct 19 → no match (already used)
// Actually: Oct 17 is exact match (no migration needed), Oct 18 maps to Oct 19 (within 1 day = half of 2),
// Oct 19 was the original schedule date but the new schedule also has Oct 19,
// which was already taken by Oct 18's migration
const after = await testClient.execute({
sql: `SELECT dose_id FROM dose_tracking WHERE dose_id LIKE ? ORDER BY dose_id`,
args: [`${medId}-%`],
});
// We should have at least the doses that could be mapped
expect(after.rows.length).toBeGreaterThanOrEqual(2);
});
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Share Link + Dose Tracking Integration // Share Link + Dose Tracking Integration
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+2 -2
View File
@@ -6,6 +6,7 @@
import { existsSync, mkdirSync } from "node:fs"; import { existsSync, mkdirSync } from "node:fs";
import { resolve } from "node:path"; import { resolve } from "node:path";
import type { CookieSerializeOptions } from "@fastify/cookie"; import type { CookieSerializeOptions } from "@fastify/cookie";
import { getDataDir } from "../db/db-utils.js";
/** /**
* Parse comma-separated CORS origins string * Parse comma-separated CORS origins string
@@ -81,8 +82,7 @@ export function buildAppConfig(options: AppConfigOptions): AppConfig {
* Ensure images directory exists * Ensure images directory exists
*/ */
export function ensureImagesDirectory(cwd?: string): string { export function ensureImagesDirectory(cwd?: string): string {
const basePath = cwd || process.cwd(); const imagesDir = resolve(getDataDir(cwd), "images");
const imagesDir = resolve(basePath, "data/images");
if (!existsSync(imagesDir)) { if (!existsSync(imagesDir)) {
mkdirSync(imagesDir, { recursive: true }); mkdirSync(imagesDir, { recursive: true });
} }
+2
View File
@@ -9,6 +9,8 @@ services:
- ./data:/app/data - ./data:/app/data
env_file: env_file:
- .env - .env
environment:
- DATA_DIR=/app/data
ports: ports:
- "3000:3000" - "3000:3000"
security_opt: security_opt:
+3
View File
@@ -7,6 +7,7 @@ services:
environment: environment:
- PUID=${PUID:-1000} - PUID=${PUID:-1000}
- PGID=${PGID:-1000} - PGID=${PGID:-1000}
- DATA_DIR=/app/data
volumes: volumes:
- ./data:/app/data - ./data:/app/data
ports: ports:
@@ -34,6 +35,8 @@ services:
frontend: frontend:
image: ghcr.io/danielvolz/medassist-ng-frontend:latest image: ghcr.io/danielvolz/medassist-ng-frontend:latest
container_name: medassist-ng-frontend container_name: medassist-ng-frontend
environment:
- BACKEND_URL=backend:3000
ports: ports:
- "4174:8080" - "4174:8080"
networks: networks:
+9 -3
View File
@@ -32,8 +32,14 @@ RUN npm run build
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
FROM nginxinc/nginx-unprivileged:1.27-alpine AS runner FROM nginxinc/nginx-unprivileged:1.27-alpine AS runner
# Copy custom nginx config (must listen on 8080, not 80) # Redirect envsubst output to /tmp (writable under read_only: true)
COPY nginx.conf /etc/nginx/conf.d/default.conf # and update nginx main config to include from there instead of /etc/nginx/conf.d/
ENV NGINX_ENVSUBST_OUTPUT_DIR=/tmp
RUN sed -i 's|include /etc/nginx/conf.d/\*.conf;|include /tmp/default.conf;|' /etc/nginx/nginx.conf
# Copy custom nginx config as template for envsubst processing
# nginx-unprivileged automatically substitutes env vars in .template files
COPY nginx.conf /etc/nginx/templates/default.conf.template
# Copy built static files with correct ownership (nginx user = uid 101) # Copy built static files with correct ownership (nginx user = uid 101)
COPY --from=builder --chown=101:101 /app/dist /usr/share/nginx/html COPY --from=builder --chown=101:101 /app/dist /usr/share/nginx/html
@@ -44,5 +50,5 @@ EXPOSE 8080
# Already runs as non-root (nginx user, uid 101) # Already runs as non-root (nginx user, uid 101)
USER nginx USER nginx
# Start nginx # Start nginx (entrypoint processes templates automatically)
CMD ["nginx", "-g", "daemon off;"] CMD ["nginx", "-g", "daemon off;"]
+8 -1
View File
@@ -20,7 +20,14 @@ server {
} }
location /api/ { location /api/ {
proxy_pass http://medassist-ng-backend:3000/; # Use variable for runtime DNS resolution (nginx resolves at startup by default)
# Docker embedded DNS (127.0.0.11) with 10s cache
resolver 127.0.0.11 valid=10s ipv6=off;
set $backend_upstream ${BACKEND_URL};
# Strip /api prefix (nginx doesn't auto-rewrite when using variables in proxy_pass)
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://$backend_upstream;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+12 -19
View File
@@ -1,12 +1,12 @@
{ {
"name": "medassist-ng-frontend", "name": "medassist-ng-frontend",
"version": "1.7.1", "version": "1.8.8",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "medassist-ng-frontend", "name": "medassist-ng-frontend",
"version": "1.7.1", "version": "1.8.8",
"dependencies": { "dependencies": {
"i18next": "^24.2.2", "i18next": "^24.2.2",
"i18next-browser-languagedetector": "^8.0.4", "i18next-browser-languagedetector": "^8.0.4",
@@ -133,7 +133,6 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.27.1", "@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5", "@babel/generator": "^7.28.5",
@@ -655,7 +654,6 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=18" "node": ">=18"
}, },
@@ -699,7 +697,6 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=18" "node": ">=18"
} }
@@ -1647,7 +1644,8 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true, "dev": true,
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/@types/babel__core": { "node_modules/@types/babel__core": {
"version": "7.20.5", "version": "7.20.5",
@@ -1739,7 +1737,6 @@
"integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==", "integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/prop-types": "*", "@types/prop-types": "*",
"csstype": "^3.2.2" "csstype": "^3.2.2"
@@ -1751,7 +1748,6 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"peerDependencies": { "peerDependencies": {
"@types/react": "^18.0.0" "@types/react": "^18.0.0"
} }
@@ -1958,6 +1954,7 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=8" "node": ">=8"
} }
@@ -1968,6 +1965,7 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=10" "node": ">=10"
}, },
@@ -2054,7 +2052,6 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"baseline-browser-mapping": "^2.9.0", "baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759", "caniuse-lite": "^1.0.30001759",
@@ -2238,7 +2235,8 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true, "dev": true,
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/electron-to-chromium": { "node_modules/electron-to-chromium": {
"version": "1.5.267", "version": "1.5.267",
@@ -2468,7 +2466,6 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.26.10" "@babel/runtime": "^7.26.10"
}, },
@@ -2558,7 +2555,6 @@
"integrity": "sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==", "integrity": "sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@acemir/cssom": "^0.9.28", "@acemir/cssom": "^0.9.28",
"@asamuzakjp/dom-selector": "^6.7.6", "@asamuzakjp/dom-selector": "^6.7.6",
@@ -2647,6 +2643,7 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"lz-string": "bin/bin.js" "lz-string": "bin/bin.js"
} }
@@ -2796,7 +2793,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -2886,6 +2882,7 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"ansi-regex": "^5.0.1", "ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0", "ansi-styles": "^5.0.0",
@@ -2910,7 +2907,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0" "loose-envify": "^1.1.0"
}, },
@@ -2923,7 +2919,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"scheduler": "^0.23.2" "scheduler": "^0.23.2"
@@ -2963,7 +2958,8 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true, "dev": true,
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/react-refresh": { "node_modules/react-refresh": {
"version": "0.17.0", "version": "0.17.0",
@@ -3277,7 +3273,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true, "devOptional": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
@@ -3323,7 +3318,6 @@
"integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==", "integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.27.0", "esbuild": "^0.27.0",
"fdir": "^6.5.0", "fdir": "^6.5.0",
@@ -3399,7 +3393,6 @@
"integrity": "sha512-FQMeF0DJdWY0iOnbv466n/0BudNdKj1l5jYgl5JVTwjSsZSlqyXFt/9+1sEyhR6CLowbZpV7O1sCHrzBhucKKg==", "integrity": "sha512-FQMeF0DJdWY0iOnbv466n/0BudNdKj1l5jYgl5JVTwjSsZSlqyXFt/9+1sEyhR6CLowbZpV7O1sCHrzBhucKKg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@vitest/expect": "4.0.17", "@vitest/expect": "4.0.17",
"@vitest/mocker": "4.0.17", "@vitest/mocker": "4.0.17",
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "medassist-ng-frontend", "name": "medassist-ng-frontend",
"private": true, "private": true,
"version": "1.7.1", "version": "1.8.8",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+32 -56
View File
@@ -3,9 +3,8 @@ import { useTranslation } from "react-i18next";
import { FRONTEND_VERSION, GITHUB_URL } from "../App"; import { FRONTEND_VERSION, GITHUB_URL } from "../App";
interface UpdateCheckResult { interface UpdateCheckResult {
status: "checking" | "up-to-date" | "update-available" | "error"; status: "up-to-date" | "update-available" | "error";
latestVersion?: string; latestVersion?: string;
lastChecked?: string;
} }
interface AboutModalProps { interface AboutModalProps {
@@ -15,52 +14,37 @@ interface AboutModalProps {
export default function AboutModal({ isOpen, onClose }: AboutModalProps) { export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [backendVersion, setBackendVersion] = useState<string | null>(null); const [isChecking, setIsChecking] = useState(false);
const [updateCheckResult, setUpdateCheckResult] = useState<UpdateCheckResult | null>(null); const [updateCheckResult, setUpdateCheckResult] = useState<UpdateCheckResult | null>(null);
// Fetch backend version and cached update result on mount // Reset check result when modal opens so stale results are never shown
useEffect(() => { useEffect(() => {
if (!isOpen) return; if (isOpen) {
setUpdateCheckResult(null);
// Fetch backend version
fetch("/api/health")
.then((res) => res.json())
.then((data) => setBackendVersion(data.version || "unknown"))
.catch(() => setBackendVersion("unknown"));
// Load cached update check result
const cached = sessionStorage.getItem("updateCheckResult");
if (cached) {
try {
const parsed = JSON.parse(cached);
if (parsed && typeof parsed === "object") {
setUpdateCheckResult(parsed);
}
} catch {
// ignore
}
} }
}, [isOpen]); }, [isOpen]);
async function checkForUpdates() { async function checkForUpdates() {
setUpdateCheckResult({ status: "checking" }); setIsChecking(true);
const minDelay = new Promise((resolve) => setTimeout(resolve, 1000));
try { try {
const res = await fetch(`https://api.github.com/repos/DanielVolz/medassist-ng/releases/latest`); const [res] = await Promise.all([
fetch(`https://api.github.com/repos/DanielVolz/medassist-ng/releases/latest`),
minDelay,
]);
if (!res.ok) throw new Error("Failed to fetch"); if (!res.ok) throw new Error("Failed to fetch");
const data = await res.json(); const data = await res.json();
const latestVersion = (data.tag_name || "").replace(/^v/, ""); const latestVersion = (data.tag_name || "").replace(/^v/, "");
const currentVersion = FRONTEND_VERSION.replace(/^v/, ""); const currentVersion = FRONTEND_VERSION.replace(/^v/, "");
const isUpToDate = latestVersion === currentVersion; const isUpToDate = latestVersion === currentVersion;
const result: UpdateCheckResult = { setUpdateCheckResult({
status: isUpToDate ? "up-to-date" : "update-available", status: isUpToDate ? "up-to-date" : "update-available",
latestVersion, latestVersion,
lastChecked: new Date().toISOString(), });
};
setUpdateCheckResult(result);
// Cache the result
sessionStorage.setItem("updateCheckResult", JSON.stringify(result));
} catch { } catch {
setUpdateCheckResult({ status: "error" }); setUpdateCheckResult({ status: "error" });
} finally {
setIsChecking(false);
} }
} }
@@ -74,32 +58,27 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
</button> </button>
<div className="about-header"> <div className="about-header">
<div className="about-logo"> <div className="about-logo">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"> <img src="/favicon.svg" alt="MedAssist-ng" />
<path d="M19.5 12c0 4.14-3.36 7.5-7.5 7.5S4.5 16.14 4.5 12 7.86 4.5 12 4.5s7.5 3.36 7.5 7.5z" />
<path d="M12 8v4l2.5 2.5" />
<path d="M9 2h6M12 2v2" />
</svg>
</div> </div>
<h2>{t("about.appName", "MedAssist-ng")}</h2> <h2>{t("about.appName", "MedAssist-ng")}</h2>
<p className="about-tagline">{t("about.description", "Personal medication tracking and reminder app")}</p> <p className="about-tagline">{t("about.description", "Personal medication tracking and reminder app")}</p>
</div> </div>
<div className="about-versions"> <div className="about-versions">
<div className="about-version-row"> <div className="about-version-row">
<span className="about-version-label">{t("about.frontendVersion", "Frontend")}</span> <span className="about-version-label">{t("about.version", "Version")}</span>
<span className="about-version-value">{FRONTEND_VERSION}</span> <a
</div> href={`${GITHUB_URL}/releases/tag/v${FRONTEND_VERSION}`}
<div className="about-version-row"> target="_blank"
<span className="about-version-label">{t("about.backendVersion", "Backend")}</span> rel="noopener noreferrer"
<span className="about-version-value">{backendVersion || "..."}</span> className="about-version-value about-version-link"
>
{FRONTEND_VERSION}
</a>
</div> </div>
</div> </div>
<div className="about-update-section"> <div className="about-update-section">
<button <button className="about-update-btn" onClick={checkForUpdates} disabled={isChecking}>
className="about-update-btn" {isChecking ? (
onClick={checkForUpdates}
disabled={updateCheckResult?.status === "checking"}
>
{updateCheckResult?.status === "checking" ? (
<> <>
<span className="spinner-small"></span> <span className="spinner-small"></span>
{t("about.checking", "Checking...")} {t("about.checking", "Checking...")}
@@ -116,14 +95,14 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
</> </>
)} )}
</button> </button>
{updateCheckResult && updateCheckResult.status !== "checking" && ( {updateCheckResult && (
<div className={`about-update-result ${updateCheckResult.status}`}> <div className={`about-update-result ${updateCheckResult.status}`}>
{updateCheckResult.status === "up-to-date" && ( {updateCheckResult.status === "up-to-date" && (
<span className="update-status-text"> {t("about.upToDate", "You are up to date!")}</span> <span className="update-status-text">&#10003; {t("about.upToDate", "You are up to date!")}</span>
)} )}
{updateCheckResult.status === "update-available" && ( {updateCheckResult.status === "update-available" && (
<span className="update-status-text"> <span className="update-status-text">
{t("about.updateAvailable", "Update available")}:{" "} &#11014; {t("about.updateAvailable", "Update available")}:{" "}
<strong>v{updateCheckResult.latestVersion}</strong> <strong>v{updateCheckResult.latestVersion}</strong>
<a <a
href={`${GITHUB_URL}/releases/latest`} href={`${GITHUB_URL}/releases/latest`}
@@ -136,11 +115,8 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
</span> </span>
)} )}
{updateCheckResult.status === "error" && ( {updateCheckResult.status === "error" && (
<span className="update-status-text"> {t("about.checkFailed", "Could not check for updates")}</span> <span className="update-status-text">
)} &#9888; {t("about.checkFailed", "Could not check for updates")}
{updateCheckResult.lastChecked && (
<span className="update-last-checked">
{t("about.lastChecked", "Last checked")}: {new Date(updateCheckResult.lastChecked).toLocaleString()}
</span> </span>
)} )}
</div> </div>
+75 -9
View File
@@ -1,10 +1,11 @@
/** /**
* AppHeader - Main application header with navigation and user menu * AppHeader - Main application header with navigation and user menu
*/ */
import { useEffect, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom"; import { useLocation, useNavigate } from "react-router-dom";
import { useUnsavedChanges } from "../context"; import { useUnsavedChanges } from "../context";
import type { ThemePreference } from "../hooks";
import { useTheme } from "../hooks"; import { useTheme } from "../hooks";
import { useAuth } from "./Auth"; import { useAuth } from "./Auth";
@@ -19,9 +20,25 @@ export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
const location = useLocation(); const location = useLocation();
const currentPath = location.pathname; const currentPath = location.pathname;
const { user, authState, logout } = useAuth(); const { user, authState, logout } = useAuth();
const { theme, toggleTheme } = useTheme(); const { theme, themePreference, setThemePreference } = useTheme();
const { confirmNavigation } = useUnsavedChanges(); const { confirmNavigation } = useUnsavedChanges();
// Theme dropdown state
const [themeMenuOpen, setThemeMenuOpen] = useState(false);
const themeMenuRef = useRef<HTMLDivElement>(null);
// Close theme dropdown when clicking outside
useEffect(() => {
if (!themeMenuOpen) return;
const handleClickOutside = (e: MouseEvent) => {
if (themeMenuRef.current && !themeMenuRef.current.contains(e.target as Node)) {
setThemeMenuOpen(false);
}
};
document.addEventListener("click", handleClickOutside);
return () => document.removeEventListener("click", handleClickOutside);
}, [themeMenuOpen]);
// Safe navigation that checks for unsaved changes first // Safe navigation that checks for unsaved changes first
const safeNavigate = async (path: string) => { const safeNavigate = async (path: string) => {
if (await confirmNavigation()) { if (await confirmNavigation()) {
@@ -94,13 +111,62 @@ export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
</button> </button>
)} )}
<button <div className={`theme-menu ${themeMenuOpen ? "open" : ""}`} ref={themeMenuRef}>
className="icon-btn" <button className="icon-btn" onClick={() => setThemeMenuOpen(!themeMenuOpen)} title={t("theme.title")}>
onClick={toggleTheme} {theme === "dark" ? "🌙" : "☀️"}
title={theme === "dark" ? t("tooltips.lightMode") : t("tooltips.darkMode")} </button>
> <div className="theme-dropdown">
{theme === "dark" ? "☀️" : "🌙"} <button
</button> className={`theme-dropdown-item${themePreference === "light" ? " active" : ""}`}
onClick={() => {
setThemePreference("light");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" />
<line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" />
<line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</svg>
{t("theme.light")}
{themePreference === "light" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "dark" ? " active" : ""}`}
onClick={() => {
setThemePreference("dark");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
{t("theme.dark")}
{themePreference === "dark" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "system" ? " active" : ""}`}
onClick={() => {
setThemePreference("system");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>
{t("theme.system")}
{themePreference === "system" && <span className="theme-check"></span>}
</button>
</div>
</div>
{authState?.authEnabled && user && ( {authState?.authEnabled && user && (
<div className={`user-menu ${userDropdownOpen ? "open" : ""}`}> <div className={`user-menu ${userDropdownOpen ? "open" : ""}`}>
<button className="user-menu-btn" onClick={() => setUserDropdownOpen(!userDropdownOpen)}> <button className="user-menu-btn" onClick={() => setUserDropdownOpen(!userDropdownOpen)}>
+104 -18
View File
@@ -2,7 +2,7 @@
// SharedSchedule Component - Public view for shared schedules // SharedSchedule Component - Public view for shared schedules
// ============================================================================= // =============================================================================
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import type { ExpiredLinkData, SharedScheduleData } from "../types"; import type { ExpiredLinkData, SharedScheduleData } from "../types";
@@ -24,23 +24,60 @@ export function SharedSchedule() {
const [lightboxImage, setLightboxImage] = useState<{ url: string; name: string } | null>(null); const [lightboxImage, setLightboxImage] = useState<{ url: string; name: string } | null>(null);
const [showPastDays, setShowPastDays] = useState(false); const [showPastDays, setShowPastDays] = useState(false);
const [showFutureDays, setShowFutureDays] = useState(false); const [showFutureDays, setShowFutureDays] = useState(false);
const [theme, setTheme] = useState<"light" | "dark">(() => {
// Theme preference: light, dark, or system
type ThemePreference = "light" | "dark" | "system";
const [themePreference, setThemePreference] = useState<ThemePreference>(() => {
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
return (localStorage.getItem("theme") as "light" | "dark") || "dark"; const stored = localStorage.getItem("theme") as ThemePreference | null;
if (stored === "light" || stored === "dark" || stored === "system") return stored;
} }
return "dark"; return "dark";
}); });
// Apply theme to document function getSystemTheme(): "light" | "dark" {
useEffect(() => { if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: light)").matches) {
document.documentElement.setAttribute("data-theme", theme); return "light";
localStorage.setItem("theme", theme); }
}, [theme]); return "dark";
function toggleTheme() {
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
} }
const resolvedTheme = themePreference === "system" ? getSystemTheme() : themePreference;
// Apply resolved theme to document
useEffect(() => {
document.documentElement.setAttribute("data-theme", resolvedTheme);
localStorage.setItem("theme", themePreference);
}, [themePreference, resolvedTheme]);
// Listen for system theme changes when preference is "system"
useEffect(() => {
if (themePreference !== "system") return;
const mq = window.matchMedia?.("(prefers-color-scheme: light)");
if (!mq) return;
const handler = () => {
const resolved = mq.matches ? "light" : "dark";
document.documentElement.setAttribute("data-theme", resolved);
};
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, [themePreference]);
// Theme dropdown state
const [themeMenuOpen, setThemeMenuOpen] = useState(false);
const themeMenuRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!themeMenuOpen) return;
const handleClickOutside = (e: MouseEvent) => {
if (themeMenuRef.current && !themeMenuRef.current.contains(e.target as Node)) {
setThemeMenuOpen(false);
}
};
document.addEventListener("click", handleClickOutside);
return () => document.removeEventListener("click", handleClickOutside);
}, [themeMenuOpen]);
// Collapsed days state for SharedSchedule (token-specific localStorage) // Collapsed days state for SharedSchedule (token-specific localStorage)
const [manuallyCollapsedDays, setManuallyCollapsedDays] = useState<Set<string>>(new Set()); const [manuallyCollapsedDays, setManuallyCollapsedDays] = useState<Set<string>>(new Set());
const [manuallyExpandedDays, setManuallyExpandedDays] = useState<Set<string>>(new Set()); const [manuallyExpandedDays, setManuallyExpandedDays] = useState<Set<string>>(new Set());
@@ -522,13 +559,62 @@ export function SharedSchedule() {
💊 {t("share.scheduleFor")} {data.takenBy} 💊 {t("share.scheduleFor")} {data.takenBy}
</h1> </h1>
<div className="shared-schedule-header-actions"> <div className="shared-schedule-header-actions">
<button <div className={`theme-menu ${themeMenuOpen ? "open" : ""}`} ref={themeMenuRef}>
className="icon-btn" <button className="icon-btn" onClick={() => setThemeMenuOpen(!themeMenuOpen)} title={t("theme.title")}>
onClick={toggleTheme} {resolvedTheme === "dark" ? "🌙" : "☀️"}
title={theme === "dark" ? t("tooltips.lightMode") : t("tooltips.darkMode")} </button>
> <div className="theme-dropdown">
{theme === "dark" ? "☀️" : "🌙"} <button
</button> className={`theme-dropdown-item${themePreference === "light" ? " active" : ""}`}
onClick={() => {
setThemePreference("light");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" />
<line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" />
<line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</svg>
{t("theme.light")}
{themePreference === "light" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "dark" ? " active" : ""}`}
onClick={() => {
setThemePreference("dark");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
{t("theme.dark")}
{themePreference === "dark" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "system" ? " active" : ""}`}
onClick={() => {
setThemePreference("system");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>
{t("theme.system")}
{themePreference === "system" && <span className="theme-check"></span>}
</button>
</div>
</div>
</div> </div>
<p className="shared-schedule-period"> <p className="shared-schedule-period">
{t("share.period")}:{" "} {t("share.period")}:{" "}
+37 -26
View File
@@ -278,7 +278,8 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
systemLocale, systemLocale,
settingsHook.settings.reminderDaysBefore, settingsHook.settings.reminderDaysBefore,
settingsHook.settings.stockCalculationMode, settingsHook.settings.stockCalculationMode,
doses.takenDoses doses.takenDoses,
doses.takenDoseTimestamps
), ),
[ [
medications.meds, medications.meds,
@@ -287,6 +288,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
settingsHook.settings.reminderDaysBefore, settingsHook.settings.reminderDaysBefore,
settingsHook.settings.stockCalculationMode, settingsHook.settings.stockCalculationMode,
doses.takenDoses, doses.takenDoses,
doses.takenDoseTimestamps,
] ]
); );
@@ -351,38 +353,47 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
const groupedSchedule = useMemo(() => { const groupedSchedule = useMemo(() => {
const days = new Map<string, { dateStr: string; date: Date; isPast: boolean; meds: Map<string, DayMedEntry> }>(); const days = new Map<string, { dateStr: string; date: Date; isPast: boolean; meds: Map<string, DayMedEntry> }>();
schedule.events.slice(0, 2000).forEach((event) => { // Limit past events to scheduleDays window to avoid overwhelming the UI.
const day = days.get(event.dateStr) ?? { // Without this, medications with start dates far in the past generate thousands
dateStr: event.dateStr, // of events that fill the display budget and push out today/future events.
date: new Date(event.when), const pastCutoff = new Date();
isPast: event.isPast, pastCutoff.setDate(pastCutoff.getDate() - scheduleDays);
meds: new Map(), pastCutoff.setHours(0, 0, 0, 0);
}; const pastCutoffMs = pastCutoff.getTime();
const medEntry = day.meds.get(event.medName) ?? { schedule.events
medName: event.medName, .filter((e) => !e.isPast || e.when >= pastCutoffMs)
total: 0, .forEach((event) => {
doses: [], const day = days.get(event.dateStr) ?? {
lastWhen: event.when, dateStr: event.dateStr,
}; date: new Date(event.when),
medEntry.total += event.usage; isPast: event.isPast,
medEntry.doses.push({ meds: new Map(),
id: event.id, };
timeStr: event.timeStr, const medEntry = day.meds.get(event.medName) ?? {
when: event.when, medName: event.medName,
usage: event.usage, total: 0,
takenBy: event.takenBy ? [event.takenBy] : [], doses: [],
lastWhen: event.when,
};
medEntry.total += event.usage;
medEntry.doses.push({
id: event.id,
timeStr: event.timeStr,
when: event.when,
usage: event.usage,
takenBy: event.takenBy ? [event.takenBy] : [],
});
medEntry.lastWhen = Math.max(medEntry.lastWhen, event.when);
day.meds.set(event.medName, medEntry);
days.set(event.dateStr, day);
}); });
medEntry.lastWhen = Math.max(medEntry.lastWhen, event.when);
day.meds.set(event.medName, medEntry);
days.set(event.dateStr, day);
});
return Array.from(days.values()).map((d) => ({ return Array.from(days.values()).map((d) => ({
dateStr: d.dateStr, dateStr: d.dateStr,
date: d.date, date: d.date,
isPast: d.isPast, isPast: d.isPast,
meds: Array.from(d.meds.values()), meds: Array.from(d.meds.values()),
})); }));
}, [schedule.events]); }, [schedule.events, scheduleDays]);
const pastDays = useMemo(() => groupedSchedule.filter((d) => d.isPast), [groupedSchedule]); const pastDays = useMemo(() => groupedSchedule.filter((d) => d.isPast), [groupedSchedule]);
+1 -1
View File
@@ -14,7 +14,7 @@ export type { Settings, UseSettingsReturn } from "./useSettings";
export { useSettings } from "./useSettings"; export { useSettings } from "./useSettings";
export type { UseShareReturn } from "./useShare"; export type { UseShareReturn } from "./useShare";
export { useShare } from "./useShare"; export { useShare } from "./useShare";
export type { Theme, UseThemeReturn } from "./useTheme"; export type { Theme, ThemePreference, UseThemeReturn } from "./useTheme";
export { useTheme } from "./useTheme"; export { useTheme } from "./useTheme";
export type { UseUnsavedChangesWarningReturn } from "./useUnsavedChangesWarning"; export type { UseUnsavedChangesWarningReturn } from "./useUnsavedChangesWarning";
export { useUnsavedChangesWarning } from "./useUnsavedChangesWarning"; export { useUnsavedChangesWarning } from "./useUnsavedChangesWarning";
+92 -45
View File
@@ -2,11 +2,12 @@
// useDoses Hook - Dose tracking state and operations // useDoses Hook - Dose tracking state and operations
// ============================================================================= // =============================================================================
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
export interface UseDosesReturn { export interface UseDosesReturn {
takenDoses: Set<string>; takenDoses: Set<string>;
setTakenDoses: React.Dispatch<React.SetStateAction<Set<string>>>; setTakenDoses: React.Dispatch<React.SetStateAction<Set<string>>>;
takenDoseTimestamps: Map<string, number>;
dismissedDoses: Set<string>; dismissedDoses: Set<string>;
showClearMissedConfirm: boolean; showClearMissedConfirm: boolean;
setShowClearMissedConfirm: (show: boolean) => void; setShowClearMissedConfirm: (show: boolean) => void;
@@ -19,25 +20,39 @@ export interface UseDosesReturn {
export function useDoses(): UseDosesReturn { export function useDoses(): UseDosesReturn {
const [takenDoses, setTakenDoses] = useState<Set<string>>(new Set()); const [takenDoses, setTakenDoses] = useState<Set<string>>(new Set());
const [takenDoseTimestamps, setTakenDoseTimestamps] = useState<Map<string, number>>(new Map());
const [dismissedDoses, setDismissedDoses] = useState<Set<string>>(new Set()); const [dismissedDoses, setDismissedDoses] = useState<Set<string>>(new Set());
const [showClearMissedConfirm, setShowClearMissedConfirm] = useState(false); const [showClearMissedConfirm, setShowClearMissedConfirm] = useState(false);
// Track in-flight mutations to prevent polling from overwriting optimistic updates
const mutationInFlightRef = useRef(0);
// Load taken doses from server // Load taken doses from server
const loadTakenDoses = useCallback(async () => { const loadTakenDoses = useCallback(async () => {
// Skip polling while mutations are in-flight to prevent race conditions
// where a poll response with stale data overwrites optimistic updates
if (mutationInFlightRef.current > 0) return;
try { try {
const res = await fetch("/api/doses/taken", { credentials: "include" }); const res = await fetch("/api/doses/taken", { credentials: "include" });
if (res.ok) { if (res.ok) {
// Double-check no mutation started while we were fetching
if (mutationInFlightRef.current > 0) return;
const data = await res.json(); const data = await res.json();
const taken = new Set<string>(); const taken = new Set<string>();
const timestamps = new Map<string, number>();
const dismissed = new Set<string>(); const dismissed = new Set<string>();
for (const d of data.doses) { for (const d of data.doses) {
if (d.dismissed) { if (d.dismissed) {
dismissed.add(d.doseId); dismissed.add(d.doseId);
} else { } else {
taken.add(d.doseId); taken.add(d.doseId);
timestamps.set(d.doseId, d.takenAt);
} }
} }
setTakenDoses(taken); setTakenDoses(taken);
setTakenDoseTimestamps(timestamps);
setDismissedDoses(dismissed); setDismissedDoses(dismissed);
} }
// Don't reset on error - keep current state // Don't reset on error - keep current state
@@ -77,59 +92,91 @@ export function useDoses(): UseDosesReturn {
[takenDoses, getDoseId] [takenDoses, getDoseId]
); );
const markDoseTaken = useCallback(async (doseId: string) => { const markDoseTaken = useCallback(
// Optimistic update async (doseId: string) => {
setTakenDoses((prev) => { // Optimistic update
const next = new Set(prev); mutationInFlightRef.current++;
next.add(doseId);
return next;
});
// Send to server
try {
await fetch("/api/doses/taken", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ doseId }),
});
} catch {
// Revert on error
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
}
}, []);
const undoDoseTaken = useCallback(async (doseId: string) => {
// Optimistic update
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
// Send to server
try {
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
method: "DELETE",
credentials: "include",
});
} catch {
// Revert on error
setTakenDoses((prev) => { setTakenDoses((prev) => {
const next = new Set(prev); const next = new Set(prev);
next.add(doseId); next.add(doseId);
return next; return next;
}); });
} setTakenDoseTimestamps((prev) => {
}, []); const next = new Map(prev);
next.set(doseId, Date.now());
return next;
});
// Send to server
try {
await fetch("/api/doses/taken", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ doseId }),
});
} catch {
// Revert on error
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
setTakenDoseTimestamps((prev) => {
const next = new Map(prev);
next.delete(doseId);
return next;
});
} finally {
mutationInFlightRef.current--;
// Re-sync with server after mutation completes
loadTakenDoses();
}
},
[loadTakenDoses]
);
const undoDoseTaken = useCallback(
async (doseId: string) => {
// Optimistic update
mutationInFlightRef.current++;
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
setTakenDoseTimestamps((prev) => {
const next = new Map(prev);
next.delete(doseId);
return next;
});
// Send to server
try {
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
method: "DELETE",
credentials: "include",
});
} catch {
// Revert on error
setTakenDoses((prev) => {
const next = new Set(prev);
next.add(doseId);
return next;
});
} finally {
mutationInFlightRef.current--;
// Re-sync with server after mutation completes
loadTakenDoses();
}
},
[loadTakenDoses]
);
return { return {
takenDoses, takenDoses,
setTakenDoses, setTakenDoses,
takenDoseTimestamps,
dismissedDoses, dismissedDoses,
showClearMissedConfirm, showClearMissedConfirm,
setShowClearMissedConfirm, setShowClearMissedConfirm,
+3 -3
View File
@@ -1,6 +1,6 @@
import { useCallback, useState } from "react"; import { useCallback, useState } from "react";
import type { Coverage, FormState, Medication, RefillEntry } from "../types"; import type { Coverage, FormState, Medication, RefillEntry } from "../types";
import { getMedTotal } from "../types"; import { getMedTotal, getPackageSize } from "../types";
export interface UseRefillReturn { export interface UseRefillReturn {
// Refill state // Refill state
@@ -146,8 +146,8 @@ export function useRefill(): UseRefillReturn {
const desiredTotal = finalFullBlisters * selectedMed.pillsPerBlister + finalPartialPills; const desiredTotal = finalFullBlisters * selectedMed.pillsPerBlister + finalPartialPills;
// The "base" from DB structure (without any stockAdjustment) // The "base" from DB structure (without any stockAdjustment)
const baseTotal = // Use getPackageSize() which handles both blister and bottle types correctly
selectedMed.packCount * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + selectedMed.looseTablets; const baseTotal = getPackageSize(selectedMed);
// stockAdjustment = what we need to make getMedTotal() return desiredTotal // stockAdjustment = what we need to make getMedTotal() return desiredTotal
const newStockAdjustment = desiredTotal - baseTotal; const newStockAdjustment = desiredTotal - baseTotal;
+58 -10
View File
@@ -1,32 +1,80 @@
// ============================================================================= // =============================================================================
// useTheme Hook - Theme (dark/light mode) state management // useTheme Hook - Theme (dark/light/system mode) state management
// ============================================================================= // =============================================================================
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
export type Theme = "light" | "dark"; export type Theme = "light" | "dark";
export type ThemePreference = "light" | "dark" | "system";
export interface UseThemeReturn { export interface UseThemeReturn {
/** The resolved theme applied to the DOM ("light" | "dark") */
theme: Theme; theme: Theme;
/** The user's preference ("light" | "dark" | "system") */
themePreference: ThemePreference;
/** Set the theme preference */
setThemePreference: (pref: ThemePreference) => void;
/** Legacy toggle: cycles light → dark → system → light */
toggleTheme: () => void; toggleTheme: () => void;
} }
function getSystemTheme(): Theme {
if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: light)").matches) {
return "light";
}
return "dark";
}
function resolveTheme(pref: ThemePreference): Theme {
return pref === "system" ? getSystemTheme() : pref;
}
export function useTheme(): UseThemeReturn { export function useTheme(): UseThemeReturn {
const [theme, setTheme] = useState<Theme>(() => { const [themePreference, setThemePreferenceState] = useState<ThemePreference>(() => {
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
return (localStorage.getItem("theme") as Theme) || "dark"; const stored = localStorage.getItem("theme") as ThemePreference | null;
if (stored === "light" || stored === "dark" || stored === "system") return stored;
return "dark";
} }
return "dark"; return "dark";
}); });
useEffect(() => { const [theme, setTheme] = useState<Theme>(() => resolveTheme(themePreference));
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
}, [theme]);
const toggleTheme = useCallback(() => { // Apply resolved theme to DOM whenever preference or system theme changes
setTheme((prev) => (prev === "dark" ? "light" : "dark")); useEffect(() => {
const resolved = resolveTheme(themePreference);
setTheme(resolved);
document.documentElement.setAttribute("data-theme", resolved);
localStorage.setItem("theme", themePreference);
}, [themePreference]);
// Listen for system theme changes when preference is "system"
useEffect(() => {
if (themePreference !== "system") return;
const mq = window.matchMedia?.("(prefers-color-scheme: light)");
if (!mq) return;
const handler = () => {
const resolved = resolveTheme("system");
setTheme(resolved);
document.documentElement.setAttribute("data-theme", resolved);
};
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, [themePreference]);
const setThemePreference = useCallback((pref: ThemePreference) => {
setThemePreferenceState(pref);
}, []); }, []);
return { theme, toggleTheme }; const toggleTheme = useCallback(() => {
setThemePreferenceState((prev) => {
if (prev === "light") return "dark";
if (prev === "dark") return "system";
return "light";
});
}, []);
return { theme, themePreference, setThemePreference, toggleTheme };
} }
+9 -5
View File
@@ -176,7 +176,8 @@
"badge": "Vorrat planen", "badge": "Vorrat planen",
"from": "Von", "from": "Von",
"until": "Bis", "until": "Bis",
"includeUntilStart": "Verbrauch von heute bis Startdatum einrechnen", "includeUntilStart": "Aktuellen Verbrauch einrechnen",
"includeUntilStartTooltip": "Wenn aktiviert, werden die Pillen, die zwischen heute und dem gewählten Startdatum verbraucht werden, vom aktuellen Bestand abgezogen. So erhältst du ein genaueres Bild davon, wie viel du zu Beginn des Planungszeitraums tatsächlich noch übrig hast.",
"calculate": "Berechnen", "calculate": "Berechnen",
"calculating": "Wird berechnet...", "calculating": "Wird berechnet...",
"sendEmail": "📧 Per E-Mail senden", "sendEmail": "📧 Per E-Mail senden",
@@ -290,6 +291,12 @@
"lightMode": "Zum hellen Modus wechseln", "lightMode": "Zum hellen Modus wechseln",
"darkMode": "Zum dunklen Modus wechseln" "darkMode": "Zum dunklen Modus wechseln"
}, },
"theme": {
"title": "Design",
"light": "Hell",
"dark": "Dunkel",
"system": "System"
},
"dose": { "dose": {
"takenBy": "eingenommen von", "takenBy": "eingenommen von",
"markAsTaken": "Als eingenommen markieren" "markAsTaken": "Als eingenommen markieren"
@@ -474,16 +481,13 @@
"appName": "MedAssist-ng", "appName": "MedAssist-ng",
"description": "Open-Source Medikamentenverwaltung und Planungsanwendung für selbst gehostete Umgebungen.", "description": "Open-Source Medikamentenverwaltung und Planungsanwendung für selbst gehostete Umgebungen.",
"version": "Version", "version": "Version",
"frontend": "Frontend",
"backend": "Backend",
"checkForUpdates": "Nach Updates suchen", "checkForUpdates": "Nach Updates suchen",
"checking": "Prüfe...", "checking": "Prüfe...",
"upToDate": "Du bist auf dem neuesten Stand!", "upToDate": "Du bist auf dem neuesten Stand!",
"updateAvailable": "Update verfügbar", "updateAvailable": "Update verfügbar",
"viewOnGitHub": "Auf GitHub ansehen",
"downloadUpdate": "Update herunterladen", "downloadUpdate": "Update herunterladen",
"checkFailed": "Update-Prüfung fehlgeschlagen", "checkFailed": "Update-Prüfung fehlgeschlagen",
"lastChecked": "Zuletzt geprüft", "viewOnGitHub": "Auf GitHub ansehen",
"github": "GitHub", "github": "GitHub",
"license": "MIT-Lizenz", "license": "MIT-Lizenz",
"copyright": "© {{year}} Daniel Volz", "copyright": "© {{year}} Daniel Volz",
+9 -5
View File
@@ -176,7 +176,8 @@
"badge": "Plan your supply", "badge": "Plan your supply",
"from": "From", "from": "From",
"until": "Until", "until": "Until",
"includeUntilStart": "Include consumption from today until start date", "includeUntilStart": "Include current consumption",
"includeUntilStartTooltip": "When enabled, pills consumed between today and the selected start date are subtracted from your current stock. This gives a more accurate picture of how much you'll actually have left when the planning period begins.",
"calculate": "Calculate", "calculate": "Calculate",
"calculating": "Calculating...", "calculating": "Calculating...",
"sendEmail": "📧 Send via Email", "sendEmail": "📧 Send via Email",
@@ -290,6 +291,12 @@
"lightMode": "Switch to light mode", "lightMode": "Switch to light mode",
"darkMode": "Switch to dark mode" "darkMode": "Switch to dark mode"
}, },
"theme": {
"title": "Theme",
"light": "Light",
"dark": "Dark",
"system": "System"
},
"dose": { "dose": {
"takenBy": "taken by", "takenBy": "taken by",
"markAsTaken": "Mark as taken" "markAsTaken": "Mark as taken"
@@ -474,16 +481,13 @@
"appName": "MedAssist-ng", "appName": "MedAssist-ng",
"description": "Open-source medication tracking and planning application for self-hosted environments.", "description": "Open-source medication tracking and planning application for self-hosted environments.",
"version": "Version", "version": "Version",
"frontend": "Frontend",
"backend": "Backend",
"checkForUpdates": "Check for Updates", "checkForUpdates": "Check for Updates",
"checking": "Checking...", "checking": "Checking...",
"upToDate": "You're up to date!", "upToDate": "You're up to date!",
"updateAvailable": "Update available", "updateAvailable": "Update available",
"viewOnGitHub": "View on GitHub",
"downloadUpdate": "Download Update", "downloadUpdate": "Download Update",
"checkFailed": "Could not check for updates", "checkFailed": "Could not check for updates",
"lastChecked": "Last checked", "viewOnGitHub": "View on GitHub",
"github": "GitHub", "github": "GitHub",
"license": "MIT License", "license": "MIT License",
"copyright": "© {{year}} Daniel Volz", "copyright": "© {{year}} Daniel Volz",
+28 -21
View File
@@ -4,7 +4,7 @@ import { useAuth } from "../components/Auth";
import { useAppContext } from "../context"; import { useAppContext } from "../context";
import type { Coverage } from "../types"; import type { Coverage } from "../types";
import { formatNumber, getExpiryClass, getSystemLocale } from "../utils/formatters"; import { formatNumber, getExpiryClass, getSystemLocale } from "../utils/formatters";
import { getStockStatus } from "../utils/schedule"; import { expandDoseIds, getStockStatus } from "../utils/schedule";
// Helper for user-specific localStorage keys // Helper for user-specific localStorage keys
function userStorageKey(userId: number | undefined, key: string): string { function userStorageKey(userId: number | undefined, key: string): string {
@@ -34,14 +34,18 @@ function formatOpenBlisterAndLoose(
return `${openBlisterPills} ${t("common.of")} ${pillsPerBlister} ${t("common.pills")}`; return `${openBlisterPills} ${t("common.of")} ${pillsPerBlister} ${t("common.pills")}`;
} }
// Get total pills for a medication // Get total pills for a medication (packageType-aware)
function getMedTotal(med: { function getMedTotal(med: {
packCount: number; packCount: number;
blistersPerPack: number; blistersPerPack: number;
pillsPerBlister: number; pillsPerBlister: number;
looseTablets: number; looseTablets: number;
stockAdjustment?: number | null; stockAdjustment?: number | null;
packageType?: string;
}): number { }): number {
if (med.packageType === "bottle") {
return med.looseTablets + (med.stockAdjustment ?? 0);
}
return med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0); return med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
} }
@@ -276,9 +280,17 @@ export function DashboardPage() {
<div className="reminder-status-row"> <div className="reminder-status-row">
<span className="reminder-status-label">{t("dashboard.reminders.lastSent")}:</span> <span className="reminder-status-label">{t("dashboard.reminders.lastSent")}:</span>
<span className="reminder-status-value"> <span className="reminder-status-value">
{reminderData.lastSent.medName && ( {reminderData.lastSent.medName &&
<span className="reminder-med-name">{reminderData.lastSent.medName}</span> (() => {
)} const medication = meds.find((m) => m.name === reminderData.lastSent!.medName);
return medication ? (
<span className="med-link clickable" onClick={() => openMedDetail(medication)}>
{reminderData.lastSent!.medName}
</span>
) : (
<span className="reminder-med-name">{reminderData.lastSent!.medName}</span>
);
})()}
{reminderData.lastSent.takenBy && ( {reminderData.lastSent.takenBy && (
<span className="reminder-taken-by"> ({reminderData.lastSent.takenBy})</span> <span className="reminder-taken-by"> ({reminderData.lastSent.takenBy})</span>
)} )}
@@ -490,11 +502,7 @@ export function DashboardPage() {
{pastDays.length > 0 && {pastDays.length > 0 &&
(() => { (() => {
const missedCount = missedPastDoseIds.length; const missedCount = missedPastDoseIds.length;
const totalPastDoses = pastDays.flatMap((d) => const totalPastDoses = pastDays.flatMap((d) => d.meds.flatMap((m) => expandDoseIds(m.doses)));
d.meds.flatMap((m) =>
m.doses.flatMap((dose) => (dose.takenBy ? [`${dose.id}-${dose.takenBy}`] : [dose.id]))
)
);
return ( return (
<div className="past-days-header"> <div className="past-days-header">
<div <div
@@ -541,7 +549,10 @@ export function DashboardPage() {
{showPastDays && {showPastDays &&
pastDays.map((day) => { pastDays.map((day) => {
const allDoseIds = day.meds.flatMap((item) => const allDoseIds = day.meds.flatMap((item) =>
item.doses.flatMap((d) => (d.takenBy ? [`${d.id}-${d.takenBy}`] : [d.id])) item.doses.flatMap((d) => {
const takenByArray = Array.isArray(d.takenBy) ? d.takenBy : [];
return takenByArray.length > 0 ? takenByArray.map((p) => `${d.id}-${p}`) : [d.id];
})
); );
const allDayTaken = const allDayTaken =
allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id) || dismissedDoses.has(id)); allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id) || dismissedDoses.has(id));
@@ -586,7 +597,7 @@ export function DashboardPage() {
const med = meds.find((m) => m.name === item.medName); const med = meds.find((m) => m.name === item.medName);
const medCov = coverageByMed[item.medName]; const medCov = coverageByMed[item.medName];
const isEmpty = medCov ? medCov.medsLeft <= 0 : false; const isEmpty = medCov ? medCov.medsLeft <= 0 : false;
const itemDoseIds = item.doses.flatMap((d) => (d.takenBy ? [`${d.id}-${d.takenBy}`] : [d.id])); const itemDoseIds = expandDoseIds(item.doses);
const allTaken = itemDoseIds.every((id) => takenDoses.has(id)); const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return ( return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}> <div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
@@ -676,9 +687,7 @@ export function DashboardPage() {
{todayDay && {todayDay &&
(() => { (() => {
const day = todayDay; const day = todayDay;
const allDoseIds = day.meds.flatMap((item) => const allDoseIds = day.meds.flatMap((item) => expandDoseIds(item.doses));
item.doses.flatMap((d) => (d.takenBy ? [`${d.id}-${d.takenBy}`] : [d.id]))
);
const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id)); const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id));
const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length; const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length;
@@ -737,7 +746,7 @@ export function DashboardPage() {
: medCoverage : medCoverage
? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, stockThresholds) ? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, stockThresholds)
: null; : null;
const itemDoseIds = item.doses.flatMap((d) => (d.takenBy ? [`${d.id}-${d.takenBy}`] : [d.id])); const itemDoseIds = expandDoseIds(item.doses);
const allTaken = itemDoseIds.every((id) => takenDoses.has(id)); const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return ( return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}> <div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
@@ -769,7 +778,7 @@ export function DashboardPage() {
<div className="doses-col"> <div className="doses-col">
{item.doses.map((dose) => { {item.doses.map((dose) => {
const isOverdue = dose.when < Date.now(); const isOverdue = dose.when < Date.now();
const people = dose.takenBy ? [dose.takenBy] : [null]; const people = dose.takenBy.length > 0 ? dose.takenBy : [null];
const allTaken = people.every((person) => takenDoses.has(getDoseId(dose.id, person))); const allTaken = people.every((person) => takenDoses.has(getDoseId(dose.id, person)));
return ( return (
<div <div
@@ -866,9 +875,7 @@ export function DashboardPage() {
{/* Future days */} {/* Future days */}
{showFutureDays && {showFutureDays &&
futureDays.map((day) => { futureDays.map((day) => {
const allDoseIds = day.meds.flatMap((item) => const allDoseIds = day.meds.flatMap((item) => expandDoseIds(item.doses));
item.doses.flatMap((d) => (d.takenBy ? [`${d.id}-${d.takenBy}`] : [d.id]))
);
const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id)); const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id));
const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length; const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length;
@@ -926,7 +933,7 @@ export function DashboardPage() {
: medCoverage : medCoverage
? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, stockThresholds) ? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, stockThresholds)
: null; : null;
const itemDoseIds = item.doses.flatMap((d) => (d.takenBy ? [`${d.id}-${d.takenBy}`] : [d.id])); const itemDoseIds = expandDoseIds(item.doses);
const allTaken = itemDoseIds.every((id) => takenDoses.has(id)); const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return ( return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}> <div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
+1 -1
View File
@@ -526,7 +526,7 @@ export function MedicationsPage() {
</label> </label>
</> </>
)} )}
<label> <label className="full">
{t("form.pillWeight")} ({form.doseUnit}) {t("form.pillWeight")} ({form.doseUnit})
<div className="dose-input-group"> <div className="dose-input-group">
<input <input
+14 -3
View File
@@ -178,6 +178,9 @@ export function PlannerPage() {
onChange={(e) => setIncludeUntilStart(e.target.checked)} onChange={(e) => setIncludeUntilStart(e.target.checked)}
/> />
{t("planner.includeUntilStart")} {t("planner.includeUntilStart")}
<span className="info-tooltip small" data-tooltip={t("planner.includeUntilStartTooltip")}>
</span>
</label> </label>
<div className="planner-actions"> <div className="planner-actions">
<button type="button" className="ghost" onClick={resetRange}> <button type="button" className="ghost" onClick={resetRange}>
@@ -210,11 +213,19 @@ export function PlannerPage() {
<strong>{row.plannerUsage}</strong>&nbsp;{t("common.pills")} <strong>{row.plannerUsage}</strong>&nbsp;{t("common.pills")}
</span> </span>
<span data-label={t("planner.table.blisters")}> <span data-label={t("planner.table.blisters")}>
{row.blistersNeeded} × {row.blisterSize} {row.packageType === "bottle"
? `${row.plannerUsage} ${t("common.pills")}`
: `${row.blistersNeeded} × ${row.blisterSize}`}
</span> </span>
<span data-label={t("planner.table.available")}> <span data-label={t("planner.table.available")}>
{row.fullBlisters} {t("common.blisters")} {row.packageType === "bottle" ? (
{row.loosePills > 0 && ` + ${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`} `${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`
) : (
<>
{row.fullBlisters} {t("common.blisters")}
{row.loosePills > 0 && ` + ${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`}
</>
)}
</span> </span>
<span <span
data-label={t("table.status")} data-label={t("table.status")}
+4 -14
View File
@@ -3,6 +3,7 @@ import { MedicationAvatar } from "../components";
import { useAuth } from "../components/Auth"; import { useAuth } from "../components/Auth";
import { useAppContext } from "../context"; import { useAppContext } from "../context";
import type { Coverage } from "../types"; import type { Coverage } from "../types";
import { expandDoseIds } from "../utils/schedule";
// Helper for user-specific localStorage keys // Helper for user-specific localStorage keys
function userStorageKey(userId: number | undefined, key: string): string { function userStorageKey(userId: number | undefined, key: string): string {
@@ -125,12 +126,7 @@ export function SchedulePage() {
{/* Past days (when expanded) */} {/* Past days (when expanded) */}
{showPastDays && {showPastDays &&
pastDays.map((day) => { pastDays.map((day) => {
const allDoseIds = day.meds.flatMap((item) => const allDoseIds = day.meds.flatMap((item) => expandDoseIds(item.doses));
item.doses.flatMap((d) => {
const takenByArray = Array.isArray(d.takenBy) ? d.takenBy : [];
return takenByArray.length > 0 ? takenByArray.map((p) => `${d.id}-${p}`) : [d.id];
})
);
const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id)); const allDayTaken = allDoseIds.length > 0 && allDoseIds.every((id) => takenDoses.has(id));
const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length; const takenCount = allDoseIds.filter((id) => takenDoses.has(id)).length;
const isManuallyExpanded = manuallyExpandedDays.has(day.dateStr); const isManuallyExpanded = manuallyExpandedDays.has(day.dateStr);
@@ -172,10 +168,7 @@ export function SchedulePage() {
const med = meds.find((m) => m.name === item.medName); const med = meds.find((m) => m.name === item.medName);
const medCov = coverageByMed[item.medName]; const medCov = coverageByMed[item.medName];
const isEmpty = medCov ? medCov.medsLeft <= 0 : false; const isEmpty = medCov ? medCov.medsLeft <= 0 : false;
const itemDoseIds = item.doses.flatMap((d) => { const itemDoseIds = expandDoseIds(item.doses);
const takenByArray = Array.isArray(d.takenBy) ? d.takenBy : [];
return takenByArray.length > 0 ? takenByArray.map((p) => `${d.id}-${p}`) : [d.id];
});
const allTaken = itemDoseIds.every((id) => takenDoses.has(id)); const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return ( return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}> <div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
@@ -277,10 +270,7 @@ export function SchedulePage() {
: medCoverage : medCoverage
? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings) ? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings)
: null; : null;
const itemDoseIds = item.doses.flatMap((d) => { const itemDoseIds = expandDoseIds(item.doses);
const takenByArray = Array.isArray(d.takenBy) ? d.takenBy : [];
return takenByArray.length > 0 ? takenByArray.map((p) => `${d.id}-${p}`) : [d.id];
});
const allTaken = itemDoseIds.every((id) => takenDoses.has(id)); const allTaken = itemDoseIds.every((id) => takenDoses.has(id));
return ( return (
<div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}> <div key={`${day.dateStr}-${item.medName}`} className={`time-row ${allTaken ? "taken" : ""}`}>
+106 -25
View File
@@ -152,6 +152,90 @@ body.modal-open {
background: rgba(47, 134, 246, 0.12); background: rgba(47, 134, 246, 0.12);
} }
/* =============================================================================
Theme Dropdown Menu
============================================================================= */
.theme-menu {
position: relative;
}
.theme-dropdown {
position: absolute;
top: calc(100% + 0.5rem);
right: 0;
min-width: 160px;
background: rgba(15, 23, 42, 0.85);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px;
box-shadow:
0 12px 32px rgba(0, 0, 0, 0.4),
inset 0 0 0 1px rgba(255, 255, 255, 0.05);
opacity: 0;
visibility: hidden;
transform: translateY(-6px) scale(0.95);
transition: all 0.2s ease;
z-index: 1000;
overflow: hidden;
padding: 0.375rem;
}
[data-theme="light"] .theme-dropdown {
background: rgba(255, 255, 255, 0.85);
border: 1px solid rgba(0, 0, 0, 0.08);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
}
.theme-menu.open .theme-dropdown {
opacity: 1;
visibility: visible;
transform: translateY(0) scale(1);
}
.theme-dropdown-item {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
padding: 0.625rem 0.75rem;
border: none;
background: none;
color: var(--text-primary);
font-size: 0.875rem;
cursor: pointer;
border-radius: 8px;
transition: background 0.15s ease;
text-align: left;
box-shadow: none;
}
.theme-dropdown-item:hover {
background: rgba(59, 130, 246, 0.15);
}
.theme-dropdown-item.active {
color: var(--accent-primary);
}
.theme-dropdown-item svg {
width: 18px;
height: 18px;
flex-shrink: 0;
opacity: 0.7;
}
.theme-dropdown-item.active svg {
opacity: 1;
color: var(--accent-primary);
}
.theme-check {
margin-left: auto;
font-size: 0.8rem;
opacity: 0.8;
}
.hero-title { .hero-title {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -1024,12 +1108,14 @@ textarea.auto-resize {
.dose-input-group input { .dose-input-group input {
flex: 1; flex: 1;
min-width: 0; min-width: 100px;
} }
.dose-unit-select { .dose-unit-select {
width: auto; width: auto;
min-width: 80px; min-width: unset;
max-width: 120px;
flex-shrink: 0;
padding: 0.5rem 0.75rem; padding: 0.5rem 0.75rem;
background: var(--bg-primary); background: var(--bg-primary);
border: 1px solid var(--border-primary); border: 1px solid var(--border-primary);
@@ -2019,11 +2105,12 @@ textarea.auto-resize {
text-transform: uppercase; text-transform: uppercase;
letter-spacing: 0.04em; letter-spacing: 0.04em;
} }
.planner-checkbox { .planner label.planner-checkbox {
grid-column: 1 / -1; grid-column: 1 / -1;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
align-items: center; align-items: center;
flex-wrap: nowrap;
gap: 0.75rem; gap: 0.75rem;
color: var(--text-secondary); color: var(--text-secondary);
font-size: 0.875rem; font-size: 0.875rem;
@@ -4551,18 +4638,12 @@ h3 .reminder-icon.info-tooltip {
width: 64px; width: 64px;
height: 64px; height: 64px;
margin: 0 auto 1rem; margin: 0 auto 1rem;
background: linear-gradient(135deg, var(--accent) 0%, var(--accent-hover) 100%);
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 12px rgba(var(--accent-rgb, 59, 130, 246), 0.25);
} }
.about-logo svg { .about-logo img {
width: 36px; width: 64px;
height: 36px; height: 64px;
stroke: white; border-radius: 16px;
} }
.about-header h2 { .about-header h2 {
@@ -4586,15 +4667,12 @@ h3 .reminder-icon.info-tooltip {
.about-version-row { .about-version-row {
display: flex; display: flex;
justify-content: space-between; justify-content: center;
align-items: center; align-items: center;
gap: 0.75rem;
padding: 0.5rem 0; padding: 0.5rem 0;
} }
.about-version-row:not(:last-child) {
border-bottom: 1px dashed var(--border-secondary);
}
.about-version-label { .about-version-label {
font-size: 0.875rem; font-size: 0.875rem;
color: var(--text-secondary); color: var(--text-secondary);
@@ -4610,6 +4688,16 @@ h3 .reminder-icon.info-tooltip {
border-radius: 4px; border-radius: 4px;
} }
a.about-version-link {
color: var(--accent-primary);
text-decoration: none;
transition: text-decoration 0.15s ease;
}
a.about-version-link:hover {
text-decoration: underline;
}
.about-update-section { .about-update-section {
padding: 1.25rem 1.5rem; padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--border-primary); border-bottom: 1px solid var(--border-primary);
@@ -4711,13 +4799,6 @@ h3 .reminder-icon.info-tooltip {
background: var(--accent-hover); background: var(--accent-hover);
} }
.update-last-checked {
display: block;
margin-top: 0.5rem;
font-size: 0.75rem;
opacity: 0.8;
}
.about-links { .about-links {
padding: 1.25rem 1.5rem; padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--border-primary); border-bottom: 1px solid var(--border-primary);
@@ -16,10 +16,6 @@ describe("AboutModal", () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: true,
json: () => Promise.resolve({ version: "1.0.0" }),
});
}); });
it("returns null when not open", () => { it("returns null when not open", () => {
@@ -65,8 +61,10 @@ describe("AboutModal", () => {
expect(links.length).toBeGreaterThan(0); expect(links.length).toBeGreaterThan(0);
}); });
it("fetches backend version on open", async () => { it("renders version as link to GitHub release", () => {
render(<AboutModal {...defaultProps} />); render(<AboutModal {...defaultProps} />);
expect(fetch).toHaveBeenCalledWith("/api/health"); const versionLink = screen.getByText("1.0.0").closest("a");
expect(versionLink).toHaveAttribute("href", "https://github.com/test/repo/releases/tag/v1.0.0");
expect(versionLink).toHaveAttribute("target", "_blank");
}); });
}); });
@@ -82,7 +82,7 @@ describe("AppHeader", () => {
}); });
}); });
it("renders theme toggle button", async () => { it("renders theme menu button", async () => {
const mockOnOpenProfile = vi.fn(); const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn(); const mockOnOpenAbout = vi.fn();
@@ -95,12 +95,33 @@ describe("AppHeader", () => {
); );
await waitFor(() => { await waitFor(() => {
const buttons = screen.getAllByRole("button"); const themeBtn = screen.getByTitle(/theme\.title/i);
const themeBtn = buttons.find((btn) => btn.textContent?.includes("🌙") || btn.textContent?.includes("☀️"));
expect(themeBtn).toBeInTheDocument(); expect(themeBtn).toBeInTheDocument();
}); });
}); });
it("opens theme dropdown and shows Light/Dark/System options", async () => {
const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn();
render(
<MemoryRouter initialEntries={["/dashboard"]}>
<AuthProvider>
<AppHeader onOpenProfile={mockOnOpenProfile} onOpenAbout={mockOnOpenAbout} />
</AuthProvider>
</MemoryRouter>
);
await waitFor(() => {
const themeBtn = screen.getByTitle(/theme\.title/i);
fireEvent.click(themeBtn);
});
expect(screen.getByText(/theme\.light/i)).toBeInTheDocument();
expect(screen.getByText(/theme\.dark/i)).toBeInTheDocument();
expect(screen.getByText(/theme\.system/i)).toBeInTheDocument();
});
it("renders settings button when auth is disabled", async () => { it("renders settings button when auth is disabled", async () => {
const mockOnOpenProfile = vi.fn(); const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn(); const mockOnOpenAbout = vi.fn();
+107 -8
View File
@@ -103,10 +103,14 @@ describe("useDoses", () => {
}); });
it("marks dose as taken optimistically", async () => { it("marks dose as taken optimistically", async () => {
// First call for initial load, subsequent calls for marking dose // First call for initial load, second for marking dose, third for re-sync
(global.fetch as ReturnType<typeof vi.fn>) (global.fetch as ReturnType<typeof vi.fn>)
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) }) .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
.mockResolvedValueOnce({ ok: true }); .mockResolvedValueOnce({ ok: true })
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ doses: [{ doseId: "new-dose", takenAt: Date.now(), dismissed: false }] }),
});
const { result } = renderHook(() => useDoses()); const { result } = renderHook(() => useDoses());
@@ -119,7 +123,9 @@ describe("useDoses", () => {
await result.current.markDoseTaken("new-dose"); await result.current.markDoseTaken("new-dose");
}); });
expect(result.current.takenDoses.has("new-dose")).toBe(true); await waitFor(() => {
expect(result.current.takenDoses.has("new-dose")).toBe(true);
});
expect(fetch).toHaveBeenCalledWith( expect(fetch).toHaveBeenCalledWith(
"/api/doses/taken", "/api/doses/taken",
expect.objectContaining({ expect.objectContaining({
@@ -130,10 +136,11 @@ describe("useDoses", () => {
}); });
it("reverts optimistic update on error", async () => { it("reverts optimistic update on error", async () => {
// First call for initial load, second for marking dose fails // First call for initial load, second for marking dose fails, third for re-sync
(global.fetch as ReturnType<typeof vi.fn>) (global.fetch as ReturnType<typeof vi.fn>)
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) }) .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
.mockRejectedValueOnce(new Error("Network error")); .mockRejectedValueOnce(new Error("Network error"))
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) });
const { result } = renderHook(() => useDoses()); const { result } = renderHook(() => useDoses());
@@ -153,12 +160,13 @@ describe("useDoses", () => {
it("undoes dose taken optimistically", async () => { it("undoes dose taken optimistically", async () => {
const mockDoses = { const mockDoses = {
doses: [{ doseId: "taken-dose", dismissed: false }], doses: [{ doseId: "taken-dose", takenAt: Date.now(), dismissed: false }],
}; };
(global.fetch as ReturnType<typeof vi.fn>) (global.fetch as ReturnType<typeof vi.fn>)
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) }) .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
.mockResolvedValueOnce({ ok: true }); .mockResolvedValueOnce({ ok: true })
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) });
const { result } = renderHook(() => useDoses()); const { result } = renderHook(() => useDoses());
@@ -170,10 +178,101 @@ describe("useDoses", () => {
await result.current.undoDoseTaken("taken-dose"); await result.current.undoDoseTaken("taken-dose");
}); });
expect(result.current.takenDoses.has("taken-dose")).toBe(false); await waitFor(() => {
expect(result.current.takenDoses.has("taken-dose")).toBe(false);
});
expect(fetch).toHaveBeenCalledWith("/api/doses/taken/taken-dose", expect.objectContaining({ method: "DELETE" })); expect(fetch).toHaveBeenCalledWith("/api/doses/taken/taken-dose", expect.objectContaining({ method: "DELETE" }));
}); });
it("reverts undo on error by re-adding the dose", async () => {
const mockDoses = {
doses: [{ doseId: "taken-dose", takenAt: 1710500000000, dismissed: false }],
};
// Initial load returns taken-dose, DELETE fails, re-sync returns taken-dose still there
(global.fetch as ReturnType<typeof vi.fn>)
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
.mockRejectedValueOnce(new Error("Network error"))
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) });
const { result } = renderHook(() => useDoses());
await waitFor(() => {
expect(result.current.takenDoses.has("taken-dose")).toBe(true);
});
await act(async () => {
await result.current.undoDoseTaken("taken-dose");
});
// After error, the dose should be re-added (reverted)
await waitFor(() => {
expect(result.current.takenDoses.has("taken-dose")).toBe(true);
});
});
it("populates takenDoseTimestamps from API response", async () => {
const takenAt = 1710500000000;
const mockDoses = {
doses: [{ doseId: "dose-1", takenAt, dismissed: false }],
};
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockDoses),
});
const { result } = renderHook(() => useDoses());
await waitFor(() => {
expect(result.current.takenDoseTimestamps.get("dose-1")).toBe(takenAt);
});
});
it("markDoseTaken sets takenDoseTimestamp optimistically", async () => {
const now = Date.now();
vi.setSystemTime(now);
// Initial load, POST success, re-sync
(global.fetch as ReturnType<typeof vi.fn>)
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
.mockResolvedValueOnce({ ok: true })
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ doses: [{ doseId: "new-dose", takenAt: now, dismissed: false }] }),
});
const { result } = renderHook(() => useDoses());
await waitFor(() => {
expect(result.current.takenDoses.size).toBe(0);
});
await act(async () => {
await result.current.markDoseTaken("new-dose");
});
await waitFor(() => {
expect(result.current.takenDoseTimestamps.has("new-dose")).toBe(true);
expect(result.current.takenDoseTimestamps.get("new-dose")).toBe(now);
});
vi.useRealTimers();
});
it("keeps state on fetch error during initial load", async () => {
// Initial load fails
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("Network error"));
const { result } = renderHook(() => useDoses());
// Should keep empty state, not crash
await waitFor(() => {
expect(result.current.takenDoses.size).toBe(0);
expect(result.current.dismissedDoses.size).toBe(0);
});
});
it("setShowClearMissedConfirm works", () => { it("setShowClearMissedConfirm works", () => {
const { result } = renderHook(() => useDoses()); const { result } = renderHook(() => useDoses());
+108
View File
@@ -287,6 +287,114 @@ describe("useRefill", () => {
expect(mockLoadMeds).toHaveBeenCalled(); expect(mockLoadMeds).toHaveBeenCalled();
}); });
it("stock correction uses correct base for bottle type medications", async () => {
// BUG FIX: submitStockCorrection used blister formula (packCount * blistersPerPack * pillsPerBlister + looseTablets)
// for ALL medications, but getMedTotal() uses only looseTablets + stockAdjustment for bottles.
// This mismatch caused the correction to compute the wrong stockAdjustment.
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
const bottleMed: Medication = {
id: 4,
name: "Pills in a Box",
packageType: "bottle",
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 1,
looseTablets: 150,
stockAdjustment: -2,
takenBy: [],
blisters: [{ usage: 1, every: 1, start: "2026-01-31T20:27:00" }],
updatedAt: null,
};
// getMedTotal for bottle = looseTablets + stockAdjustment = 150 + (-2) = 148
// getPackageSize for bottle = looseTablets = 150
const mockLoadMeds = vi.fn();
const { result } = renderHook(() => useRefill());
// Pre-fill: user sees 148 pills (148 / 1 = 148 full, 0 partial)
act(() => {
result.current.openEditStockModal(bottleMed, {
all: [{ name: "Pills in a Box", medsLeft: 148, daysLeft: 148 }] as Coverage[],
});
});
// User adds +1 → 149 full blisters (pillsPerBlister=1)
act(() => {
result.current.setEditStockFullBlisters(149);
result.current.setEditStockPartialBlisterPills(0);
});
await act(async () => {
await result.current.submitStockCorrection(4, bottleMed, mockLoadMeds);
});
// desiredTotal = 149 * 1 + 0 = 149
// baseTotal (fixed) = getPackageSize(bottle) = looseTablets = 150
// newStockAdjustment = 149 - 150 = -1
// → getMedTotal = 150 + (-1) = 149 ✓
const fetchCall = (global.fetch as ReturnType<typeof vi.fn>).mock.calls.find(
(call: [string, RequestInit]) => call[0] === "/api/medications/4/stock-adjustment"
);
expect(fetchCall).toBeDefined();
const body = JSON.parse(fetchCall![1].body as string);
expect(body.stockAdjustment).toBe(-1); // NOT -2 (the old bug)
});
it("stock correction uses correct base for blister type medications", async () => {
// Ensure blister type still works correctly after the bottle fix
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
const blisterMed: Medication = {
id: 2,
name: "Blister Med",
packageType: "blister",
packCount: 1,
blistersPerPack: 5,
pillsPerBlister: 5,
looseTablets: 0,
stockAdjustment: 1,
takenBy: [],
blisters: [{ usage: 1, every: 1, start: "2026-01-30T21:07:00" }],
updatedAt: null,
};
// getMedTotal for blister = 1*5*5 + 0 + 1 = 26
// getPackageSize for blister = 1*5*5 + 0 = 25
const mockLoadMeds = vi.fn();
const { result } = renderHook(() => useRefill());
// User sees 26 pills → 5 full blisters (5pills each) + 1 partial
act(() => {
result.current.openEditStockModal(blisterMed, {
all: [{ name: "Blister Med", medsLeft: 26, daysLeft: 26 }] as Coverage[],
});
});
// User changes to 27 (+1): 5 full + 2 partial
act(() => {
result.current.setEditStockFullBlisters(5);
result.current.setEditStockPartialBlisterPills(2);
});
await act(async () => {
await result.current.submitStockCorrection(2, blisterMed, mockLoadMeds);
});
// desiredTotal = 5 * 5 + 2 = 27
// baseTotal = getPackageSize(blister) = 1*5*5 + 0 = 25
// newStockAdjustment = 27 - 25 = 2
// → getMedTotal = 25 + 2 = 27 ✓
const fetchCall = (global.fetch as ReturnType<typeof vi.fn>).mock.calls.find(
(call: [string, RequestInit]) => call[0] === "/api/medications/2/stock-adjustment"
);
expect(fetchCall).toBeDefined();
const body = JSON.parse(fetchCall![1].body as string);
expect(body.stockAdjustment).toBe(2);
});
it("allows setting state directly", () => { it("allows setting state directly", () => {
const { result } = renderHook(() => useRefill()); const { result } = renderHook(() => useRefill());
+54 -22
View File
@@ -8,6 +8,20 @@ describe("useTheme", () => {
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null); (window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null);
// Reset mock to default behavior // Reset mock to default behavior
(window.localStorage.setItem as ReturnType<typeof vi.fn>).mockImplementation(() => {}); (window.localStorage.setItem as ReturnType<typeof vi.fn>).mockImplementation(() => {});
// Mock matchMedia to return dark system theme by default
Object.defineProperty(window, "matchMedia", {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
})),
});
}); });
afterEach(() => { afterEach(() => {
@@ -17,58 +31,76 @@ describe("useTheme", () => {
it("returns dark as default theme", () => { it("returns dark as default theme", () => {
const { result } = renderHook(() => useTheme()); const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe("dark"); expect(result.current.theme).toBe("dark");
expect(result.current.themePreference).toBe("dark");
}); });
it("reads theme from localStorage", () => { it("reads theme preference from localStorage", () => {
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light"); (window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
const { result } = renderHook(() => useTheme()); const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe("light"); expect(result.current.theme).toBe("light");
expect(result.current.themePreference).toBe("light");
}); });
it("toggles theme from dark to light", () => { it("toggles theme through light → dark → system → light", () => {
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe("dark");
act(() => {
result.current.toggleTheme();
});
expect(result.current.theme).toBe("light");
});
it("toggles theme from light to dark", () => {
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light"); (window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
const { result } = renderHook(() => useTheme()); const { result } = renderHook(() => useTheme());
expect(result.current.themePreference).toBe("light");
act(() => {
result.current.toggleTheme();
});
expect(result.current.themePreference).toBe("dark");
act(() => {
result.current.toggleTheme();
});
expect(result.current.themePreference).toBe("system");
act(() => {
result.current.toggleTheme();
});
expect(result.current.themePreference).toBe("light");
});
it("sets theme preference directly", () => {
const { result } = renderHook(() => useTheme());
expect(result.current.themePreference).toBe("dark");
act(() => {
result.current.setThemePreference("light");
});
expect(result.current.themePreference).toBe("light");
expect(result.current.theme).toBe("light"); expect(result.current.theme).toBe("light");
act(() => { act(() => {
result.current.toggleTheme(); result.current.setThemePreference("system");
}); });
expect(result.current.themePreference).toBe("system");
// System resolves to dark (matchMedia returns false for light)
expect(result.current.theme).toBe("dark"); expect(result.current.theme).toBe("dark");
}); });
it("saves theme to localStorage on change", () => { it("saves theme preference to localStorage on change", () => {
const { result } = renderHook(() => useTheme()); const { result } = renderHook(() => useTheme());
act(() => { act(() => {
result.current.toggleTheme(); result.current.setThemePreference("light");
}); });
expect(window.localStorage.setItem).toHaveBeenCalledWith("theme", "light"); expect(window.localStorage.setItem).toHaveBeenCalledWith("theme", "light");
act(() => {
result.current.setThemePreference("system");
});
expect(window.localStorage.setItem).toHaveBeenCalledWith("theme", "system");
}); });
it("sets data-theme attribute on document", () => { it("sets data-theme attribute on document", () => {
const { result } = renderHook(() => useTheme()); const { result } = renderHook(() => useTheme());
expect(document.documentElement.getAttribute("data-theme")).toBe("dark"); expect(document.documentElement.getAttribute("data-theme")).toBe("dark");
act(() => { act(() => {
result.current.toggleTheme(); result.current.setThemePreference("light");
}); });
expect(document.documentElement.getAttribute("data-theme")).toBe("light"); expect(document.documentElement.getAttribute("data-theme")).toBe("light");
}); });
}); });
File diff suppressed because it is too large Load Diff
+2
View File
@@ -67,6 +67,7 @@ export type PlannerRow = {
fullBlisters: number; fullBlisters: number;
loosePills: number; loosePills: number;
enough: boolean; enough: boolean;
packageType?: PackageType;
}; };
export type RefillEntry = { export type RefillEntry = {
@@ -170,6 +171,7 @@ export type SharedMedication = {
doseUnit?: DoseUnit | null; doseUnit?: DoseUnit | null;
imageUrl?: string | null; imageUrl?: string | null;
totalPills: number; totalPills: number;
packageType?: PackageType;
packCount: number; packCount: number;
blistersPerPack: number; blistersPerPack: number;
looseTablets: number; looseTablets: number;
+105 -39
View File
@@ -100,7 +100,8 @@ export function calculateCoverage(
locale: string, locale: string,
reminderDaysBefore: number, reminderDaysBefore: number,
stockCalculationMode: "automatic" | "manual", stockCalculationMode: "automatic" | "manual",
takenDoses: Set<string> takenDoses: Set<string>,
takenDoseTimestamps?: Map<string, number>
): { low: Coverage[]; all: Coverage[] } { ): { low: Coverage[]; all: Coverage[] } {
const MS_PER_DAY = 86_400_000; const MS_PER_DAY = 86_400_000;
const now = Date.now(); const now = Date.now();
@@ -116,57 +117,112 @@ export function calculateCoverage(
// Also add medication-level takenBy for backward compatibility // Also add medication-level takenBy for backward compatibility
m.takenBy?.forEach((person) => uniquePeople.add(person)); m.takenBy?.forEach((person) => uniquePeople.add(person));
const personCount = Math.max(1, uniquePeople.size || m.takenBy?.length || 1); const personCount = Math.max(1, uniquePeople.size || m.takenBy?.length || 1);
const dailyRate = blisters.reduce((sum, s) => sum + (s.every > 0 ? s.usage / s.every : 0), 0) * personCount;
// Calculate daily consumption rate per intake, accounting for per-intake takenBy.
// When an intake has a per-intake takenBy (new format), it represents exactly
// one person's dose — do NOT multiply by personCount again.
// For legacy intakes (no takenBy), the intake applies to ALL people.
let dailyRate = 0;
blisters.forEach((s, idx) => {
const baseRate = s.every > 0 ? s.usage / s.every : 0;
const intake = intakes[idx];
if (intake?.takenBy) {
// Per-intake takenBy: this intake is for exactly 1 person
dailyRate += baseRate;
} else {
// Legacy: this intake applies to all people
dailyRate += baseRate * personCount;
}
});
let consumed = 0; let consumed = 0;
const stockCorrectionCutoff = m.lastStockCorrectionAt ? new Date(m.lastStockCorrectionAt).getTime() : 0; const stockCorrectionCutoff = m.lastStockCorrectionAt ? new Date(m.lastStockCorrectionAt).getTime() : 0;
if (stockCalculationMode === "automatic") { if (stockCalculationMode === "automatic") {
// In automatic mode, calculate expected consumption based on time // In automatic mode, stock is reduced automatically based on the schedule.
// but also account for manual corrections (doses marked as not taken) // Every scheduled dose counts as consumed once its time has passed.
// Additionally, if a user marks a future dose as taken BEFORE the scheduled
// time (early intake), that dose is also counted as consumed immediately.
// This prevents double-counting: once the scheduled time arrives, the dose
// was already counted via the early-taken path, not again via time.
blisters.forEach((s, blisterIdx) => { blisters.forEach((s, blisterIdx) => {
const blisterStart = new Date(s.start).getTime(); const blisterStart = new Date(s.start).getTime();
const effectiveStart = Math.max(blisterStart, stockCorrectionCutoff);
if (Number.isNaN(effectiveStart) || effectiveStart > now) return;
const period = Math.max(1, s.every) * MS_PER_DAY; const period = Math.max(1, s.every) * MS_PER_DAY;
const occurrences = Math.floor((now - effectiveStart) / period) + 1;
// After a stock correction, start counting consumption from the NEXT
// scheduled dose on this blister's grid, because the user's pill count
// already reflects all consumption up to the correction time.
// We align to the schedule grid so that e.g. correction at 15:40 with
// a daily 15:42 dose counts today's 15:42 dose (2 min later), not
// tomorrow's dose (24h later as the old code did).
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;
}
if (Number.isNaN(effectiveStart)) return;
const intake = intakes[blisterIdx]; const intake = intakes[blisterIdx];
const intakePerson = intake?.takenBy; const intakePerson = intake?.takenBy;
// For per-intake takenBy, only count for that person // For per-intake takenBy, only count for that person
// For legacy (no takenBy), count for all people in medication takenBy // For legacy (no takenBy), count for all people in medication takenBy
const peopleForThisIntake = intakePerson ? [intakePerson] : m.takenBy?.length > 0 ? m.takenBy : [null]; const peopleForThisIntake = intakePerson ? [intakePerson] : m.takenBy?.length > 0 ? m.takenBy : [null];
const expectedConsumed = occurrences * s.usage * peopleForThisIntake.length;
// Count how many doses were actually marked as taken for this blister // Time-based: count doses where the scheduled time has already passed
let actualConsumed = 0; let timeBasedConsumed = 0;
let lastAutoConsumedDateMs = 0;
// Generate all expected dose IDs for this blister up to now if (effectiveStart <= now) {
for (let i = 0; i < occurrences; i++) { const occurrences = Math.floor((now - effectiveStart) / period) + 1;
const doseDate = new Date(effectiveStart + i * period); timeBasedConsumed = occurrences * s.usage * peopleForThisIntake.length;
const dateOnlyMs = new Date(doseDate.getFullYear(), doseDate.getMonth(), doseDate.getDate()).getTime();
const baseDoseId = `${m.id}-${blisterIdx}-${dateOnlyMs}`;
// Check if each person has taken this dose // Date-only timestamp of the last auto-consumed dose
for (const person of peopleForThisIntake) { const lastDoseTime = new Date(effectiveStart + (occurrences - 1) * period);
const doseId = person ? `${baseDoseId}-${person}` : baseDoseId; lastAutoConsumedDateMs = new Date(
if (takenDoses.has(doseId)) { lastDoseTime.getFullYear(),
actualConsumed += s.usage; lastDoseTime.getMonth(),
lastDoseTime.getDate()
).getTime();
}
// Early intakes: count future doses already marked as taken.
// The cutoff is the later of: last auto-consumed date or stock correction date.
// This prevents double-counting (time-based + early-taken) and respects corrections.
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 takenDoses) {
const parts = doseId.split("-");
if (parts.length >= 3) {
const medId = parseInt(parts[0], 10);
const bIdx = parseInt(parts[1], 10);
const timestamp = parseInt(parts[2], 10);
if (medId === m.id && bIdx === blisterIdx && timestamp > earlyCutoff) {
earlyTakenConsumed += s.usage;
} }
} }
} }
// If we have tracking data (any doses marked), use actual consumed consumed += timeBasedConsumed + earlyTakenConsumed;
// Otherwise fall back to expected (for backwards compatibility)
const hasTrackingData = Array.from(takenDoses).some((id) => {
const parts = id.split("-");
return parts.length >= 3 && parseInt(parts[0], 10) === m.id && parseInt(parts[1], 10) === blisterIdx;
});
consumed += hasTrackingData ? actualConsumed : expectedConsumed;
}); });
} else { } else {
// In manual mode, only count doses that are explicitly marked as taken // In manual mode, only count doses that are explicitly marked as taken.
// For stock correction filtering, we use the actual time the dose was marked
// as taken (takenAt), not the scheduled date. This correctly handles same-day
// scenarios: if a user corrects stock at 3pm, then takes a dose at 4pm,
// the dose counts because takenAt (4pm) > correctionTime (3pm).
takenDoses.forEach((doseId) => { takenDoses.forEach((doseId) => {
const parts = doseId.split("-"); const parts = doseId.split("-");
if (parts.length >= 3) { if (parts.length >= 3) {
@@ -181,19 +237,17 @@ export function calculateCoverage(
blisterStartDate.getMonth(), blisterStartDate.getMonth(),
blisterStartDate.getDate() blisterStartDate.getDate()
).getTime(); ).getTime();
// Convert stock correction cutoff to date-only as well
const stockCorrectionDateOnly = // Use actual takenAt timestamp for stock correction comparison.
stockCorrectionCutoff > 0 // A dose counts only if it was MARKED after the stock correction,
? new Date( // regardless of what day it was scheduled for.
new Date(stockCorrectionCutoff).getFullYear(), const takenAt = takenDoseTimestamps?.get(doseId) ?? 0;
new Date(stockCorrectionCutoff).getMonth(), const afterCorrectionOrNoCorrectionMs = stockCorrectionCutoff === 0 || takenAt > stockCorrectionCutoff;
new Date(stockCorrectionCutoff).getDate()
).getTime()
: 0;
if ( if (
!Number.isNaN(blisterStartDateOnly) && !Number.isNaN(blisterStartDateOnly) &&
doseTimestamp >= blisterStartDateOnly && doseTimestamp >= blisterStartDateOnly &&
doseTimestamp >= stockCorrectionDateOnly afterCorrectionOrNoCorrectionMs
) { ) {
consumed += blisters[blisterIdx].usage; consumed += blisters[blisterIdx].usage;
} }
@@ -446,6 +500,18 @@ export function isDoseDismissed(doseId: string, dismissedUntilDate: string | und
* @param dismissedDoses - Set of dose IDs individually dismissed * @param dismissedDoses - Set of dose IDs individually dismissed
* @returns Array of dose IDs that are missed * @returns Array of dose IDs that are missed
*/ */
/**
* Compute the full set of dose IDs for a list of doses, correctly handling
* per-intake takenBy arrays. Empty arrays produce base IDs (no suffix),
* non-empty arrays produce one ID per person with a `-person` suffix.
*/
export function expandDoseIds(doses: ReadonlyArray<{ id: string; takenBy: string[] }>): string[] {
return doses.flatMap((d) => {
const takenByArray = Array.isArray(d.takenBy) ? d.takenBy : [];
return takenByArray.length > 0 ? takenByArray.map((p) => `${d.id}-${p}`) : [d.id];
});
}
export function computeMissedPastDoseIds( export function computeMissedPastDoseIds(
pastDays: ReadonlyArray<{ pastDays: ReadonlyArray<{
meds: ReadonlyArray<{ meds: ReadonlyArray<{
+86 -55
View File
@@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
# ============================================================================= # =============================================================================
# MedAssist Release Script # MedAssist Release Script (non-interactive)
# ============================================================================= # =============================================================================
# Usage: # Usage:
# ./scripts/release.sh patch # 1.0.0 -> 1.0.1 (bugfixes) # ./scripts/release.sh patch # 1.0.0 -> 1.0.1 (bugfixes)
@@ -8,8 +8,9 @@
# ./scripts/release.sh major # 1.0.0 -> 2.0.0 (breaking changes) # ./scripts/release.sh major # 1.0.0 -> 2.0.0 (breaking changes)
# ./scripts/release.sh 1.2.3 # explicit version # ./scripts/release.sh 1.2.3 # explicit version
# #
# This script creates a PR for the version bump (required due to branch protection), # Fully non-interactive: no y/N prompts. Designed to be called by AI agents
# waits for CI, merges it, and then creates a signed tag for the release. # or CI systems. Creates a PR for the version bump (required due to branch
# protection), waits for CI with retry logic, merges, and creates a signed tag.
# ============================================================================= # =============================================================================
set -e set -e
@@ -21,45 +22,98 @@ YELLOW='\033[1;33m'
BLUE='\033[0;34m' BLUE='\033[0;34m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
# GitHub repo # Configuration
GITHUB_REPO="DanielVolz/medassist-ng" GITHUB_REPO="DanielVolz/medassist-ng"
CI_POLL_INTERVAL=15 # seconds between CI status polls
CI_INITIAL_DELAY=20 # seconds to wait before first CI check
CI_MAX_WAIT=600 # maximum seconds to wait for CI (10 minutes)
# Get script directory and project root # Get script directory and project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_ROOT" cd "$PROJECT_ROOT"
# Check for gh CLI # Detect git remote name (prefer 'origin', fall back to 'github')
detect_remote() {
if git remote | grep -q '^origin$'; then
echo "origin"
elif git remote | grep -q '^github$'; then
echo "github"
else
echo -e "${RED}Error: No 'origin' or 'github' remote found.${NC}" >&2
exit 1
fi
}
GIT_REMOTE=$(detect_remote)
# Wait for CI checks on a PR with retry logic
# GitHub Actions can take 10-30 seconds before checks are reported.
# This function polls until checks appear and then watches them.
wait_for_ci() {
local pr_number="$1"
local elapsed=0
echo -e "${BLUE}Waiting ${CI_INITIAL_DELAY}s for CI checks to be registered...${NC}"
sleep "${CI_INITIAL_DELAY}"
elapsed=$CI_INITIAL_DELAY
while [[ $elapsed -lt $CI_MAX_WAIT ]]; do
# Check if any checks have been reported
local check_output
check_output=$(gh pr checks "${pr_number}" --repo "${GITHUB_REPO}" 2>&1) || true
if echo "$check_output" | grep -q "no checks reported"; then
echo -e "${YELLOW}No checks reported yet (${elapsed}s elapsed). Retrying in ${CI_POLL_INTERVAL}s...${NC}"
sleep "${CI_POLL_INTERVAL}"
elapsed=$((elapsed + CI_POLL_INTERVAL))
continue
fi
# Checks are registered — use --watch to wait for completion
echo -e "${BLUE}CI checks registered. Watching for completion...${NC}"
if gh pr checks "${pr_number}" --repo "${GITHUB_REPO}" --watch; then
echo -e "${GREEN}CI checks passed!${NC}"
return 0
else
echo -e "${RED}CI checks failed!${NC}"
return 1
fi
done
echo -e "${RED}Timed out waiting for CI checks after ${CI_MAX_WAIT}s.${NC}"
return 1
}
# ─── Preflight checks ────────────────────────────────────────────────────────
if ! command -v gh &> /dev/null; then if ! command -v gh &> /dev/null; then
echo -e "${RED}Error: GitHub CLI (gh) is required but not installed.${NC}" echo -e "${RED}Error: GitHub CLI (gh) is required but not installed.${NC}"
echo "Install it with: brew install gh" echo "Install it with: brew install gh"
exit 1 exit 1
fi fi
# Check gh authentication
if ! gh auth status &> /dev/null; then if ! gh auth status &> /dev/null; then
echo -e "${RED}Error: Not authenticated with GitHub CLI.${NC}" echo -e "${RED}Error: Not authenticated with GitHub CLI.${NC}"
echo "Run: gh auth login" echo "Run: gh auth login"
exit 1 exit 1
fi fi
# Check for uncommitted changes
if [[ -n $(git status --porcelain) ]]; then if [[ -n $(git status --porcelain) ]]; then
echo -e "${RED}Error: You have uncommitted changes. Commit or stash them first.${NC}" echo -e "${RED}Error: You have uncommitted changes. Commit or stash them first.${NC}"
git status --short git status --short
exit 1 exit 1
fi fi
# Make sure we're on main and up to date # ─── Determine version ───────────────────────────────────────────────────────
echo -e "${BLUE}Updating main branch...${NC}" echo -e "${BLUE}Updating main branch...${NC}"
git checkout main git checkout main
git pull origin main 2>/dev/null || git pull github main 2>/dev/null || true git pull "${GIT_REMOTE}" main
# Get current version from backend/package.json
CURRENT_VERSION=$(grep '"version"' backend/package.json | sed 's/.*"version": "\(.*\)".*/\1/') CURRENT_VERSION=$(grep '"version"' backend/package.json | sed 's/.*"version": "\(.*\)".*/\1/')
echo -e "${BLUE}Current version: ${YELLOW}v${CURRENT_VERSION}${NC}" echo -e "${BLUE}Current version: ${YELLOW}v${CURRENT_VERSION}${NC}"
# Calculate new version
if [[ -z "$1" ]]; then if [[ -z "$1" ]]; then
echo -e "${RED}Usage: $0 <patch|minor|major|x.y.z>${NC}" echo -e "${RED}Usage: $0 <patch|minor|major|x.y.z>${NC}"
exit 1 exit 1
@@ -79,7 +133,6 @@ case "$1" in
NEW_VERSION="$((major + 1)).0.0" NEW_VERSION="$((major + 1)).0.0"
;; ;;
*) *)
# Assume explicit version (validate format)
if [[ ! "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then if [[ ! "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo -e "${RED}Invalid version format. Use: x.y.z${NC}" echo -e "${RED}Invalid version format. Use: x.y.z${NC}"
exit 1 exit 1
@@ -88,45 +141,31 @@ case "$1" in
;; ;;
esac esac
echo -e "${GREEN}New version: ${YELLOW}v${NEW_VERSION}${NC}" echo -e "${GREEN}Releasing: ${YELLOW}v${CURRENT_VERSION} → v${NEW_VERSION}${NC}"
echo ""
# Confirm # ─── Create release branch and PR ────────────────────────────────────────────
read -p "Release v${NEW_VERSION}? (y/N) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Aborted."
exit 1
fi
# Branch name for the release
RELEASE_BRANCH="chore/release-${NEW_VERSION}" RELEASE_BRANCH="chore/release-${NEW_VERSION}"
# Check if branch already exists
if git show-ref --verify --quiet "refs/heads/${RELEASE_BRANCH}"; then if git show-ref --verify --quiet "refs/heads/${RELEASE_BRANCH}"; then
echo -e "${YELLOW}Branch ${RELEASE_BRANCH} already exists locally. Deleting...${NC}" echo -e "${YELLOW}Branch ${RELEASE_BRANCH} already exists locally. Deleting...${NC}"
git branch -D "${RELEASE_BRANCH}" git branch -D "${RELEASE_BRANCH}"
fi fi
# Create release branch
echo -e "${BLUE}Creating release branch...${NC}" echo -e "${BLUE}Creating release branch...${NC}"
git checkout -b "${RELEASE_BRANCH}" git checkout -b "${RELEASE_BRANCH}"
# Update version in package.json files
echo -e "${BLUE}Updating package.json files...${NC}" echo -e "${BLUE}Updating package.json files...${NC}"
sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" backend/package.json sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" backend/package.json
sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" frontend/package.json 2>/dev/null || true sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" frontend/package.json 2>/dev/null || true
# Commit version bump
echo -e "${BLUE}Committing version bump...${NC}" echo -e "${BLUE}Committing version bump...${NC}"
git add backend/package.json frontend/package.json 2>/dev/null || git add backend/package.json git add backend/package.json frontend/package.json 2>/dev/null || git add backend/package.json
git commit -m "chore: release v${NEW_VERSION}" git commit -m "chore: release v${NEW_VERSION}"
# Push branch to GitHub echo -e "${BLUE}Pushing release branch...${NC}"
echo -e "${BLUE}Pushing release branch to GitHub...${NC}" git push -u "${GIT_REMOTE}" "${RELEASE_BRANCH}"
git push -u origin "${RELEASE_BRANCH}" 2>/dev/null || git push -u github "${RELEASE_BRANCH}"
# Create PR
echo -e "${BLUE}Creating Pull Request...${NC}" echo -e "${BLUE}Creating Pull Request...${NC}"
PR_URL=$(gh pr create \ PR_URL=$(gh pr create \
--repo "${GITHUB_REPO}" \ --repo "${GITHUB_REPO}" \
@@ -136,57 +175,49 @@ PR_URL=$(gh pr create \
Automated version bump for release v${NEW_VERSION}. Automated version bump for release v${NEW_VERSION}.
This PR was created by the release script." \ This PR was created by the release script.")
2>&1)
echo -e "${GREEN}PR created: ${YELLOW}${PR_URL}${NC}" echo -e "${GREEN}PR created: ${YELLOW}${PR_URL}${NC}"
# Extract PR number
PR_NUMBER=$(echo "$PR_URL" | grep -oE '[0-9]+$') PR_NUMBER=$(echo "$PR_URL" | grep -oE '[0-9]+$')
# Wait for CI checks # ─── Wait for CI and merge ────────────────────────────────────────────────────
echo -e "${BLUE}Waiting for CI checks to complete...${NC}"
if ! gh pr checks "${PR_NUMBER}" --repo "${GITHUB_REPO}" --watch; then if ! wait_for_ci "${PR_NUMBER}"; then
echo -e "${RED}CI checks failed! Please fix the issues and try again.${NC}" echo -e "${RED}CI checks failed! Please fix the issues and try again.${NC}"
echo -e "${RED}Release branch '${RELEASE_BRANCH}' and PR #${PR_NUMBER} are still open.${NC}"
exit 1 exit 1
fi fi
echo -e "${GREEN}CI checks passed!${NC}" echo -e "${BLUE}Merging PR #${PR_NUMBER}...${NC}"
# Merge PR
echo -e "${BLUE}Merging PR...${NC}"
gh pr merge "${PR_NUMBER}" --repo "${GITHUB_REPO}" --squash --delete-branch gh pr merge "${PR_NUMBER}" --repo "${GITHUB_REPO}" --squash --delete-branch
# Switch back to main and pull echo -e "${BLUE}Updating main branch...${NC}"
echo -e "${BLUE}Updating main branch with merged changes...${NC}"
git checkout main git checkout main
git pull origin main 2>/dev/null || git pull github main 2>/dev/null || true git pull "${GIT_REMOTE}" main
# ─── Create and push signed tag ──────────────────────────────────────────────
# Check if tag exists and delete it
if git rev-parse "v${NEW_VERSION}" >/dev/null 2>&1; then if git rev-parse "v${NEW_VERSION}" >/dev/null 2>&1; then
echo -e "${YELLOW}Tag v${NEW_VERSION} already exists locally. Deleting...${NC}" echo -e "${YELLOW}Tag v${NEW_VERSION} already exists locally. Deleting...${NC}"
git tag -d "v${NEW_VERSION}" git tag -d "v${NEW_VERSION}"
fi fi
# Check if remote tag exists if git ls-remote --tags "${GIT_REMOTE}" "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}"; then
if git ls-remote --tags origin "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}" || \
git ls-remote --tags github "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}"; then
echo -e "${YELLOW}Tag v${NEW_VERSION} exists on remote. Deleting...${NC}" echo -e "${YELLOW}Tag v${NEW_VERSION} exists on remote. Deleting...${NC}"
git push origin ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true git push "${GIT_REMOTE}" ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
git push github ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
fi fi
# Create signed tag
echo -e "${BLUE}Creating signed tag v${NEW_VERSION}...${NC}" echo -e "${BLUE}Creating signed tag v${NEW_VERSION}...${NC}"
git tag -s "v${NEW_VERSION}" -m "Release v${NEW_VERSION}" git tag -s "v${NEW_VERSION}" -m "Release v${NEW_VERSION}"
# Push tag echo -e "${BLUE}Pushing tag...${NC}"
echo -e "${BLUE}Pushing tag to GitHub...${NC}" git push "${GIT_REMOTE}" "v${NEW_VERSION}"
git push origin "v${NEW_VERSION}" 2>/dev/null || git push github "v${NEW_VERSION}"
# ─── Done ─────────────────────────────────────────────────────────────────────
echo "" echo ""
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}" echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✓ Released v${NEW_VERSION}${NC}" echo -e "${GREEN} ✓ Released v${NEW_VERSION}${NC}"
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}" echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo "" echo ""
echo -e "${BLUE}GitHub Actions will now build and publish Docker images.${NC}" echo -e "${BLUE}GitHub Actions will now build and publish Docker images.${NC}"