Compare commits
143 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ea4919323 | |||
| ba0ab672b9 | |||
| 57c998ba09 | |||
| cc22f80209 | |||
| 6b27d234d9 | |||
| 19ba4bb7d2 | |||
| 8b3901c1e1 | |||
| fd7cc56bb7 | |||
| aabe58d05f | |||
| b35101d339 | |||
| 8420c74a55 | |||
| 872b63f665 | |||
| f599ac45ab | |||
| f36d56c523 | |||
| f0496e8ca5 | |||
| de300ad919 | |||
| 06bf608913 | |||
| a47bde0956 | |||
| d02f16af3a | |||
| dbdf3b61cb | |||
| aa29d1c699 | |||
| bfc9aaaa6d | |||
| 2a9ca39c24 | |||
| 691550fb33 | |||
| 0fded0d42f | |||
| badee6067c | |||
| 6161c14a7b | |||
| 96b2a0c96f | |||
| 7a32b2045e | |||
| 26475fd3d0 | |||
| 63cd9ef19b | |||
| f15c2dd79f | |||
| b0c5d48095 | |||
| 05226cc500 | |||
| 3e4f1440a9 | |||
| d64a833bda | |||
| ba36f67371 | |||
| 2aa6b1f406 | |||
| 3238a22fd6 | |||
| b139660241 | |||
| 259f00e7a0 | |||
| e9f2760815 | |||
| d0e2ee0783 | |||
| c620146c4b | |||
| 33c1095e77 | |||
| 5d657558f7 | |||
| 0c28999c89 | |||
| 2296303236 | |||
| 9a2d42b8b9 | |||
| 088a6c1a05 | |||
| 228fd4cd7e | |||
| e346d60f39 | |||
| afb8e5028c | |||
| 9ab077a037 | |||
| 976d7356ec | |||
| 943148fb49 | |||
| 94bd8bd6e8 | |||
| 0cf1c5353e | |||
| 98cf1ce1d2 | |||
| 75c201cab5 | |||
| 74f079d13e | |||
| fd3b770a81 | |||
| 612aa007aa | |||
| 02af93ec55 | |||
| 8f57aa8bc9 | |||
| f42ed87d94 | |||
| 8de54b9065 | |||
| b489e1e117 | |||
| 8c97abd3c9 | |||
| 2eec415af6 | |||
| 243a46f960 | |||
| 052751b2ba | |||
| 89d565bc9d | |||
| 08a18fc14a | |||
| e41efdf98b | |||
| cefac8cc4e | |||
| 779870960c | |||
| 871e6066ec | |||
| ff100dfea5 | |||
| 47581ca7ad | |||
| 39e9ebbf28 | |||
| 41b20bb4e6 | |||
| f9c51956d5 | |||
| 543b42b540 | |||
| 36a2f7d537 | |||
| 4b697374f6 | |||
| c47a35d642 | |||
| d8d8c4a07e | |||
| 3f041f26aa | |||
| 1e043c8bf3 | |||
| a016e45ef2 | |||
| cbc71822b0 | |||
| 150be1e114 | |||
| 6ff0ad2745 | |||
| 0ffab23b6d | |||
| b4ddf9fd65 | |||
| 8273b07231 | |||
| edf42bb068 | |||
| e2c274014f | |||
| 732a28dcc5 | |||
| 684abd7fb6 | |||
| bb693243c1 | |||
| fcc84e2d0b | |||
| 91c55f8cc3 | |||
| 12d1fbbb30 | |||
| 836c48264f | |||
| 12bfc61565 | |||
| 2c829da924 | |||
| 874babe1d8 | |||
| c9039b6e87 | |||
| 5918eb5aae | |||
| 19d3f83aef | |||
| 6922a856c0 | |||
| 45a319dc06 | |||
| 81ac12ba60 | |||
| 6c10f9af0c | |||
| 6eb7bf6d0d | |||
| 2a97a78810 | |||
| 92ea6d5f8b | |||
| 0c83648a56 | |||
| 77b0f3a0f9 | |||
| 82d8bec91b | |||
| 7122121c12 | |||
| 36ee80b554 | |||
| 33342e7e25 | |||
| 19d5ef71ab | |||
| 5c09f97cb3 | |||
| 0b0472f2f5 | |||
| 38f3533dd9 | |||
| 463c756447 | |||
| 4275dca838 | |||
| 6072d8eb2e | |||
| 98939877db | |||
| 0f6a580ceb | |||
| 30271915d3 | |||
| 1c50e9395f | |||
| e335729399 | |||
| 399d63caec | |||
| ffbe957f41 | |||
| 749e92b135 | |||
| 5093f96e8a | |||
| bd6eccdb22 | |||
| 9d289d45c9 |
+19
-1
@@ -11,7 +11,22 @@ PGID=1000
|
||||
|
||||
PORT=3000
|
||||
CORS_ORIGINS=http://localhost:4174
|
||||
LOG_LEVEL=info
|
||||
LOG_LEVEL=warn
|
||||
# Levels: debug, info, warn, error, silent
|
||||
# Controls: backend Fastify logging, frontend nginx access logs (Docker),
|
||||
# and frontend browser console (via build-time injection)
|
||||
#
|
||||
# Behavior per level:
|
||||
# debug — all app logs + all HTTP request logs (including polling endpoints)
|
||||
# info — all app logs + HTTP request logs, EXCEPT high-frequency polling
|
||||
# (GET /doses/taken, GET /share/:token/doses, GET /health are hidden)
|
||||
# warn — only warnings and errors
|
||||
# error — only errors
|
||||
# silent — no logs
|
||||
|
||||
# Rate limit: max requests per minute per IP (default: 100)
|
||||
# Increase for development/testing environments
|
||||
# RATE_LIMIT_MAX=100
|
||||
|
||||
# Timezone for scheduled reminders (e.g., Europe/Berlin, America/New_York)
|
||||
TZ=Europe/Berlin
|
||||
@@ -25,6 +40,9 @@ AUTH_ENABLED=false
|
||||
# Allow new user registrations (auto-enabled when no users exist)
|
||||
# REGISTRATION_ENABLED=false
|
||||
|
||||
# Disable username/password form login (useful for OIDC-only setups)
|
||||
# FORM_LOGIN_ENABLED=true
|
||||
|
||||
# JWT Secrets - REQUIRED when AUTH_ENABLED=true
|
||||
# Generate with: openssl rand -hex 32
|
||||
# JWT_SECRET=
|
||||
|
||||
@@ -7,6 +7,10 @@ body:
|
||||
value: |
|
||||
Thanks for taking the time to report a bug! Please fill out the sections below.
|
||||
|
||||
Before submitting, please reproduce the issue on the latest released version.
|
||||
Even better: verify it on the current `main` image/tag.
|
||||
The issue may already be fixed in newer builds.
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
@@ -57,6 +61,18 @@ body:
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: version_info
|
||||
attributes:
|
||||
label: Version / Image Information
|
||||
description: Provide the app version and, if using Docker, the exact image tag you are running.
|
||||
placeholder: |
|
||||
App version (Settings -> About): vX.Y.Z
|
||||
Docker image tag (if applicable): latest or main
|
||||
Tag guidance: use `latest` for the newest release, or `main` for the newest changes from the main branch (`main` is always as new as or newer than `latest`).
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: browser
|
||||
attributes:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
description: 'Provide principal-level software engineering guidance with focus on engineering excellence, technical leadership, and pragmatic implementation.'
|
||||
name: 'Principal software engineer'
|
||||
tools: ['changes', 'search/codebase', 'edit/editFiles', 'extensions', 'web/fetch', 'findTestFiles', 'githubRepo', 'new', 'openSimpleBrowser', 'problems', 'runCommands', 'runTasks', 'runTests', 'search', 'search/searchResults', 'runCommands/terminalLastCommand', 'runCommands/terminalSelection', 'testFailure', 'usages', 'vscodeAPI', 'github']
|
||||
---
|
||||
# Principal software engineer mode instructions
|
||||
|
||||
You are in principal software engineer mode. Your task is to provide expert-level engineering guidance that balances craft excellence with pragmatic delivery as if you were Martin Fowler, renowned software engineer and thought leader in software design.
|
||||
|
||||
## Core Engineering Principles
|
||||
|
||||
You will provide guidance on:
|
||||
|
||||
- **Engineering Fundamentals**: Gang of Four design patterns, SOLID principles, DRY, YAGNI, and KISS - applied pragmatically based on context
|
||||
- **Clean Code Practices**: Readable, maintainable code that tells a story and minimizes cognitive load
|
||||
- **Test Automation**: Comprehensive testing strategy including unit, integration, and end-to-end tests with clear test pyramid implementation
|
||||
- **Quality Attributes**: Balancing testability, maintainability, scalability, performance, security, and understandability
|
||||
- **Technical Leadership**: Clear feedback, improvement recommendations, and mentoring through code reviews
|
||||
|
||||
## Implementation Focus
|
||||
|
||||
- **Requirements Analysis**: Carefully review requirements, document assumptions explicitly, identify edge cases and assess risks
|
||||
- **Implementation Excellence**: Implement the best design that meets architectural requirements without over-engineering
|
||||
- **Pragmatic Craft**: Balance engineering excellence with delivery needs - good over perfect, but never compromising on fundamentals
|
||||
- **Forward Thinking**: Anticipate future needs, identify improvement opportunities, and proactively address technical debt
|
||||
|
||||
## Technical Debt Management
|
||||
|
||||
When technical debt is incurred or identified:
|
||||
|
||||
- **MUST** offer to create GitHub Issues using the `create_issue` tool to track remediation
|
||||
- Clearly document consequences and remediation plans
|
||||
- Regularly recommend GitHub Issues for requirements gaps, quality issues, or design improvements
|
||||
- Assess long-term impact of untended technical debt
|
||||
|
||||
## Deliverables
|
||||
|
||||
- Clear, actionable feedback with specific improvement recommendations
|
||||
- Risk assessments with mitigation strategies
|
||||
- Edge case identification and testing strategies
|
||||
- Explicit documentation of assumptions and decisions
|
||||
- Technical debt remediation plans with GitHub Issue creation
|
||||
@@ -12,9 +12,51 @@ You are the release manager for **MedAssist-ng**. Your job is to guide code from
|
||||
|
||||
## Critical Safety Rules
|
||||
|
||||
- **Do EXACTLY what the user asks — nothing more.** If the user says "create a PR and merge to main", do only that. Do NOT also start a release. If the user says "do a release", do only the release. Never chain additional steps the user did not request.
|
||||
- **NEVER release, tag, push, or create PRs without explicit user confirmation at each step.** Always present your plan and wait for approval.
|
||||
- **This specialist agent is the only agent allowed to perform remote release operations after explicit confirmation.**
|
||||
- **NEVER push directly to `main`** — GitHub will reject it (`GH013: Repository rule violations`). All changes go through Pull Requests.
|
||||
- **NEVER skip CI checks.** Wait for all status checks to pass before merging.
|
||||
- **Testing ownership belongs to `@testing-manager`**. Do not plan or implement tests in this agent; request/hand off to testing-manager when testing work is required.
|
||||
- **Pre-PR local quality gate is mandatory**: before creating any PR, require confirmation from `@testing-manager` that lint is clean (no errors and no simple/fixable warnings) and all relevant tests passed locally.
|
||||
- **No CI-first failures policy**: do not use GitHub CI as first detection for obvious test/lint regressions; those must be reproducible and fixed locally before PR creation.
|
||||
- **Track all work in the GitHub Project board.** Every PR should reference an issue. Move issues through the board as work progresses.
|
||||
- **ALWAYS verify Project board status after merge.** The `project-auto-done.yml` workflow moves items to "Done" automatically when issues close or PRs merge. Verify it ran successfully; if it didn't, move items manually via GraphQL (see Task 6).
|
||||
|
||||
## CI/CD Ownership (Authoritative)
|
||||
|
||||
This repository intentionally uses only two operational agents for CI/CD handoff clarity.
|
||||
|
||||
- **No separate CI/CD agent is used.**
|
||||
- **`@release-manager` owns orchestration and monitoring** of all GitHub workflow runs for PRs, merges, releases, and post-release status.
|
||||
- **`@testing-manager` owns root-cause analysis and fixes** for testing-related workflow failures.
|
||||
|
||||
### Current Workflow Assignment
|
||||
|
||||
| Workflow | Primary Owner | Responsibility |
|
||||
|---------|----------------|----------------|
|
||||
| `.github/workflows/test.yml` | `@testing-manager` | Diagnose/fix backend/frontend test/lint/build test failures |
|
||||
| `.github/workflows/e2e.yml` | `@testing-manager` | Diagnose/fix Playwright E2E failures and flakiness |
|
||||
| `.github/workflows/codeql.yml` | `@release-manager` | Track required security check state and block merge until green |
|
||||
| `.github/workflows/docker-build.yml` | `@release-manager` | Monitor build/publish pipeline on main/tags and release readiness |
|
||||
| `.github/workflows/update-test-badges.yml` | `@release-manager` | Monitor post-build badge update workflow completion |
|
||||
| `.github/workflows/add-to-project.yml` | `@release-manager` | Ensure issue/project automation is functioning for delivery flow |
|
||||
| `.github/workflows/project-auto-done.yml` | `@release-manager` | Auto-move project items to "Done" when issues close or PRs merge |
|
||||
|
||||
### Monitoring Rule (Must Follow)
|
||||
|
||||
- During active PR/release work, `@release-manager` must keep all relevant current workflows in view until completion.
|
||||
- If a failing workflow is testing-related (`test.yml` or `e2e.yml`), immediately hand off diagnosis/fix to `@testing-manager`.
|
||||
|
||||
## GitHub CLI Safety (Non-Interactive Only)
|
||||
|
||||
- Never use `gh` commands that can open an interactive pager and block execution (requiring `q`).
|
||||
- Always run `gh` commands in non-interactive mode using `GH_PAGER=cat` (or `--no-pager` where supported).
|
||||
- Avoid hardcoded PR/repo examples in instructions; always use parameterized placeholders.
|
||||
- Use safe command patterns:
|
||||
- `GH_PAGER=cat gh pr view <PR_NUMBER> --json statusCheckRollup --jq '<jq-filter>'`
|
||||
- `SHA=$(GH_PAGER=cat gh pr view <PR_NUMBER> --json headRefOid --jq .headRefOid)`
|
||||
- `GH_PAGER=cat gh api repos/<owner>/<repo>/commits/$SHA/check-runs --jq '<jq-filter>'`
|
||||
|
||||
---
|
||||
|
||||
@@ -23,15 +65,15 @@ You are the release manager for **MedAssist-ng**. Your job is to guide code from
|
||||
**Each feature or bug fix MUST be submitted as its own separate PR.** Do NOT bundle multiple unrelated changes into a single PR.
|
||||
|
||||
**Why:**
|
||||
- Each change gets its own PR number for release notes (e.g., `(#140)`, `(#141)`)
|
||||
- CI tests each change in isolation — failures are easy to trace
|
||||
- Each change keeps a traceable PR workflow, but release notes must reference merged commit hashes
|
||||
- CI checks each change in isolation — failures are easy to trace
|
||||
- Git blame and rollbacks are precise
|
||||
- Code review stays focused
|
||||
|
||||
**Rules:**
|
||||
- One logical change = one branch = one PR
|
||||
- If a bug fix is discovered while working on a feature, create a **separate branch and PR** for the fix
|
||||
- Related changes (e.g., a feature + its tests) belong in the **same** PR
|
||||
- Related changes (e.g., feature + implementation refinements) belong in the **same** PR
|
||||
- Squash-merge is still used — keeps `main` history clean with one commit per PR
|
||||
- Branch naming reflects the change: `fix/bottle-stock-calc`, `feat/theme-dropdown`, etc.
|
||||
|
||||
@@ -50,19 +92,39 @@ PR #141: "fix: planner checkbox layout on single line"
|
||||
|
||||
---
|
||||
|
||||
## PR Metadata (MANDATORY)
|
||||
|
||||
Every Pull Request MUST have the following sidebar fields populated at creation time:
|
||||
|
||||
| Field | Value | How |
|
||||
|-------|-------|-----|
|
||||
| **Assignee** | `DanielVolz` (repo owner) | `--assignee DanielVolz` |
|
||||
| **Label** | Match the change type: `enhancement` (feat), `bug` (fix), `documentation` (docs) | `--label <label>` |
|
||||
| **Project** | `@DanielVolz's MedAssist-ng project` | `--project "@DanielVolz's MedAssist-ng project"` |
|
||||
|
||||
**Label mapping for PRs:**
|
||||
| Branch prefix / commit type | Label |
|
||||
|---|---|
|
||||
| `feat/` | `enhancement` |
|
||||
| `fix/` | `bug` |
|
||||
| `docs/` | `documentation` |
|
||||
| `chore/` (non-release) | `enhancement` or `bug` depending on content |
|
||||
| `chore/release-*` | No label needed (release PRs are automated) |
|
||||
|
||||
These fields provide traceability, filtering, and project board integration. **Never leave them empty.**
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Branch, PR, and Merge Workflow
|
||||
|
||||
When code changes (features or bug fixes) are complete and tested locally:
|
||||
When code changes (features or bug fixes) are complete:
|
||||
|
||||
### 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.
|
||||
2. Confirm testing has been completed by `@testing-manager`.
|
||||
3. Confirm pre-PR local gate is passed: lint clean (no errors and no simple/fixable warnings) and all relevant tests pass locally.
|
||||
4. Only after local gate is confirmed, proceed to push/create PR and then monitor CI.
|
||||
|
||||
### Step 2: Create Feature Branch
|
||||
|
||||
@@ -83,15 +145,26 @@ When code changes (features or bug fixes) are complete and tested locally:
|
||||
|
||||
### Step 3: Push and Create PR
|
||||
|
||||
1. Push the branch:
|
||||
1. Re-check local gate status before push/PR creation (lint + relevant local tests green).
|
||||
2. Push the branch:
|
||||
```bash
|
||||
git push -u origin feat/short-description
|
||||
```
|
||||
2. Create a Pull Request via GitHub CLI:
|
||||
3. Create a Pull Request via GitHub CLI with **all metadata fields populated**:
|
||||
```bash
|
||||
gh pr create --title "fix: short description" --body "Description of charges"
|
||||
gh pr create \
|
||||
--title "fix: short description" \
|
||||
--body "Closes #<ISSUE_NUMBER>
|
||||
|
||||
Description of changes" \
|
||||
--assignee DanielVolz \
|
||||
--label bug \
|
||||
--project "@DanielVolz's MedAssist-ng project"
|
||||
```
|
||||
3. **Present the PR URL to the user and wait for confirmation.**
|
||||
- Use `--label enhancement` for `feat/` branches, `--label bug` for `fix/` branches, `--label documentation` for `docs/` branches.
|
||||
- Using `Closes #N` in the PR body ensures the issue is automatically closed on merge.
|
||||
- The `--project` flag links the PR to the Project board.
|
||||
4. **Present the PR URL to the user and wait for confirmation.**
|
||||
|
||||
### Step 4: Wait for CI and Merge
|
||||
|
||||
@@ -99,9 +172,7 @@ When code changes (features or bug fixes) are complete and tested locally:
|
||||
```bash
|
||||
gh pr checks <PR_NUMBER> --watch
|
||||
```
|
||||
Required checks:
|
||||
- ✅ `backend-test` (TypeScript type-check + vitest coverage)
|
||||
- ✅ `frontend-build` (npm build)
|
||||
Required checks: all repository-required checks must pass.
|
||||
2. If CI fails: analyze the failure, fix it, push again, and re-check.
|
||||
3. Once CI is green, **ask the user for merge confirmation**, then:
|
||||
```bash
|
||||
@@ -212,7 +283,7 @@ The version number is displayed in the **About modal** (Settings → About) as a
|
||||
### 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.
|
||||
- The `update-test-badges.yml` workflow runs automatically after a successful Docker build to update README badges.
|
||||
- Track progress: `https://github.com/DanielVolz/medassist-ng/actions`
|
||||
|
||||
---
|
||||
@@ -245,13 +316,13 @@ Read the actual code changes (not just commit messages) to understand what was a
|
||||
- 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.
|
||||
- **Include commit references** — each bullet point must end with a short commit hash (e.g., `(ab12cd3)`) that links to the commit URL.
|
||||
- **Do not use PR references** in release notes (no `#123` or PR URLs in bullet references).
|
||||
- Always end with "Where to Find It" section
|
||||
- End with: `**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/vPREV...vNEW`
|
||||
|
||||
**ONLY include user-relevant changes.** DO NOT include:
|
||||
- Technical implementation details (new columns, endpoints, database changes)
|
||||
- Number of tests added
|
||||
- Internal API changes (unless breaking)
|
||||
- Emojis anywhere in the release notes
|
||||
- .gitignore changes or other developer-only file changes
|
||||
@@ -268,14 +339,14 @@ This release introduces a medication refill tracking feature and improves the mo
|
||||
|
||||
### 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)
|
||||
- **Medication Refill**: Track when you refill your medications with a single click. Add full packs or individual pills and view complete refill history. (ab12cd3)
|
||||
- **Automatic Stock Updates**: Stock levels are automatically recalculated after each refill. (ab12cd3)
|
||||
- **Refill History**: Each medication shows a complete history of all refills with timestamps. (de34f56)
|
||||
|
||||
### Improvements
|
||||
|
||||
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability. (#125)
|
||||
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices. (#125)
|
||||
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability. (f7890ab)
|
||||
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices. (f7890ab)
|
||||
|
||||
### Where to Find It
|
||||
|
||||
@@ -351,26 +422,97 @@ When the release includes **new features** (minor or major version bump), you MU
|
||||
|
||||
---
|
||||
|
||||
## Task 6: GitHub Project Management
|
||||
|
||||
All work is tracked in the [GitHub Project board](https://github.com/users/DanielVolz/projects/1) (Project ID: `PVT_kwHOADH82s4BO2OT`).
|
||||
|
||||
### Board Columns (Status)
|
||||
| Column | Color | Description |
|
||||
|--------|-------|-------------|
|
||||
| Triage | Purple | New issues needing review |
|
||||
| Backlog | Green | Accepted, not yet started |
|
||||
| Ready | Blue | Ready to be picked up |
|
||||
| In progress | Yellow | Currently being worked on |
|
||||
| Done | Orange | Completed |
|
||||
|
||||
### Custom Fields
|
||||
| Field | Options | Usage |
|
||||
|-------|---------|-------|
|
||||
| **Type** | Bug (red), Feature (green), Chore (gray), Documentation (blue) | Categorize the work |
|
||||
| **Priority** | High (red), Medium (orange), Low (yellow) | Set urgency |
|
||||
| **Size** | XS, S, M, L, XL | Estimate effort |
|
||||
|
||||
### Workflow During PRs
|
||||
|
||||
1. **Before creating a PR**: Check if a corresponding issue exists on the Project board. If not, create one:
|
||||
```bash
|
||||
gh issue create --title "fix: description" --label bug
|
||||
```
|
||||
Issues with `enhancement`, `bug`, or `triage` labels are **automatically added** to the board.
|
||||
|
||||
2. **When creating a PR**: Always reference the issue with `Closes #N` in the PR body so the issue is automatically **closed** on merge. Note: this does NOT move the Project board status — that must be done manually (see step 3).
|
||||
|
||||
3. **After merge — verify automation**: The `project-auto-done.yml` workflow automatically moves project items to "Done" when issues close or PRs merge. After merge, verify it ran:
|
||||
```bash
|
||||
GH_PAGER=cat gh issue view <ISSUE_NUMBER> --json state,projectItems --jq '{state, projects: [.projectItems[] | {title: .title, status: .status.name}]}'
|
||||
```
|
||||
|
||||
**Manual fallback** — if the workflow fails or the item wasn't moved, use GraphQL:
|
||||
```bash
|
||||
GH_PAGER=cat gh api graphql -f query='mutation {
|
||||
updateProjectV2ItemFieldValue(input: {
|
||||
projectId: "PVT_kwHOADH82s4BO2OT"
|
||||
itemId: "<ITEM_ID>"
|
||||
fieldId: "PVTSSF_lAHOADH82s4BO2OTzg9bdkE"
|
||||
value: { singleSelectOptionId: "ca45af98" }
|
||||
}) { projectV2Item { id } }
|
||||
}'
|
||||
```
|
||||
|
||||
**Known Project field IDs (Status):**
|
||||
| Status | Option ID |
|
||||
|--------|-----------|
|
||||
| Triage | `826183f5` |
|
||||
| Backlog | `c7cb819e` |
|
||||
| Ready | `13307944` |
|
||||
| In progress | `732e285e` |
|
||||
| Done | `ca45af98` |
|
||||
|
||||
Status field ID: `PVTSSF_lAHOADH82s4BO2OTzg9bdkE`
|
||||
|
||||
### Issue Labels
|
||||
| Label | Applied by | Purpose |
|
||||
|-------|-----------|--------|
|
||||
| `enhancement` | Feature request template | New features |
|
||||
| `bug` | Bug report template | Bug fixes |
|
||||
| `triage` | Both templates | Needs review |
|
||||
|
||||
All three labels trigger the `add-to-project.yml` workflow, which automatically adds the issue to the Project board.
|
||||
|
||||
---
|
||||
|
||||
## Complete Workflow Summary
|
||||
|
||||
```
|
||||
Code complete & tests pass locally
|
||||
Code complete & validated by testing-manager
|
||||
↓
|
||||
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)
|
||||
1. Ensure a GitHub issue exists (create if not)
|
||||
2. Create feature branch (fix/... or feat/...)
|
||||
3. Commit, push, create PR (with "Closes #N" in body, assignee, label, project)
|
||||
4. Wait for CI (all required checks)
|
||||
5. Merge PR to main (squash + delete branch)
|
||||
6. Verify issue moved to "Done" on Project board (automated by `project-auto-done.yml`; fallback: GraphQL, see Task 6)
|
||||
↓
|
||||
Ready for release?
|
||||
↓
|
||||
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)
|
||||
7. Check current version (git tag + package.json)
|
||||
8. Analyze changes → determine SemVer level
|
||||
9. If minor/major: check README.md for needed updates (Task 5)
|
||||
10. Run ./scripts/release.sh <patch|minor|major>
|
||||
(or manually: branch → version bump → PR → CI → merge → tag)
|
||||
↓
|
||||
9. Write release notes (mandatory for minor/major)
|
||||
10. Publish GitHub release
|
||||
11. Write release notes (mandatory for minor/major)
|
||||
12. Publish GitHub release
|
||||
↓
|
||||
Docker images built automatically via CI
|
||||
```
|
||||
@@ -0,0 +1,161 @@
|
||||
---
|
||||
name: testing-manager
|
||||
description: Owns testing strategy, test implementation, local validation, and CI test triage for backend, frontend, and Playwright E2E.
|
||||
argument-hint: Describe what to test, e.g., "add tests for stock warning fix" or "analyze failing Playwright checks"
|
||||
---
|
||||
|
||||
# Testing Manager Agent
|
||||
|
||||
You are the testing manager for **MedAssist-ng**. Your job is to ensure every feature and bug fix is validated with the right tests, that CI test failures are diagnosed and fixed at the root cause, and that test coverage quality does not regress.
|
||||
|
||||
**All output (test code, comments, notes) MUST be in English**, even if the user communicates in German.
|
||||
|
||||
## Critical Testing Rules
|
||||
|
||||
- **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests.
|
||||
- **Fix bugs, don't test around them**: If behavior is incorrect, fix the implementation first, then write tests for correct behavior.
|
||||
- **Linting is a hard quality gate**: resolve all lint errors and all simple/fixable warnings before handoff, especially before PR handoff from `@release-manager`.
|
||||
- **Pre-PR local gate is mandatory**: before any PR is created, all lint errors must be fixed and all relevant tests must pass locally.
|
||||
- **No CI-first failures**: tests must fail locally when broken and be fixed locally before PR handoff; do not rely on GitHub CI to discover obvious regressions.
|
||||
- **Run tests non-interactively**: Use `CI=true` where required to avoid watch-mode hangs.
|
||||
- **Playwright must disable auto-open reports**: Always prefix Playwright runs with `PLAYWRIGHT_HTML_OPEN=never`.
|
||||
- **Keep CI E2E stable**: Use `PLAYWRIGHT_WORKERS=1` in CI unless a change is explicitly requested.
|
||||
- **Never start interactive report servers**: Do not run commands that wait for manual input (for example Playwright HTML report server: `Serving HTML report ... Press Ctrl+C to quit`). Always use finite, non-interactive commands and reporters.
|
||||
- **No remote git operations**: Do not push, merge, create PRs, tags, or releases. Hand over to `@release-manager` when ready.
|
||||
- **Keep scope focused**: Do not fix unrelated failures unless explicitly requested.
|
||||
- **Tests must be valid and reliable**: no fake-green tests, no assertions that skip core logic, no over-mocking that hides real behavior, and no brittle timing-only assertions.
|
||||
- **Regression prevention is mandatory**: every fixed bug must get a deterministic regression test that fails before the fix and passes after it.
|
||||
|
||||
## CI/CD Ownership Boundary
|
||||
|
||||
- **`@testing-manager` owns testing workflows only**: `.github/workflows/test.yml` and `.github/workflows/e2e.yml`.
|
||||
- **`@release-manager` owns orchestration/monitoring** of full workflow lifecycle and all non-testing workflows.
|
||||
- If a failure is outside testing scope (`codeql`, `docker-build`, `update-test-badges`, `add-to-project`), report and hand off to `@release-manager`.
|
||||
|
||||
## Test Stack & Locations
|
||||
|
||||
- **Backend unit/integration**: Vitest 4 + v8 coverage (`backend/src/test/*.test.ts`)
|
||||
- **Frontend unit/integration**: Vitest 4 + Testing Library (`frontend/src/test/**`)
|
||||
- **Frontend E2E**: Playwright (`frontend/e2e/**`) using stable config for CI-like runs
|
||||
|
||||
Primary locations:
|
||||
|
||||
- Backend tests: `backend/src/test/*.test.ts`
|
||||
- Frontend tests: `frontend/src/test/**`
|
||||
- Playwright E2E: `frontend/e2e/**`
|
||||
|
||||
## Required Test Workflow
|
||||
|
||||
1. Identify changed behavior and expected outcomes.
|
||||
2. Add/update tests near the affected feature.
|
||||
3. Run the smallest relevant subset first.
|
||||
4. Expand to broader suites if subset passes.
|
||||
5. Run lint + required local test/build gates before PR handoff.
|
||||
6. Report what was run, what passed, and any remaining known failures.
|
||||
|
||||
## Lint and Quality Gates
|
||||
|
||||
- Run lint as part of every validation cycle when code changed.
|
||||
- Required before PR creation and before PR-ready handoff from `@release-manager`: no lint errors and no simple/fixable warnings left unresolved.
|
||||
- If lint fails, fix root causes first, then re-run affected tests.
|
||||
- Required before PR creation: relevant local tests must pass (`backend`/`frontend` unit tests and relevant Playwright scope when affected).
|
||||
- If CI fails after a claimed local pass, treat it as a test validity gap and close that gap with deterministic local reproduction.
|
||||
|
||||
Recommended commands:
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
cd backend && npm run check
|
||||
cd frontend && npm run check
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
### Backend
|
||||
|
||||
```bash
|
||||
cd backend && CI=true npm run test:run
|
||||
cd backend && CI=true npm run test:coverage
|
||||
cd backend && CI=true npm run test:run -- -t "test name"
|
||||
```
|
||||
|
||||
### Frontend
|
||||
|
||||
```bash
|
||||
cd frontend && CI=true npm run test:run
|
||||
cd frontend && CI=true npm run test:coverage
|
||||
cd frontend && CI=true npm run test:run -- -t "test name"
|
||||
cd frontend && npm run lint
|
||||
cd frontend && npm run build
|
||||
```
|
||||
|
||||
### Playwright E2E
|
||||
|
||||
```bash
|
||||
cd frontend && PLAYWRIGHT_HTML_OPEN=never npm run test:e2e
|
||||
cd frontend && PLAYWRIGHT_HTML_OPEN=never PLAYWRIGHT_WORKERS=1 npm run test:e2e -- --workers=1
|
||||
cd frontend && PLAYWRIGHT_HTML_OPEN=never PLAYWRIGHT_WORKERS=4 npm run test:e2e:local
|
||||
cd frontend && PLAYWRIGHT_HTML_OPEN=never npm run test:e2e -- --project=chromium
|
||||
# Never use interactive UI/headed/report-server commands in agent runs.
|
||||
# Do not use: npm run test:e2e:ui, npm run test:e2e:headed, npx playwright show-report
|
||||
```
|
||||
|
||||
## Backend Test Patterns
|
||||
|
||||
- Prefer using test utilities from backend test setup (e.g. `buildTestApp`, helper factories).
|
||||
- Validate both status codes and response payloads.
|
||||
- Add regression tests for every fixed bug.
|
||||
- Keep tests deterministic and isolated.
|
||||
- Validate observable behavior, not implementation details.
|
||||
|
||||
## E2E Test Patterns
|
||||
|
||||
- Use stable selectors and explicit assertions.
|
||||
- Avoid flaky timing assumptions; prefer waiting for concrete UI states.
|
||||
- For auth-sensitive flows, handle both auth-enabled and auth-disabled environments when applicable.
|
||||
- For CI triage, inspect failed run logs first, then reproduce locally with targeted specs.
|
||||
- Prefer user-meaningful assertions (visible state, persisted effects, API-visible outcomes) over brittle internal hooks.
|
||||
|
||||
## Test Validity Checklist
|
||||
|
||||
- The test fails when the real target logic is intentionally broken.
|
||||
- The assertion verifies functional behavior, not just mocked calls.
|
||||
- Mocks/stubs are minimal and do not replace the unit under test.
|
||||
- The test is deterministic across repeated local and CI runs.
|
||||
- The test protects against the specific regression that was fixed.
|
||||
|
||||
## CI Failure Triage
|
||||
|
||||
When test checks fail:
|
||||
|
||||
1. Retrieve exact failed jobs and logs.
|
||||
2. Categorize failure: lint/format, environment/proxy, flaky selectors, app bug.
|
||||
3. Fix root cause.
|
||||
4. Re-run focused tests locally.
|
||||
5. Re-run broader checks if needed.
|
||||
6. Hand off for PR/merge via `@release-manager`.
|
||||
|
||||
## CI/CD Testing Context
|
||||
|
||||
- PR validation includes backend tests and frontend build/lint checks.
|
||||
- E2E runs in GitHub Actions through `.github/workflows/e2e.yml`.
|
||||
- Docker build and badge update workflows run after merge/tag and may include test-related verification.
|
||||
|
||||
### Testing Workflow Focus (Current)
|
||||
|
||||
| Workflow | Testing-Manager Action |
|
||||
|---------|------------------------|
|
||||
| `.github/workflows/test.yml` | Investigate failures, implement fixes, revalidate locally |
|
||||
| `.github/workflows/e2e.yml` | Investigate failures/flakes, stabilize tests, revalidate locally |
|
||||
|
||||
## Done Criteria
|
||||
|
||||
Testing work is complete when:
|
||||
|
||||
- Required tests exist and validate intended behavior.
|
||||
- Tests are proven valid (not fake-green) and reliable.
|
||||
- Lint is clean: no errors and no simple/fixable warnings left.
|
||||
- Pre-PR local gate passed: lint and all relevant tests pass locally before handoff for PR creation.
|
||||
- Relevant local test commands pass.
|
||||
- CI test failures are resolved or clearly documented with rationale.
|
||||
- No temporary debugging files remain in the workspace.
|
||||
+12
-459
@@ -1,466 +1,19 @@
|
||||
# MedAssist-ng - AI Coding Instructions
|
||||
# MedAssist-ng - Copilot Entry Point
|
||||
|
||||
## General Rules
|
||||
## VERY IMPORTANT
|
||||
|
||||
- **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English.
|
||||
- **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action.
|
||||
- **NEVER create PRs, push, or merge**: Only the **release-manager agent** (`@release-manager`) is allowed to create Pull Requests, push branches to the remote, or merge code. Regular agents and Copilot MUST NOT perform any git operations that affect the remote repository (no `git push`, no `gh pr create`, no `gh pr merge`). Present your local changes and tell the user to invoke `@release-manager` when ready to ship.
|
||||
- **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository.
|
||||
- **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done.
|
||||
- **Remove old code when re-implementing**: When fixing a bug or re-implementing a feature that didn't work, ALWAYS remove the old/broken code completely. Never leave dead code, unused functions, or obsolete implementations in the codebase.
|
||||
- **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests. When modifying existing features, update or add tests accordingly. If old tests become obsolete due to code changes, remove or update them.
|
||||
- **Fix bugs, don't test around them**: If you discover incorrect behavior in the code while writing tests, ALWAYS fix the buggy code first, then write tests that verify the correct behavior. NEVER write tests that mimic or assert broken behavior. The user's time is finite and irreplaceable — every bug left unfixed wastes it.
|
||||
- **Keep README.md up to date**: After implementing code changes, check whether the `README.md` needs to be updated (e.g., new features, changed ENV variables, new commands, changed architecture, new endpoints, updated screenshots). If changes are relevant to the README, **ask the user for confirmation** before updating it. Do NOT silently update the README — always present the proposed README changes and wait for approval. Examples of README-relevant changes: new ENV variables, new API endpoints, new UI features, changed setup/install steps, new dependencies, changed Docker configuration.
|
||||
- Always keep agent work memory updated in `doku/memory_notes.md` so progress and decisions remain recoverable across context loss.
|
||||
- Always keep a user-facing work report updated in `doku/report.md` so completed work is easy to review.
|
||||
- This memory/report rule replaces the previous `doku/APP_BEHAVIOR.md` persistence requirement.
|
||||
|
||||
## Architecture Overview
|
||||
Use `AGENTS.md` as the single source of truth for all governance, workflow, and skill rules.
|
||||
|
||||
MedAssist-ng is a **medication tracking and planning app** with a monorepo structure:
|
||||
## Required Startup Steps
|
||||
|
||||
- **Backend**: Fastify 5 + TypeScript + SQLite (Drizzle ORM) at `backend/`
|
||||
- **Frontend**: React 18 + Vite + TypeScript at `frontend/`
|
||||
- **Database**: SQLite with migrations in `backend/src/db/migrations/`
|
||||
- **Deployment**: Docker Compose with separate dev containers
|
||||
- **i18n**: English (en) and German (de) via react-i18next
|
||||
1. Read `AGENTS.md` first.
|
||||
2. Identify triggered skills from `AGENTS.md` and read each referenced `SKILL.md` before making changes.
|
||||
3. Follow delegation boundaries exactly (`@testing-manager` for testing, `@release-manager` for release orchestration).
|
||||
|
||||
### Data Flow
|
||||
```
|
||||
Frontend (React) → /api/* proxy → Backend (Fastify) → SQLite
|
||||
↓ (Vite rewrites /api to /)
|
||||
```
|
||||
## Scope
|
||||
|
||||
The Vite proxy at `frontend/vite.config.ts` rewrites `/api/*` to `/` - so frontend calls `/api/medications` but backend route is just `/medications`.
|
||||
|
||||
## Development Commands
|
||||
|
||||
```bash
|
||||
# Start dev environment (preferred)
|
||||
docker compose -f docker-compose.dev.yml up
|
||||
|
||||
# Or run services separately:
|
||||
cd backend && npm run dev # tsx watch on port 3000
|
||||
cd frontend && npm run dev # Vite on port 5173
|
||||
|
||||
# Production
|
||||
docker compose up -d
|
||||
|
||||
# Database migrations
|
||||
cd backend && npm run migrate
|
||||
|
||||
# Run tests
|
||||
cd backend && npm test # Run all tests
|
||||
cd backend && npm run test:coverage # Run with coverage report
|
||||
```
|
||||
|
||||
## Testing (MANDATORY)
|
||||
|
||||
> ⚠️ **IMPORTANT**: Every new feature MUST be covered by tests!
|
||||
> Pull Requests without tests for new features will not be accepted.
|
||||
|
||||
### Test Framework
|
||||
- **Vitest 2.1** with v8 Coverage
|
||||
- Tests in `backend/src/test/*.test.ts`
|
||||
- Coverage goal: At least equal or better coverage after changes
|
||||
|
||||
### Test Structure
|
||||
| File | Tests |
|
||||
|------|-------|
|
||||
| `routes.test.ts` | API endpoints (Auth, Medications, Doses, Settings, Share, Planner) |
|
||||
| `services.test.ts` | Scheduler utilities (Timezone, Blisters, Usage calculation) |
|
||||
| `db.test.ts` | Database schema and operations |
|
||||
|
||||
### Writing Tests
|
||||
|
||||
```typescript
|
||||
// Backend Test Example (backend/src/test/example.test.ts)
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { createTestApp, createTestUser } from './routes.test'; // Test-Utilities
|
||||
|
||||
describe('Feature Name', () => {
|
||||
let app: FastifyInstance;
|
||||
let authToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
const user = await createTestUser(app);
|
||||
authToken = user.token;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('should do something specific', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/endpoint',
|
||||
headers: { Authorization: `Bearer ${authToken}` }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toHaveProperty('expectedField');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Test Commands
|
||||
```bash
|
||||
cd backend
|
||||
CI=true npm test # Run tests once (ALWAYS run this way!)
|
||||
CI=true npm run test:coverage # With coverage report
|
||||
npm test -- --watch # Watch mode for manual development
|
||||
npm test -- -t "test name" # Run single test
|
||||
```
|
||||
|
||||
> ⚠️ **IMPORTANT for AI agents**: ALWAYS run tests with `CI=true`!
|
||||
> Without `CI=true`, Vitest runs in watch mode and waits for input.
|
||||
|
||||
## CI/CD Pipeline (GitHub Actions)
|
||||
|
||||
### Workflow Overview
|
||||
|
||||
```
|
||||
Pull Request created
|
||||
↓
|
||||
┌─────────────────────────────────────┐
|
||||
│ test.yml │
|
||||
│ ├─ backend-test (parallel) │
|
||||
│ │ ├─ npm ci │
|
||||
│ │ ├─ tsc --noEmit (Type-Check) │
|
||||
│ │ └─ npm run test:coverage │
|
||||
│ └─ frontend-build (parallel) │
|
||||
│ ├─ npm ci │
|
||||
│ └─ npm run build │
|
||||
└─────────────────────────────────────┘
|
||||
↓ Tests must pass
|
||||
PR can be merged
|
||||
↓
|
||||
Push to main / Tag created
|
||||
↓
|
||||
┌─────────────────────────────────────┐
|
||||
│ docker-build.yml │
|
||||
│ └─ build-and-push │
|
||||
│ ├─ Build Docker images │
|
||||
│ └─ Push to GHCR │
|
||||
│ (Tag builds also set "latest") │
|
||||
└─────────────────────────────────────┘
|
||||
↓ After successful build
|
||||
┌─────────────────────────────────────┐
|
||||
│ update-test-badges.yml │
|
||||
│ (workflow_run after docker-build) │
|
||||
│ └─ Run tests, update badge counts │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Branch Protection
|
||||
|
||||
> ⚠️ **IMPORTANT**: The `main` branch is protected!
|
||||
> Direct pushing to `main` is **not possible** - GitHub will reject the push.
|
||||
> All changes must go through Pull Requests.
|
||||
|
||||
- **main** branch is protected (Repository Rules)
|
||||
- Direct pushing is rejected by GitHub with: `GH013: Repository rule violations`
|
||||
- PRs require:
|
||||
- ✅ `backend-test` Status Check passed
|
||||
- ✅ `frontend-build` Status Check passed
|
||||
- After successful merge, the feature branch is automatically deleted
|
||||
|
||||
**Workflow for changes:**
|
||||
```bash
|
||||
# 1. Create feature branch
|
||||
git checkout -b feat/my-feature
|
||||
|
||||
# 2. Commit and push changes
|
||||
git add . && git commit -m "feat: Description"
|
||||
git push -u origin feat/my-feature
|
||||
|
||||
# 3. Create PR (via GitHub CLI or Web)
|
||||
gh pr create --title "My Feature" --body "Description"
|
||||
|
||||
# 4. Wait until CI is green, then merge
|
||||
gh pr merge --squash --delete-branch
|
||||
```
|
||||
|
||||
### Workflow Files
|
||||
| File | Trigger | Purpose |
|
||||
|------|---------|--------|
|
||||
| `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures |
|
||||
| `.github/workflows/docker-build.yml` | Push to main, Tags | Build and push Docker images (+ create GitHub release on tags) |
|
||||
| `.github/workflows/update-test-badges.yml` | After successful docker-build | Update test count badges in README |
|
||||
| `.github/workflows/codeql.yml` | Push to main, PRs, Weekly | Security analysis |
|
||||
|
||||
## Key Patterns
|
||||
|
||||
### Backend Routes (`backend/src/routes/`)
|
||||
| Route File | Endpoints |
|
||||
|------------|-----------|
|
||||
| `auth.ts` | `/auth/login`, `/auth/register`, `/auth/logout`, `/auth/refresh`, `/auth/me` |
|
||||
| `medications.ts` | CRUD `/medications`, `/medications/:id/image` |
|
||||
| `doses.ts` | `/doses/taken` - track dose intake |
|
||||
| `planner.ts` | `/medications/usage` - calculate usage for date range |
|
||||
| `settings.ts` | `/settings` - user settings CRUD |
|
||||
| `share.ts` | `/share` - create share tokens, `/share/:token` - public access |
|
||||
| `health.ts` | `/health` - health check endpoint |
|
||||
|
||||
### Backend Services (`backend/src/services/`)
|
||||
| Service | Description |
|
||||
|---------|-------------|
|
||||
| `reminder-scheduler.ts` | Stock reminder emails/push notifications |
|
||||
| `intake-reminder-scheduler.ts` | Intake reminder notifications |
|
||||
|
||||
### Frontend (`frontend/src/App.tsx`)
|
||||
- Single-file React app with all components and state
|
||||
- Uses React Router for navigation
|
||||
- API calls use `/api/` prefix (proxied by Vite)
|
||||
- Medication scheduling logic with intake schedules (multiple time entries per medication)
|
||||
|
||||
## Frontend Components & Views
|
||||
|
||||
### Routes / Pages
|
||||
| Route | Description |
|
||||
|-------|-------------|
|
||||
| `/dashboard` | Main view with Coverage Cards + Upcoming Schedules timeline |
|
||||
| `/medications` | Medications list + New/Edit form with all fields |
|
||||
| `/planner` | Usage planner - calculate needed pills for date range |
|
||||
| `/settings` | App settings: notifications, email, thresholds, language |
|
||||
| `/schedule` | Full schedule view (simplified, no coverage cards) |
|
||||
| `/share/:token` | Public share link for "taken by" user schedule |
|
||||
|
||||
### Key React Components (in App.tsx)
|
||||
| Component | Description |
|
||||
|-----------|-------------|
|
||||
| `App` | Root component with BrowserRouter |
|
||||
| `AppRouter` | Handles auth check, renders AppContent or Auth |
|
||||
| `AppContent` | Main app shell with navigation, header, all routes |
|
||||
| `SharedSchedule` | Public share page for medication schedules by person |
|
||||
| `MedicationAvatar` | Round avatar with medication image or colored initial |
|
||||
|
||||
### Dashboard Sections
|
||||
| Section | Description |
|
||||
|---------|-------------|
|
||||
| **Coverage Cards** | Stock status cards per medication: days left, blisters, status (Normal/Warning/Critical) |
|
||||
| **Upcoming Schedules** | Timeline grouped by day, collapsible days, dose tracking |
|
||||
|
||||
### Schedule/Timeline Elements
|
||||
| Element | CSS Class | Description |
|
||||
|---------|-----------|-------------|
|
||||
| Past days toggle | `.past-days-toggle` | Click to show/hide past days |
|
||||
| Day container | `.day-block` | Container for one day, collapsible |
|
||||
| Today highlight | `.day-block.today` | Blue border/background for current day |
|
||||
| Past day | `.day-block.past` | Dashed border, reduced opacity |
|
||||
| All taken | `.day-block.all-taken` | Green styling when all doses taken |
|
||||
| Day header | `.day-divider` | Date header with collapse toggle arrow |
|
||||
| Collapse icon | `.day-collapse-icon` | ▶/▼ arrow for expand/collapse |
|
||||
| Day summary | `.day-summary` | Shows "X/Y" doses taken or "✓ All taken" |
|
||||
| Medication row | `.time-row` | One medication's doses for that day |
|
||||
| Dose item | `.dose-item` | Individual dose with time, amount, take/undo button |
|
||||
| Dose taken | `.dose-item.taken` | Green background when dose is marked taken |
|
||||
| Dose overdue | `.dose-item.overdue` | Styling for past untaken doses |
|
||||
| Dose future | `.dose-item.future` | Disabled button for future days |
|
||||
|
||||
### Medication Form (New/Edit)
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| Commercial Name | Main medication name (required) |
|
||||
| Generic Name | Scientific/generic name (optional) |
|
||||
| Taken By | Person taking the medication (optional, enables filtering/sharing) |
|
||||
| Packs | Number of full packs |
|
||||
| Blisters per Pack | Strips/blisters in each pack |
|
||||
| Pills per Blister | Tablets per strip |
|
||||
| Loose Pills | Extra pills not in blisters |
|
||||
| Pill Weight (mg) | Weight per pill for dose calculation display |
|
||||
| Expiry Date | Medication expiration |
|
||||
| Notes | Free text notes |
|
||||
| Image Upload | Medication photo (preview for new, direct upload for edit) |
|
||||
| **Intake Schedule** | One or more intake entries defining usage pattern |
|
||||
|
||||
### Intake Schedule
|
||||
Each blister defines a recurring intake:
|
||||
- **Usage (Pills)**: How many pills per dose
|
||||
- **Every (Days)**: Interval (1 = daily, 7 = weekly)
|
||||
- **Start (Date/Time)**: When the schedule starts (determines past/future doses)
|
||||
- **Remind checkbox**: Enable intake reminders (🔔)
|
||||
|
||||
### Modals
|
||||
| Modal | Trigger | Content |
|
||||
|-------|---------|---------|
|
||||
| Medication Detail | Click on coverage card or medication row | Full medication info, stock, schedule preview, edit/delete/ICS buttons |
|
||||
| Image Lightbox | Click medication image | Full-size medication image |
|
||||
| Share Dialog | "Share" button on schedules | Generate share link for specific "taken by" person |
|
||||
| User Schedule Filter | Click on "taken by" badge | Filter schedule by person |
|
||||
|
||||
### Settings Sections
|
||||
| Section | Settings |
|
||||
|---------|----------|
|
||||
| General | Language toggle (EN/DE) |
|
||||
| Stock Thresholds | Warning days, critical days, expiry warning days |
|
||||
| Email Notifications | Enable, email address, stock/intake toggles |
|
||||
| Push Notifications (Shoutrrr) | Enable, URL (ntfy/gotify/etc), stock/intake toggles |
|
||||
| Reminder Settings | Days before, repeat daily, skip for taken, repeat/nagging |
|
||||
| SMTP | Email config (read-only from .env) |
|
||||
|
||||
### Settings ENV Defaults
|
||||
All user settings can be pre-configured via ENV variables (see `.env.example`).
|
||||
These are only used as **defaults when a new user is created**.
|
||||
Once a user saves settings in the app, their saved values take precedence over ENV.
|
||||
|
||||
| ENV Variable | Setting | Default |
|
||||
|--------------|---------|---------|
|
||||
| `DEFAULT_EMAIL_ENABLED` | Email notifications | false |
|
||||
| `DEFAULT_SHOUTRRR_ENABLED` | Push notifications | false |
|
||||
| `DEFAULT_SHOUTRRR_URL` | ntfy/gotify URL | (empty) |
|
||||
| `DEFAULT_REPEAT_REMINDERS_ENABLED` | Nagging reminders | false |
|
||||
| `DEFAULT_REMINDER_REPEAT_INTERVAL_MINUTES` | Nag interval | 30 |
|
||||
| `DEFAULT_MAX_NAGGING_REMINDERS` | Max nags | 5 |
|
||||
| `DEFAULT_LOW_STOCK_DAYS` | Low stock threshold | 30 |
|
||||
| `DEFAULT_LANGUAGE` | UI language | en |
|
||||
|
||||
## Database Schema (`backend/src/db/schema.ts`)
|
||||
|
||||
| Table | Description |
|
||||
|-------|-------------|
|
||||
| `users` | User accounts with password hash, auth provider, timestamps |
|
||||
| `medications` | Per-user medications with inventory, schedules as JSON arrays |
|
||||
| `userSettings` | Per-user settings: notifications, thresholds, language |
|
||||
| `refreshTokens` | JWT refresh tokens for auth rotation |
|
||||
| `shareTokens` | Public share links by takenBy person |
|
||||
| `doseTracking` | Tracks when doses are marked as taken |
|
||||
|
||||
### Key Medication Fields
|
||||
```typescript
|
||||
{
|
||||
name, genericName, takenByJson, // Identity (takenByJson is JSON array)
|
||||
packCount, blistersPerPack, pillsPerBlister, looseTablets, // Inventory
|
||||
pillWeightMg, // For mg display
|
||||
usageJson, everyJson, startJson, // Intake schedules as JSON arrays
|
||||
imageUrl, expiryDate, notes, // Optional metadata
|
||||
intakeRemindersEnabled // Per-med reminder toggle
|
||||
}
|
||||
```
|
||||
|
||||
### Dose ID Format
|
||||
Dose IDs follow the pattern: `{medicationId}-{blisterIndex}-{timestampMs}`
|
||||
Example: `5-0-1735344000000` = Medication 5, Blister 0, timestamp
|
||||
|
||||
## State Management (AppContent)
|
||||
|
||||
### Key State Variables
|
||||
| State | Purpose |
|
||||
|-------|---------|
|
||||
| `meds` | Array of all user's medications |
|
||||
| `form` | Current medication form data |
|
||||
| `editingId` | ID of medication being edited (null for new) |
|
||||
| `pendingImage` / `pendingImagePreview` | Image upload for new medications |
|
||||
| `settings` / `savedSettings` | User settings current vs saved |
|
||||
| `scheduleDays` | How many days to show (30/90/180) |
|
||||
| `showPastDays` | Toggle for past days visibility |
|
||||
| `takenDoses` | Set of dose IDs that are marked taken |
|
||||
| `manuallyCollapsedDays` / `manuallyExpandedDays` | Day collapse state |
|
||||
| `selectedMed` | Medication shown in detail modal |
|
||||
| `selectedUser` | Filter schedule by "taken by" person |
|
||||
|
||||
### Key Computed Values (useMemo)
|
||||
| Value | Purpose |
|
||||
|-------|---------|
|
||||
| `schedule` | All scheduled events from `buildSchedulePreview()` |
|
||||
| `groupedSchedule` | Events grouped by day |
|
||||
| `pastDays` / `futureDays` | Split groupedSchedule by today |
|
||||
| `coverage` | Stock coverage calculations |
|
||||
| `coverageByMed` / `depletionByMed` | Coverage lookups |
|
||||
|
||||
## Conventions
|
||||
|
||||
- **TypeScript**: Strict mode, ESM modules (`"type": "module"`)
|
||||
- **Styling**: CSS custom properties in `frontend/src/styles.css`, dark/light theme via `data-theme`
|
||||
- **API responses**: Return objects directly, Fastify serializes to JSON
|
||||
- **Environment**: Copy `.env.example` → `.env`, secrets must be 10+ chars
|
||||
- **i18n**: All UI text via `t('key')` function, translations in `frontend/src/i18n/*.json`
|
||||
- **UI Consistency**: Always use existing components for modals, buttons, and forms. For confirmation dialogs, use `ConfirmModal` component. Never create inline modals with custom button styling - all UI elements must match the existing design system. When adding new sections to existing components, ensure font sizes, spacing, margins, and button styles match exactly with other sections. Check existing CSS classes before creating new ones.
|
||||
|
||||
## Database Schema Changes (IMPORTANT: Backward Compatibility!)
|
||||
|
||||
> ⚠️ **CRITICAL**: The app MUST remain backward compatible with older databases!
|
||||
> Users upgrade their Docker containers but keep their existing DB.
|
||||
> The app must NOT crash if old columns are missing.
|
||||
|
||||
### ⚠️ MANDATORY for EVERY New Feature
|
||||
|
||||
**Before implementing ANY feature that touches user data or settings:**
|
||||
|
||||
1. **Check if new DB columns are needed** - Does the feature require storing new data?
|
||||
2. **If YES → Follow ALL steps below** - Schema.ts + Drizzle migration + ALTER migration + NULL-safe code
|
||||
3. **NEVER skip the ALTER migration** - This is the #1 cause of production 500 errors!
|
||||
|
||||
**Common mistake:** Adding a column to `schema.ts` and forgetting the ALTER migration in `client.ts`.
|
||||
The Drizzle migration only works for NEW databases. Existing production databases need the ALTER migration!
|
||||
|
||||
### Schema Management with Drizzle Kit
|
||||
|
||||
The database schema uses **Drizzle Kit** for migrations. There is a **single source of truth**:
|
||||
|
||||
- **`backend/src/db/schema.ts`** - Drizzle ORM schema definitions (TypeScript)
|
||||
- **`backend/drizzle/`** - Generated SQL migrations (auto-generated from schema.ts)
|
||||
|
||||
**DO NOT manually edit migration files!** They are generated from schema.ts.
|
||||
|
||||
### Adding New Columns
|
||||
|
||||
1. **Add to schema.ts** with DEFAULT value:
|
||||
```typescript
|
||||
maxNaggingReminders: integer("max_nagging_reminders").notNull().default(5),
|
||||
```
|
||||
|
||||
2. **Generate migration**:
|
||||
```bash
|
||||
cd backend && npx drizzle-kit generate --name add_column_name
|
||||
```
|
||||
|
||||
3. **Add backward-compatible ALTER migration** in `client.ts` `runAlterMigrations()`:
|
||||
```typescript
|
||||
`ALTER TABLE user_settings ADD COLUMN max_nagging_reminders integer NOT NULL DEFAULT 5`,
|
||||
```
|
||||
|
||||
4. **NULL-safe reading** in routes:
|
||||
```typescript
|
||||
maxNaggingReminders: settings.maxNaggingReminders ?? 5,
|
||||
```
|
||||
|
||||
### Rules for New Columns
|
||||
|
||||
1. **ALWAYS with DEFAULT value**: New columns must have `NOT NULL DEFAULT <value>`
|
||||
2. **NULL-safe in code**: All queries must use `?? defaultValue` or `?? false`
|
||||
3. **Generate migration**: Run `npx drizzle-kit generate` after schema changes
|
||||
4. **Add ALTER migration**: For backward compatibility with existing DBs
|
||||
|
||||
### What is NOT Allowed
|
||||
|
||||
- ❌ Deleting or renaming columns (breaks old DBs)
|
||||
- ❌ `NOT NULL` without `DEFAULT` (INSERT fails)
|
||||
- ❌ Reading columns without fallback in code
|
||||
- ❌ Manually editing migration SQL files
|
||||
- ❌ Documenting "delete DB" as a solution
|
||||
|
||||
### When Backward Compatibility is NOT Possible
|
||||
|
||||
If a breaking change is unavoidable:
|
||||
1. **Explicitly communicate**: Document in release notes
|
||||
2. **Migration script**: Provide automatic upgrade script
|
||||
3. **Version check**: App should check DB version and warn
|
||||
|
||||
## File Locations
|
||||
|
||||
| Purpose | Location |
|
||||
|---------|----------|
|
||||
| Backend entry | `backend/src/index.ts` |
|
||||
| Database schema | `backend/src/db/schema.ts` |
|
||||
| Drizzle migrations | `backend/drizzle/*.sql` |
|
||||
| Drizzle config | `backend/drizzle.config.ts` |
|
||||
| Backend routes | `backend/src/routes/*.ts` |
|
||||
| Backend services | `backend/src/services/*.ts` |
|
||||
| Frontend app | `frontend/src/App.tsx` |
|
||||
| Frontend auth | `frontend/src/components/Auth.tsx` |
|
||||
| Styles | `frontend/src/styles.css` |
|
||||
| i18n English | `frontend/src/i18n/en.json` |
|
||||
| i18n German | `frontend/src/i18n/de.json` |
|
||||
| Docker prod | `docker-compose.yml` |
|
||||
| Docker dev | `docker-compose.dev.yml` |
|
||||
| Env template | `.env.example` |
|
||||
This file intentionally stays minimal to prevent duplicated or conflicting instructions.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
version: 2
|
||||
|
||||
updates:
|
||||
# Backend dependencies
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/backend"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "06:20"
|
||||
open-pull-requests-limit: 10
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "backend"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
|
||||
# Frontend dependencies
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/frontend"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "06:10"
|
||||
open-pull-requests-limit: 10
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "frontend"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
|
||||
# Root dev dependencies
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "06:00"
|
||||
open-pull-requests-limit: 5
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "root"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
|
||||
# GitHub Actions
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "06:30"
|
||||
open-pull-requests-limit: 5
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "ci"
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
@@ -0,0 +1,28 @@
|
||||
# MedAssist Agent Skills
|
||||
|
||||
This directory contains project skills for VS Code Copilot.
|
||||
|
||||
Each skill lives in its own folder and must include a `SKILL.md` file.
|
||||
|
||||
## Global Rule Reminder
|
||||
|
||||
When re-implementing a feature or fix path, remove obsolete/unused code immediately.
|
||||
Do not leave dead code behind.
|
||||
Also follow the canonical global engineering rules in `AGENTS.md`.
|
||||
Use one governance source to avoid duplicated or conflicting policy text.
|
||||
|
||||
## Skills
|
||||
|
||||
- `medassist-karpathy-core` — enforce think-before-coding, simplicity-first changes, surgical diffs, and goal-driven verification.
|
||||
- `medassist-architecture-guard` — enforce frontend/backend boundary and `/api/*` data-flow conventions.
|
||||
- `medassist-db-compat-check` — enforce backward-compatible SQLite/Drizzle schema changes.
|
||||
- `medassist-i18n-enforcer` — enforce translation-key-only UI copy with EN/DE parity.
|
||||
- `medassist-ui-consistency` — enforce non-negotiable UI guardrails and component/style reuse.
|
||||
- `medassist-frontend-polish` — apply tasteful visual refinement after consistency guardrails are met.
|
||||
- `medassist-security-sanity` — apply baseline security checks for backend and input/auth-sensitive changes.
|
||||
- `medassist-config-change-guard` — validate env, Docker, proxy, and runtime-config compatibility.
|
||||
- `medassist-doc-sync-guard` — ensure docs stay aligned with behavior/setup/config changes.
|
||||
- `medassist-observability-guard` — preserve actionable logging, health checks, and failure visibility.
|
||||
- `medassist-skill-quality-review` — review skill quality, trigger clarity, and governance alignment.
|
||||
- `medassist-testing-handoff` — delegate testing and CI test-failure triage to `@testing-manager`.
|
||||
- `medassist-release-handoff` — delegate PR/merge/release actions to `@release-manager`.
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
name: medassist-architecture-guard
|
||||
description: Guard MedAssist architectural boundaries and route/data-flow conventions when changing backend or frontend code, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when a task touches API endpoints, frontend API calls, routing, or code placement.
|
||||
|
||||
## Goals
|
||||
|
||||
- Keep responsibilities in the correct layer.
|
||||
- Preserve MedAssist proxy and routing conventions.
|
||||
- Prevent architecture drift and cross-layer anti-patterns.
|
||||
|
||||
## Required Checks
|
||||
|
||||
1. Frontend network calls use `/api/*` paths.
|
||||
2. Backend routes are implemented under `backend/src/routes/` with matching service logic in `backend/src/services/` when needed.
|
||||
3. No frontend-only logic is moved into backend and no backend-only logic is embedded in UI components.
|
||||
4. Type definitions are shared through existing project structure (`types/`, route DTO patterns) without creating duplicate source-of-truth models.
|
||||
|
||||
## MedAssist-Specific Guardrails
|
||||
|
||||
- Respect Vite proxy behavior: frontend calls `/api/*`, backend exposes `/...` routes.
|
||||
- Keep app shell and routing patterns aligned with existing frontend pages/components.
|
||||
- Prefer minimal, local changes over broad restructures.
|
||||
|
||||
## Response Format
|
||||
|
||||
When this skill is used, summarize:
|
||||
|
||||
- Which architectural checks were applied
|
||||
- Which files are affected
|
||||
- Any boundary risks found and how they were resolved
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
name: medassist-config-change-guard
|
||||
description: Validate MedAssist configuration changes across env vars, Docker compose, proxy settings, and runtime defaults, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when changes touch `.env`, Docker files, Vite proxy settings, runtime defaults, or app startup behavior.
|
||||
|
||||
## Objective
|
||||
|
||||
Prevent configuration drift and broken local/CI environments.
|
||||
|
||||
## Required Checks
|
||||
|
||||
1. New/changed config has safe defaults.
|
||||
2. Env changes are backward-compatible where feasible.
|
||||
3. Docker/dev runtime changes remain consistent across services.
|
||||
4. Frontend/backend URL/proxy conventions remain valid (`/api/*`).
|
||||
5. Documentation reflects configuration changes.
|
||||
|
||||
## Files to Prioritize
|
||||
|
||||
- `.env.example`
|
||||
- `docker-compose.yml`
|
||||
- `docker-compose.dev.yml`
|
||||
- `frontend/vite.config.ts`
|
||||
- Relevant package scripts and startup files
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Hidden required env vars with no defaults.
|
||||
- Inconsistent host/port/proxy settings across environments.
|
||||
- Config changes without doc updates.
|
||||
|
||||
## Response Format
|
||||
|
||||
Report:
|
||||
|
||||
- Config files reviewed
|
||||
- Compatibility impact (none/low/high)
|
||||
- Required follow-up updates
|
||||
- Final readiness recommendation
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
name: medassist-db-compat-check
|
||||
description: Enforce backward-compatible database changes for MedAssist SQLite and Drizzle migrations, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill for any feature or fix that adds or reads persisted data.
|
||||
|
||||
## Mandatory Sequence
|
||||
|
||||
For every new persisted field/column:
|
||||
|
||||
1. Add the column in `backend/src/db/schema.ts` with `NOT NULL DEFAULT <value>`.
|
||||
2. Generate migration with Drizzle Kit.
|
||||
3. Add matching `ALTER TABLE` logic in `backend/src/db/client.ts` inside `runAlterMigrations()`.
|
||||
4. Read values null-safe in routes/services (`?? defaultValue`).
|
||||
|
||||
## Hard Rules
|
||||
|
||||
- Never remove or rename existing columns.
|
||||
- Never add non-null columns without defaults.
|
||||
- Never read newly added fields without fallback.
|
||||
- Never manually edit generated Drizzle SQL migrations.
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- Schema update exists.
|
||||
- Generated migration exists.
|
||||
- Alter migration for existing DBs exists.
|
||||
- Runtime reads are fallback-safe.
|
||||
|
||||
## Response Format
|
||||
|
||||
Report these items explicitly:
|
||||
|
||||
- New/changed columns
|
||||
- Added alter-migration statements
|
||||
- Null-safe read locations
|
||||
- Remaining migration risk (if any)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
name: medassist-doc-sync-guard
|
||||
description: Ensure MedAssist documentation stays aligned with behavior changes in APIs, configuration, setup, and operations, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when code changes alter behavior, setup steps, environment variables, user workflows, or operational commands.
|
||||
|
||||
## Objective
|
||||
|
||||
Keep docs consistent with actual product behavior and avoid stale setup/run guidance.
|
||||
|
||||
## Required Checks
|
||||
|
||||
1. If API behavior changed, verify relevant docs are updated.
|
||||
2. If ENV/config changed, update documented variables/defaults.
|
||||
3. If workflow/commands changed, update setup/run instructions.
|
||||
4. If user-facing behavior changed, update user-facing description.
|
||||
|
||||
## Candidate Documentation Files
|
||||
|
||||
- `README.md`
|
||||
- `docs/PROJECT_SETUP.md`
|
||||
- `docs/TECH_STACK.md`
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Shipping behavior changes without docs updates.
|
||||
- Updating docs with speculative/unverified commands.
|
||||
- Duplicating conflicting instructions across files.
|
||||
|
||||
## Response Format
|
||||
|
||||
Return:
|
||||
|
||||
- Doc files that should change
|
||||
- Proposed update summary per file
|
||||
- Any intentionally skipped docs and reason
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: medassist-frontend-polish
|
||||
description: Improve frontend visual quality within the existing MedAssist design system, without introducing new themes, font stacks, or disruptive UI patterns, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when the user wants UI improvements, better styling, or a more polished frontend, but the feature must stay consistent with MedAssist product UX.
|
||||
|
||||
## Scope
|
||||
|
||||
This is the **visual enhancement skill**.
|
||||
It refines quality *within* existing product conventions.
|
||||
|
||||
Apply `medassist-ui-consistency` rules first, then use this skill for tasteful polish.
|
||||
|
||||
## Do Not Use This Skill For
|
||||
|
||||
- Replacing base UI patterns/components with new ones.
|
||||
- New design-system direction, visual identity, or broad layout language changes.
|
||||
- Marketing/brand-experiment pages that intentionally break product conventions.
|
||||
|
||||
## Objective
|
||||
|
||||
Deliver production-grade visual refinement that feels intentionally designed while remaining fully consistent with existing MedAssist components, spacing, typography, and interaction patterns.
|
||||
|
||||
## Strict Constraints
|
||||
|
||||
- Reuse existing components and patterns first (`ConfirmModal`, `MedicationAvatar`, existing form/button/layout patterns).
|
||||
- Do not introduce new global theme systems, font families, or visual identity changes.
|
||||
- Do not invent new UX flows, pages, or interaction models unless explicitly requested.
|
||||
- Keep frontend text i18n-safe: use `t("...")` and EN/DE keys.
|
||||
- Respect accessibility and readability over decorative effects.
|
||||
|
||||
## Allowed Enhancements
|
||||
|
||||
- Better spacing rhythm and visual hierarchy.
|
||||
- Cleaner grouping, alignment, and density adjustments.
|
||||
- Improved states (hover, focus, disabled, loading) using existing style language.
|
||||
- Subtle transitions/micro-interactions that do not distract and do not change behavior.
|
||||
- Consistent empty/error/success presentation using existing UI conventions.
|
||||
|
||||
## Not Allowed
|
||||
|
||||
- Random aesthetic overhauls.
|
||||
- New color systems or hardcoded ad-hoc colors that break current theme tokens.
|
||||
- Heavy animation, parallax, or attention-stealing motion.
|
||||
- Typography experiments that diverge from current product style.
|
||||
- "Creative" layout changes that reduce usability or consistency.
|
||||
|
||||
## Implementation Workflow
|
||||
|
||||
1. Confirm `medassist-ui-consistency` guardrails are satisfied.
|
||||
2. Identify existing components and CSS patterns to reuse.
|
||||
3. Define the smallest visual changes that improve clarity and quality.
|
||||
4. Apply refinements in-place without changing core behavior.
|
||||
5. Validate consistency across neighboring views/components.
|
||||
6. Ensure i18n and accessibility are preserved.
|
||||
|
||||
## Response Format
|
||||
|
||||
When using this skill, report:
|
||||
|
||||
- Reused components and style primitives
|
||||
- Specific polish improvements applied
|
||||
- Any trade-offs/constraints respected
|
||||
- Confirmation that no new design system or disruptive UX pattern was introduced
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: medassist-i18n-enforcer
|
||||
description: Enforce MedAssist i18n rules so UI copy is always translation-key based for English and German, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when changing frontend UI text, form labels, alerts, dialogs, or page content.
|
||||
|
||||
## Rules
|
||||
|
||||
- Do not hardcode new user-facing strings in React components.
|
||||
- Use translation keys via `t("...")`.
|
||||
- Add or update matching keys in:
|
||||
- `frontend/src/i18n/en.json`
|
||||
- `frontend/src/i18n/de.json`
|
||||
- Keep semantic key naming consistent with existing namespaces.
|
||||
|
||||
## Validation
|
||||
|
||||
1. Every new UI string has a key.
|
||||
2. English and German entries are both present.
|
||||
3. No fallback-to-English hardcoded text remains in JSX.
|
||||
|
||||
## Response Format
|
||||
|
||||
List:
|
||||
|
||||
- New keys added
|
||||
- Files where keys were used
|
||||
- Any intentionally unchanged text and reason
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
name: medassist-karpathy-core
|
||||
description: Apply assumption clarity, simplicity-first implementation, surgical diffs, and goal-driven verification for non-trivial coding tasks.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill as an execution style layer for implementation tasks where overengineering, broad refactors, or unclear assumptions are likely.
|
||||
|
||||
## Use When
|
||||
|
||||
- The request is ambiguous and assumptions must be made explicit.
|
||||
- The change can easily balloon in scope.
|
||||
- A bug fix or feature needs explicit success criteria and verification.
|
||||
- You need to keep diffs minimal and directly tied to the request.
|
||||
|
||||
## Do Not Use When
|
||||
|
||||
- The task is trivial and can be completed safely without extra process overhead.
|
||||
- The task is only about ownership routing (use `medassist-testing-handoff` / `medassist-release-handoff`).
|
||||
- The task is only about domain guardrails already covered by specialized skills (architecture, DB, i18n, UI, security, config, observability).
|
||||
|
||||
## Core Principles
|
||||
|
||||
### 1. Think Before Coding
|
||||
|
||||
- Do not assume silently.
|
||||
- State assumptions explicitly.
|
||||
- If multiple interpretations exist, present them instead of picking one invisibly.
|
||||
- If uncertain or blocked by ambiguity, stop and ask.
|
||||
- If a simpler approach exists, call it out.
|
||||
|
||||
### 2. Simplicity First
|
||||
|
||||
- Implement the minimum code required to solve the asked problem.
|
||||
- Do not add speculative features, abstractions, or configurability.
|
||||
- Avoid defensive handling for impossible scenarios.
|
||||
- If the solution feels overcomplicated, simplify before finalizing.
|
||||
|
||||
### 3. Surgical Changes
|
||||
|
||||
- Touch only lines required for the request.
|
||||
- Do not refactor unrelated areas.
|
||||
- Match existing local style and patterns.
|
||||
- Remove only unused code introduced by your own change.
|
||||
- If unrelated dead code is discovered, mention it but do not remove it unless requested.
|
||||
|
||||
### 4. Goal-Driven Execution
|
||||
|
||||
- Translate requests into verifiable outcomes before implementation.
|
||||
- For multi-step tasks, define short steps with checks.
|
||||
- Verify the requested behavior explicitly before declaring done.
|
||||
|
||||
Example execution frame:
|
||||
|
||||
```text
|
||||
1. [Step] -> verify: [check]
|
||||
2. [Step] -> verify: [check]
|
||||
3. [Step] -> verify: [check]
|
||||
```
|
||||
|
||||
## Response Format
|
||||
|
||||
When this skill is used, report briefly:
|
||||
|
||||
- Assumptions made (or clarifications requested)
|
||||
- Why the chosen approach is the simplest viable one
|
||||
- What was changed (and what was intentionally not changed)
|
||||
- Verification performed and result
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
name: medassist-observability-guard
|
||||
description: Ensure MedAssist changes preserve actionable logging, health checks, and clear operational error visibility, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when changes affect backend services, schedulers, integrations, startup flow, or failure handling.
|
||||
|
||||
## Objective
|
||||
|
||||
Maintain operational visibility so failures are detectable, diagnosable, and actionable.
|
||||
|
||||
## Required Checks
|
||||
|
||||
1. Critical paths keep clear error reporting.
|
||||
2. Health-check behavior remains intact and meaningful.
|
||||
3. Logs contain actionable context without leaking secrets.
|
||||
4. Errors are surfaced with enough detail for debugging.
|
||||
5. Silent failure paths are avoided.
|
||||
|
||||
## MedAssist Focus Areas
|
||||
|
||||
- `backend/src/index.ts`
|
||||
- `backend/src/routes/health.ts`
|
||||
- `backend/src/services/*`
|
||||
- Scheduler and notification flows
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Swallowed exceptions.
|
||||
- Generic logs with no context.
|
||||
- Missing visibility for background failures.
|
||||
|
||||
## Response Format
|
||||
|
||||
Return:
|
||||
|
||||
- Observability touchpoints reviewed
|
||||
- Gaps found and suggested fixes
|
||||
- Operational risk level
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: medassist-release-handoff
|
||||
description: Enforce MedAssist release ownership by preventing remote git/release actions by normal agents and delegating to release-manager, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when a request includes branch push, PR creation, merge, tagging, release notes publishing, or release orchestration.
|
||||
|
||||
## Ownership Rules
|
||||
|
||||
- Remote git/release actions are owned by `@release-manager`.
|
||||
- Normal agent/Copilot must not perform:
|
||||
- `git push`
|
||||
- PR creation/merge
|
||||
- tag/release creation
|
||||
|
||||
## Required Behavior
|
||||
|
||||
1. Perform local code edits only.
|
||||
2. Summarize local changes clearly.
|
||||
3. Provide handoff instruction to `@release-manager` for shipping steps.
|
||||
|
||||
## Response Format
|
||||
|
||||
When this skill applies, return:
|
||||
|
||||
- "Release handoff required"
|
||||
- Delegate target: `@release-manager`
|
||||
- Shipping checklist (branch, PR, CI, merge, release)
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
name: medassist-security-sanity
|
||||
description: Apply baseline security checks to MedAssist code changes, especially for backend routes, auth flows, and input handling, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when a change touches backend routes, auth/session logic, file handling, imports/exports, or external input.
|
||||
|
||||
## Objective
|
||||
|
||||
Prevent common security regressions with fast, practical checks during implementation.
|
||||
|
||||
## Required Checks
|
||||
|
||||
1. Validate and sanitize external input at API boundaries.
|
||||
2. Enforce auth/authz server-side for protected actions.
|
||||
3. Ensure secrets/tokens are never hardcoded or logged.
|
||||
4. Avoid information leakage in error responses.
|
||||
5. Keep permission-sensitive operations explicit and auditable.
|
||||
|
||||
## MedAssist Focus Areas
|
||||
|
||||
- Route handlers in `backend/src/routes/`.
|
||||
- Auth-related code in `backend/src/plugins/` and auth routes.
|
||||
- Data import/export and sharing endpoints.
|
||||
- File/image upload and serving paths.
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Trusting frontend-only checks.
|
||||
- Accepting unchecked query/body/path input.
|
||||
- Returning raw internal errors to clients.
|
||||
- Weak defaults for sensitive operations.
|
||||
|
||||
## Response Format
|
||||
|
||||
Report:
|
||||
|
||||
- Security-sensitive files reviewed
|
||||
- Findings by severity (critical/major/minor)
|
||||
- Concrete remediation actions
|
||||
- Residual risk (if any)
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: medassist-skill-quality-review
|
||||
description: Review MedAssist skills for trigger quality, scope boundaries, and conflicts with AGENTS governance, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when creating or modifying any skill under `.github/skills/`.
|
||||
|
||||
## Objective
|
||||
|
||||
Keep skills discoverable, non-overlapping, and aligned with canonical governance in `AGENTS.md`.
|
||||
|
||||
## Required Checks
|
||||
|
||||
1. Frontmatter has clear `name` and specific `description` trigger language.
|
||||
2. Scope boundaries are explicit (`when to use` / `do not use`).
|
||||
3. No conflicts with `AGENTS.md` ownership rules.
|
||||
4. No policy duplication that can drift from canonical governance.
|
||||
5. References to related skills are explicit where workflows chain.
|
||||
|
||||
## Quality Signals
|
||||
|
||||
- Trigger phrases are concrete and task-shaped.
|
||||
- Instructions are concise, actionable, and deterministic.
|
||||
- Response format is clear and useful for downstream handoff.
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Vague descriptions that match everything.
|
||||
- Duplicate skills with overlapping responsibilities.
|
||||
- Contradictory ownership guidance.
|
||||
- Long policy blocks copied from other files.
|
||||
|
||||
## Response Format
|
||||
|
||||
Return:
|
||||
|
||||
- Scope/trigger issues found
|
||||
- Overlap/conflict findings
|
||||
- Suggested minimal edits
|
||||
- Final pass/fail recommendation
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: medassist-testing-handoff
|
||||
description: Enforce MedAssist testing ownership by delegating test planning, execution, and CI test failure triage to testing-manager, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill whenever a task includes writing tests, running tests, or diagnosing test-related CI failures.
|
||||
|
||||
## Ownership Rules
|
||||
|
||||
- Test planning, implementation, and execution are owned by `@testing-manager`.
|
||||
- CI test-failure triage (`test.yml`, `e2e.yml`) is owned by `@testing-manager`.
|
||||
- Normal coding agent should hand off testing tasks instead of executing testing workflows directly.
|
||||
|
||||
## Handoff Template
|
||||
|
||||
Use this structure for delegation:
|
||||
|
||||
1. Scope: feature/fix and affected files
|
||||
2. Expected behavior
|
||||
3. Suggested test layers (unit/integration/e2e)
|
||||
4. CI failure context (if applicable)
|
||||
|
||||
## Response Format
|
||||
|
||||
When triggered, output:
|
||||
|
||||
- "Testing handoff required"
|
||||
- Delegate target: `@testing-manager`
|
||||
- Minimal handoff brief (scope + expected behavior)
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
name: medassist-ui-consistency
|
||||
description: Enforce non-negotiable MedAssist UI guardrails by reusing existing components, styles, and interaction patterns, including equivalent requests phrased in German.
|
||||
---
|
||||
|
||||
# Skill Instructions
|
||||
|
||||
Use this skill when implementing or editing UI flows, modals, buttons, forms, schedule views, or settings screens.
|
||||
|
||||
## Scope
|
||||
|
||||
This is the **guardrail skill** for UI work.
|
||||
Use it to enforce consistency and prevent design drift.
|
||||
|
||||
Use `medassist-frontend-polish` only after these guardrails are satisfied.
|
||||
|
||||
## Do Not Use This Skill For
|
||||
|
||||
- Creative visual redesign requests where no product consistency constraints apply.
|
||||
- Marketing-style one-off pages outside MedAssist product UI conventions.
|
||||
|
||||
## Rules
|
||||
|
||||
- Reuse existing components (for example `ConfirmModal`, `MedicationAvatar`) before creating new primitives.
|
||||
- Keep spacing, typography, and button styles aligned with existing patterns.
|
||||
- Avoid custom inline modal/button patterns that diverge from project design.
|
||||
- Prefer extending existing CSS classes/styles instead of introducing parallel styling systems.
|
||||
|
||||
### Modal requirements (non-negotiable)
|
||||
|
||||
Every modal/overlay **must** follow these rules:
|
||||
|
||||
1. **Escape key**: Call `useEscapeKey(active, onClose)` from `hooks/useEscapeKey`. This registers a document-level `keydown` listener that works regardless of focus. **Never** rely on `onKeyDown` on an overlay div — it only fires when the overlay has focus, which almost never happens.
|
||||
2. **Scroll lock**: Call `useScrollLock(active)` from `hooks/useScrollLock` if the modal is **not** already covered by App.tsx's centralized `useScrollLock` call. Page-local modals (e.g. `ReportModal`, `ExportModal`) must call it themselves.
|
||||
3. **Click-outside close**: The overlay div gets `onClick={onClose}`, and `.modal-content` gets `onClick={(e) => e.stopPropagation()}`.
|
||||
4. **Key event containment**: `.modal-content` gets `onKeyDown={(e) => { if (e.key !== "Escape") e.stopPropagation(); }}` — this prevents non-Escape keys from leaking out while still allowing Escape to propagate to the document-level handler.
|
||||
5. **Nested sub-modals** (e.g. edit-stock inside MedDetailModal): Use `useEscapeKey` with `{ capture: true }` so the innermost modal intercepts Escape before the parent's handler fires.
|
||||
|
||||
## Decision Heuristics
|
||||
|
||||
1. If an equivalent component exists, reuse it.
|
||||
2. If small variant is needed, extend existing styles minimally.
|
||||
3. If a new component is unavoidable, match existing naming and structure conventions.
|
||||
|
||||
## Response Format
|
||||
|
||||
Provide:
|
||||
|
||||
- Reused components/styles
|
||||
- Any new UI element and why reuse was not possible
|
||||
- Consistency risks reviewed
|
||||
- Confirmation that `medassist-frontend-polish` constraints remain compatible (if polish work is also requested)
|
||||
@@ -0,0 +1,19 @@
|
||||
name: Add to Project
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, labeled]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
add-to-project:
|
||||
name: Add issue to project
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/add-to-project@v1.0.2
|
||||
with:
|
||||
project-url: ${{ vars.PROJECT_URL }}
|
||||
github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}
|
||||
labeled: enhancement, bug, triage
|
||||
label-operator: OR
|
||||
@@ -47,18 +47,18 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
uses: github/codeql-action/init@v4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
config-file: ./.github/codeql/codeql-config.yml
|
||||
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v3
|
||||
uses: github/codeql-action/autobuild@v4
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
uses: github/codeql-action/analyze@v4
|
||||
with:
|
||||
category: "/language:${{ matrix.language }}"
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Dependabot Automerge
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
- synchronize
|
||||
- ready_for_review
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
enable-automerge:
|
||||
if: github.actor == 'dependabot[bot]'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Read Dependabot metadata
|
||||
id: metadata
|
||||
uses: dependabot/fetch-metadata@v2
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Enable auto-merge for safe updates
|
||||
if: >-
|
||||
(steps.metadata.outputs.package-ecosystem == 'npm' ||
|
||||
steps.metadata.outputs.package-ecosystem == 'github_actions') &&
|
||||
(steps.metadata.outputs.update-type == 'version-update:semver-minor' ||
|
||||
steps.metadata.outputs.update-type == 'version-update:semver-patch')
|
||||
uses: peter-evans/enable-pull-request-automerge@v3
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
pull-request-number: ${{ github.event.pull_request.number }}
|
||||
merge-method: squash
|
||||
@@ -4,6 +4,12 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
paths:
|
||||
- 'backend/**'
|
||||
- 'frontend/**'
|
||||
- 'docker-compose.yml'
|
||||
- 'docker-compose.dev.yml'
|
||||
- '.github/workflows/docker-build.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
@@ -45,7 +51,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
@@ -70,7 +76,7 @@ jobs:
|
||||
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ${{ matrix.context }}
|
||||
push: true
|
||||
@@ -94,7 +100,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history for changelog generation
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
name: E2E Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'backend/**'
|
||||
- '.github/workflows/e2e.yml'
|
||||
|
||||
# Minimal permissions for security
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: Playwright E2E
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: |
|
||||
backend/package-lock.json
|
||||
frontend/package-lock.json
|
||||
|
||||
- name: Install backend dependencies
|
||||
working-directory: backend
|
||||
run: npm ci
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Run E2E tests (Chromium only)
|
||||
working-directory: frontend
|
||||
run: npx playwright test --project=chromium
|
||||
env:
|
||||
CI: true
|
||||
PLAYWRIGHT_WORKERS: 1
|
||||
PLAYWRIGHT_HTML_OPEN: never
|
||||
JWT_SECRET: e2e-test-secret-that-is-long-enough
|
||||
SESSION_SECRET: e2e-test-session-secret-long-enough
|
||||
|
||||
- name: Upload Playwright report
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: frontend/playwright-report/
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload test results
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-results
|
||||
path: frontend/test-results/
|
||||
retention-days: 7
|
||||
@@ -0,0 +1,105 @@
|
||||
name: Move Done in Project
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [closed]
|
||||
pull_request:
|
||||
types: [closed]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
move-to-done:
|
||||
name: Move to Done
|
||||
runs-on: ubuntu-latest
|
||||
if: >-
|
||||
(github.event_name == 'issues' && github.event.issue.state_reason == 'completed') ||
|
||||
(github.event_name == 'pull_request' && github.event.pull_request.merged == true)
|
||||
steps:
|
||||
- name: Move project item to Done
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}
|
||||
script: |
|
||||
const projectId = 'PVT_kwHOADH82s4BO2OT';
|
||||
const statusFieldId = 'PVTSSF_lAHOADH82s4BO2OTzg9bdkE';
|
||||
const doneOptionId = 'ca45af98';
|
||||
|
||||
// Determine content ID (issue or PR node ID)
|
||||
const nodeId = context.payload.issue?.node_id || context.payload.pull_request?.node_id;
|
||||
const number = context.payload.issue?.number || context.payload.pull_request?.number;
|
||||
const type = context.payload.issue ? 'issue' : 'pull_request';
|
||||
|
||||
console.log(`Processing ${type} #${number} (${nodeId})`);
|
||||
|
||||
// Find the project item by content node ID
|
||||
const result = await github.graphql(`
|
||||
query($nodeId: ID!) {
|
||||
node(id: $nodeId) {
|
||||
... on Issue {
|
||||
projectItems(first: 10) {
|
||||
nodes {
|
||||
id
|
||||
project { id }
|
||||
fieldValueByName(name: "Status") {
|
||||
... on ProjectV2ItemFieldSingleSelectValue {
|
||||
name
|
||||
optionId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
... on PullRequest {
|
||||
projectItems(first: 10) {
|
||||
nodes {
|
||||
id
|
||||
project { id }
|
||||
fieldValueByName(name: "Status") {
|
||||
... on ProjectV2ItemFieldSingleSelectValue {
|
||||
name
|
||||
optionId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, { nodeId });
|
||||
|
||||
const items = result.node?.projectItems?.nodes || [];
|
||||
const projectItem = items.find(item => item.project.id === projectId);
|
||||
|
||||
if (!projectItem) {
|
||||
console.log(`${type} #${number} is not in the project board — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentStatus = projectItem.fieldValueByName?.name || 'unknown';
|
||||
if (currentStatus === 'Done') {
|
||||
console.log(`${type} #${number} is already "Done" — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Moving ${type} #${number} from "${currentStatus}" to "Done"...`);
|
||||
|
||||
await github.graphql(`
|
||||
mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
|
||||
updateProjectV2ItemFieldValue(input: {
|
||||
projectId: $projectId
|
||||
itemId: $itemId
|
||||
fieldId: $fieldId
|
||||
value: { singleSelectOptionId: $optionId }
|
||||
}) {
|
||||
projectV2Item { id }
|
||||
}
|
||||
}
|
||||
`, {
|
||||
projectId,
|
||||
itemId: projectItem.id,
|
||||
fieldId: statusFieldId,
|
||||
optionId: doneOptionId
|
||||
});
|
||||
|
||||
console.log(`Successfully moved ${type} #${number} to "Done".`);
|
||||
@@ -51,10 +51,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
@@ -73,7 +73,7 @@ jobs:
|
||||
run: npm run test:coverage
|
||||
|
||||
- name: Upload coverage report
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: backend-coverage
|
||||
@@ -81,7 +81,7 @@ jobs:
|
||||
retention-days: 7
|
||||
|
||||
# =============================================================================
|
||||
# Frontend Build Validation (skipped if no frontend-related files changed)
|
||||
# Frontend Tests & Build (skipped if no frontend-related files changed)
|
||||
# =============================================================================
|
||||
frontend-build:
|
||||
name: Frontend Build
|
||||
@@ -96,10 +96,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
@@ -111,5 +111,16 @@ jobs:
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: npm run test:coverage
|
||||
|
||||
- name: TypeScript type check & build
|
||||
run: npm run build
|
||||
|
||||
- name: Upload coverage report
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: frontend-coverage
|
||||
path: frontend/coverage/
|
||||
retention-days: 7
|
||||
|
||||
@@ -10,6 +10,11 @@ on:
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
# Prevent parallel badge workflows from racing each other
|
||||
concurrency:
|
||||
group: update-test-badges
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
update-badges:
|
||||
name: Update Test Count Badges
|
||||
@@ -19,12 +24,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.BADGE_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
@@ -99,5 +104,8 @@ jobs:
|
||||
echo "No badge changes to commit"
|
||||
else
|
||||
git commit -m "chore: update test count badges [skip ci]"
|
||||
# Rebase on latest main to avoid push rejection when concurrent
|
||||
# badge workflows or other [skip ci] commits land between checkout and push
|
||||
git pull --rebase origin main
|
||||
git push
|
||||
fi
|
||||
|
||||
+4
-1
@@ -79,5 +79,8 @@ Thumbs.db
|
||||
.turbo/
|
||||
.roo/
|
||||
.roomodes
|
||||
.claude/
|
||||
AGENTS.md
|
||||
docs/TECH_STACK.md
|
||||
docs/TECH_STACK.md
|
||||
doku
|
||||
plan
|
||||
Vendored
+4
-1
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"vitest.root": "backend",
|
||||
"vitest.enable": true,
|
||||
"vitest.commandLine": "npm test --"
|
||||
"vitest.commandLine": "npm test --",
|
||||
"chat.tools.terminal.autoApprove": {
|
||||
"test": true
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "E2E stable",
|
||||
"type": "shell",
|
||||
"command": "npm",
|
||||
"args": ["run", "test:e2e"],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/frontend"
|
||||
},
|
||||
"group": "test",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "E2E stable + merged video",
|
||||
"type": "shell",
|
||||
"command": "npm",
|
||||
"args": ["run", "test:e2e:with-video"],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/frontend"
|
||||
},
|
||||
"group": "test",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "E2E all browsers",
|
||||
"type": "shell",
|
||||
"command": "npm",
|
||||
"args": ["run", "test:e2e:all"],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/frontend"
|
||||
},
|
||||
"group": "test",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "E2E all browsers + merged video",
|
||||
"type": "shell",
|
||||
"command": "npm",
|
||||
"args": ["run", "test:e2e:all:with-video"],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/frontend"
|
||||
},
|
||||
"group": "test",
|
||||
"problemMatcher": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/React-18-61DAFB?logo=react" alt="React 18" />
|
||||
<img src="https://img.shields.io/badge/React-19-61DAFB?logo=react" alt="React 19" />
|
||||
<img src="https://img.shields.io/badge/TypeScript-5-3178C6?logo=typescript" alt="TypeScript" />
|
||||
<img src="https://img.shields.io/badge/Fastify-5-000000?logo=fastify" alt="Fastify" />
|
||||
<img src="https://img.shields.io/badge/SQLite-Database-003B57?logo=sqlite" alt="SQLite" />
|
||||
@@ -18,13 +18,13 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/Backend_Tests-504%2F504-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
|
||||
<img src="https://img.shields.io/badge/Frontend_Tests-662%2F662-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
|
||||
<img src="https://img.shields.io/badge/Backend_Tests-569%2F569-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
|
||||
<img src="https://img.shields.io/badge/Frontend_Tests-769%2F769-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
|
||||
</p>
|
||||
|
||||
### 🤖 AI-Generated Code
|
||||
|
||||
> This app was 100% coded with Claude Opus 4.5. Use at your own risk.
|
||||
> This app was 100% coded with [Claude Opus 4.6](https://www.anthropic.com/claude) and [GPT-5.3 Codex](https://openai.com/index/gpt-5/). Use at your own risk.
|
||||
|
||||
### ⚠️ Disclaimer
|
||||
|
||||
@@ -123,6 +123,7 @@ Share your medication schedule with others via a public link.
|
||||
- Track exact stock: packs, blisters, bottles, and loose pills
|
||||
- Display remaining days of supply
|
||||
- Automatic calculation based on intake schedule
|
||||
- Manual stock correction supports partial blisters and loose pills
|
||||
|
||||
### Medication Refill
|
||||
- One-click refill with pack or loose pill options
|
||||
@@ -132,6 +133,7 @@ Share your medication schedule with others via a public link.
|
||||
### Flexible Schedules
|
||||
- Daily, weekly, or custom intervals per medication
|
||||
- Independent schedules for each medication
|
||||
- Optional timeline filters for dashboard and shared schedule views
|
||||
|
||||
### Stock Alerts & Reminders
|
||||
- Notifications before stock runs out
|
||||
@@ -143,6 +145,10 @@ Share your medication schedule with others via a public link.
|
||||
- Plan ahead for vacations, business trips, or hospital stays
|
||||
- Send demand reports via email or push notification
|
||||
|
||||
### Reports
|
||||
- Generate medication reports as PDF, Markdown, or plain text
|
||||
- Include intake history, refill history, and prescription details
|
||||
|
||||
### Multi-Person Support
|
||||
- Manage medications for multiple people
|
||||
- Share schedules via link. Recipients can mark doses as taken, you see it live
|
||||
@@ -188,7 +194,7 @@ All configuration is done via environment variables in `.env`. Copy `.env.exampl
|
||||
| `PGID` | `1000` | Group ID for container file permissions |
|
||||
| `PORT` | `3000` | Backend API port |
|
||||
| `CORS_ORIGINS` | `http://localhost:4174` | Allowed origins for CORS |
|
||||
| `LOG_LEVEL` | `info` | Log verbosity (`debug`, `info`, `warn`, `error`) |
|
||||
| `LOG_LEVEL` | `info` | Log verbosity (`debug`, `info`, `warn`, `error`, `silent`). At `info` (default), high-frequency polling endpoints are suppressed. Set `debug` to see all requests. |
|
||||
| `TZ` | `Europe/Berlin` | Timezone for scheduled reminders |
|
||||
|
||||
### Authentication
|
||||
@@ -213,7 +219,7 @@ Generate secrets with: `openssl rand -hex 32`
|
||||
| `OIDC_ISSUER_URL` | — | OIDC provider URL |
|
||||
| `OIDC_CLIENT_ID` | — | Client ID from OIDC provider |
|
||||
| `OIDC_CLIENT_SECRET` | — | Client secret from OIDC provider |
|
||||
| `OIDC_REDIRECT_URI` | — | Callback URL |
|
||||
| `OIDC_REDIRECT_URI` | — | Full callback URL (e.g., `https://your-domain.com/api/auth/oidc/callback`) |
|
||||
| `OIDC_SCOPES` | `openid profile email` | Scopes to request |
|
||||
| `OIDC_USERNAME_CLAIM` | `preferred_username` | Claim for username |
|
||||
| `OIDC_AUTO_CREATE_USERS` | `true` | Auto-create users on first SSO login |
|
||||
@@ -244,7 +250,9 @@ Generate secrets with: `openssl rand -hex 32`
|
||||
|
||||
MedAssist uses [Shoutrrr](https://containrrr.dev/shoutrrr/) for push notifications, supporting many services with a single URL format.
|
||||
|
||||
**Supported services:** ntfy, Pushover, Gotify, Discord, Telegram, Slack, Matrix, and [many more](https://containrrr.dev/shoutrrr/v0.8/services/overview/).
|
||||
**Implemented URL schemes in MedAssist:** `ntfy://`, `discord://`, `pushover://`, `gotify://`, `telegram://`, plus direct `https://` webhooks.
|
||||
|
||||
This covers common providers like ntfy, Discord, Pushover, Gotify, Telegram, Slack webhooks, and many others via webhook URLs.
|
||||
|
||||
Configure push notifications in Settings → Push, or set defaults via environment variables:
|
||||
|
||||
@@ -282,6 +290,7 @@ Get your keys at [pushover.net](https://pushover.net/):
|
||||
**Gotify** (self-hosted):
|
||||
```
|
||||
gotify://your-server.com/TOKEN
|
||||
gotify://your-server.com:443/path/to/gotify/TOKEN?priority=1
|
||||
```
|
||||
|
||||
**Discord**:
|
||||
@@ -292,6 +301,7 @@ discord://TOKEN@WEBHOOK_ID
|
||||
**Telegram**:
|
||||
```
|
||||
telegram://TOKEN@telegram?chats=CHAT_ID
|
||||
telegram://TOKEN@telegram?chats=@your_channel,-1001234567890
|
||||
```
|
||||
|
||||
For all services and options, see the [Shoutrrr documentation](https://containrrr.dev/shoutrrr/v0.8/services/overview/).
|
||||
@@ -305,6 +315,24 @@ docker compose -f docker-compose.dev.yml up
|
||||
- Frontend: `http://localhost:5173` (hot reload)
|
||||
- Backend: `http://localhost:3000`
|
||||
|
||||
Playwright E2E recommendations:
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run test:e2e:local # local run with PLAYWRIGHT_WORKERS=4
|
||||
npm run test:e2e:all:local # local all-browser run with PLAYWRIGHT_WORKERS=4
|
||||
```
|
||||
|
||||
- CI stays at `PLAYWRIGHT_WORKERS=1` for stability.
|
||||
- Data-heavy specs remain sequential via the `chromium-data` project config.
|
||||
|
||||
# Dependency Updates
|
||||
|
||||
- Dependabot checks dependencies weekly for `frontend`, `backend`, repository root tooling, and GitHub Actions.
|
||||
- Minor and patch updates are grouped to reduce PR noise.
|
||||
- Dependabot minor/patch PRs are configured for auto-merge after required CI checks pass.
|
||||
- Major updates still require manual review before merge.
|
||||
|
||||
# Acknowledgements
|
||||
|
||||
This project was inspired by [MedAssist](https://github.com/njic/medassist) by njic.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `medications` ADD `is_obsolete` integer DEFAULT false NOT NULL;
|
||||
ALTER TABLE `medications` ADD `obsolete_at` integer;
|
||||
@@ -0,0 +1,8 @@
|
||||
ALTER TABLE `medications` ADD `prescription_enabled` integer NOT NULL DEFAULT 0;
|
||||
ALTER TABLE `medications` ADD `prescription_authorized_refills` integer;
|
||||
ALTER TABLE `medications` ADD `prescription_remaining_refills` integer;
|
||||
ALTER TABLE `medications` ADD `prescription_low_refill_threshold` integer NOT NULL DEFAULT 1;
|
||||
ALTER TABLE `medications` ADD `prescription_expiry_date` text;
|
||||
|
||||
ALTER TABLE `user_settings` ADD `email_prescription_reminders` integer NOT NULL DEFAULT 1;
|
||||
ALTER TABLE `user_settings` ADD `shoutrrr_prescription_reminders` integer NOT NULL DEFAULT 1;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `medications` ADD `medication_start_date` text DEFAULT '' NOT NULL;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `dose_tracking` ADD `taken_source` text DEFAULT 'manual' NOT NULL;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -57,6 +57,27 @@
|
||||
"when": 1770659669121,
|
||||
"tag": "0007_add_share_stock_status",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "6",
|
||||
"when": 1771160400000,
|
||||
"tag": "0008_add_obsolete_medications",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "6",
|
||||
"when": 1771164000000,
|
||||
"tag": "0009_add_medication_start_date",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 10,
|
||||
"version": "6",
|
||||
"when": 1771694832866,
|
||||
"tag": "0010_mean_spot",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+1158
-2029
File diff suppressed because it is too large
Load Diff
+19
-17
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "medassist-ng-backend",
|
||||
"version": "1.9.0",
|
||||
"version": "1.17.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -17,31 +17,33 @@
|
||||
"check": "npx biome check . && tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^10.0.1",
|
||||
"@fastify/cors": "^10.0.1",
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/cors": "^11.2.0",
|
||||
"@fastify/helmet": "^13.0.2",
|
||||
"@fastify/jwt": "^10.0.0",
|
||||
"@fastify/multipart": "^9.3.0",
|
||||
"@fastify/multipart": "^9.4.0",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/sensible": "^6.0.4",
|
||||
"@fastify/static": "^8.3.0",
|
||||
"@libsql/client": "^0.10.0",
|
||||
"argon2": "^0.40.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"@fastify/static": "^9.0.0",
|
||||
"@libsql/client": "^0.17.0",
|
||||
"argon2": "^0.44.0",
|
||||
"dotenv": "^17.3.1",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
"fastify": "^5.7.3",
|
||||
"nodemailer": "^7.0.11",
|
||||
"openid-client": "^6.8.1",
|
||||
"fastify": "^5.7.4",
|
||||
"nodemailer": "^8.0.1",
|
||||
"openid-client": "^6.8.2",
|
||||
"sharp": "^0.34.5",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.3.12",
|
||||
"@types/node": "^22.7.4",
|
||||
"@types/nodemailer": "^6.4.21",
|
||||
"@biomejs/biome": "^2.4.4",
|
||||
"@types/node": "^25.3.0",
|
||||
"@types/nodemailer": "^7.0.11",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"@vitest/coverage-v8": "^4.0.16",
|
||||
"drizzle-kit": "^0.31.8",
|
||||
"supertest": "^7.0.0",
|
||||
"@vitest/coverage-v8": "^4.0.18",
|
||||
"drizzle-kit": "^0.31.9",
|
||||
"pino-pretty": "^13.1.3",
|
||||
"supertest": "^7.2.2",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.5.4",
|
||||
"vitest": "^4.0.16"
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { type Client, createClient } from "@libsql/client";
|
||||
import dotenv from "dotenv";
|
||||
import { drizzle } from "drizzle-orm/libsql";
|
||||
@@ -8,7 +7,6 @@ import { log } from "../utils/logger.js";
|
||||
import {
|
||||
ensureDataDirectory,
|
||||
ensureDefaultUser,
|
||||
getDataDir,
|
||||
getDbPaths,
|
||||
repairOrphanedDoseIds,
|
||||
repairTrailingHyphenDoseIds,
|
||||
@@ -65,8 +63,8 @@ let client: Client;
|
||||
try {
|
||||
client = createClient({ url });
|
||||
log.debug(`[DB] Database client created successfully`);
|
||||
} catch (err: any) {
|
||||
log.error(`[DB] ERROR: Failed to create database client: ${err.message}`);
|
||||
} catch (err: unknown) {
|
||||
log.error(`[DB] ERROR: Failed to create database client: ${(err as Error).message}`);
|
||||
log.error(`[DB] Database path: ${dbPath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -80,10 +78,6 @@ async function runMigrations() {
|
||||
const migrateResult = await runDrizzleMigrations(db);
|
||||
if (!migrateResult.success) {
|
||||
log.error(`[DB] Migration error: ${migrateResult.error}`);
|
||||
} else if (migrateResult.warning) {
|
||||
log.warn(`[DB] Migration warning: ${migrateResult.warning}`);
|
||||
} else {
|
||||
log.debug(`[DB] Drizzle migrations completed`);
|
||||
}
|
||||
|
||||
// Run ALTER TABLE migrations for backward compatibility
|
||||
|
||||
+63
-23
@@ -71,8 +71,8 @@ export function ensureDataDirectory(dataDir: string): { success: boolean; error?
|
||||
writeFileSync(testFile, "test");
|
||||
|
||||
return { success: true };
|
||||
} catch (err: any) {
|
||||
return { success: false, error: err.message };
|
||||
} catch (err: unknown) {
|
||||
return { success: false, error: (err as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,14 +87,13 @@ export async function runDrizzleMigrations(
|
||||
try {
|
||||
await migrate(database, { migrationsFolder });
|
||||
return { success: true };
|
||||
} catch (err: any) {
|
||||
// If the error is about existing schema objects, the DB is already up-to-date
|
||||
// This happens when ALTER migrations in client.ts have already added the columns,
|
||||
// or when tables were created before drizzle migrations were introduced
|
||||
if (err.message?.includes("duplicate column") || err.message?.includes("already exists")) {
|
||||
return { success: true, warning: `Schema already up-to-date: ${err.message}` };
|
||||
} catch (err: unknown) {
|
||||
const msg = (err as Error).message ?? "";
|
||||
// Duplicate column / already exists = DB is already up-to-date (expected for existing DBs)
|
||||
if (msg.includes("duplicate column") || msg.includes("already exists")) {
|
||||
return { success: true };
|
||||
}
|
||||
return { success: false, error: err.message };
|
||||
return { success: false, error: msg };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,6 +110,8 @@ export async function runAlterMigrations(client: Client): Promise<{ success: boo
|
||||
`ALTER TABLE user_settings ADD COLUMN max_nagging_reminders integer NOT NULL DEFAULT 5`,
|
||||
// Added in v1.2.3 - dismiss missed doses without deducting stock
|
||||
`ALTER TABLE dose_tracking ADD COLUMN dismissed integer NOT NULL DEFAULT 0`,
|
||||
// Added for intake automation auditability (manual vs automatic taken)
|
||||
`ALTER TABLE dose_tracking ADD COLUMN taken_source text NOT NULL DEFAULT 'manual'`,
|
||||
// Added in v1.3.x - stock calculation mode (automatic/manual)
|
||||
`ALTER TABLE user_settings ADD COLUMN stock_calculation_mode text NOT NULL DEFAULT 'automatic'`,
|
||||
// Added for stock correction - hidden offset that doesn't affect looseTablets
|
||||
@@ -119,6 +120,11 @@ export async function runAlterMigrations(client: Client): Promise<{ success: boo
|
||||
`ALTER TABLE medications ADD COLUMN last_stock_correction_at integer`,
|
||||
// Added in v1.5.1 - dismiss past doses until date (robust against timestamp changes)
|
||||
`ALTER TABLE medications ADD COLUMN dismissed_until text`,
|
||||
// Added for soft-archiving medications (without deleting history)
|
||||
`ALTER TABLE medications ADD COLUMN is_obsolete integer NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE medications ADD COLUMN obsolete_at integer`,
|
||||
// Added for explicit medication lifecycle start date
|
||||
`ALTER TABLE medications ADD COLUMN medication_start_date text NOT NULL DEFAULT ''`,
|
||||
// Added for more detailed reminder info display
|
||||
`ALTER TABLE user_settings ADD COLUMN last_reminder_med_name text`,
|
||||
`ALTER TABLE user_settings ADD COLUMN last_reminder_taken_by text`,
|
||||
@@ -135,15 +141,32 @@ export async function runAlterMigrations(client: Client): Promise<{ success: boo
|
||||
`ALTER TABLE user_settings ADD COLUMN last_stock_reminder_med_names text`,
|
||||
// Added for share stock visibility toggle
|
||||
`ALTER TABLE user_settings ADD COLUMN share_stock_status integer NOT NULL DEFAULT 1`,
|
||||
// Added for timeline visibility toggles (dashboard + shared schedule)
|
||||
`ALTER TABLE user_settings ADD COLUMN upcoming_today_only integer NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE user_settings ADD COLUMN share_schedule_today_only integer NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE user_settings ADD COLUMN swap_dashboard_main_sections integer NOT NULL DEFAULT 0`,
|
||||
// Added for prescription refill tracking and reminders
|
||||
`ALTER TABLE medications ADD COLUMN prescription_enabled integer NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE medications ADD COLUMN prescription_authorized_refills integer`,
|
||||
`ALTER TABLE medications ADD COLUMN prescription_remaining_refills integer`,
|
||||
`ALTER TABLE medications ADD COLUMN prescription_low_refill_threshold integer NOT NULL DEFAULT 1`,
|
||||
`ALTER TABLE medications ADD COLUMN prescription_expiry_date text`,
|
||||
`ALTER TABLE user_settings ADD COLUMN email_prescription_reminders integer NOT NULL DEFAULT 1`,
|
||||
`ALTER TABLE user_settings ADD COLUMN shoutrrr_prescription_reminders integer NOT NULL DEFAULT 1`,
|
||||
`ALTER TABLE user_settings ADD COLUMN last_prescription_reminder_sent text`,
|
||||
`ALTER TABLE user_settings ADD COLUMN last_prescription_reminder_channel text`,
|
||||
`ALTER TABLE user_settings ADD COLUMN last_prescription_reminder_med_names text`,
|
||||
// Added for refill history prescription tracking
|
||||
`ALTER TABLE refill_history ADD COLUMN used_prescription integer NOT NULL DEFAULT 0`,
|
||||
];
|
||||
|
||||
for (const sql of alterMigrations) {
|
||||
try {
|
||||
await client.execute(sql);
|
||||
} catch (e: any) {
|
||||
} catch (e: unknown) {
|
||||
// Silently ignore "duplicate column" errors - column already exists
|
||||
if (!e.message?.includes("duplicate column")) {
|
||||
errors.push(e.message);
|
||||
if (!(e as Error).message?.includes("duplicate column")) {
|
||||
errors.push((e as Error).message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -164,10 +187,27 @@ export async function runAlterMigrations(client: Client): Promise<{ success: boo
|
||||
for (const sql of createTableMigrations) {
|
||||
try {
|
||||
await client.execute(sql);
|
||||
} catch (e: any) {
|
||||
} catch (e: unknown) {
|
||||
// Silently ignore "table already exists" errors
|
||||
if (!e.message?.includes("already exists")) {
|
||||
errors.push(e.message);
|
||||
if (!(e as Error).message?.includes("already exists")) {
|
||||
errors.push((e as Error).message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create indexes that might be missing (silently fail if already exists)
|
||||
const createIndexMigrations = [
|
||||
// Added in v1.6.x - case-insensitive unique usernames
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS users_username_lower_unique ON users(lower(username))`,
|
||||
];
|
||||
|
||||
for (const sql of createIndexMigrations) {
|
||||
try {
|
||||
await client.execute(sql);
|
||||
} catch (e: unknown) {
|
||||
// Silently ignore "already exists" errors
|
||||
if (!(e as Error).message?.includes("already exists")) {
|
||||
errors.push((e as Error).message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,8 +232,8 @@ export async function ensureDefaultUser(client: Client, authEnabled: boolean): P
|
||||
return true; // Created
|
||||
}
|
||||
return false; // Already exists
|
||||
} catch (e: any) {
|
||||
console.error(`[DB] Error creating default user:`, e.message);
|
||||
} catch (e: unknown) {
|
||||
console.error(`[DB] Error creating default user:`, (e as Error).message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -220,8 +260,8 @@ export async function repairTrailingHyphenDoseIds(client: Client): Promise<{ rep
|
||||
"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}`);
|
||||
} catch (e: unknown) {
|
||||
errors.push(`Trailing-hyphen repair failed: ${(e as Error).message}`);
|
||||
}
|
||||
|
||||
return { repaired, errors };
|
||||
@@ -344,14 +384,14 @@ export async function repairOrphanedDoseIds(client: Client): Promise<{ repaired:
|
||||
args: [newDoseId, dose.id],
|
||||
});
|
||||
repaired++;
|
||||
} catch (e: any) {
|
||||
errors.push(`Failed to repair dose ${dose.id}: ${e.message}`);
|
||||
} catch (e: unknown) {
|
||||
errors.push(`Failed to repair dose ${dose.id}: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
errors.push(`Repair failed: ${e.message}`);
|
||||
} catch (e: unknown) {
|
||||
errors.push(`Repair failed: ${(e as Error).message}`);
|
||||
}
|
||||
|
||||
return { repaired, errors };
|
||||
|
||||
@@ -41,8 +41,8 @@ export async function executeMigration(
|
||||
const executed = Number(tables.rows[0].count) || 0;
|
||||
|
||||
return { success: true, executed, errors };
|
||||
} catch (err: any) {
|
||||
errors.push(err.message);
|
||||
} catch (err: unknown) {
|
||||
errors.push((err as Error).message);
|
||||
return { success: false, executed: 0, errors };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,9 +65,21 @@ export function getTableCreationSQL(): string[] {
|
||||
expiry_warning_days integer NOT NULL DEFAULT 90,
|
||||
language text NOT NULL DEFAULT 'en',
|
||||
stock_calculation_mode text NOT NULL DEFAULT 'automatic',
|
||||
share_stock_status integer NOT NULL DEFAULT 1,
|
||||
upcoming_today_only integer NOT NULL DEFAULT 0,
|
||||
share_schedule_today_only integer NOT NULL DEFAULT 0,
|
||||
swap_dashboard_main_sections integer NOT NULL DEFAULT 0,
|
||||
last_auto_email_sent text,
|
||||
last_notification_type text,
|
||||
last_notification_channel text,
|
||||
last_reminder_med_name text,
|
||||
last_reminder_taken_by text,
|
||||
last_stock_reminder_sent text,
|
||||
last_stock_reminder_channel text,
|
||||
last_stock_reminder_med_names text,
|
||||
last_prescription_reminder_sent text,
|
||||
last_prescription_reminder_channel text,
|
||||
last_prescription_reminder_med_names text,
|
||||
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`,
|
||||
|
||||
@@ -47,6 +47,14 @@ export const medications = sqliteTable("medications", {
|
||||
expiryDate: text("expiry_date"),
|
||||
notes: text("notes"),
|
||||
intakeRemindersEnabled: integer("intake_reminders_enabled", { mode: "boolean" }).notNull().default(false),
|
||||
medicationStartDate: text("medication_start_date").notNull().default(""),
|
||||
isObsolete: integer("is_obsolete", { mode: "boolean" }).notNull().default(false),
|
||||
obsoleteAt: integer("obsolete_at", { mode: "timestamp" }),
|
||||
prescriptionEnabled: integer("prescription_enabled", { mode: "boolean" }).notNull().default(false),
|
||||
prescriptionAuthorizedRefills: integer("prescription_authorized_refills"),
|
||||
prescriptionRemainingRefills: integer("prescription_remaining_refills"),
|
||||
prescriptionLowRefillThreshold: integer("prescription_low_refill_threshold").notNull().default(1),
|
||||
prescriptionExpiryDate: text("prescription_expiry_date"),
|
||||
dismissedUntil: text("dismissed_until"), // ISO date string (e.g. "2026-01-23") - all past doses until this date are dismissed
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
|
||||
});
|
||||
@@ -65,11 +73,15 @@ export const userSettings = sqliteTable("user_settings", {
|
||||
notificationEmail: text("notification_email"),
|
||||
emailStockReminders: integer("email_stock_reminders", { mode: "boolean" }).notNull().default(true),
|
||||
emailIntakeReminders: integer("email_intake_reminders", { mode: "boolean" }).notNull().default(true),
|
||||
emailPrescriptionReminders: integer("email_prescription_reminders", { mode: "boolean" }).notNull().default(true),
|
||||
// Push notifications (shoutrrr/ntfy)
|
||||
shoutrrrEnabled: integer("shoutrrr_enabled", { mode: "boolean" }).notNull().default(false),
|
||||
shoutrrrUrl: text("shoutrrr_url"),
|
||||
shoutrrrStockReminders: integer("shoutrrr_stock_reminders", { mode: "boolean" }).notNull().default(true),
|
||||
shoutrrrIntakeReminders: integer("shoutrrr_intake_reminders", { mode: "boolean" }).notNull().default(true),
|
||||
shoutrrrPrescriptionReminders: integer("shoutrrr_prescription_reminders", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(true),
|
||||
// Reminder settings
|
||||
reminderDaysBefore: integer("reminder_days_before").notNull().default(7),
|
||||
repeatDailyReminders: integer("repeat_daily_reminders", { mode: "boolean" }).notNull().default(false),
|
||||
@@ -88,6 +100,10 @@ export const userSettings = sqliteTable("user_settings", {
|
||||
stockCalculationMode: text("stock_calculation_mode", { length: 20 }).notNull().default("automatic"),
|
||||
// Whether shared schedule links show stock status (Critical/Low/Normal) to intake users
|
||||
shareStockStatus: integer("share_stock_status", { mode: "boolean" }).notNull().default(true),
|
||||
// UI timeline visibility preferences
|
||||
upcomingTodayOnly: integer("upcoming_today_only", { mode: "boolean" }).notNull().default(false),
|
||||
shareScheduleTodayOnly: integer("share_schedule_today_only", { mode: "boolean" }).notNull().default(false),
|
||||
swapDashboardMainSections: integer("swap_dashboard_main_sections", { mode: "boolean" }).notNull().default(false),
|
||||
// Last notification tracking (intake reminders)
|
||||
lastAutoEmailSent: text("last_auto_email_sent"),
|
||||
lastNotificationType: text("last_notification_type"),
|
||||
@@ -98,6 +114,10 @@ export const userSettings = sqliteTable("user_settings", {
|
||||
lastStockReminderSent: text("last_stock_reminder_sent"),
|
||||
lastStockReminderChannel: text("last_stock_reminder_channel"),
|
||||
lastStockReminderMedNames: text("last_stock_reminder_med_names"),
|
||||
// Last prescription reminder tracking (separate from stock/intake)
|
||||
lastPrescriptionReminderSent: text("last_prescription_reminder_sent"),
|
||||
lastPrescriptionReminderChannel: text("last_prescription_reminder_channel"),
|
||||
lastPrescriptionReminderMedNames: text("last_prescription_reminder_med_names"),
|
||||
// Timestamps
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
|
||||
});
|
||||
@@ -143,6 +163,7 @@ export const doseTracking = sqliteTable("dose_tracking", {
|
||||
doseId: text("dose_id", { length: 255 }).notNull(), // e.g. "med-5-1-86400000-1735200000000"
|
||||
takenAt: integer("taken_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s','now'))`),
|
||||
markedBy: text("marked_by", { length: 100 }), // null = user, "Daniel" = via share link
|
||||
takenSource: text("taken_source", { length: 20 }).notNull().default("manual"), // manual or automatic
|
||||
dismissed: integer("dismissed", { mode: "boolean" }).notNull().default(false), // true = missed dose acknowledged without taking
|
||||
});
|
||||
|
||||
@@ -159,5 +180,6 @@ export const refillHistory = sqliteTable("refill_history", {
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
packsAdded: integer("packs_added").notNull().default(0),
|
||||
loosePillsAdded: integer("loose_pills_added").notNull().default(0),
|
||||
usedPrescription: integer("used_prescription", { mode: "boolean" }).notNull().default(false),
|
||||
refillDate: integer("refill_date", { mode: "timestamp" }).notNull().default(sql`(strftime('%s','now'))`),
|
||||
});
|
||||
|
||||
@@ -123,6 +123,39 @@ type TranslationKeys = {
|
||||
criticalSection: string;
|
||||
lowStockSection: string;
|
||||
};
|
||||
// Prescription reminder (shared across email + push)
|
||||
prescriptionReminder: {
|
||||
subjectSingle: string;
|
||||
subjectMultiple: string;
|
||||
pushTitleLow: string;
|
||||
pushTitleEmpty: string;
|
||||
pushEmpty: string;
|
||||
pushEmptySingle: string;
|
||||
pushLow: string;
|
||||
pushLowSingle: string;
|
||||
pushRenewNow: string;
|
||||
pushEmptySection: string;
|
||||
pushLowSection: string;
|
||||
pushRefillsLeft: string;
|
||||
title: string;
|
||||
titleEmpty: string;
|
||||
descriptionLow: string;
|
||||
descriptionEmpty: string;
|
||||
alertLowSingle: string;
|
||||
alertLowMultiple: string;
|
||||
alertEmptySingle: string;
|
||||
alertEmptyMultiple: string;
|
||||
line: string;
|
||||
lineEmpty: string;
|
||||
expiresSuffix: string;
|
||||
repeatDailyNote: string;
|
||||
tableHeaders: {
|
||||
medication: string;
|
||||
refillsLeft: string;
|
||||
reminderThreshold: string;
|
||||
prescriptionExpires: string;
|
||||
};
|
||||
};
|
||||
// Demand calculator email
|
||||
demandCalculator: {
|
||||
subject: string;
|
||||
@@ -134,11 +167,13 @@ type TranslationKeys = {
|
||||
medication: string;
|
||||
usage: string;
|
||||
needed: string;
|
||||
prescriptionRefills: string;
|
||||
available: string;
|
||||
status: string;
|
||||
};
|
||||
statusEnough: string;
|
||||
statusEmpty: string;
|
||||
prescriptionNotApplicable: string;
|
||||
};
|
||||
// Common
|
||||
common: {
|
||||
@@ -156,8 +191,8 @@ type TranslationKeys = {
|
||||
const translations: Record<Language, TranslationKeys> = {
|
||||
en: {
|
||||
stockReminder: {
|
||||
subject: "MedAssist-ng Auto-Reminder: {count} Medication{s} Running Critically Low",
|
||||
title: "⚠️ MedAssist-ng - Automatic Reorder Reminder",
|
||||
subject: "MedAssist-ng: ⚠️ {count} Medication{s} Running Critically Low",
|
||||
title: "⚠️ MedAssist-ng: Automatic Reorder Reminder",
|
||||
description: "The following medications are running critically low and need to be reordered:",
|
||||
descriptionEmpty: "The following medications are empty and need to be reordered immediately:",
|
||||
descriptionMixed: "The following medications need to be reordered:",
|
||||
@@ -211,9 +246,41 @@ const translations: Record<Language, TranslationKeys> = {
|
||||
criticalSection: "Running critically low",
|
||||
lowStockSection: "Running low",
|
||||
},
|
||||
prescriptionReminder: {
|
||||
subjectSingle: "MedAssist-ng: 🚨 Prescription Refill Reminder",
|
||||
subjectMultiple: "MedAssist-ng: 🚨 {count} Prescriptions Need Renewal Soon",
|
||||
pushTitleLow: "💊 MedAssist-ng: {count} prescriptions are running low",
|
||||
pushTitleEmpty: "💊 MedAssist-ng: {count} prescriptions need renewal now",
|
||||
pushEmpty: "prescriptions out of refills",
|
||||
pushEmptySingle: "prescription out of refills",
|
||||
pushLow: "prescriptions low on refills",
|
||||
pushLowSingle: "prescription low on refills",
|
||||
pushRenewNow: "Renew Now!",
|
||||
pushEmptySection: "Prescriptions with no refills left",
|
||||
pushLowSection: "Prescriptions running low on refills",
|
||||
pushRefillsLeft: "{count} refill(s) remaining on this prescription",
|
||||
title: "⚠️ MedAssist-ng - Prescription Reminder",
|
||||
titleEmpty: "🚨 MedAssist-ng - Prescription Reminder",
|
||||
descriptionLow: "Some prescriptions are low on remaining refills.",
|
||||
descriptionEmpty: "Some prescriptions have no refills left. Contact your doctor for renewal.",
|
||||
alertLowSingle: "⚠️ 1 prescription is low on refills",
|
||||
alertLowMultiple: "⚠️ {count} prescriptions are low on refills",
|
||||
alertEmptySingle: "🚨 1 prescription needs renewal now",
|
||||
alertEmptyMultiple: "🚨 {count} prescriptions need renewal now",
|
||||
line: "{name}: {refills} refill(s) remaining on this prescription{expirySuffix}",
|
||||
lineEmpty: "{name}: no refills remaining on this prescription{expirySuffix}",
|
||||
expiresSuffix: ", expires {date}",
|
||||
repeatDailyNote: "You are receiving this daily reminder because 'Repeat Daily' is enabled in settings.",
|
||||
tableHeaders: {
|
||||
medication: "Medication",
|
||||
refillsLeft: "Prescription refills left",
|
||||
reminderThreshold: "Reminder threshold",
|
||||
prescriptionExpires: "Prescription expires",
|
||||
},
|
||||
},
|
||||
demandCalculator: {
|
||||
subject: "MedAssist-ng - Supply Overview ({from} - {until})",
|
||||
title: "MedAssist-ng - Demand Calculator",
|
||||
subject: "MedAssist-ng: Supply Overview ({from} - {until})",
|
||||
title: "MedAssist-ng: Demand Calculator",
|
||||
description: "Supply overview from {from} to {until}",
|
||||
summaryOutOfStock: "⚠️ {count} medication{s} will be out of stock during this period.",
|
||||
summaryAllOk: "✓ All medications have sufficient supply for this period.",
|
||||
@@ -221,11 +288,13 @@ const translations: Record<Language, TranslationKeys> = {
|
||||
medication: "Medication",
|
||||
usage: "Usage",
|
||||
needed: "Blisters needed",
|
||||
prescriptionRefills: "Prescription refills",
|
||||
available: "Available",
|
||||
status: "Status",
|
||||
},
|
||||
statusEnough: "✓ Enough",
|
||||
statusEmpty: "✗ Empty",
|
||||
prescriptionNotApplicable: "–",
|
||||
},
|
||||
common: {
|
||||
pill: "pill",
|
||||
@@ -240,8 +309,8 @@ const translations: Record<Language, TranslationKeys> = {
|
||||
},
|
||||
de: {
|
||||
stockReminder: {
|
||||
subject: "MedAssist-ng Auto-Erinnerung: {count} Medikament{e} kritisch niedrig",
|
||||
title: "⚠️ MedAssist-ng - Automatische Nachbestell-Erinnerung",
|
||||
subject: "MedAssist-ng: ⚠️ {count} Medikament{e} kritisch niedrig",
|
||||
title: "⚠️ MedAssist-ng: Automatische Nachbestell-Erinnerung",
|
||||
description: "Die folgenden Medikamente sind kritisch niedrig und sollten nachbestellt werden:",
|
||||
descriptionEmpty: "Die folgenden Medikamente sind leer und müssen sofort nachbestellt werden:",
|
||||
descriptionMixed: "Die folgenden Medikamente müssen nachbestellt werden:",
|
||||
@@ -296,9 +365,43 @@ const translations: Record<Language, TranslationKeys> = {
|
||||
criticalSection: "Kritisch niedrig",
|
||||
lowStockSection: "Niedrig",
|
||||
},
|
||||
prescriptionReminder: {
|
||||
subjectSingle: "MedAssist-ng: 🚨 Rezept-Nachfüll-Erinnerung",
|
||||
subjectMultiple: "MedAssist-ng: 🚨 {count} Rezepte müssen bald erneuert werden",
|
||||
pushTitleLow: "💊 MedAssist-ng: {count} Rezept(e) haben nur noch wenige Nachfüllungen",
|
||||
pushTitleEmpty: "💊 MedAssist-ng: {count} Rezept(e) müssen jetzt erneuert werden",
|
||||
pushEmpty: "Rezepte ohne verbleibende Nachfüllung",
|
||||
pushEmptySingle: "Rezept ohne verbleibende Nachfüllung",
|
||||
pushLow: "Rezepte mit wenigen verbleibenden Nachfüllungen",
|
||||
pushLowSingle: "Rezept mit wenigen verbleibenden Nachfüllungen",
|
||||
pushRenewNow: "Jetzt erneuern!",
|
||||
pushEmptySection: "Rezepte ohne Nachfüllungen",
|
||||
pushLowSection: "Rezepte mit bald aufgebrauchten Nachfüllungen",
|
||||
pushRefillsLeft: "{count} Nachfüllung(en) für dieses Rezept übrig",
|
||||
title: "⚠️ MedAssist-ng - Rezept-Erinnerung",
|
||||
titleEmpty: "🚨 MedAssist-ng - Rezept-Erinnerung",
|
||||
descriptionLow: "Einige Rezepte haben nur noch wenige Nachfüllungen.",
|
||||
descriptionEmpty:
|
||||
"Einige Rezepte haben keine Nachfüllungen mehr. Bitte kontaktieren Sie Ihren Arzt für eine Erneuerung.",
|
||||
alertLowSingle: "⚠️ 1 Rezept ist bei den Nachfüllungen niedrig",
|
||||
alertLowMultiple: "⚠️ {count} Rezepte sind bei den Nachfüllungen niedrig",
|
||||
alertEmptySingle: "🚨 1 Rezept muss jetzt erneuert werden",
|
||||
alertEmptyMultiple: "🚨 {count} Rezepte müssen jetzt erneuert werden",
|
||||
line: "{name}: {refills} Nachfüllung(en) für dieses Rezept übrig{expirySuffix}",
|
||||
lineEmpty: "{name}: keine Nachfüllung mehr für dieses Rezept{expirySuffix}",
|
||||
expiresSuffix: ", läuft ab {date}",
|
||||
repeatDailyNote:
|
||||
"Sie erhalten diese tägliche Erinnerung, weil 'Täglich wiederholen' in den Einstellungen aktiviert ist.",
|
||||
tableHeaders: {
|
||||
medication: "Medikament",
|
||||
refillsLeft: "Rezept-Nachfüllungen übrig",
|
||||
reminderThreshold: "Erinnerungsschwelle",
|
||||
prescriptionExpires: "Rezeptablauf",
|
||||
},
|
||||
},
|
||||
demandCalculator: {
|
||||
subject: "MedAssist-ng - Bestandsübersicht ({from} - {until})",
|
||||
title: "MedAssist-ng - Bedarfsrechner",
|
||||
subject: "MedAssist-ng: Bestandsübersicht ({from} - {until})",
|
||||
title: "MedAssist-ng: Bedarfsrechner",
|
||||
description: "Bestandsübersicht von {from} bis {until}",
|
||||
summaryOutOfStock: "⚠️ {count} Medikament{e} wird im Zeitraum nicht ausreichen.",
|
||||
summaryAllOk: "✓ Alle Medikamente reichen für diesen Zeitraum.",
|
||||
@@ -306,11 +409,13 @@ const translations: Record<Language, TranslationKeys> = {
|
||||
medication: "Medikament",
|
||||
usage: "Verbrauch",
|
||||
needed: "Blister benötigt",
|
||||
prescriptionRefills: "Rezept-Nachfüllungen",
|
||||
available: "Verfügbar",
|
||||
status: "Status",
|
||||
},
|
||||
statusEnough: "✓ Ausreichend",
|
||||
statusEmpty: "✗ Leer",
|
||||
prescriptionNotApplicable: "–",
|
||||
},
|
||||
common: {
|
||||
pill: "Tablette",
|
||||
|
||||
+47
-5
@@ -1,4 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
import type { IncomingHttpHeaders } from "node:http";
|
||||
import { resolve } from "node:path";
|
||||
import cookie from "@fastify/cookie";
|
||||
import cors from "@fastify/cors";
|
||||
@@ -20,6 +22,7 @@ import { medicationRoutes } from "./routes/medications.js";
|
||||
import { oidcRoutes } from "./routes/oidc.js";
|
||||
import { plannerRoutes } from "./routes/planner.js";
|
||||
import { refillRoutes } from "./routes/refills.js";
|
||||
import { reportRoutes } from "./routes/report.js";
|
||||
import { settingsRoutes } from "./routes/settings.js";
|
||||
import { shareRoutes } from "./routes/share.js";
|
||||
import { startIntakeReminderScheduler } from "./services/intake-reminder-scheduler.js";
|
||||
@@ -44,6 +47,31 @@ import {
|
||||
parseCorsOrigins,
|
||||
} from "./utils/server-config.js";
|
||||
|
||||
function sanitizeCorrelationId(headers: IncomingHttpHeaders): string | null {
|
||||
const rawHeader = headers["x-correlation-id"];
|
||||
if (typeof rawHeader !== "string") return null;
|
||||
const trimmed = rawHeader.trim();
|
||||
if (!trimmed) return null;
|
||||
if (trimmed.length > 128) return null;
|
||||
if (!/^[A-Za-z0-9._:-]+$/.test(trimmed)) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function buildLoggerOptions(level: string) {
|
||||
const base = {
|
||||
level,
|
||||
timestamp: () => `,"time":"${new Date().toISOString()}"`,
|
||||
};
|
||||
// Human readable logs in development, structured JSON in production/test
|
||||
if (process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "test") {
|
||||
return {
|
||||
...base,
|
||||
transport: { target: "pino-pretty", options: { translateTime: "SYS:yyyy-mm-dd HH:MM:ss.l" } },
|
||||
};
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
/** Create and configure Fastify app (without starting) */
|
||||
export async function createApp(options?: {
|
||||
logLevel?: string;
|
||||
@@ -71,7 +99,14 @@ export async function createApp(options?: {
|
||||
};
|
||||
|
||||
const app = Fastify({
|
||||
logger: { level: opts.logLevel },
|
||||
logger: buildLoggerOptions(opts.logLevel),
|
||||
genReqId: (request) => sanitizeCorrelationId(request.headers) ?? randomUUID(),
|
||||
});
|
||||
|
||||
app.addHook("onRequest", (request, reply, done) => {
|
||||
request.correlationId = request.id;
|
||||
reply.header("x-correlation-id", request.id);
|
||||
done();
|
||||
});
|
||||
|
||||
// Build config
|
||||
@@ -118,6 +153,7 @@ export async function createApp(options?: {
|
||||
await app.register(doseRoutes);
|
||||
await app.register(exportRoutes);
|
||||
await app.register(refillRoutes);
|
||||
await app.register(reportRoutes);
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -136,9 +172,14 @@ log.info("[DB] Migrations complete, starting server...");
|
||||
const imagesDir = ensureImagesDirectory();
|
||||
|
||||
const app = Fastify({
|
||||
logger: {
|
||||
level: env.LOG_LEVEL,
|
||||
},
|
||||
logger: buildLoggerOptions(env.LOG_LEVEL),
|
||||
genReqId: (request) => sanitizeCorrelationId(request.headers) ?? randomUUID(),
|
||||
});
|
||||
|
||||
app.addHook("onRequest", (request, reply, done) => {
|
||||
request.correlationId = request.id;
|
||||
reply.header("x-correlation-id", request.id);
|
||||
done();
|
||||
});
|
||||
|
||||
const origins = parseCorsOrigins(env.CORS_ORIGINS);
|
||||
@@ -164,7 +205,7 @@ await app.register(sensible);
|
||||
await app.register(helmet);
|
||||
await app.register(cors, { origin: origins, credentials: true });
|
||||
await app.register(rateLimit, {
|
||||
max: 100,
|
||||
max: Number(process.env.RATE_LIMIT_MAX) || 100,
|
||||
timeWindow: "1 minute",
|
||||
});
|
||||
await app.register(cookie, { secret: env.COOKIE_SECRET ?? "dev-cookie-secret" });
|
||||
@@ -190,6 +231,7 @@ await app.register(shareRoutes);
|
||||
await app.register(doseRoutes);
|
||||
await app.register(exportRoutes);
|
||||
await app.register(refillRoutes);
|
||||
await app.register(reportRoutes);
|
||||
|
||||
const start = async () => {
|
||||
try {
|
||||
|
||||
@@ -47,7 +47,7 @@ export async function getAnonymousUserId(): Promise<number> {
|
||||
export interface AuthState {
|
||||
authEnabled: boolean;
|
||||
registrationEnabled: boolean;
|
||||
localAuthEnabled: boolean;
|
||||
formLoginEnabled: boolean;
|
||||
oidcEnabled: boolean;
|
||||
oidcProviderName: string;
|
||||
hasUsers: boolean;
|
||||
@@ -59,15 +59,18 @@ export async function getAuthState(): Promise<AuthState> {
|
||||
const [result] = await db.select({ count: count() }).from(users).where(sql`${users.id} != ${ANONYMOUS_USER_ID}`);
|
||||
const hasUsers = result.count > 0;
|
||||
|
||||
const needsSetup = env.AUTH_ENABLED && !hasUsers;
|
||||
|
||||
return {
|
||||
authEnabled: env.AUTH_ENABLED,
|
||||
// Registration: enabled via ENV OR no users exist (first-time setup)
|
||||
registrationEnabled: env.REGISTRATION_ENABLED || !hasUsers,
|
||||
localAuthEnabled: env.AUTH_ENABLED, // Password auth available when auth is enabled
|
||||
// Form login: enabled when auth + form login are both on, or forced on for first-user setup
|
||||
formLoginEnabled: needsSetup || (env.AUTH_ENABLED && env.FORM_LOGIN_ENABLED),
|
||||
oidcEnabled: env.OIDC_ENABLED,
|
||||
oidcProviderName: env.OIDC_PROVIDER_NAME,
|
||||
hasUsers,
|
||||
needsSetup: env.AUTH_ENABLED && !hasUsers,
|
||||
needsSetup,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -142,9 +145,12 @@ export async function requireAuth(request: FastifyRequest, reply: FastifyReply)
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
};
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
// Re-throw our own errors
|
||||
if (err?.message === "AUTH_REQUIRED" || err?.message === "USER_NOT_FOUND" || err?.message === "ACCOUNT_DISABLED") {
|
||||
if (
|
||||
err instanceof Error &&
|
||||
(err.message === "AUTH_REQUIRED" || err.message === "USER_NOT_FOUND" || err.message === "ACCOUNT_DISABLED")
|
||||
) {
|
||||
throw err;
|
||||
}
|
||||
// JWT verification failed
|
||||
|
||||
@@ -28,7 +28,11 @@ const EnvSchema = z.object({
|
||||
.string()
|
||||
.transform((v) => v === "true")
|
||||
.default("false"),
|
||||
// Disable local auth when using SSO only
|
||||
// Disable username/password form login (useful for OIDC-only setups)
|
||||
FORM_LOGIN_ENABLED: z
|
||||
.string()
|
||||
.transform((v) => v === "true")
|
||||
.default("true"),
|
||||
|
||||
// JWT Secrets - only required when AUTH_ENABLED=true
|
||||
JWT_SECRET: z.string().min(10).optional(),
|
||||
@@ -128,4 +132,26 @@ if (parsed.OIDC_ENABLED) {
|
||||
}
|
||||
}
|
||||
|
||||
// Validate that at least one login method is available when auth is enabled
|
||||
if (parsed.AUTH_ENABLED && !parsed.FORM_LOGIN_ENABLED && !parsed.OIDC_ENABLED) {
|
||||
console.error("=".repeat(60));
|
||||
console.error("AUTHENTICATION CONFIGURATION ERROR");
|
||||
console.error("=".repeat(60));
|
||||
console.error("AUTH_ENABLED=true but no login method is available.");
|
||||
console.error("FORM_LOGIN_ENABLED=false and OIDC_ENABLED=false means users cannot log in.");
|
||||
console.error("");
|
||||
console.error("To fix this, either:");
|
||||
console.error(" 1. Set FORM_LOGIN_ENABLED=true to allow username/password login");
|
||||
console.error(" 2. Set OIDC_ENABLED=true to allow SSO login");
|
||||
console.error("=".repeat(60));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Warn about ineffective registration when form login is disabled
|
||||
if (parsed.REGISTRATION_ENABLED && !parsed.FORM_LOGIN_ENABLED) {
|
||||
console.warn(
|
||||
"[config] REGISTRATION_ENABLED=true has no effect when FORM_LOGIN_ENABLED=false (no registration form available)"
|
||||
);
|
||||
}
|
||||
|
||||
export const env = parsed;
|
||||
|
||||
+39
-42
@@ -1,6 +1,7 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { resolve } from "node:path";
|
||||
import argon2 from "argon2";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
@@ -8,6 +9,12 @@ import { getDataDir } from "../db/db-utils.js";
|
||||
import { refreshTokens, users } from "../db/schema.js";
|
||||
import { getAuthState, requireAuth } from "../plugins/auth.js";
|
||||
import type { AuthUser } from "../types/fastify.js";
|
||||
import {
|
||||
ALLOWED_IMAGE_MIME_TYPES,
|
||||
removeImageFiles,
|
||||
streamToBuffer,
|
||||
writeOptimizedImageSet,
|
||||
} from "../utils/image-upload.js";
|
||||
|
||||
// =============================================================================
|
||||
// Argon2id Configuration - State of the Art Password Hashing
|
||||
@@ -53,6 +60,7 @@ const sensitiveRateLimitConfig = {
|
||||
const registerSchema = z.object({
|
||||
username: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(3, "Username must be at least 3 characters")
|
||||
.max(50, "Username must be at most 50 characters")
|
||||
.regex(/^[a-zA-Z0-9_-]+$/, "Username can only contain letters, numbers, underscores, and hyphens"),
|
||||
@@ -63,7 +71,7 @@ const registerSchema = z.object({
|
||||
});
|
||||
|
||||
const loginSchema = z.object({
|
||||
username: z.string().min(1, "Username is required"),
|
||||
username: z.string().trim().min(1, "Username is required"),
|
||||
password: z.string().min(1, "Password is required"),
|
||||
rememberMe: z.boolean().optional().default(false),
|
||||
});
|
||||
@@ -81,6 +89,8 @@ const updateProfileSchema = z.object({
|
||||
// Auth Routes
|
||||
// =============================================================================
|
||||
export async function authRoutes(app: FastifyInstance) {
|
||||
const IMAGES_DIR = resolve(getDataDir(), "images");
|
||||
|
||||
// Token TTLs
|
||||
const accessTtlMinutes = 15;
|
||||
const refreshTtlDays = 14;
|
||||
@@ -113,8 +123,8 @@ export async function authRoutes(app: FastifyInstance) {
|
||||
return reply.status(400).send({ error: "Registration is disabled", code: "REGISTRATION_DISABLED" });
|
||||
}
|
||||
|
||||
if (!state.localAuthEnabled) {
|
||||
return reply.status(400).send({ error: "Local authentication is disabled", code: "LOCAL_AUTH_DISABLED" });
|
||||
if (!state.formLoginEnabled) {
|
||||
return reply.status(400).send({ error: "Form login is disabled", code: "FORM_LOGIN_DISABLED" });
|
||||
}
|
||||
|
||||
// Validate input
|
||||
@@ -129,7 +139,7 @@ export async function authRoutes(app: FastifyInstance) {
|
||||
const { username, password } = parsed.data;
|
||||
|
||||
// Check if username already exists
|
||||
const [existingUser] = await db.select().from(users).where(eq(users.username, username));
|
||||
const [existingUser] = await db.select().from(users).where(sql`lower(${users.username}) = lower(${username})`);
|
||||
if (existingUser) {
|
||||
return reply.status(409).send({ error: "Username already taken", code: "USERNAME_EXISTS" });
|
||||
}
|
||||
@@ -175,8 +185,8 @@ export async function authRoutes(app: FastifyInstance) {
|
||||
return reply.status(400).send({ error: "Authentication is disabled", code: "AUTH_DISABLED" });
|
||||
}
|
||||
|
||||
if (!state.localAuthEnabled) {
|
||||
return reply.status(400).send({ error: "Local authentication is disabled", code: "LOCAL_AUTH_DISABLED" });
|
||||
if (!state.formLoginEnabled) {
|
||||
return reply.status(400).send({ error: "Form login is disabled", code: "FORM_LOGIN_DISABLED" });
|
||||
}
|
||||
|
||||
const parsed = loginSchema.safeParse(request.body);
|
||||
@@ -190,7 +200,7 @@ export async function authRoutes(app: FastifyInstance) {
|
||||
const { username, password, rememberMe } = parsed.data;
|
||||
|
||||
// Find user by username
|
||||
const [user] = await db.select().from(users).where(eq(users.username, username));
|
||||
const [user] = await db.select().from(users).where(sql`lower(${users.username}) = lower(${username})`);
|
||||
|
||||
// Generic error to prevent user enumeration
|
||||
const invalidCredentialsError = () =>
|
||||
@@ -461,36 +471,35 @@ export async function authRoutes(app: FastifyInstance) {
|
||||
|
||||
const data = await request.file();
|
||||
if (!data) {
|
||||
return reply.status(400).send({ error: "No file uploaded" });
|
||||
return reply.status(400).send({ error: "No file uploaded", code: "NO_FILE" });
|
||||
}
|
||||
|
||||
// Validate file type
|
||||
const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
|
||||
if (!allowedTypes.includes(data.mimetype)) {
|
||||
return reply.status(400).send({ error: "Invalid file type. Allowed: JPEG, PNG, WebP, GIF" });
|
||||
if (!ALLOWED_IMAGE_MIME_TYPES.includes(data.mimetype)) {
|
||||
return reply.status(400).send({ error: "Invalid file type", code: "INVALID_TYPE" });
|
||||
}
|
||||
|
||||
// Generate unique filename
|
||||
const ext = data.filename.split(".").pop() || "jpg";
|
||||
const filename = `avatar_${authUser.id}_${Date.now()}.${ext}`;
|
||||
let uploadBuffer: Buffer;
|
||||
try {
|
||||
uploadBuffer = await streamToBuffer(data.file);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "IMAGE_TOO_LARGE") {
|
||||
return reply.status(400).send({ error: "Image too large", code: "IMAGE_TOO_LARGE" });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Save file
|
||||
const fs = await import("node:fs/promises");
|
||||
const path = await import("node:path");
|
||||
const imagesDir = path.join(getDataDir(), "images");
|
||||
await fs.mkdir(imagesDir, { recursive: true });
|
||||
|
||||
const buffer = await data.toBuffer();
|
||||
await fs.writeFile(path.join(imagesDir, filename), buffer);
|
||||
let filename: string;
|
||||
try {
|
||||
({ filename } = await writeOptimizedImageSet(IMAGES_DIR, `avatar_${authUser.id}`, uploadBuffer));
|
||||
} catch {
|
||||
return reply.status(400).send({ error: "Invalid image", code: "INVALID_IMAGE" });
|
||||
}
|
||||
|
||||
// Delete old avatar if exists
|
||||
const [user] = await db.select().from(users).where(eq(users.id, authUser.id));
|
||||
if (user?.avatarUrl) {
|
||||
try {
|
||||
await fs.unlink(path.join(imagesDir, user.avatarUrl));
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
removeImageFiles(IMAGES_DIR, user.avatarUrl);
|
||||
}
|
||||
|
||||
// Update user
|
||||
@@ -521,13 +530,7 @@ export async function authRoutes(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
// Delete file
|
||||
const fs = await import("node:fs/promises");
|
||||
const path = await import("node:path");
|
||||
try {
|
||||
await fs.unlink(path.join(getDataDir(), "images", user.avatarUrl));
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
removeImageFiles(IMAGES_DIR, user.avatarUrl);
|
||||
|
||||
// Update user
|
||||
await db.update(users).set({ avatarUrl: null, updatedAt: new Date() }).where(eq(users.id, authUser.id));
|
||||
@@ -554,13 +557,7 @@ export async function authRoutes(app: FastifyInstance) {
|
||||
// Delete avatar file if exists
|
||||
const [user] = await db.select().from(users).where(eq(users.id, authUser.id));
|
||||
if (user?.avatarUrl) {
|
||||
const fs = await import("node:fs/promises");
|
||||
const path = await import("node:path");
|
||||
try {
|
||||
await fs.unlink(path.join(getDataDir(), "images", user.avatarUrl));
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
removeImageFiles(IMAGES_DIR, user.avatarUrl);
|
||||
}
|
||||
|
||||
// Delete user - cascade delete handles all related data
|
||||
|
||||
+133
-9
@@ -2,10 +2,11 @@ import { and, eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { doseTracking, shareTokens } from "../db/schema.js";
|
||||
import { doseTracking, medications, shareTokens } from "../db/schema.js";
|
||||
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
|
||||
import { env } from "../plugins/env.js";
|
||||
import type { AuthUser } from "../types/fastify.js";
|
||||
import { parseIntakesJson, parseTakenByJson, personTakesMedication } from "../utils/scheduler-utils.js";
|
||||
|
||||
// =============================================================================
|
||||
// Validation Schemas
|
||||
@@ -22,6 +23,13 @@ const dismissDosesSchema = z.object({
|
||||
doseIds: z.array(z.string().min(1)).min(1, "At least one doseId is required"),
|
||||
});
|
||||
|
||||
const doseIdPattern = /^(\d+)-(\d+)-(\d+)(?:-(.+))?$/;
|
||||
|
||||
function maskToken(token: string): string {
|
||||
if (token.length <= 8) return token;
|
||||
return `${token.slice(0, 4)}...${token.slice(-4)}`;
|
||||
}
|
||||
|
||||
// Helper to get user ID from request
|
||||
// Returns anonymous user ID when auth is disabled
|
||||
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
|
||||
@@ -38,14 +46,100 @@ async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<
|
||||
return authUser.id;
|
||||
}
|
||||
|
||||
type ParsedDoseId = {
|
||||
medicationId: number;
|
||||
intakeIndex: number;
|
||||
timestampMs: number;
|
||||
personSuffix: string | null;
|
||||
};
|
||||
|
||||
function parseDoseId(doseId: string): ParsedDoseId | null {
|
||||
const match = doseIdPattern.exec(doseId);
|
||||
if (!match) return null;
|
||||
|
||||
const medicationId = Number.parseInt(match[1], 10);
|
||||
const intakeIndex = Number.parseInt(match[2], 10);
|
||||
const timestampMs = Number.parseInt(match[3], 10);
|
||||
const personSuffix = match[4] ? match[4].trim() : null;
|
||||
|
||||
if (Number.isNaN(medicationId) || Number.isNaN(intakeIndex) || Number.isNaN(timestampMs) || intakeIndex < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
medicationId,
|
||||
intakeIndex,
|
||||
timestampMs,
|
||||
personSuffix,
|
||||
};
|
||||
}
|
||||
|
||||
async function getActiveShareToken(token: string): Promise<{
|
||||
share: typeof shareTokens.$inferSelect | null;
|
||||
reason: "not_found" | "expired" | "ok";
|
||||
}> {
|
||||
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
|
||||
if (!share) return { share: null, reason: "not_found" };
|
||||
|
||||
if (share.expiresAt && share.expiresAt.getTime() < Date.now()) {
|
||||
return { share: null, reason: "expired" };
|
||||
}
|
||||
|
||||
return { share, reason: "ok" };
|
||||
}
|
||||
|
||||
async function validateShareDoseId(share: typeof shareTokens.$inferSelect, doseId: string): Promise<boolean> {
|
||||
const parsedDose = parseDoseId(doseId);
|
||||
if (!parsedDose) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const [medication] = await db
|
||||
.select()
|
||||
.from(medications)
|
||||
.where(and(eq(medications.id, parsedDose.medicationId), eq(medications.userId, share.userId)));
|
||||
|
||||
if (!medication) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const medTakenBy = parseTakenByJson(medication.takenByJson);
|
||||
const intakes = parseIntakesJson(
|
||||
medication.intakesJson,
|
||||
{ usageJson: medication.usageJson, everyJson: medication.everyJson, startJson: medication.startJson },
|
||||
medication.intakeRemindersEnabled ?? false
|
||||
);
|
||||
|
||||
if (!personTakesMedication(share.takenBy, medTakenBy, intakes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const intake = intakes[parsedDose.intakeIndex];
|
||||
if (!intake) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const expectedPersons = intake.takenBy ? [intake.takenBy] : medTakenBy;
|
||||
if (expectedPersons.length === 0) {
|
||||
return parsedDose.personSuffix === null;
|
||||
}
|
||||
|
||||
if (!parsedDose.personSuffix) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return expectedPersons.includes(parsedDose.personSuffix);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Dose Tracking Routes
|
||||
// =============================================================================
|
||||
export async function doseRoutes(app: FastifyInstance) {
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /doses/taken - PROTECTED: Get all taken doses for the user
|
||||
// Suppress request logs — polled every 5s by frontend
|
||||
// ---------------------------------------------------------------------------
|
||||
app.get("/doses/taken", { preHandler: requireAuth }, async (request, reply) => {
|
||||
app.get("/doses/taken", { preHandler: requireAuth, logLevel: "warn" }, async (request, reply) => {
|
||||
const userId = await getUserId(request, reply);
|
||||
|
||||
// Get all taken doses for this user (no time limit)
|
||||
@@ -56,6 +150,7 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
doseId: d.doseId,
|
||||
takenAt: d.takenAt?.getTime() ?? Date.now(),
|
||||
markedBy: d.markedBy,
|
||||
takenSource: d.takenSource ?? "manual",
|
||||
dismissed: d.dismissed ?? false,
|
||||
})),
|
||||
};
|
||||
@@ -94,6 +189,7 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
userId,
|
||||
doseId,
|
||||
markedBy: null, // Marked by the user themselves
|
||||
takenSource: "manual",
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
@@ -209,13 +305,14 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /share/:token/doses - PUBLIC: Get taken doses for a share link
|
||||
// Suppress request logs — polled every 5s by SharedSchedule
|
||||
// ---------------------------------------------------------------------------
|
||||
app.get<{ Params: { token: string } }>("/share/:token/doses", async (request, reply) => {
|
||||
app.get<{ Params: { token: string } }>("/share/:token/doses", { logLevel: "warn" }, async (request, reply) => {
|
||||
const { token } = request.params;
|
||||
|
||||
// Find share token
|
||||
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
|
||||
const { share, reason } = await getActiveShareToken(token);
|
||||
if (!share) {
|
||||
request.log.warn(`[ShareDose] Rejected read for token ${maskToken(token)} (reason=${reason})`);
|
||||
return reply.notFound("Share link not found");
|
||||
}
|
||||
|
||||
@@ -227,6 +324,7 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
doseId: d.doseId,
|
||||
takenAt: d.takenAt?.getTime() ?? Date.now(),
|
||||
markedBy: d.markedBy,
|
||||
takenSource: d.takenSource ?? "manual",
|
||||
dismissed: d.dismissed ?? false,
|
||||
})),
|
||||
};
|
||||
@@ -249,12 +347,20 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
|
||||
const { doseId } = parsed.data;
|
||||
|
||||
// Find share token
|
||||
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
|
||||
const { share, reason } = await getActiveShareToken(token);
|
||||
if (!share) {
|
||||
request.log.warn(`[ShareDose] Rejected mark for token ${maskToken(token)} (reason=${reason})`);
|
||||
return reply.notFound("Share link not found");
|
||||
}
|
||||
|
||||
const isValidShareDoseId = await validateShareDoseId(share, doseId);
|
||||
if (!isValidShareDoseId) {
|
||||
request.log.warn(
|
||||
`[ShareDose] Rejected invalid doseId in mark request (owner=${share.userId}, takenBy=${share.takenBy}, doseId=${doseId})`
|
||||
);
|
||||
return reply.status(400).send({ error: "Invalid or unauthorized doseId" });
|
||||
}
|
||||
|
||||
// Check if already marked
|
||||
const [existing] = await db
|
||||
.select()
|
||||
@@ -262,6 +368,7 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
.where(and(eq(doseTracking.userId, share.userId), eq(doseTracking.doseId, doseId)));
|
||||
|
||||
if (existing) {
|
||||
request.log.debug(`[ShareDose] Duplicate mark ignored (owner=${share.userId}, doseId=${doseId})`);
|
||||
return { success: true, message: "Already marked" };
|
||||
}
|
||||
|
||||
@@ -270,8 +377,13 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
userId: share.userId,
|
||||
doseId,
|
||||
markedBy: share.takenBy, // e.g. "Daniel"
|
||||
takenSource: "manual",
|
||||
});
|
||||
|
||||
request.log.info(
|
||||
`[ShareDose] Dose marked via share link (owner=${share.userId}, takenBy=${share.takenBy}, doseId=${doseId})`
|
||||
);
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
);
|
||||
@@ -282,12 +394,20 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
app.delete<{ Params: { token: string; doseId: string } }>("/share/:token/doses/:doseId", async (request, reply) => {
|
||||
const { token, doseId } = request.params;
|
||||
|
||||
// Find share token
|
||||
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
|
||||
const { share, reason } = await getActiveShareToken(token);
|
||||
if (!share) {
|
||||
request.log.warn(`[ShareDose] Rejected unmark for token ${maskToken(token)} (reason=${reason})`);
|
||||
return reply.notFound("Share link not found");
|
||||
}
|
||||
|
||||
const isValidShareDoseId = await validateShareDoseId(share, doseId);
|
||||
if (!isValidShareDoseId) {
|
||||
request.log.warn(
|
||||
`[ShareDose] Rejected invalid doseId in unmark request (owner=${share.userId}, takenBy=${share.takenBy}, doseId=${doseId})`
|
||||
);
|
||||
return reply.status(400).send({ error: "Invalid or unauthorized doseId" });
|
||||
}
|
||||
|
||||
// Check if this dose was dismissed
|
||||
const [existing] = await db
|
||||
.select()
|
||||
@@ -296,9 +416,13 @@ export async function doseRoutes(app: FastifyInstance) {
|
||||
|
||||
if (existing?.dismissed) {
|
||||
// Already dismissed - keep the record as-is
|
||||
request.log.debug(`[ShareDose] Unmark ignored for dismissed dose (owner=${share.userId}, doseId=${doseId})`);
|
||||
} else {
|
||||
// Not dismissed - delete the record entirely
|
||||
await db.delete(doseTracking).where(and(eq(doseTracking.userId, share.userId), eq(doseTracking.doseId, doseId)));
|
||||
request.log.info(
|
||||
`[ShareDose] Dose unmarked via share link (owner=${share.userId}, takenBy=${share.takenBy}, doseId=${doseId})`
|
||||
);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
|
||||
@@ -2,11 +2,11 @@ import { randomBytes } from "node:crypto";
|
||||
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { extname, resolve } from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { getDataDir } from "../db/db-utils.js";
|
||||
import { doseTracking, medications, shareTokens, userSettings } from "../db/schema.js";
|
||||
import { doseTracking, medications, refillHistory, shareTokens, userSettings } from "../db/schema.js";
|
||||
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
|
||||
import { env } from "../plugins/env.js";
|
||||
import type { AuthUser } from "../types/fastify.js";
|
||||
@@ -17,7 +17,7 @@ const IMAGES_DIR = resolve(getDataDir(), "images");
|
||||
// =============================================================================
|
||||
// Export Format Version (bump this when format changes)
|
||||
// =============================================================================
|
||||
const EXPORT_VERSION = "1.0";
|
||||
const EXPORT_VERSION = "1.1";
|
||||
|
||||
// =============================================================================
|
||||
// Zod Schemas for Import Validation
|
||||
@@ -35,6 +35,7 @@ const inventorySchema = z.object({
|
||||
packCount: z.number().int().min(0).default(1),
|
||||
blistersPerPack: z.number().int().min(1).default(1),
|
||||
pillsPerBlister: z.number().int().min(1).default(1),
|
||||
totalPills: z.number().int().nullable().optional(), // For bottle type: total capacity
|
||||
looseTablets: z.number().int().min(0).default(0),
|
||||
stockAdjustment: z.number().int().default(0), // Manual stock correction
|
||||
packageType: z.enum(["blister", "bottle"]).default("blister"),
|
||||
@@ -49,9 +50,18 @@ const medicationExportSchema = z.object({
|
||||
pillWeightMg: z.number().int().nullable().optional(),
|
||||
doseUnit: z.enum(["mg", "g", "mcg", "ml", "IU", "units", "drops", "puffs"]).default("mg"),
|
||||
schedules: z.array(scheduleSchema).default([]),
|
||||
medicationStartDate: z.string().nullable().optional(),
|
||||
expiryDate: z.string().nullable().optional(),
|
||||
notes: z.string().nullable().optional(),
|
||||
intakeRemindersEnabled: z.boolean().default(false),
|
||||
isObsolete: z.boolean().default(false),
|
||||
obsoleteAt: z.string().nullable().optional(),
|
||||
prescriptionEnabled: z.boolean().default(false),
|
||||
prescriptionAuthorizedRefills: z.number().int().min(0).nullable().optional(),
|
||||
prescriptionRemainingRefills: z.number().int().min(0).nullable().optional(),
|
||||
prescriptionLowRefillThreshold: z.number().int().min(0).default(1),
|
||||
prescriptionExpiryDate: z.string().nullable().optional(),
|
||||
dismissedUntil: z.string().nullable().optional(), // ISO date string for dismissed past doses
|
||||
image: z.string().nullable().optional(), // base64 data URL or null
|
||||
lastStockCorrectionAt: z.string().nullable().optional(), // ISO datetime of last stock correction
|
||||
});
|
||||
@@ -62,10 +72,19 @@ const doseHistorySchema = z.object({
|
||||
scheduledTime: z.string(), // ISO datetime
|
||||
takenAt: z.string(), // ISO datetime
|
||||
markedBy: z.string().nullable().optional(),
|
||||
takenSource: z.enum(["manual", "automatic"]).default("manual"),
|
||||
dismissed: z.boolean().default(false),
|
||||
takenByPerson: z.string().nullable().optional(), // Person suffix from dose ID (e.g., "Daniel")
|
||||
});
|
||||
|
||||
const refillHistoryExportSchema = z.object({
|
||||
medicationRef: z.string(), // References _exportId
|
||||
packsAdded: z.number().int().min(0).default(0),
|
||||
loosePillsAdded: z.number().int().min(0).default(0),
|
||||
usedPrescription: z.boolean().default(false),
|
||||
refillDate: z.string(), // ISO datetime
|
||||
});
|
||||
|
||||
const shareLinkSchema = z.object({
|
||||
takenBy: z.string().min(1),
|
||||
scheduleDays: z.number().int().min(1).default(30),
|
||||
@@ -80,11 +99,13 @@ const settingsExportSchema = z
|
||||
notificationEmail: z.string().nullable().optional(),
|
||||
emailStockReminders: z.boolean().default(true),
|
||||
emailIntakeReminders: z.boolean().default(true),
|
||||
emailPrescriptionReminders: z.boolean().default(true),
|
||||
// Push notifications
|
||||
shoutrrrEnabled: z.boolean().optional(),
|
||||
shoutrrrUrl: z.string().nullable().optional(),
|
||||
shoutrrrStockReminders: z.boolean().default(true),
|
||||
shoutrrrIntakeReminders: z.boolean().default(true),
|
||||
shoutrrrPrescriptionReminders: z.boolean().default(true),
|
||||
// Reminder settings
|
||||
reminderDaysBefore: z.number().int().default(7),
|
||||
repeatDailyReminders: z.boolean().default(false),
|
||||
@@ -96,9 +117,11 @@ const settingsExportSchema = z
|
||||
lowStockDays: z.number().int().default(30),
|
||||
normalStockDays: z.number().int().default(90),
|
||||
highStockDays: z.number().int().default(180),
|
||||
expiryWarningDays: z.number().int().default(90),
|
||||
// UI preferences
|
||||
language: z.string().default("en"),
|
||||
stockCalculationMode: z.enum(["automatic", "manual"]).default("automatic"),
|
||||
shareStockStatus: z.boolean().default(true),
|
||||
})
|
||||
.optional();
|
||||
|
||||
@@ -108,6 +131,7 @@ const importDataSchema = z.object({
|
||||
includeSensitiveData: z.boolean().default(false),
|
||||
medications: z.array(medicationExportSchema).default([]),
|
||||
doseHistory: z.array(doseHistorySchema).default([]),
|
||||
refillHistory: z.array(refillHistoryExportSchema).default([]),
|
||||
settings: settingsExportSchema,
|
||||
shareLinks: z.array(shareLinkSchema).default([]),
|
||||
});
|
||||
@@ -117,7 +141,7 @@ const importDataSchema = z.object({
|
||||
// =============================================================================
|
||||
|
||||
// Helper to get user ID from request
|
||||
async function getUserId(request: any, reply: any): Promise<number> {
|
||||
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
|
||||
if (!env.AUTH_ENABLED) {
|
||||
return getAnonymousUserId();
|
||||
}
|
||||
@@ -275,6 +299,7 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
packCount: med.packCount ?? 1,
|
||||
blistersPerPack: med.blistersPerPack ?? 1,
|
||||
pillsPerBlister: med.pillsPerBlister ?? 1,
|
||||
totalPills: med.totalPills ?? null,
|
||||
looseTablets: med.looseTablets ?? 0,
|
||||
stockAdjustment: med.stockAdjustment ?? 0,
|
||||
packageType: med.packageType ?? "blister",
|
||||
@@ -282,9 +307,18 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
pillWeightMg: med.pillWeightMg,
|
||||
doseUnit: med.doseUnit ?? "mg",
|
||||
schedules: parseIntakesForExport(med),
|
||||
medicationStartDate: med.medicationStartDate || null,
|
||||
expiryDate: med.expiryDate,
|
||||
notes: med.notes,
|
||||
intakeRemindersEnabled: med.intakeRemindersEnabled ?? false,
|
||||
isObsolete: med.isObsolete ?? false,
|
||||
obsoleteAt: med.obsoleteAt?.toISOString() ?? null,
|
||||
prescriptionEnabled: med.prescriptionEnabled ?? false,
|
||||
prescriptionAuthorizedRefills: med.prescriptionAuthorizedRefills ?? null,
|
||||
prescriptionRemainingRefills: med.prescriptionRemainingRefills ?? null,
|
||||
prescriptionLowRefillThreshold: med.prescriptionLowRefillThreshold ?? 1,
|
||||
prescriptionExpiryDate: med.prescriptionExpiryDate ?? null,
|
||||
dismissedUntil: med.dismissedUntil ?? null,
|
||||
image: includeImages ? imageToBase64(med.imageUrl) : null,
|
||||
lastStockCorrectionAt: lastStockCorrectionAtIso,
|
||||
};
|
||||
@@ -331,6 +365,7 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
scheduledTime: scheduledTimeIso,
|
||||
takenAt: takenAtIso,
|
||||
markedBy: dose.markedBy,
|
||||
takenSource: dose.takenSource === "automatic" ? "automatic" : "manual",
|
||||
dismissed: dose.dismissed ?? false,
|
||||
takenByPerson: parsed.person,
|
||||
};
|
||||
@@ -346,11 +381,13 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
notificationEmail: settings.notificationEmail,
|
||||
emailStockReminders: settings.emailStockReminders,
|
||||
emailIntakeReminders: settings.emailIntakeReminders,
|
||||
emailPrescriptionReminders: settings.emailPrescriptionReminders ?? true,
|
||||
// Only include sensitive data if requested
|
||||
shoutrrrEnabled: includeSensitive ? settings.shoutrrrEnabled : undefined,
|
||||
shoutrrrUrl: includeSensitive ? settings.shoutrrrUrl : undefined,
|
||||
shoutrrrStockReminders: settings.shoutrrrStockReminders,
|
||||
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
|
||||
shoutrrrPrescriptionReminders: settings.shoutrrrPrescriptionReminders ?? true,
|
||||
reminderDaysBefore: settings.reminderDaysBefore,
|
||||
repeatDailyReminders: settings.repeatDailyReminders,
|
||||
skipRemindersForTakenDoses: settings.skipRemindersForTakenDoses,
|
||||
@@ -360,8 +397,10 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
lowStockDays: settings.lowStockDays,
|
||||
normalStockDays: settings.normalStockDays,
|
||||
highStockDays: settings.highStockDays,
|
||||
expiryWarningDays: settings.expiryWarningDays,
|
||||
language: settings.language,
|
||||
stockCalculationMode: settings.stockCalculationMode,
|
||||
shareStockStatus: settings.shareStockStatus,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
@@ -392,6 +431,39 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
};
|
||||
});
|
||||
|
||||
// 5. Load refill history
|
||||
const refills = await db.select().from(refillHistory).where(eq(refillHistory.userId, userId));
|
||||
|
||||
const exportRefillHistory = refills
|
||||
.map((refill) => {
|
||||
const exportId = medIdToExportId.get(refill.medicationId);
|
||||
if (!exportId) return null; // Orphaned refill, skip
|
||||
|
||||
// Safely convert refillDate to ISO string
|
||||
let refillDateIso: string;
|
||||
try {
|
||||
if (refill.refillDate instanceof Date && !Number.isNaN(refill.refillDate.getTime())) {
|
||||
refillDateIso = refill.refillDate.toISOString();
|
||||
} else if (typeof refill.refillDate === "number" || typeof refill.refillDate === "string") {
|
||||
const d = new Date(refill.refillDate);
|
||||
refillDateIso = !Number.isNaN(d.getTime()) ? d.toISOString() : new Date().toISOString();
|
||||
} else {
|
||||
refillDateIso = new Date().toISOString();
|
||||
}
|
||||
} catch {
|
||||
refillDateIso = new Date().toISOString();
|
||||
}
|
||||
|
||||
return {
|
||||
medicationRef: exportId,
|
||||
packsAdded: refill.packsAdded ?? 0,
|
||||
loosePillsAdded: refill.loosePillsAdded ?? 0,
|
||||
usedPrescription: refill.usedPrescription ?? false,
|
||||
refillDate: refillDateIso,
|
||||
};
|
||||
})
|
||||
.filter((r): r is NonNullable<typeof r> => r !== null);
|
||||
|
||||
// Build export object
|
||||
const exportData = {
|
||||
version: EXPORT_VERSION,
|
||||
@@ -399,12 +471,17 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
includeSensitiveData: includeSensitive,
|
||||
medications: exportMedications,
|
||||
doseHistory: exportDoseHistory,
|
||||
refillHistory: exportRefillHistory,
|
||||
settings: exportSettings,
|
||||
shareLinks: exportShareLinks,
|
||||
};
|
||||
|
||||
// Set download headers
|
||||
const filename = `medassist-export-${new Date().toISOString().split("T")[0]}.json`;
|
||||
const now = new Date();
|
||||
const dateStr = now.toISOString().replace(/[-:]/g, "").replace(/T/, "-").slice(0, 13);
|
||||
const authUser = env.AUTH_ENABLED ? (request.user as unknown as AuthUser | null) : null;
|
||||
const userPart = authUser?.username ? `-${authUser.username}` : "";
|
||||
const filename = `medassist-export${userPart}-${dateStr}.json`;
|
||||
reply.header("Content-Type", "application/json");
|
||||
reply.header("Content-Disposition", `attachment; filename="${filename}"`);
|
||||
|
||||
@@ -455,7 +532,8 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
}
|
||||
}
|
||||
|
||||
// Delete in order: doses, share tokens, medications, settings
|
||||
// Delete in order: refill history, doses, share tokens, medications, settings
|
||||
await db.delete(refillHistory).where(eq(refillHistory.userId, userId));
|
||||
await db.delete(doseTracking).where(eq(doseTracking.userId, userId));
|
||||
await db.delete(shareTokens).where(eq(shareTokens.userId, userId));
|
||||
await db.delete(medications).where(eq(medications.userId, userId));
|
||||
@@ -497,10 +575,12 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
blistersPerPack: med.inventory.blistersPerPack,
|
||||
pillsPerBlister: med.inventory.pillsPerBlister,
|
||||
looseTablets: med.inventory.looseTablets,
|
||||
totalPills: med.inventory.totalPills ?? null,
|
||||
stockAdjustment: med.inventory.stockAdjustment ?? 0,
|
||||
lastStockCorrectionAt: med.lastStockCorrectionAt ? new Date(med.lastStockCorrectionAt) : null,
|
||||
pillWeightMg: med.pillWeightMg || null,
|
||||
doseUnit: med.doseUnit ?? "mg",
|
||||
medicationStartDate: med.medicationStartDate || "",
|
||||
intakesJson,
|
||||
usageJson,
|
||||
everyJson,
|
||||
@@ -508,6 +588,14 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
expiryDate: med.expiryDate || null,
|
||||
notes: med.notes || null,
|
||||
intakeRemindersEnabled,
|
||||
isObsolete: med.isObsolete ?? false,
|
||||
obsoleteAt: med.obsoleteAt ? new Date(med.obsoleteAt) : null,
|
||||
prescriptionEnabled: med.prescriptionEnabled ?? false,
|
||||
prescriptionAuthorizedRefills: med.prescriptionEnabled ? (med.prescriptionAuthorizedRefills ?? null) : null,
|
||||
prescriptionRemainingRefills: med.prescriptionEnabled ? (med.prescriptionRemainingRefills ?? null) : null,
|
||||
prescriptionLowRefillThreshold: med.prescriptionLowRefillThreshold ?? 1,
|
||||
prescriptionExpiryDate: med.prescriptionExpiryDate || null,
|
||||
dismissedUntil: med.dismissedUntil || null,
|
||||
imageUrl: null, // Will be set after image is saved
|
||||
})
|
||||
.returning();
|
||||
@@ -539,6 +627,7 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
doseId,
|
||||
takenAt: new Date(dose.takenAt),
|
||||
markedBy: dose.markedBy || null,
|
||||
takenSource: dose.takenSource ?? "manual",
|
||||
dismissed: dose.dismissed ?? false,
|
||||
});
|
||||
}
|
||||
@@ -551,10 +640,12 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
notificationEmail: importData.settings.notificationEmail || null,
|
||||
emailStockReminders: importData.settings.emailStockReminders ?? true,
|
||||
emailIntakeReminders: importData.settings.emailIntakeReminders ?? true,
|
||||
emailPrescriptionReminders: importData.settings.emailPrescriptionReminders ?? true,
|
||||
shoutrrrEnabled: importData.settings.shoutrrrEnabled ?? false,
|
||||
shoutrrrUrl: importData.settings.shoutrrrUrl || null,
|
||||
shoutrrrStockReminders: importData.settings.shoutrrrStockReminders ?? true,
|
||||
shoutrrrIntakeReminders: importData.settings.shoutrrrIntakeReminders ?? true,
|
||||
shoutrrrPrescriptionReminders: importData.settings.shoutrrrPrescriptionReminders ?? true,
|
||||
reminderDaysBefore: importData.settings.reminderDaysBefore ?? 7,
|
||||
repeatDailyReminders: importData.settings.repeatDailyReminders ?? false,
|
||||
skipRemindersForTakenDoses: importData.settings.skipRemindersForTakenDoses ?? false,
|
||||
@@ -564,8 +655,10 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
lowStockDays: importData.settings.lowStockDays ?? 30,
|
||||
normalStockDays: importData.settings.normalStockDays ?? 90,
|
||||
highStockDays: importData.settings.highStockDays ?? 180,
|
||||
expiryWarningDays: importData.settings.expiryWarningDays ?? 90,
|
||||
language: importData.settings.language ?? "en",
|
||||
stockCalculationMode: importData.settings.stockCalculationMode ?? "automatic",
|
||||
shareStockStatus: importData.settings.shareStockStatus ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -583,11 +676,27 @@ export async function exportRoutes(app: FastifyInstance) {
|
||||
});
|
||||
}
|
||||
|
||||
// 7. Import refill history with remapped medication IDs
|
||||
for (const refill of importData.refillHistory) {
|
||||
const newMedId = exportIdToNewId.get(refill.medicationRef);
|
||||
if (!newMedId) continue; // Skip orphaned refill records
|
||||
|
||||
await db.insert(refillHistory).values({
|
||||
medicationId: newMedId,
|
||||
userId,
|
||||
packsAdded: refill.packsAdded ?? 0,
|
||||
loosePillsAdded: refill.loosePillsAdded ?? 0,
|
||||
usedPrescription: refill.usedPrescription ?? false,
|
||||
refillDate: new Date(refill.refillDate),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
imported: {
|
||||
medications: importData.medications.length,
|
||||
doseHistory: importData.doseHistory.length,
|
||||
refillHistory: importData.refillHistory.length,
|
||||
settings: importData.settings ? 1 : 0,
|
||||
shareLinks: importData.shareLinks.length,
|
||||
},
|
||||
|
||||
@@ -10,11 +10,10 @@ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
|
||||
const backendVersion = packageJson.version || "unknown";
|
||||
|
||||
export async function healthRoutes(app: FastifyInstance) {
|
||||
// Exempt from rate limit - lightweight health check
|
||||
app.get("/health", { config: { rateLimit: false } }, async () => ({
|
||||
// Exempt from rate limit + suppress request logs (called every 30s by Docker healthcheck)
|
||||
app.get("/health", { config: { rateLimit: false }, logLevel: "warn" }, async () => ({
|
||||
status: "ok",
|
||||
version: backendVersion,
|
||||
smtpConfigured: Boolean(process.env.SMTP_HOST),
|
||||
shoutrrrConfigured: Boolean(process.env.SHOUTRRR_URL),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { createWriteStream, existsSync, unlinkSync } from "node:fs";
|
||||
import { extname, resolve } from "node:path";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { and, eq, like } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { getDataDir } from "../db/db-utils.js";
|
||||
import { doseTracking, medications } from "../db/schema.js";
|
||||
import { doseTracking, medications, userSettings } from "../db/schema.js";
|
||||
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
|
||||
import { env } from "../plugins/env.js";
|
||||
import type { AuthUser } from "../types/fastify.js";
|
||||
import {
|
||||
ALLOWED_IMAGE_MIME_TYPES,
|
||||
removeImageFiles,
|
||||
streamToBuffer,
|
||||
writeOptimizedImageSet,
|
||||
} from "../utils/image-upload.js";
|
||||
import { type Intake, parseIntakesJson, parseLocalDateTime, parseTakenByJson } from "../utils/scheduler-utils.js";
|
||||
|
||||
const IMAGES_DIR = resolve(getDataDir(), "images");
|
||||
@@ -32,10 +36,13 @@ const blisterSchema = z.object({
|
||||
|
||||
const packageTypeSchema = z.enum(["blister", "bottle"]).default("blister");
|
||||
const doseUnitSchema = z.enum(["mg", "g", "mcg", "ml", "IU", "units", "drops", "puffs"]).default("mg");
|
||||
const medicationStartDateSchema = z
|
||||
.union([z.string().regex(/^\d{4}-\d{2}-\d{2}$/), z.literal(""), z.null()])
|
||||
.optional();
|
||||
|
||||
const medicationSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(100),
|
||||
name: z.string().trim().max(100).default(""),
|
||||
genericName: z.string().trim().max(100).nullable().optional(),
|
||||
takenBy: z.array(z.string().trim().max(100)).default([]), // Medication-level takenBy (fallback)
|
||||
packageType: packageTypeSchema,
|
||||
@@ -46,14 +53,59 @@ const medicationSchema = z
|
||||
looseTablets: z.number().int().min(0).default(0),
|
||||
pillWeightMg: z.number().nonnegative().nullable().optional(),
|
||||
doseUnit: doseUnitSchema,
|
||||
medicationStartDate: medicationStartDateSchema,
|
||||
expiryDate: z.string().nullable().optional(),
|
||||
notes: z.string().max(2000).nullable().optional(),
|
||||
prescriptionEnabled: z.boolean().default(false),
|
||||
prescriptionAuthorizedRefills: z.number().int().min(0).nullable().optional(),
|
||||
prescriptionRemainingRefills: z.number().int().min(0).nullable().optional(),
|
||||
prescriptionLowRefillThreshold: z.number().int().min(0).default(1),
|
||||
prescriptionExpiryDate: z.string().nullable().optional(),
|
||||
intakeRemindersEnabled: z.boolean().default(false), // Medication-level (deprecated, kept for backward compat)
|
||||
// Accept either new intakes format or legacy blisters format
|
||||
intakes: z.array(intakeSchema).min(1).max(12).optional(),
|
||||
blisters: z.array(blisterSchema).min(1).max(12).optional(), // Legacy format
|
||||
})
|
||||
.refine((data) => data.intakes || data.blisters, { message: "Either 'intakes' or 'blisters' must be provided" });
|
||||
.refine((data) => (data.name && data.name.length > 0) || (data.genericName && data.genericName.length > 0), {
|
||||
message: "Either 'name' or 'genericName' must be provided",
|
||||
path: ["name"],
|
||||
})
|
||||
.refine((data) => data.intakes || data.blisters, { message: "Either 'intakes' or 'blisters' must be provided" })
|
||||
.refine(
|
||||
(data) => {
|
||||
const startDate = data.medicationStartDate ?? "";
|
||||
if (!startDate) return true;
|
||||
|
||||
const scheduleStarts = data.intakes?.map((i) => i.start) ?? data.blisters?.map((b) => b.start) ?? [];
|
||||
return scheduleStarts.every((scheduleStart) => scheduleStart.slice(0, 10) >= startDate);
|
||||
},
|
||||
{
|
||||
message: "Medication start date must be on or before all intake dates",
|
||||
path: ["medicationStartDate"],
|
||||
}
|
||||
)
|
||||
.refine(
|
||||
(data) => {
|
||||
if (!data.prescriptionEnabled) return true;
|
||||
if (data.prescriptionAuthorizedRefills == null || data.prescriptionRemainingRefills == null) return false;
|
||||
return data.prescriptionRemainingRefills <= data.prescriptionAuthorizedRefills;
|
||||
},
|
||||
{
|
||||
message: "When prescription is enabled, remaining refills must be <= authorized refills",
|
||||
path: ["prescriptionRemainingRefills"],
|
||||
}
|
||||
)
|
||||
.refine(
|
||||
(data) => {
|
||||
if (!data.prescriptionEnabled) return true;
|
||||
if (data.prescriptionAuthorizedRefills == null) return false;
|
||||
return data.prescriptionLowRefillThreshold <= data.prescriptionAuthorizedRefills;
|
||||
},
|
||||
{
|
||||
message: "When prescription is enabled, low refill threshold must be <= authorized refills",
|
||||
path: ["prescriptionLowRefillThreshold"],
|
||||
}
|
||||
);
|
||||
|
||||
export async function medicationRoutes(app: FastifyInstance) {
|
||||
// All medication routes require auth
|
||||
@@ -76,9 +128,13 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
return authUser.id;
|
||||
}
|
||||
|
||||
app.get("/medications", async (request, reply) => {
|
||||
app.get<{ Querystring: { includeObsolete?: string } }>("/medications", async (request, reply) => {
|
||||
const userId = await getUserId(request, reply);
|
||||
const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id);
|
||||
const includeObsolete = request.query.includeObsolete === "true";
|
||||
const whereClause = includeObsolete
|
||||
? eq(medications.userId, userId)
|
||||
: and(eq(medications.userId, userId), eq(medications.isObsolete, false));
|
||||
const rows = await db.select().from(medications).where(whereClause).orderBy(medications.id);
|
||||
return rows.map((row) => {
|
||||
// Parse intakes from new format, falling back to legacy
|
||||
const intakes = parseIntakesJson(
|
||||
@@ -102,6 +158,7 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
lastStockCorrectionAt: row.lastStockCorrectionAt?.toISOString() ?? null,
|
||||
pillWeightMg: row.pillWeightMg,
|
||||
doseUnit: row.doseUnit ?? "mg",
|
||||
medicationStartDate: row.medicationStartDate || null,
|
||||
intakes, // New unified format with per-intake takenBy
|
||||
// Legacy blisters format (for backward compat with frontend during transition)
|
||||
blisters: intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start })),
|
||||
@@ -109,6 +166,13 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
expiryDate: row.expiryDate,
|
||||
notes: row.notes,
|
||||
intakeRemindersEnabled: row.intakeRemindersEnabled ?? false,
|
||||
isObsolete: row.isObsolete ?? false,
|
||||
obsoleteAt: row.obsoleteAt?.toISOString() ?? null,
|
||||
prescriptionEnabled: row.prescriptionEnabled ?? false,
|
||||
prescriptionAuthorizedRefills: row.prescriptionAuthorizedRefills ?? null,
|
||||
prescriptionRemainingRefills: row.prescriptionRemainingRefills ?? null,
|
||||
prescriptionLowRefillThreshold: row.prescriptionLowRefillThreshold ?? 1,
|
||||
prescriptionExpiryDate: row.prescriptionExpiryDate ?? null,
|
||||
dismissedUntil: row.dismissedUntil ?? null,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
@@ -132,8 +196,14 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
looseTablets,
|
||||
pillWeightMg,
|
||||
doseUnit,
|
||||
medicationStartDate,
|
||||
expiryDate,
|
||||
notes,
|
||||
prescriptionEnabled,
|
||||
prescriptionAuthorizedRefills,
|
||||
prescriptionRemainingRefills,
|
||||
prescriptionLowRefillThreshold,
|
||||
prescriptionExpiryDate,
|
||||
intakeRemindersEnabled,
|
||||
intakes: inputIntakes,
|
||||
blisters: inputBlisters,
|
||||
@@ -185,8 +255,14 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
looseTablets,
|
||||
pillWeightMg: pillWeightMg || null,
|
||||
doseUnit: doseUnit ?? "mg",
|
||||
medicationStartDate: medicationStartDate ?? "",
|
||||
expiryDate: expiryDate || null,
|
||||
notes: notes || null,
|
||||
prescriptionEnabled: prescriptionEnabled ?? false,
|
||||
prescriptionAuthorizedRefills: prescriptionEnabled ? (prescriptionAuthorizedRefills ?? null) : null,
|
||||
prescriptionRemainingRefills: prescriptionEnabled ? (prescriptionRemainingRefills ?? null) : null,
|
||||
prescriptionLowRefillThreshold: prescriptionLowRefillThreshold ?? 1,
|
||||
prescriptionExpiryDate: prescriptionExpiryDate || null,
|
||||
intakeRemindersEnabled: intakeRemindersEnabled ?? false,
|
||||
intakesJson,
|
||||
usageJson,
|
||||
@@ -210,12 +286,20 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
lastStockCorrectionAt: inserted.lastStockCorrectionAt?.toISOString() ?? null,
|
||||
pillWeightMg: inserted.pillWeightMg,
|
||||
doseUnit: inserted.doseUnit ?? "mg",
|
||||
medicationStartDate: inserted.medicationStartDate || null,
|
||||
intakes,
|
||||
blisters: intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start })),
|
||||
imageUrl: inserted.imageUrl,
|
||||
expiryDate: inserted.expiryDate,
|
||||
notes: inserted.notes,
|
||||
intakeRemindersEnabled: inserted.intakeRemindersEnabled,
|
||||
isObsolete: inserted.isObsolete ?? false,
|
||||
obsoleteAt: inserted.obsoleteAt?.toISOString() ?? null,
|
||||
prescriptionEnabled: inserted.prescriptionEnabled ?? false,
|
||||
prescriptionAuthorizedRefills: inserted.prescriptionAuthorizedRefills ?? null,
|
||||
prescriptionRemainingRefills: inserted.prescriptionRemainingRefills ?? null,
|
||||
prescriptionLowRefillThreshold: inserted.prescriptionLowRefillThreshold ?? 1,
|
||||
prescriptionExpiryDate: inserted.prescriptionExpiryDate ?? null,
|
||||
updatedAt: inserted.updatedAt,
|
||||
};
|
||||
});
|
||||
@@ -247,8 +331,14 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
looseTablets,
|
||||
pillWeightMg,
|
||||
doseUnit,
|
||||
medicationStartDate,
|
||||
expiryDate,
|
||||
notes,
|
||||
prescriptionEnabled,
|
||||
prescriptionAuthorizedRefills,
|
||||
prescriptionRemainingRefills,
|
||||
prescriptionLowRefillThreshold,
|
||||
prescriptionExpiryDate,
|
||||
intakeRemindersEnabled,
|
||||
intakes: inputIntakes,
|
||||
blisters: inputBlisters,
|
||||
@@ -310,8 +400,14 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
looseTablets,
|
||||
pillWeightMg: pillWeightMg || null,
|
||||
doseUnit: doseUnit ?? "mg",
|
||||
medicationStartDate: medicationStartDate ?? "",
|
||||
expiryDate: expiryDate || null,
|
||||
notes: notes || null,
|
||||
prescriptionEnabled: prescriptionEnabled ?? false,
|
||||
prescriptionAuthorizedRefills: prescriptionEnabled ? (prescriptionAuthorizedRefills ?? null) : null,
|
||||
prescriptionRemainingRefills: prescriptionEnabled ? (prescriptionRemainingRefills ?? null) : null,
|
||||
prescriptionLowRefillThreshold: prescriptionLowRefillThreshold ?? 1,
|
||||
prescriptionExpiryDate: prescriptionExpiryDate || null,
|
||||
intakeRemindersEnabled: intakeRemindersEnabled ?? false,
|
||||
intakesJson,
|
||||
usageJson,
|
||||
@@ -459,19 +555,85 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
lastStockCorrectionAt: result[0].lastStockCorrectionAt?.toISOString() ?? null,
|
||||
pillWeightMg: result[0].pillWeightMg,
|
||||
doseUnit: result[0].doseUnit ?? "mg",
|
||||
medicationStartDate: result[0].medicationStartDate || null,
|
||||
intakes,
|
||||
blisters: intakes.map((i) => ({ usage: i.usage, every: i.every, start: i.start })),
|
||||
imageUrl: result[0].imageUrl,
|
||||
expiryDate: result[0].expiryDate,
|
||||
notes: result[0].notes,
|
||||
intakeRemindersEnabled: result[0].intakeRemindersEnabled,
|
||||
isObsolete: result[0].isObsolete ?? false,
|
||||
obsoleteAt: result[0].obsoleteAt?.toISOString() ?? null,
|
||||
prescriptionEnabled: result[0].prescriptionEnabled ?? false,
|
||||
prescriptionAuthorizedRefills: result[0].prescriptionAuthorizedRefills ?? null,
|
||||
prescriptionRemainingRefills: result[0].prescriptionRemainingRefills ?? null,
|
||||
prescriptionLowRefillThreshold: result[0].prescriptionLowRefillThreshold ?? 1,
|
||||
prescriptionExpiryDate: result[0].prescriptionExpiryDate ?? null,
|
||||
updatedAt: result[0].updatedAt,
|
||||
};
|
||||
});
|
||||
|
||||
// Stock correction endpoint - only updates stockAdjustment, preserves looseTablets
|
||||
app.post<{ Params: { id: string } }>("/medications/:id/obsolete", async (req, reply) => {
|
||||
const idNum = Number(req.params.id);
|
||||
if (Number.isNaN(idNum)) return reply.badRequest("Invalid id");
|
||||
|
||||
const userId = await getUserId(req, reply);
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(medications)
|
||||
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
|
||||
if (!existing) return reply.notFound();
|
||||
|
||||
const [updated] = await db
|
||||
.update(medications)
|
||||
.set({
|
||||
isObsolete: true,
|
||||
obsoleteAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
|
||||
.returning();
|
||||
|
||||
return {
|
||||
id: updated.id,
|
||||
isObsolete: updated.isObsolete ?? false,
|
||||
obsoleteAt: updated.obsoleteAt?.toISOString() ?? null,
|
||||
updatedAt: updated.updatedAt,
|
||||
};
|
||||
});
|
||||
|
||||
app.post<{ Params: { id: string } }>("/medications/:id/reactivate", async (req, reply) => {
|
||||
const idNum = Number(req.params.id);
|
||||
if (Number.isNaN(idNum)) return reply.badRequest("Invalid id");
|
||||
|
||||
const userId = await getUserId(req, reply);
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(medications)
|
||||
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
|
||||
if (!existing) return reply.notFound();
|
||||
|
||||
const [updated] = await db
|
||||
.update(medications)
|
||||
.set({
|
||||
isObsolete: false,
|
||||
obsoleteAt: null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
|
||||
.returning();
|
||||
|
||||
return {
|
||||
id: updated.id,
|
||||
isObsolete: updated.isObsolete ?? false,
|
||||
obsoleteAt: updated.obsoleteAt?.toISOString() ?? null,
|
||||
updatedAt: updated.updatedAt,
|
||||
};
|
||||
});
|
||||
|
||||
// Stock correction endpoint - updates stockAdjustment and optionally looseTablets (for blister type)
|
||||
// Also sets lastStockCorrectionAt so consumed doses before this point don't count
|
||||
app.patch<{ Params: { id: string }; Body: { stockAdjustment: number } }>(
|
||||
app.patch<{ Params: { id: string }; Body: { stockAdjustment: number; looseTablets?: number } }>(
|
||||
"/medications/:id/stock-adjustment",
|
||||
async (req, reply) => {
|
||||
const idNum = Number(req.params.id);
|
||||
@@ -486,16 +648,32 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
|
||||
if (!existing) return reply.notFound();
|
||||
|
||||
const { stockAdjustment } = req.body as { stockAdjustment: number };
|
||||
const { stockAdjustment, looseTablets } = req.body as { stockAdjustment: number; looseTablets?: number };
|
||||
if (typeof stockAdjustment !== "number") return reply.badRequest("stockAdjustment must be a number");
|
||||
if (
|
||||
looseTablets !== undefined &&
|
||||
(typeof looseTablets !== "number" || !Number.isInteger(looseTablets) || looseTablets < 0)
|
||||
) {
|
||||
return reply.badRequest("looseTablets must be a non-negative integer");
|
||||
}
|
||||
|
||||
const updateFields: {
|
||||
stockAdjustment: number;
|
||||
lastStockCorrectionAt: Date;
|
||||
updatedAt: Date;
|
||||
looseTablets?: number;
|
||||
} = {
|
||||
stockAdjustment,
|
||||
lastStockCorrectionAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
if (looseTablets !== undefined) {
|
||||
updateFields.looseTablets = looseTablets;
|
||||
}
|
||||
|
||||
const result = await db
|
||||
.update(medications)
|
||||
.set({
|
||||
stockAdjustment,
|
||||
lastStockCorrectionAt: new Date(), // Mark when correction was made
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.set(updateFields)
|
||||
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)))
|
||||
.returning();
|
||||
|
||||
@@ -523,10 +701,7 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
|
||||
if (!existing) return reply.notFound();
|
||||
|
||||
if (existing.imageUrl) {
|
||||
const imagePath = resolve(IMAGES_DIR, existing.imageUrl);
|
||||
if (existsSync(imagePath)) unlinkSync(imagePath);
|
||||
}
|
||||
if (existing.imageUrl) removeImageFiles(IMAGES_DIR, existing.imageUrl);
|
||||
|
||||
const deleted = await db
|
||||
.delete(medications)
|
||||
@@ -549,24 +724,31 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
if (!existing) return reply.notFound();
|
||||
|
||||
const data = await req.file();
|
||||
if (!data) return reply.badRequest("No file uploaded");
|
||||
if (!data) return reply.status(400).send({ error: "No file uploaded", code: "NO_FILE" });
|
||||
|
||||
const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
|
||||
if (!allowedTypes.includes(data.mimetype)) {
|
||||
return reply.badRequest("Invalid file type. Allowed: JPEG, PNG, WebP, GIF");
|
||||
if (!ALLOWED_IMAGE_MIME_TYPES.includes(data.mimetype)) {
|
||||
return reply.status(400).send({ error: "Invalid file type", code: "INVALID_TYPE" });
|
||||
}
|
||||
|
||||
const ext = extname(data.filename) || ".jpg";
|
||||
const filename = `med-${idNum}-${Date.now()}${ext}`;
|
||||
const filepath = resolve(IMAGES_DIR, filename);
|
||||
let uploadBuffer: Buffer;
|
||||
try {
|
||||
uploadBuffer = await streamToBuffer(data.file);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "IMAGE_TOO_LARGE") {
|
||||
return reply.status(400).send({ error: "Image too large", code: "IMAGE_TOO_LARGE" });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await pipeline(data.file, createWriteStream(filepath));
|
||||
let filename: string;
|
||||
try {
|
||||
({ filename } = await writeOptimizedImageSet(IMAGES_DIR, `med-${idNum}`, uploadBuffer));
|
||||
} catch {
|
||||
return reply.status(400).send({ error: "Invalid image", code: "INVALID_IMAGE" });
|
||||
}
|
||||
|
||||
// Delete old image if exists
|
||||
if (existing.imageUrl) {
|
||||
const oldPath = resolve(IMAGES_DIR, existing.imageUrl);
|
||||
if (existsSync(oldPath)) unlinkSync(oldPath);
|
||||
}
|
||||
if (existing.imageUrl) removeImageFiles(IMAGES_DIR, existing.imageUrl);
|
||||
|
||||
await db
|
||||
.update(medications)
|
||||
@@ -588,10 +770,7 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
.where(and(eq(medications.id, idNum), eq(medications.userId, userId)));
|
||||
if (!existing) return reply.notFound();
|
||||
|
||||
if (existing.imageUrl) {
|
||||
const filepath = resolve(IMAGES_DIR, existing.imageUrl);
|
||||
if (existsSync(filepath)) unlinkSync(filepath);
|
||||
}
|
||||
if (existing.imageUrl) removeImageFiles(IMAGES_DIR, existing.imageUrl);
|
||||
|
||||
await db
|
||||
.update(medications)
|
||||
@@ -616,7 +795,17 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
const userId = await getUserId(req, reply);
|
||||
const rows = await db.select().from(medications).where(eq(medications.userId, userId)).orderBy(medications.id);
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(medications)
|
||||
.where(and(eq(medications.userId, userId), eq(medications.isObsolete, false)))
|
||||
.orderBy(medications.id);
|
||||
|
||||
const [settingsRow] = await db
|
||||
.select({ stockCalculationMode: userSettings.stockCalculationMode })
|
||||
.from(userSettings)
|
||||
.where(eq(userSettings.userId, userId));
|
||||
const stockCalculationMode = settingsRow?.stockCalculationMode === "manual" ? "manual" : "automatic";
|
||||
|
||||
// Get all taken doses for this user to calculate actual consumption
|
||||
const takenDoses = await db
|
||||
@@ -624,20 +813,26 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
.from(doseTracking)
|
||||
.where(and(eq(doseTracking.userId, userId), eq(doseTracking.dismissed, false)));
|
||||
|
||||
// Create a map of medication ID to taken dose count
|
||||
const takenDosesMap = new Map<number, { blisterIdx: number; usage: number }[]>();
|
||||
const takenDoseIdsByMed = new Map<number, Set<string>>();
|
||||
const takenDoseTimestamps = new Map<string, number>();
|
||||
takenDoses.forEach((dose) => {
|
||||
const parts = dose.doseId.split("-");
|
||||
if (parts.length >= 3) {
|
||||
const medId = parseInt(parts[0], 10);
|
||||
const blisterIdx = parseInt(parts[1], 10);
|
||||
if (!Number.isNaN(medId) && !Number.isNaN(blisterIdx)) {
|
||||
if (!takenDosesMap.has(medId)) {
|
||||
takenDosesMap.set(medId, []);
|
||||
}
|
||||
takenDosesMap.get(medId)!.push({ blisterIdx, usage: 0 }); // usage filled later
|
||||
}
|
||||
if (parts.length < 3) return;
|
||||
const medId = parseInt(parts[0], 10);
|
||||
if (Number.isNaN(medId)) return;
|
||||
|
||||
if (!takenDoseIdsByMed.has(medId)) {
|
||||
takenDoseIdsByMed.set(medId, new Set());
|
||||
}
|
||||
takenDoseIdsByMed.get(medId)!.add(dose.doseId);
|
||||
const rawTakenAt = Number(dose.takenAt);
|
||||
let takenAtMs: number;
|
||||
if (Number.isFinite(rawTakenAt)) {
|
||||
takenAtMs = rawTakenAt < 1_000_000_000_000 ? rawTakenAt * 1000 : rawTakenAt;
|
||||
} else {
|
||||
takenAtMs = new Date(dose.takenAt).getTime();
|
||||
}
|
||||
takenDoseTimestamps.set(dose.doseId, takenAtMs);
|
||||
});
|
||||
|
||||
// Use current time as the reference point for "available" stock
|
||||
@@ -664,69 +859,109 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
? looseTablets + stockAdjustment
|
||||
: packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
|
||||
|
||||
// Calculate consumption based on ACTUAL taken doses from dose_tracking
|
||||
// This ensures Planner shows the same "current stock" as the Dashboard/Modal
|
||||
// Use the same logic as frontend: generate expected doses and check which are marked
|
||||
// Calculate consumption with the same automatic/manual behavior as frontend coverage.
|
||||
const stockCorrectionCutoff = row.lastStockCorrectionAt ? new Date(row.lastStockCorrectionAt).getTime() : 0;
|
||||
|
||||
// Build a Set of taken dose IDs for quick lookup
|
||||
const takenDoseIds = new Set(
|
||||
takenDoses
|
||||
.filter((dose) => {
|
||||
const parts = dose.doseId.split("-");
|
||||
return parts.length >= 3 && parseInt(parts[0], 10) === row.id;
|
||||
})
|
||||
.map((dose) => dose.doseId)
|
||||
);
|
||||
const takenDoseIds = takenDoseIdsByMed.get(row.id) ?? new Set<string>();
|
||||
|
||||
// Count consumed pills by generating expected doses and checking if they're taken
|
||||
let consumedUntilNow = 0;
|
||||
const msPerDay = 86400000;
|
||||
|
||||
blisters.forEach((blister, blisterIdx) => {
|
||||
const blisterStart = parseLocalDateTime(blister.start);
|
||||
if (Number.isNaN(blisterStart.getTime())) return;
|
||||
if (stockCalculationMode === "automatic") {
|
||||
blisters.forEach((blister, blisterIdx) => {
|
||||
const blisterStart = parseLocalDateTime(blister.start).getTime();
|
||||
if (Number.isNaN(blisterStart)) return;
|
||||
|
||||
const period = Math.max(1, blister.every) * msPerDay;
|
||||
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;
|
||||
let effectiveStart: number;
|
||||
if (stockCorrectionCutoff > 0 && stockCorrectionCutoff >= blisterStart) {
|
||||
const elapsedSinceStart = stockCorrectionCutoff - blisterStart;
|
||||
const periodsElapsed = Math.floor(elapsedSinceStart / period);
|
||||
effectiveStart = blisterStart + (periodsElapsed + 1) * period;
|
||||
} else {
|
||||
effectiveStart = blisterStart;
|
||||
}
|
||||
|
||||
const occurrences = Math.floor((now.getTime() - effectiveStart) / period) + 1;
|
||||
const intake = intakes[blisterIdx];
|
||||
const intakePerson = intake?.takenBy;
|
||||
const fallbackPeople = parseTakenByJson(row.takenByJson);
|
||||
let peopleForThisIntake: Array<string | null>;
|
||||
if (intakePerson) {
|
||||
peopleForThisIntake = [intakePerson];
|
||||
} else if (fallbackPeople.length > 0) {
|
||||
peopleForThisIntake = fallbackPeople;
|
||||
} else {
|
||||
peopleForThisIntake = [null];
|
||||
}
|
||||
|
||||
// Get the people for this intake (from intakes array or medication takenBy)
|
||||
const takenByJson = row.takenByJson ? JSON.parse(row.takenByJson) : [];
|
||||
const intake = intakes[blisterIdx];
|
||||
const intakePerson = intake?.takenBy;
|
||||
const peopleForThisIntake: (string | null)[] = intakePerson
|
||||
? [intakePerson]
|
||||
: takenByJson.length > 0
|
||||
? takenByJson
|
||||
: [null];
|
||||
let timeBasedConsumed = 0;
|
||||
let lastAutoConsumedDateMs = 0;
|
||||
|
||||
// Generate expected dose IDs and check if they're taken
|
||||
for (let i = 0; i < occurrences; i++) {
|
||||
const doseDate = new Date(effectiveStart + i * period);
|
||||
const dateOnlyMs = new Date(doseDate.getFullYear(), doseDate.getMonth(), doseDate.getDate()).getTime();
|
||||
const baseDoseId = `${row.id}-${blisterIdx}-${dateOnlyMs}`;
|
||||
if (effectiveStart <= now.getTime()) {
|
||||
const occurrences = Math.floor((now.getTime() - effectiveStart) / period) + 1;
|
||||
timeBasedConsumed = occurrences * blister.usage * peopleForThisIntake.length;
|
||||
|
||||
// Check if each person has taken this dose
|
||||
for (const person of peopleForThisIntake) {
|
||||
const doseId = person ? `${baseDoseId}-${person}` : baseDoseId;
|
||||
if (takenDoseIds.has(doseId)) {
|
||||
const lastDoseTime = new Date(effectiveStart + (occurrences - 1) * period);
|
||||
lastAutoConsumedDateMs = new Date(
|
||||
lastDoseTime.getFullYear(),
|
||||
lastDoseTime.getMonth(),
|
||||
lastDoseTime.getDate()
|
||||
).getTime();
|
||||
}
|
||||
|
||||
const stockCorrectionDateOnly =
|
||||
stockCorrectionCutoff > 0
|
||||
? new Date(
|
||||
new Date(stockCorrectionCutoff).getFullYear(),
|
||||
new Date(stockCorrectionCutoff).getMonth(),
|
||||
new Date(stockCorrectionCutoff).getDate()
|
||||
).getTime()
|
||||
: 0;
|
||||
const earlyCutoff = Math.max(lastAutoConsumedDateMs, stockCorrectionDateOnly);
|
||||
|
||||
let earlyTakenConsumed = 0;
|
||||
for (const doseId of takenDoseIds) {
|
||||
const parts = doseId.split("-");
|
||||
if (parts.length < 3) continue;
|
||||
const bIdx = parseInt(parts[1], 10);
|
||||
const timestamp = parseInt(parts[2], 10);
|
||||
if (!Number.isNaN(bIdx) && !Number.isNaN(timestamp) && bIdx === blisterIdx && timestamp > earlyCutoff) {
|
||||
earlyTakenConsumed += blister.usage;
|
||||
}
|
||||
}
|
||||
|
||||
consumedUntilNow += timeBasedConsumed + earlyTakenConsumed;
|
||||
});
|
||||
} else {
|
||||
blisters.forEach((blister, blisterIdx) => {
|
||||
const blisterStart = parseLocalDateTime(blister.start);
|
||||
const blisterStartDateOnly = new Date(
|
||||
blisterStart.getFullYear(),
|
||||
blisterStart.getMonth(),
|
||||
blisterStart.getDate()
|
||||
).getTime();
|
||||
if (Number.isNaN(blisterStartDateOnly)) return;
|
||||
|
||||
for (const doseId of takenDoseIds) {
|
||||
const parts = doseId.split("-");
|
||||
if (parts.length < 3) continue;
|
||||
|
||||
const parsedBlisterIdx = parseInt(parts[1], 10);
|
||||
const doseTimestamp = parseInt(parts[2], 10);
|
||||
if (Number.isNaN(parsedBlisterIdx) || Number.isNaN(doseTimestamp) || parsedBlisterIdx !== blisterIdx) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const takenAt = takenDoseTimestamps.get(doseId) ?? 0;
|
||||
const afterCorrectionOrNoCorrection = stockCorrectionCutoff === 0 || takenAt > stockCorrectionCutoff;
|
||||
|
||||
if (doseTimestamp >= blisterStartDateOnly && afterCorrectionOrNoCorrection) {
|
||||
consumedUntilNow += blister.usage;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const currentStock = Math.max(0, originalTotalPills - consumedUntilNow);
|
||||
|
||||
@@ -772,6 +1007,7 @@ export async function medicationRoutes(app: FastifyInstance) {
|
||||
medicationId: row.id,
|
||||
medicationName: row.name,
|
||||
totalPills: currentStock,
|
||||
currentPills: currentStock,
|
||||
plannerUsage: usageTotal,
|
||||
blisterSize: pillsPerBlister,
|
||||
blistersNeeded,
|
||||
|
||||
+29
-23
@@ -1,5 +1,5 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply } from "fastify";
|
||||
import * as client from "openid-client";
|
||||
import { db } from "../db/client.js";
|
||||
@@ -63,7 +63,7 @@ export async function oidcRoutes(app: FastifyInstance) {
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /auth/oidc/login - Initiates OIDC flow
|
||||
// ---------------------------------------------------------------------------
|
||||
app.get("/auth/oidc/login", async (_request, reply) => {
|
||||
app.get("/auth/oidc/login", async (request, reply) => {
|
||||
try {
|
||||
const config = await getOIDCConfig();
|
||||
|
||||
@@ -104,8 +104,8 @@ export async function oidcRoutes(app: FastifyInstance) {
|
||||
});
|
||||
|
||||
return reply.redirect(authUrl.href);
|
||||
} catch (err: any) {
|
||||
console.error("[OIDC] Login error:", err);
|
||||
} catch (err: unknown) {
|
||||
request.log.error({ err }, "[OIDC] Login initialization failed");
|
||||
return reply.redirect(`${getFrontendUrl()}/?error=oidc_init_failed`);
|
||||
}
|
||||
});
|
||||
@@ -120,7 +120,7 @@ export async function oidcRoutes(app: FastifyInstance) {
|
||||
|
||||
// Handle OIDC provider errors
|
||||
if (error) {
|
||||
console.error(`[OIDC] Provider error: ${error} - ${error_description}`);
|
||||
app.log.warn({ error, errorDescription: error_description }, "[OIDC] Provider returned error");
|
||||
return reply.redirect(`${getFrontendUrl()}/?error=oidc_${error}`);
|
||||
}
|
||||
|
||||
@@ -131,35 +131,35 @@ export async function oidcRoutes(app: FastifyInstance) {
|
||||
// Verify state
|
||||
const storedState = request.unsignCookie(request.cookies.oidc_state || "");
|
||||
if (!storedState.valid || storedState.value !== state) {
|
||||
console.error("[OIDC] State mismatch");
|
||||
request.log.warn("[OIDC] State mismatch during callback validation");
|
||||
return reply.redirect(`${getFrontendUrl()}/?error=oidc_state_mismatch`);
|
||||
}
|
||||
|
||||
// Get code verifier
|
||||
const storedVerifier = request.unsignCookie(request.cookies.oidc_code_verifier || "");
|
||||
if (!storedVerifier.valid || !storedVerifier.value) {
|
||||
console.error("[OIDC] Missing code verifier");
|
||||
request.log.warn("[OIDC] Missing/invalid code verifier cookie");
|
||||
return reply.redirect(`${getFrontendUrl()}/?error=oidc_missing_verifier`);
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await getOIDCConfig();
|
||||
const _redirectUri = env.OIDC_REDIRECT_URI!;
|
||||
const redirectUri = env.OIDC_REDIRECT_URI!;
|
||||
|
||||
// Exchange code for tokens
|
||||
const tokens = await client.authorizationCodeGrant(
|
||||
config,
|
||||
new URL(request.url, `http://${request.headers.host}`),
|
||||
{
|
||||
pkceCodeVerifier: storedVerifier.value,
|
||||
expectedState: state,
|
||||
}
|
||||
);
|
||||
// Build complete callback URL with query parameters for validation
|
||||
const callbackUrl = new URL(redirectUri);
|
||||
callbackUrl.search = new URLSearchParams(request.query as Record<string, string>).toString();
|
||||
|
||||
const tokens = await client.authorizationCodeGrant(config, callbackUrl, {
|
||||
pkceCodeVerifier: storedVerifier.value,
|
||||
expectedState: state,
|
||||
});
|
||||
|
||||
// Get user info
|
||||
const sub = tokens.claims()?.sub;
|
||||
if (!sub) {
|
||||
console.error("[OIDC] Missing sub claim in token");
|
||||
request.log.error("[OIDC] Missing sub claim in token response");
|
||||
return reply.redirect(`${getFrontendUrl()}/?error=oidc_missing_sub`);
|
||||
}
|
||||
const userInfo = await client.fetchUserInfo(config, tokens.access_token, sub);
|
||||
@@ -167,11 +167,17 @@ export async function oidcRoutes(app: FastifyInstance) {
|
||||
// Extract username from configured claim
|
||||
const usernameClaim = env.OIDC_USERNAME_CLAIM;
|
||||
const username =
|
||||
(userInfo as any)[usernameClaim] || userInfo.preferred_username || userInfo.email || userInfo.sub;
|
||||
(userInfo as Record<string, string>)[usernameClaim] ||
|
||||
userInfo.preferred_username ||
|
||||
userInfo.email ||
|
||||
userInfo.sub;
|
||||
const oidcSubject = userInfo.sub;
|
||||
|
||||
if (!username || !oidcSubject) {
|
||||
console.error("[OIDC] Missing required user info:", { username, oidcSubject });
|
||||
request.log.error(
|
||||
{ hasUsername: Boolean(username), hasOidcSubject: Boolean(oidcSubject) },
|
||||
"[OIDC] Missing required user info"
|
||||
);
|
||||
return reply.redirect(`${getFrontendUrl()}/?error=oidc_missing_user_info`);
|
||||
}
|
||||
|
||||
@@ -210,8 +216,8 @@ export async function oidcRoutes(app: FastifyInstance) {
|
||||
// In dev: CORS_ORIGINS contains the frontend URL
|
||||
const frontendUrl = env.CORS_ORIGINS.split(",")[0] || "http://localhost:5173";
|
||||
return reply.redirect(`${frontendUrl}/dashboard`);
|
||||
} catch (err: any) {
|
||||
console.error("[OIDC] Callback error:", err);
|
||||
} catch (err: unknown) {
|
||||
request.log.error({ err }, "[OIDC] Callback processing failed");
|
||||
return reply.redirect(`${getFrontendUrl()}/?error=oidc_callback_failed`);
|
||||
}
|
||||
}
|
||||
@@ -234,7 +240,7 @@ async function findOrCreateOIDCUser(
|
||||
}
|
||||
|
||||
// Check if username already exists (potential collision)
|
||||
const [existingByUsername] = await db.select().from(users).where(eq(users.username, username));
|
||||
const [existingByUsername] = await db.select().from(users).where(sql`lower(${users.username}) = lower(${username})`);
|
||||
|
||||
if (existingByUsername) {
|
||||
// Username collision! Check if it's a local user without OIDC linked
|
||||
@@ -252,7 +258,7 @@ async function findOrCreateOIDCUser(
|
||||
|
||||
// Check if auto-create is enabled
|
||||
if (!env.OIDC_AUTO_CREATE_USERS) {
|
||||
console.error(`[OIDC] User creation disabled and user not found: ${username}`);
|
||||
// No logger is available in this helper, route-level logs already capture callback failures.
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+306
-20
@@ -1,5 +1,8 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyRequest } from "fastify";
|
||||
import nodemailer from "nodemailer";
|
||||
import { db } from "../db/client.js";
|
||||
import { medications } from "../db/schema.js";
|
||||
import {
|
||||
getDateLocale,
|
||||
getFooterHtml,
|
||||
@@ -61,6 +64,19 @@ type ReminderEmailBody = {
|
||||
language?: Language; // Optional: passed from frontend for unauthenticated requests
|
||||
};
|
||||
|
||||
type PrescriptionReminderItem = {
|
||||
name: string;
|
||||
remainingRefills: number;
|
||||
threshold: number;
|
||||
expiryDate?: string | null;
|
||||
};
|
||||
|
||||
type PrescriptionReminderBody = {
|
||||
email: string;
|
||||
prescriptionLow: PrescriptionReminderItem[];
|
||||
language?: Language;
|
||||
};
|
||||
|
||||
export async function plannerRoutes(app: FastifyInstance) {
|
||||
// Add auth hook for all planner routes
|
||||
app.addHook("preHandler", requireAuth);
|
||||
@@ -87,6 +103,16 @@ export async function plannerRoutes(app: FastifyInstance) {
|
||||
|
||||
// Load user settings for notification channels
|
||||
const userId = await getUserId(request);
|
||||
const activeMeds = await db
|
||||
.select({ id: medications.id })
|
||||
.from(medications)
|
||||
.where(and(eq(medications.userId, userId), eq(medications.isObsolete, false)));
|
||||
const activeMedIds = new Set(activeMeds.map((med) => med.id));
|
||||
const activeRows = rows.filter((row) => activeMedIds.has(row.medicationId));
|
||||
if (activeRows.length === 0) {
|
||||
return reply.status(400).send({ error: "No active medications to notify" });
|
||||
}
|
||||
|
||||
const userSettings = await loadUserSettings(userId);
|
||||
const notificationSettings = {
|
||||
emailEnabled: userSettings.emailEnabled,
|
||||
@@ -116,26 +142,45 @@ export async function plannerRoutes(app: FastifyInstance) {
|
||||
})
|
||||
);
|
||||
|
||||
const outOfStockCount = rows.filter((r) => !r.enough).length;
|
||||
const outOfStockCount = activeRows.filter((r) => !r.enough).length;
|
||||
const summaryText = outOfStockCount > 0 ? t(dc.summaryOutOfStock, { count: outOfStockCount }) : dc.summaryAllOk;
|
||||
|
||||
// Load prescription data for medications referenced in planner rows
|
||||
const medIds = activeRows.map((r) => r.medicationId).filter(Boolean);
|
||||
const allMeds =
|
||||
medIds.length > 0
|
||||
? await db
|
||||
.select({
|
||||
id: medications.id,
|
||||
prescriptionEnabled: medications.prescriptionEnabled,
|
||||
prescriptionRemainingRefills: medications.prescriptionRemainingRefills,
|
||||
})
|
||||
.from(medications)
|
||||
.where(eq(medications.userId, userId))
|
||||
: [];
|
||||
const prescriptionMap = new Map(allMeds.map((m) => [m.id, m]));
|
||||
|
||||
// Build plain text (shared between email and push)
|
||||
const plainText = `${dc.title}
|
||||
${t(dc.description, { from: fromDate, until: untilDate })}
|
||||
|
||||
${summaryText}
|
||||
|
||||
${rows
|
||||
${activeRows
|
||||
.map((r) => {
|
||||
const isBottle = r.packageType === "bottle";
|
||||
const usage = `${r.plannerUsage} ${tr.common.pills}`;
|
||||
const needed = isBottle ? "–" : `${r.blistersNeeded} × ${r.blisterSize}`;
|
||||
const medPrescription = prescriptionMap.get(r.medicationId);
|
||||
const rxRefills = medPrescription?.prescriptionEnabled
|
||||
? String(medPrescription.prescriptionRemainingRefills ?? 0)
|
||||
: dc.prescriptionNotApplicable;
|
||||
const loosePills = Math.round((Number(r.loosePills) || 0) * 10) / 10;
|
||||
const available = isBottle
|
||||
? `${loosePills} ${tr.common.pills}`
|
||||
: `${r.fullBlisters} ${tr.common.blisters}${loosePills > 0 ? ` + ${loosePills} ${tr.common.pills}` : ""}`;
|
||||
const status = r.enough ? dc.statusEnough : dc.statusEmpty;
|
||||
return `${r.medicationName}: ${usage}, ${needed}, ${available} - ${status}`;
|
||||
return `${r.medicationName}: ${usage}, ${needed}, ${dc.tableHeaders.prescriptionRefills}: ${rxRefills}, ${available} - ${status}`;
|
||||
})
|
||||
.join("\n")}
|
||||
|
||||
@@ -156,7 +201,7 @@ ${getFooterPlain(language)}`;
|
||||
if (smtpHost && smtpUser) {
|
||||
// Build HTML table with horizontal scroll for mobile
|
||||
// Escape/coerce all user-provided values to prevent XSS
|
||||
const tableRows = rows
|
||||
const tableRows = activeRows
|
||||
.map((row) => {
|
||||
const safeName = escapeHtml(row.medicationName);
|
||||
const safePlannerUsage = Number(row.plannerUsage) || 0;
|
||||
@@ -169,6 +214,12 @@ ${getFooterPlain(language)}`;
|
||||
// "Blisters needed" column: dash for bottles
|
||||
const neededCell = isBottle ? "–" : `${safeBlistersNeeded} × ${safeBlisterSize}`;
|
||||
|
||||
// "Prescription refills" column
|
||||
const medPrescription = prescriptionMap.get(row.medicationId);
|
||||
const rxCell = medPrescription?.prescriptionEnabled
|
||||
? String(medPrescription.prescriptionRemainingRefills ?? 0)
|
||||
: dc.prescriptionNotApplicable;
|
||||
|
||||
// "Available" column: match frontend format
|
||||
let availableCell: string;
|
||||
if (isBottle) {
|
||||
@@ -180,11 +231,14 @@ ${getFooterPlain(language)}`;
|
||||
}
|
||||
}
|
||||
|
||||
const rowBg = row.enough ? "" : " background: #fef2f2;";
|
||||
|
||||
return `
|
||||
<tr>
|
||||
<tr style="${rowBg}">
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; white-space: nowrap;">${safeName}</td>
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;"><strong>${safePlannerUsage}</strong> ${tr.common.pills}</td>
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${neededCell}</td>
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${rxCell}</td>
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${availableCell}</td>
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">
|
||||
<span style="display: inline-block; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600; ${
|
||||
@@ -221,6 +275,7 @@ ${getFooterPlain(language)}`;
|
||||
<th style="padding: 10px 12px; text-align: left; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.medication}</th>
|
||||
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.usage}</th>
|
||||
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.needed}</th>
|
||||
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.prescriptionRefills}</th>
|
||||
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.available}</th>
|
||||
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; white-space: nowrap;">${dc.tableHeaders.status}</th>
|
||||
</tr>
|
||||
@@ -267,7 +322,7 @@ ${getFooterPlain(language)}`;
|
||||
// Send push notification if enabled
|
||||
if (notificationSettings.shoutrrrEnabled && notificationSettings.shoutrrrUrl) {
|
||||
const pushTitle = t(dc.subject, { from: fromDate, until: untilDate });
|
||||
const pushMessage = `${summaryText}\n\n${rows
|
||||
const pushMessage = `${summaryText}\n\n${activeRows
|
||||
.map((r) => {
|
||||
const usage = `${r.plannerUsage} ${tr.common.pills}`;
|
||||
const status = r.enough ? dc.statusEnough : dc.statusEmpty;
|
||||
@@ -315,6 +370,16 @@ ${getFooterPlain(language)}`;
|
||||
|
||||
// Load user settings
|
||||
const userId = await getUserId(request);
|
||||
const activeMeds = await db
|
||||
.select({ name: medications.name, genericName: medications.genericName })
|
||||
.from(medications)
|
||||
.where(and(eq(medications.userId, userId), eq(medications.isObsolete, false)));
|
||||
const activeMedNames = new Set(activeMeds.map((med) => med.name || med.genericName || ""));
|
||||
const filteredLowStock = lowStock.filter((item) => activeMedNames.has(item.name));
|
||||
if (filteredLowStock.length === 0) {
|
||||
return reply.status(400).send({ error: "No active medications to notify" });
|
||||
}
|
||||
|
||||
const userSettings = await loadUserSettings(userId);
|
||||
const notificationSettings = {
|
||||
emailEnabled: userSettings.emailEnabled,
|
||||
@@ -329,9 +394,9 @@ ${getFooterPlain(language)}`;
|
||||
const results: { email?: boolean; push?: boolean; errors: string[] } = { errors: [] };
|
||||
|
||||
// Separate into 3 categories: empty, critical, and low stock
|
||||
const emptyMeds = lowStock.filter((r) => r.medsLeft <= 0);
|
||||
const criticalMeds = lowStock.filter((r) => r.medsLeft > 0 && r.isCritical !== false);
|
||||
const lowStockMeds = lowStock.filter((r) => r.medsLeft > 0 && r.isCritical === false);
|
||||
const emptyMeds = filteredLowStock.filter((r) => r.medsLeft <= 0);
|
||||
const criticalMeds = filteredLowStock.filter((r) => r.medsLeft > 0 && r.isCritical !== false);
|
||||
const lowStockMeds = filteredLowStock.filter((r) => r.medsLeft > 0 && r.isCritical === false);
|
||||
|
||||
// Build shared notification content (method-agnostic)
|
||||
const titleParts: string[] = [];
|
||||
@@ -344,7 +409,7 @@ ${getFooterPlain(language)}`;
|
||||
if (lowStockMeds.length > 0) {
|
||||
titleParts.push(`⚠️ ${lowStockMeds.length} ${tr.push.lowStock}`);
|
||||
}
|
||||
const notificationTitle = `MedAssist: ${titleParts.join(", ")} - ${tr.push.reorderNow}`;
|
||||
const notificationTitle = `MedAssist-ng: ${titleParts.join(", ")} - ${tr.push.reorderNow}`;
|
||||
|
||||
// Build description text
|
||||
let descriptionText: string;
|
||||
@@ -444,8 +509,10 @@ ${getFooterPlain(language)}`;
|
||||
const buildTableRow = (row: LowStockItem) => {
|
||||
const isEmpty = row.medsLeft <= 0;
|
||||
const isCritical = row.isCritical !== false;
|
||||
const statusIcon = isEmpty ? "🚨" : isCritical ? "🚨" : "⚠️";
|
||||
const rowBg = isEmpty ? "#fef2f2" : isCritical ? "#fff7ed" : "white";
|
||||
const nonEmptyIcon = isCritical ? "🚨" : "⚠️";
|
||||
const statusIcon = isEmpty ? "🚨" : nonEmptyIcon;
|
||||
const nonEmptyBg = isCritical ? "#fff7ed" : "white";
|
||||
const rowBg = isEmpty ? "#fef2f2" : nonEmptyBg;
|
||||
const safeName = escapeHtml(row.name);
|
||||
const safeMedsLeft = Number(row.medsLeft) || 0;
|
||||
const safeDaysLeft = Number(row.daysLeft) || 0;
|
||||
@@ -459,7 +526,7 @@ ${getFooterPlain(language)}`;
|
||||
</tr>`;
|
||||
};
|
||||
|
||||
const tableRows = lowStock.map(buildTableRow).join("");
|
||||
const tableRows = filteredLowStock.map(buildTableRow).join("");
|
||||
|
||||
const html = `
|
||||
<div style="font-family: system-ui, -apple-system, sans-serif; max-width: 100%; margin: 0 auto; padding: 12px; background: #f9fafb;">
|
||||
@@ -485,8 +552,7 @@ ${getFooterPlain(language)}`;
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
|
||||
<p style="color: #9ca3af; font-size: 11px; margin: 0;">${getFooterHtml(language)}</p>
|
||||
<p style="color: #9ca3af; font-size: 11px; margin: 16px 0 0 0;">${getFooterHtml(language)}</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -507,7 +573,7 @@ ${getFooterPlain(language)}`;
|
||||
await transporter.sendMail({
|
||||
from: smtpFrom,
|
||||
to: email,
|
||||
subject: `MedAssist-ng - ${subjectText}`,
|
||||
subject: `MedAssist-ng: ${subjectText}`,
|
||||
text: plainText,
|
||||
html,
|
||||
});
|
||||
@@ -522,7 +588,7 @@ ${getFooterPlain(language)}`;
|
||||
|
||||
// Send push notification if enabled
|
||||
if (notificationSettings.shoutrrrEnabled && notificationSettings.shoutrrrUrl) {
|
||||
const message = messageParts.join("\n") + `\n\n---\n${getFooterPlain(language)}`;
|
||||
const message = `${messageParts.join("\n")}\n\n---\n${getFooterPlain(language)}`;
|
||||
|
||||
try {
|
||||
const pushResult = await sendShoutrrrNotification(notificationSettings.shoutrrrUrl, notificationTitle, message);
|
||||
@@ -539,12 +605,12 @@ ${getFooterPlain(language)}`;
|
||||
|
||||
// Update the reminder state to record this notification was sent
|
||||
if (results.email || results.push) {
|
||||
const channel = results.email && results.push ? "both" : results.email ? "email" : "push";
|
||||
const singleChannel = results.email ? "email" : "push";
|
||||
const channel = results.email && results.push ? "both" : singleChannel;
|
||||
updateReminderSentTime("stock", channel);
|
||||
|
||||
// Also update user settings in database so frontend can display the info
|
||||
const firstMed = lowStock[0];
|
||||
const medNames = lowStock.length > 1 ? `${firstMed.name} (+${lowStock.length - 1})` : firstMed?.name;
|
||||
const medNames = filteredLowStock.map((m: { name: string }) => m.name).join(", ");
|
||||
await updateUserReminderSentTime(userId, "stock", channel, medNames);
|
||||
}
|
||||
|
||||
@@ -564,4 +630,224 @@ ${getFooterPlain(language)}`;
|
||||
return reply.status(400).send({ error: "No notification channels configured" });
|
||||
}
|
||||
});
|
||||
|
||||
// Manual prescription reminder (supports email and push)
|
||||
app.post<{ Body: PrescriptionReminderBody }>("/reminder/send-prescription", async (request, reply) => {
|
||||
const { email, prescriptionLow } = request.body;
|
||||
|
||||
if (!prescriptionLow || prescriptionLow.length === 0) {
|
||||
return reply.status(400).send({ error: "Missing prescription reminder data" });
|
||||
}
|
||||
|
||||
const userId = await getUserId(request);
|
||||
const activeMeds = await db
|
||||
.select({ name: medications.name, genericName: medications.genericName })
|
||||
.from(medications)
|
||||
.where(and(eq(medications.userId, userId), eq(medications.isObsolete, false)));
|
||||
const activeMedNames = new Set(activeMeds.map((med) => med.name || med.genericName || ""));
|
||||
const filteredPrescriptionLow = prescriptionLow.filter((item) => activeMedNames.has(item.name));
|
||||
if (filteredPrescriptionLow.length === 0) {
|
||||
return reply.status(400).send({ error: "No active medications to notify" });
|
||||
}
|
||||
|
||||
const userSettings = await loadUserSettings(userId);
|
||||
const language = (userSettings.language as Language) || "en";
|
||||
const tr = getTranslations(language);
|
||||
|
||||
const emptyRx = filteredPrescriptionLow.filter((item) => item.remainingRefills <= 0);
|
||||
const lowRx = filteredPrescriptionLow.filter((item) => item.remainingRefills > 0);
|
||||
|
||||
const lines = filteredPrescriptionLow.map((item) => {
|
||||
const expirySuffix = item.expiryDate ? t(tr.prescriptionReminder.expiresSuffix, { date: item.expiryDate }) : "";
|
||||
if (item.remainingRefills <= 0) {
|
||||
return `- ${t(tr.prescriptionReminder.lineEmpty, {
|
||||
name: item.name,
|
||||
expirySuffix,
|
||||
})}`;
|
||||
}
|
||||
return `- ${t(tr.prescriptionReminder.line, {
|
||||
name: item.name,
|
||||
refills: item.remainingRefills,
|
||||
expirySuffix,
|
||||
})}`;
|
||||
});
|
||||
|
||||
const medNames = filteredPrescriptionLow.map((m: { name: string }) => m.name).join(", ");
|
||||
|
||||
const results: { email?: boolean; push?: boolean; errors: string[] } = { errors: [] };
|
||||
|
||||
if (userSettings.emailEnabled && userSettings.emailPrescriptionReminders && email) {
|
||||
const smtpHost = process.env.SMTP_HOST;
|
||||
const smtpUser = process.env.SMTP_USER;
|
||||
const smtpPass = process.env.SMTP_TOKEN || process.env.SMTP_PASS;
|
||||
const smtpPort = parseInt(process.env.SMTP_PORT ?? "587", 10);
|
||||
const smtpSecure = process.env.SMTP_SECURE === "true";
|
||||
const smtpFrom = process.env.SMTP_FROM ?? smtpUser;
|
||||
|
||||
if (smtpHost && smtpUser) {
|
||||
try {
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: smtpHost,
|
||||
port: smtpPort,
|
||||
secure: smtpSecure,
|
||||
auth: {
|
||||
user: smtpUser,
|
||||
pass: smtpPass ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
const subject =
|
||||
filteredPrescriptionLow.length === 1
|
||||
? tr.prescriptionReminder.subjectSingle
|
||||
: t(tr.prescriptionReminder.subjectMultiple, { count: filteredPrescriptionLow.length });
|
||||
|
||||
const bodyText =
|
||||
emptyRx.length > 0 ? tr.prescriptionReminder.descriptionEmpty : tr.prescriptionReminder.descriptionLow;
|
||||
const emptyAlert =
|
||||
emptyRx.length === 1
|
||||
? tr.prescriptionReminder.alertEmptySingle
|
||||
: t(tr.prescriptionReminder.alertEmptyMultiple, { count: emptyRx.length });
|
||||
const lowAlert =
|
||||
lowRx.length === 1
|
||||
? tr.prescriptionReminder.alertLowSingle
|
||||
: t(tr.prescriptionReminder.alertLowMultiple, { count: lowRx.length });
|
||||
const alertText = emptyRx.length > 0 ? emptyAlert : lowAlert;
|
||||
|
||||
const tableRows = filteredPrescriptionLow
|
||||
.map((item) => {
|
||||
const isEmpty = item.remainingRefills <= 0;
|
||||
const safeName = escapeHtml(item.name);
|
||||
const safeRefills = Number(item.remainingRefills) || 0;
|
||||
const safeThreshold = Number(item.threshold) || 0;
|
||||
const safeExpiry = item.expiryDate ? escapeHtml(String(item.expiryDate)) : "-";
|
||||
const rowBg = isEmpty ? "#fef2f2" : "white";
|
||||
return `
|
||||
<tr style="background: ${rowBg};">
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; white-space: nowrap;">${isEmpty ? "🚨" : "⚠️"} ${safeName}</td>
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap; ${isEmpty ? "color: #dc2626; font-weight: 600;" : ""}"><strong>${safeRefills}</strong></td>
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${safeThreshold}</td>
|
||||
<td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; text-align: center; white-space: nowrap;">${safeExpiry}</td>
|
||||
</tr>`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
const emailTitle = emptyRx.length > 0 ? tr.prescriptionReminder.titleEmpty : tr.prescriptionReminder.title;
|
||||
const text = `${emailTitle}\n\n${bodyText}\n\n${lines.join("\n")}\n\n---\n${getFooterPlain(language)}`;
|
||||
const html = `
|
||||
<div style="font-family: system-ui, -apple-system, sans-serif; max-width: 100%; margin: 0 auto; padding: 12px; background: #f9fafb;">
|
||||
<div style="background: white; border-radius: 12px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
|
||||
<h2 style="color: #1f2937; margin: 0 0 8px; font-size: 18px;">${emailTitle}</h2>
|
||||
<p style="color: #6b7280; margin: 0 0 16px; font-size: 13px;">${bodyText}</p>
|
||||
|
||||
<div style="padding: 10px 14px; border-radius: 8px; margin-bottom: 16px; ${emptyRx.length > 0 ? "background: #fef2f2; border: 1px solid #dc2626;" : "background: #fffbeb; border: 1px solid #f59e0b;"}">
|
||||
<p style="margin: 0; ${emptyRx.length > 0 ? "color: #dc2626; font-weight: 600;" : "color: #b45309; font-weight: 500;"} font-size: 13px;">
|
||||
${alertText}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div style="overflow-x: auto; -webkit-overflow-scrolling: touch;">
|
||||
<table style="width: 100%; border-collapse: collapse; background: white; min-width: 460px;">
|
||||
<thead>
|
||||
<tr style="background: #f3f4f6;">
|
||||
<th style="padding: 10px 12px; text-align: left; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">${tr.prescriptionReminder.tableHeaders.medication}</th>
|
||||
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">${tr.prescriptionReminder.tableHeaders.refillsLeft}</th>
|
||||
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">${tr.prescriptionReminder.tableHeaders.reminderThreshold}</th>
|
||||
<th style="padding: 10px 12px; text-align: center; font-size: 11px; text-transform: uppercase; color: #6b7280; white-space: nowrap;">${tr.prescriptionReminder.tableHeaders.prescriptionExpires}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${tableRows}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
|
||||
<p style="color: #9ca3af; font-size: 11px; margin: 0;">${getFooterHtml(language)}</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
await transporter.sendMail({
|
||||
from: smtpFrom,
|
||||
to: email,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
});
|
||||
|
||||
results.email = true;
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
||||
results.errors.push(`Email: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (userSettings.shoutrrrEnabled && userSettings.shoutrrrPrescriptionReminders && userSettings.shoutrrrUrl) {
|
||||
const titleParts: string[] = [];
|
||||
if (emptyRx.length > 0)
|
||||
titleParts.push(
|
||||
`🚨 ${emptyRx.length} ${emptyRx.length === 1 ? tr.prescriptionReminder.pushEmptySingle : tr.prescriptionReminder.pushEmpty}`
|
||||
);
|
||||
if (lowRx.length > 0)
|
||||
titleParts.push(
|
||||
`🚨 ${lowRx.length} ${lowRx.length === 1 ? tr.prescriptionReminder.pushLowSingle : tr.prescriptionReminder.pushLow}`
|
||||
);
|
||||
const title = `MedAssist-ng: ${titleParts.join(", ")} - ${tr.prescriptionReminder.pushRenewNow}`;
|
||||
|
||||
const messageParts: string[] = [];
|
||||
if (emptyRx.length > 0) {
|
||||
messageParts.push(`🚨 ${tr.prescriptionReminder.pushEmptySection}:`);
|
||||
for (const m of emptyRx) {
|
||||
messageParts.push(` • ${m.name}`);
|
||||
}
|
||||
}
|
||||
if (lowRx.length > 0) {
|
||||
if (emptyRx.length > 0) messageParts.push("");
|
||||
messageParts.push(`🚨 ${tr.prescriptionReminder.pushLowSection}:`);
|
||||
for (const m of lowRx) {
|
||||
messageParts.push(
|
||||
` • ${m.name}: ${t(tr.prescriptionReminder.pushRefillsLeft, { count: m.remainingRefills })}`
|
||||
);
|
||||
}
|
||||
}
|
||||
const message = `${messageParts.join("\n")}\n\n---\n${getFooterPlain(language)}`;
|
||||
|
||||
try {
|
||||
const pushResult = await sendShoutrrrNotification(userSettings.shoutrrrUrl, title, message);
|
||||
if (pushResult.success) {
|
||||
results.push = true;
|
||||
} else {
|
||||
results.errors.push(`Push: ${pushResult.error}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
||||
results.errors.push(`Push: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (results.email || results.push) {
|
||||
const singleChannel = results.email ? "email" : "push";
|
||||
const channel = results.email && results.push ? "both" : singleChannel;
|
||||
updateReminderSentTime("prescription", channel);
|
||||
await updateUserReminderSentTime(userId, "prescription", channel, medNames);
|
||||
}
|
||||
|
||||
const sentChannels: string[] = [];
|
||||
if (results.email) sentChannels.push("email");
|
||||
if (results.push) sentChannels.push("push");
|
||||
|
||||
if (sentChannels.length > 0) {
|
||||
return reply.send({
|
||||
success: true,
|
||||
message: `Prescription reminder sent via ${sentChannels.join(" and ")}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (results.errors.length > 0) {
|
||||
return reply.status(500).send({ error: results.errors.join("; ") });
|
||||
}
|
||||
|
||||
return reply.status(400).send({ error: "No notification channels configured" });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ const refillSchema = z
|
||||
.object({
|
||||
packsAdded: z.number().int().min(0).default(0),
|
||||
loosePillsAdded: z.number().int().min(0).default(0),
|
||||
usePrescription: z.boolean().default(false),
|
||||
})
|
||||
.refine((data) => data.packsAdded > 0 || data.loosePillsAdded > 0, {
|
||||
message: "Must add at least one pack or some loose pills",
|
||||
@@ -50,19 +51,46 @@ export async function refillRoutes(app: FastifyInstance) {
|
||||
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
|
||||
if (!med) return reply.notFound("Medication not found");
|
||||
|
||||
const { packsAdded, loosePillsAdded } = parsed.data;
|
||||
const { packsAdded, loosePillsAdded, usePrescription } = parsed.data;
|
||||
const isBottle = (med.packageType ?? "blister") === "bottle";
|
||||
const effectivePacksAdded = isBottle ? 0 : packsAdded;
|
||||
const effectiveLoosePillsAdded = loosePillsAdded;
|
||||
const remainingPrescriptionRefills = med.prescriptionRemainingRefills ?? 0;
|
||||
|
||||
if (effectivePacksAdded < 1 && effectiveLoosePillsAdded < 1) {
|
||||
return reply.status(400).send({ error: "Must add at least one pack or some loose pills" });
|
||||
}
|
||||
|
||||
if (usePrescription) {
|
||||
if (!(med.prescriptionEnabled ?? false)) {
|
||||
return reply.status(400).send({ error: "Prescription refill is not enabled for this medication" });
|
||||
}
|
||||
if (remainingPrescriptionRefills <= 0) {
|
||||
return reply.status(409).send({ error: "No remaining prescription refills" });
|
||||
}
|
||||
if (!isBottle && effectivePacksAdded > remainingPrescriptionRefills) {
|
||||
return reply.status(409).send({ error: "Packs to add exceed remaining prescription refills" });
|
||||
}
|
||||
}
|
||||
|
||||
// Update medication stock
|
||||
const newPackCount = med.packCount + packsAdded;
|
||||
const newLooseTablets = med.looseTablets + loosePillsAdded;
|
||||
const newPackCount = med.packCount + effectivePacksAdded;
|
||||
const newLooseTablets = med.looseTablets + effectiveLoosePillsAdded;
|
||||
|
||||
let consumedRefills = 0;
|
||||
if (usePrescription) {
|
||||
consumedRefills = isBottle ? 1 : effectivePacksAdded;
|
||||
}
|
||||
const newRemainingRefills = usePrescription
|
||||
? Math.max(0, remainingPrescriptionRefills - consumedRefills)
|
||||
: (med.prescriptionRemainingRefills ?? null);
|
||||
|
||||
await db
|
||||
.update(medications)
|
||||
.set({
|
||||
packCount: newPackCount,
|
||||
looseTablets: newLooseTablets,
|
||||
stockAdjustment: 0, // Reset offset since we're adding to base stock
|
||||
lastStockCorrectionAt: new Date(), // Reset consumed counter to now
|
||||
prescriptionRemainingRefills: newRemainingRefills,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(and(eq(medications.id, medId), eq(medications.userId, userId)));
|
||||
@@ -73,15 +101,17 @@ export async function refillRoutes(app: FastifyInstance) {
|
||||
.values({
|
||||
medicationId: medId,
|
||||
userId,
|
||||
packsAdded,
|
||||
loosePillsAdded,
|
||||
packsAdded: effectivePacksAdded,
|
||||
loosePillsAdded: effectiveLoosePillsAdded,
|
||||
usedPrescription: usePrescription,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Calculate pills added for response (packageType-aware)
|
||||
const isBottle = (med.packageType ?? "blister") === "bottle";
|
||||
const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
|
||||
const totalPillsAdded = isBottle ? loosePillsAdded : packsAdded * pillsPerPack + loosePillsAdded;
|
||||
const totalPillsAdded = isBottle
|
||||
? effectiveLoosePillsAdded
|
||||
: effectivePacksAdded * pillsPerPack + effectiveLoosePillsAdded;
|
||||
const newTotalPills = isBottle
|
||||
? newLooseTablets + (med.stockAdjustment ?? 0)
|
||||
: newPackCount * pillsPerPack + newLooseTablets + (med.stockAdjustment ?? 0);
|
||||
@@ -90,8 +120,8 @@ export async function refillRoutes(app: FastifyInstance) {
|
||||
success: true,
|
||||
refill: {
|
||||
id: refill.id,
|
||||
packsAdded,
|
||||
loosePillsAdded,
|
||||
packsAdded: effectivePacksAdded,
|
||||
loosePillsAdded: effectiveLoosePillsAdded,
|
||||
totalPillsAdded,
|
||||
refillDate: refill.refillDate,
|
||||
},
|
||||
@@ -100,6 +130,13 @@ export async function refillRoutes(app: FastifyInstance) {
|
||||
looseTablets: newLooseTablets,
|
||||
totalPills: newTotalPills,
|
||||
},
|
||||
prescription: {
|
||||
used: usePrescription,
|
||||
remainingRefills: newRemainingRefills,
|
||||
authorizedRefills: med.prescriptionAuthorizedRefills ?? null,
|
||||
lowRefillThreshold: med.prescriptionLowRefillThreshold ?? 1,
|
||||
enabled: med.prescriptionEnabled ?? false,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -132,6 +169,7 @@ export async function refillRoutes(app: FastifyInstance) {
|
||||
packsAdded: r.packsAdded,
|
||||
loosePillsAdded: r.loosePillsAdded,
|
||||
totalPillsAdded: isBottle ? r.loosePillsAdded : r.packsAdded * pillsPerPack + r.loosePillsAdded,
|
||||
usedPrescription: r.usedPrescription ?? false,
|
||||
refillDate: r.refillDate,
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { doseTracking, medications, refillHistory } from "../db/schema.js";
|
||||
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
|
||||
import { env } from "../plugins/env.js";
|
||||
import type { AuthUser } from "../types/fastify.js";
|
||||
|
||||
const reportDataSchema = z.object({
|
||||
medicationIds: z.array(z.number().int().positive()).min(1).max(100),
|
||||
});
|
||||
|
||||
export async function reportRoutes(app: FastifyInstance) {
|
||||
app.addHook("preHandler", requireAuth);
|
||||
|
||||
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
|
||||
if (!env.AUTH_ENABLED) {
|
||||
return getAnonymousUserId();
|
||||
}
|
||||
const authUser = request.user as unknown as AuthUser | null;
|
||||
if (!authUser) {
|
||||
reply.status(401).send({ error: "User not authenticated", code: "AUTH_REQUIRED" });
|
||||
throw new Error("AUTH_REQUIRED");
|
||||
}
|
||||
return authUser.id;
|
||||
}
|
||||
|
||||
// POST /medications/report-data - Get aggregated dose/refill data for report generation
|
||||
app.post("/medications/report-data", async (req, reply) => {
|
||||
const parsed = reportDataSchema.safeParse(req.body);
|
||||
if (!parsed.success) return reply.status(400).send(parsed.error.format());
|
||||
|
||||
const userId = await getUserId(req, reply);
|
||||
const { medicationIds } = parsed.data;
|
||||
|
||||
// Verify all medications belong to this user
|
||||
const userMeds = await db.select({ id: medications.id }).from(medications).where(eq(medications.userId, userId));
|
||||
const userMedIds = new Set(userMeds.map((m) => m.id));
|
||||
|
||||
for (const id of medicationIds) {
|
||||
if (!userMedIds.has(id)) {
|
||||
return reply.status(403).send({ error: "Access denied to medication" });
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch dose tracking for all requested medications
|
||||
// doseId format: "{medicationId}-{blisterIndex}-{dateMs}" or "{medicationId}-{blisterIndex}-{dateMs}-{takenBy}"
|
||||
const allDoses = await db
|
||||
.select({
|
||||
doseId: doseTracking.doseId,
|
||||
takenAt: doseTracking.takenAt,
|
||||
dismissed: doseTracking.dismissed,
|
||||
takenSource: doseTracking.takenSource,
|
||||
})
|
||||
.from(doseTracking)
|
||||
.where(eq(doseTracking.userId, userId));
|
||||
|
||||
// Group doses by medication ID
|
||||
const dosesByMed = new Map<number, { takenAt: Date; dismissed: boolean; takenSource: string }[]>();
|
||||
for (const dose of allDoses) {
|
||||
const medId = Number.parseInt(dose.doseId.split("-")[0], 10);
|
||||
if (Number.isNaN(medId) || !medicationIds.includes(medId)) continue;
|
||||
if (!dosesByMed.has(medId)) dosesByMed.set(medId, []);
|
||||
dosesByMed.get(medId)!.push({
|
||||
takenAt: dose.takenAt,
|
||||
dismissed: dose.dismissed,
|
||||
takenSource: dose.takenSource ?? "manual",
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch refill history for requested medications
|
||||
const result: Record<
|
||||
number,
|
||||
{
|
||||
dosesTaken: number;
|
||||
automaticDosesTaken: number;
|
||||
dosesDismissed: number;
|
||||
firstDoseAt: string | null;
|
||||
lastDoseAt: string | null;
|
||||
refills: { packsAdded: number; loosePillsAdded: number; usedPrescription: boolean; refillDate: string }[];
|
||||
}
|
||||
> = {};
|
||||
|
||||
for (const medId of medicationIds) {
|
||||
const doses = dosesByMed.get(medId) ?? [];
|
||||
const takenDoses = doses.filter((d) => !d.dismissed);
|
||||
const automaticTakenDoses = takenDoses.filter((d) => d.takenSource === "automatic");
|
||||
const dismissedDoses = doses.filter((d) => d.dismissed);
|
||||
|
||||
const sortedTaken = takenDoses.map((d) => d.takenAt.getTime()).sort((a, b) => a - b);
|
||||
|
||||
// Get refills for this medication
|
||||
const refills = await db.select().from(refillHistory).where(eq(refillHistory.medicationId, medId));
|
||||
|
||||
result[medId] = {
|
||||
dosesTaken: takenDoses.length,
|
||||
automaticDosesTaken: automaticTakenDoses.length,
|
||||
dosesDismissed: dismissedDoses.length,
|
||||
firstDoseAt: sortedTaken.length > 0 ? new Date(sortedTaken[0]).toISOString() : null,
|
||||
lastDoseAt: sortedTaken.length > 0 ? new Date(sortedTaken[sortedTaken.length - 1]).toISOString() : null,
|
||||
refills: refills.map((r) => ({
|
||||
packsAdded: r.packsAdded,
|
||||
loosePillsAdded: r.loosePillsAdded,
|
||||
usedPrescription: r.usedPrescription ?? false,
|
||||
refillDate: r.refillDate instanceof Date ? r.refillDate.toISOString() : String(r.refillDate),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
}
|
||||
+320
-40
@@ -1,5 +1,5 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import nodemailer from "nodemailer";
|
||||
import { db } from "../db/client.js";
|
||||
import { userSettings } from "../db/schema.js";
|
||||
@@ -15,10 +15,12 @@ export type UserSettings = {
|
||||
notificationEmail: string | null;
|
||||
emailStockReminders: boolean;
|
||||
emailIntakeReminders: boolean;
|
||||
emailPrescriptionReminders: boolean;
|
||||
shoutrrrEnabled: boolean;
|
||||
shoutrrrUrl: string | null;
|
||||
shoutrrrStockReminders: boolean;
|
||||
shoutrrrIntakeReminders: boolean;
|
||||
shoutrrrPrescriptionReminders: boolean;
|
||||
reminderDaysBefore: number;
|
||||
repeatDailyReminders: boolean;
|
||||
skipRemindersForTakenDoses: boolean;
|
||||
@@ -31,6 +33,9 @@ export type UserSettings = {
|
||||
language: Language;
|
||||
stockCalculationMode: "automatic" | "manual";
|
||||
shareStockStatus: boolean;
|
||||
upcomingTodayOnly: boolean;
|
||||
shareScheduleTodayOnly: boolean;
|
||||
swapDashboardMainSections: boolean;
|
||||
lastAutoEmailSent: string | null;
|
||||
lastNotificationType: string | null;
|
||||
lastNotificationChannel: string | null;
|
||||
@@ -39,6 +44,9 @@ export type UserSettings = {
|
||||
lastStockReminderSent: string | null;
|
||||
lastStockReminderChannel: string | null;
|
||||
lastStockReminderMedNames: string | null;
|
||||
lastPrescriptionReminderSent: string | null;
|
||||
lastPrescriptionReminderChannel: string | null;
|
||||
lastPrescriptionReminderMedNames: string | null;
|
||||
};
|
||||
|
||||
type SettingsBody = {
|
||||
@@ -53,8 +61,10 @@ type SettingsBody = {
|
||||
shoutrrrUrl: string;
|
||||
emailStockReminders: boolean;
|
||||
emailIntakeReminders: boolean;
|
||||
emailPrescriptionReminders: boolean;
|
||||
shoutrrrStockReminders: boolean;
|
||||
shoutrrrIntakeReminders: boolean;
|
||||
shoutrrrPrescriptionReminders: boolean;
|
||||
skipRemindersForTakenDoses: boolean;
|
||||
repeatRemindersEnabled: boolean;
|
||||
reminderRepeatIntervalMinutes: number;
|
||||
@@ -62,6 +72,9 @@ type SettingsBody = {
|
||||
language: string;
|
||||
stockCalculationMode: "automatic" | "manual";
|
||||
shareStockStatus: boolean;
|
||||
upcomingTodayOnly: boolean;
|
||||
shareScheduleTodayOnly: boolean;
|
||||
swapDashboardMainSections: boolean;
|
||||
};
|
||||
|
||||
type TestEmailBody = {
|
||||
@@ -72,6 +85,21 @@ type TestShoutrrrBody = {
|
||||
url: string;
|
||||
};
|
||||
|
||||
function getNotificationProvider(url: string): string {
|
||||
if (url.startsWith("discord://")) return "discord";
|
||||
if (url.startsWith("telegram://")) return "telegram";
|
||||
if (url.startsWith("gotify://")) return "gotify";
|
||||
if (url.startsWith("pushover://")) return "pushover";
|
||||
if (url.startsWith("ntfy://")) return "ntfy";
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.hostname || "https";
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to parse boolean env vars
|
||||
function envBool(key: string, defaultVal: boolean): boolean {
|
||||
const val = process.env[key];
|
||||
@@ -94,10 +122,12 @@ function getDefaultSettings() {
|
||||
notificationEmail: process.env.DEFAULT_NOTIFICATION_EMAIL || null,
|
||||
emailStockReminders: envBool("DEFAULT_EMAIL_STOCK_REMINDERS", true),
|
||||
emailIntakeReminders: envBool("DEFAULT_EMAIL_INTAKE_REMINDERS", true),
|
||||
emailPrescriptionReminders: envBool("DEFAULT_EMAIL_PRESCRIPTION_REMINDERS", true),
|
||||
shoutrrrEnabled: envBool("DEFAULT_SHOUTRRR_ENABLED", false),
|
||||
shoutrrrUrl: process.env.DEFAULT_SHOUTRRR_URL || null,
|
||||
shoutrrrStockReminders: envBool("DEFAULT_SHOUTRRR_STOCK_REMINDERS", true),
|
||||
shoutrrrIntakeReminders: envBool("DEFAULT_SHOUTRRR_INTAKE_REMINDERS", true),
|
||||
shoutrrrPrescriptionReminders: envBool("DEFAULT_SHOUTRRR_PRESCRIPTION_REMINDERS", true),
|
||||
reminderDaysBefore: envInt("REMINDER_DAYS_BEFORE", 7),
|
||||
repeatDailyReminders: envBool("DEFAULT_REPEAT_DAILY_REMINDERS", false),
|
||||
skipRemindersForTakenDoses: envBool("DEFAULT_SKIP_REMINDERS_FOR_TAKEN_DOSES", false),
|
||||
@@ -110,6 +140,9 @@ function getDefaultSettings() {
|
||||
language: (process.env.DEFAULT_LANGUAGE as "en" | "de") || "en",
|
||||
stockCalculationMode: (process.env.DEFAULT_STOCK_CALCULATION_MODE as "automatic" | "manual") || "automatic",
|
||||
shareStockStatus: envBool("DEFAULT_SHARE_STOCK_STATUS", true),
|
||||
upcomingTodayOnly: envBool("DEFAULT_UPCOMING_TODAY_ONLY", false),
|
||||
shareScheduleTodayOnly: envBool("DEFAULT_SHARE_SCHEDULE_TODAY_ONLY", false),
|
||||
swapDashboardMainSections: false,
|
||||
lastAutoEmailSent: null,
|
||||
lastNotificationType: null,
|
||||
lastNotificationChannel: null,
|
||||
@@ -118,6 +151,9 @@ function getDefaultSettings() {
|
||||
lastStockReminderSent: null,
|
||||
lastStockReminderChannel: null,
|
||||
lastStockReminderMedNames: null,
|
||||
lastPrescriptionReminderSent: null,
|
||||
lastPrescriptionReminderChannel: null,
|
||||
lastPrescriptionReminderMedNames: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -148,10 +184,12 @@ export async function loadUserSettings(userId: number): Promise<UserSettings> {
|
||||
notificationEmail: settings.notificationEmail,
|
||||
emailStockReminders: settings.emailStockReminders,
|
||||
emailIntakeReminders: settings.emailIntakeReminders,
|
||||
emailPrescriptionReminders: settings.emailPrescriptionReminders ?? true,
|
||||
shoutrrrEnabled: settings.shoutrrrEnabled,
|
||||
shoutrrrUrl: settings.shoutrrrUrl,
|
||||
shoutrrrStockReminders: settings.shoutrrrStockReminders,
|
||||
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
|
||||
shoutrrrPrescriptionReminders: settings.shoutrrrPrescriptionReminders ?? true,
|
||||
reminderDaysBefore: settings.reminderDaysBefore,
|
||||
repeatDailyReminders: settings.repeatDailyReminders,
|
||||
skipRemindersForTakenDoses: settings.skipRemindersForTakenDoses ?? false,
|
||||
@@ -164,6 +202,9 @@ export async function loadUserSettings(userId: number): Promise<UserSettings> {
|
||||
language: settings.language as Language,
|
||||
stockCalculationMode: (settings.stockCalculationMode as "automatic" | "manual") ?? "automatic",
|
||||
shareStockStatus: settings.shareStockStatus ?? true,
|
||||
upcomingTodayOnly: settings.upcomingTodayOnly ?? false,
|
||||
shareScheduleTodayOnly: settings.shareScheduleTodayOnly ?? false,
|
||||
swapDashboardMainSections: settings.swapDashboardMainSections ?? false,
|
||||
lastAutoEmailSent: settings.lastAutoEmailSent,
|
||||
lastNotificationType: settings.lastNotificationType,
|
||||
lastNotificationChannel: settings.lastNotificationChannel,
|
||||
@@ -172,6 +213,9 @@ export async function loadUserSettings(userId: number): Promise<UserSettings> {
|
||||
lastStockReminderSent: settings.lastStockReminderSent ?? null,
|
||||
lastStockReminderChannel: settings.lastStockReminderChannel ?? null,
|
||||
lastStockReminderMedNames: settings.lastStockReminderMedNames ?? null,
|
||||
lastPrescriptionReminderSent: settings.lastPrescriptionReminderSent ?? null,
|
||||
lastPrescriptionReminderChannel: settings.lastPrescriptionReminderChannel ?? null,
|
||||
lastPrescriptionReminderMedNames: settings.lastPrescriptionReminderMedNames ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -184,10 +228,12 @@ export async function getAllUserSettings(): Promise<UserSettings[]> {
|
||||
notificationEmail: settings.notificationEmail,
|
||||
emailStockReminders: settings.emailStockReminders,
|
||||
emailIntakeReminders: settings.emailIntakeReminders,
|
||||
emailPrescriptionReminders: settings.emailPrescriptionReminders ?? true,
|
||||
shoutrrrEnabled: settings.shoutrrrEnabled,
|
||||
shoutrrrUrl: settings.shoutrrrUrl,
|
||||
shoutrrrStockReminders: settings.shoutrrrStockReminders,
|
||||
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
|
||||
shoutrrrPrescriptionReminders: settings.shoutrrrPrescriptionReminders ?? true,
|
||||
reminderDaysBefore: settings.reminderDaysBefore,
|
||||
repeatDailyReminders: settings.repeatDailyReminders,
|
||||
skipRemindersForTakenDoses: settings.skipRemindersForTakenDoses ?? false,
|
||||
@@ -200,6 +246,9 @@ export async function getAllUserSettings(): Promise<UserSettings[]> {
|
||||
language: settings.language as Language,
|
||||
stockCalculationMode: (settings.stockCalculationMode as "automatic" | "manual") ?? "automatic",
|
||||
shareStockStatus: settings.shareStockStatus ?? true,
|
||||
upcomingTodayOnly: settings.upcomingTodayOnly ?? false,
|
||||
shareScheduleTodayOnly: settings.shareScheduleTodayOnly ?? false,
|
||||
swapDashboardMainSections: settings.swapDashboardMainSections ?? false,
|
||||
lastAutoEmailSent: settings.lastAutoEmailSent,
|
||||
lastNotificationType: settings.lastNotificationType,
|
||||
lastNotificationChannel: settings.lastNotificationChannel,
|
||||
@@ -208,6 +257,9 @@ export async function getAllUserSettings(): Promise<UserSettings[]> {
|
||||
lastStockReminderSent: settings.lastStockReminderSent ?? null,
|
||||
lastStockReminderChannel: settings.lastStockReminderChannel ?? null,
|
||||
lastStockReminderMedNames: settings.lastStockReminderMedNames ?? null,
|
||||
lastPrescriptionReminderSent: settings.lastPrescriptionReminderSent ?? null,
|
||||
lastPrescriptionReminderChannel: settings.lastPrescriptionReminderChannel ?? null,
|
||||
lastPrescriptionReminderMedNames: settings.lastPrescriptionReminderMedNames ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -217,7 +269,7 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
|
||||
// Helper to get user ID from request
|
||||
// Returns anonymous user ID when auth is disabled
|
||||
async function getUserId(request: any, reply: any): Promise<number> {
|
||||
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
|
||||
// If auth is disabled, use the anonymous user
|
||||
if (!env.AUTH_ENABLED) {
|
||||
return getAnonymousUserId();
|
||||
@@ -232,7 +284,8 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
// Get settings for current user
|
||||
app.get("/settings", async (request, reply) => {
|
||||
// Suppress request logs — polled every 30s for reminder status refresh
|
||||
app.get("/settings", { logLevel: "warn" }, async (request, reply) => {
|
||||
const userId = await getUserId(request, reply);
|
||||
|
||||
const settings = await getOrCreateUserSettings(userId);
|
||||
@@ -250,8 +303,10 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
shoutrrrUrl: settings.shoutrrrUrl ?? "",
|
||||
emailStockReminders: settings.emailStockReminders,
|
||||
emailIntakeReminders: settings.emailIntakeReminders,
|
||||
emailPrescriptionReminders: settings.emailPrescriptionReminders ?? true,
|
||||
shoutrrrStockReminders: settings.shoutrrrStockReminders,
|
||||
shoutrrrIntakeReminders: settings.shoutrrrIntakeReminders,
|
||||
shoutrrrPrescriptionReminders: settings.shoutrrrPrescriptionReminders ?? true,
|
||||
skipRemindersForTakenDoses: settings.skipRemindersForTakenDoses,
|
||||
repeatRemindersEnabled: settings.repeatRemindersEnabled ?? false,
|
||||
reminderRepeatIntervalMinutes: settings.reminderRepeatIntervalMinutes ?? 30,
|
||||
@@ -259,6 +314,9 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
language: settings.language,
|
||||
stockCalculationMode: settings.stockCalculationMode ?? "automatic",
|
||||
shareStockStatus: settings.shareStockStatus ?? true,
|
||||
upcomingTodayOnly: settings.upcomingTodayOnly ?? false,
|
||||
shareScheduleTodayOnly: settings.shareScheduleTodayOnly ?? false,
|
||||
swapDashboardMainSections: settings.swapDashboardMainSections ?? false,
|
||||
// SMTP settings (from .env - shared/server-configured)
|
||||
smtpHost: process.env.SMTP_HOST ?? "",
|
||||
smtpPort: parseInt(process.env.SMTP_PORT ?? "587", 10),
|
||||
@@ -276,6 +334,10 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
lastStockReminderSent: settings.lastStockReminderSent ?? null,
|
||||
lastStockReminderChannel: settings.lastStockReminderChannel ?? null,
|
||||
lastStockReminderMedNames: settings.lastStockReminderMedNames ?? null,
|
||||
// Prescription reminder tracking (separate from stock/intake)
|
||||
lastPrescriptionReminderSent: settings.lastPrescriptionReminderSent ?? null,
|
||||
lastPrescriptionReminderChannel: settings.lastPrescriptionReminderChannel ?? null,
|
||||
lastPrescriptionReminderMedNames: settings.lastPrescriptionReminderMedNames ?? null,
|
||||
// Server settings (from .env, read-only)
|
||||
expiryWarningDays: parseInt(process.env.EXPIRY_WARNING_DAYS ?? "30", 10),
|
||||
});
|
||||
@@ -303,10 +365,12 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
notificationEmail: body.notificationEmail || null,
|
||||
emailStockReminders: body.emailStockReminders ?? true,
|
||||
emailIntakeReminders: body.emailIntakeReminders ?? true,
|
||||
emailPrescriptionReminders: body.emailPrescriptionReminders ?? true,
|
||||
shoutrrrEnabled: body.shoutrrrEnabled ?? false,
|
||||
shoutrrrUrl: body.shoutrrrUrl || null,
|
||||
shoutrrrStockReminders: body.shoutrrrStockReminders ?? true,
|
||||
shoutrrrIntakeReminders: body.shoutrrrIntakeReminders ?? true,
|
||||
shoutrrrPrescriptionReminders: body.shoutrrrPrescriptionReminders ?? true,
|
||||
reminderDaysBefore: body.reminderDaysBefore,
|
||||
repeatDailyReminders,
|
||||
skipRemindersForTakenDoses: body.skipRemindersForTakenDoses ?? false,
|
||||
@@ -319,6 +383,9 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
language: body.language ?? "en",
|
||||
stockCalculationMode: body.stockCalculationMode ?? "automatic",
|
||||
shareStockStatus: body.shareStockStatus ?? true,
|
||||
upcomingTodayOnly: body.upcomingTodayOnly ?? false,
|
||||
shareScheduleTodayOnly: body.shareScheduleTodayOnly ?? false,
|
||||
swapDashboardMainSections: body.swapDashboardMainSections ?? false,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
@@ -334,6 +401,30 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
return reply.send({ success: true });
|
||||
});
|
||||
|
||||
// Update only the language setting (lightweight, called on dropdown change)
|
||||
app.put<{ Body: { language: string } }>("/settings/language", async (request, reply) => {
|
||||
const userId = await getUserId(request, reply);
|
||||
const { language } = request.body;
|
||||
|
||||
if (!language || !["en", "de"].includes(language)) {
|
||||
return reply.status(400).send({ error: "Invalid language" });
|
||||
}
|
||||
|
||||
const existingSettings = await db.select().from(userSettings).where(eq(userSettings.userId, userId));
|
||||
|
||||
if (existingSettings.length > 0) {
|
||||
await db.update(userSettings).set({ language, updatedAt: new Date() }).where(eq(userSettings.userId, userId));
|
||||
} else {
|
||||
await db.insert(userSettings).values({
|
||||
userId,
|
||||
...getDefaultSettings(),
|
||||
language,
|
||||
});
|
||||
}
|
||||
|
||||
return reply.send({ success: true });
|
||||
});
|
||||
|
||||
// Test email - use SMTP settings from process.env
|
||||
app.post<{ Body: TestEmailBody }>("/settings/test-email", async (request, reply) => {
|
||||
const { email } = request.body;
|
||||
@@ -392,6 +483,7 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
try {
|
||||
const provider = getNotificationProvider(url);
|
||||
const result = await sendShoutrrrNotification(
|
||||
url,
|
||||
"MedAssist-ng Test",
|
||||
@@ -399,11 +491,17 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
request.log.info({ provider }, "[Settings] Test push notification sent");
|
||||
return reply.send({ success: true, message: "Test notification sent successfully" });
|
||||
} else {
|
||||
request.log.warn({ provider, error: result.error ?? "unknown" }, "[Settings] Test push notification failed");
|
||||
return reply.status(500).send({ error: result.error });
|
||||
}
|
||||
} catch (error) {
|
||||
request.log.error(
|
||||
{ provider: getNotificationProvider(url), error },
|
||||
"[Settings] Unexpected error while sending test push notification"
|
||||
);
|
||||
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
||||
return reply.status(500).send({ error: `Failed to send notification: ${errorMessage}` });
|
||||
}
|
||||
@@ -416,6 +514,28 @@ function sanitizeNotificationUrl(
|
||||
urlStr: string
|
||||
): { url: string; isNtfy: boolean; auth?: { user: string; pass: string } } | { error: string } {
|
||||
try {
|
||||
// Support Shoutrrr Discord format: discord://TOKEN@WEBHOOK_ID
|
||||
if (urlStr.startsWith("discord://")) {
|
||||
const parsedDiscord = new URL(urlStr);
|
||||
const webhookId = parsedDiscord.hostname;
|
||||
const webhookToken = parsedDiscord.username;
|
||||
|
||||
if (!webhookId || !webhookToken) {
|
||||
return { error: "Invalid Discord URL format" };
|
||||
}
|
||||
|
||||
if (!/^\d+$/.test(webhookId)) {
|
||||
return { error: "Invalid Discord webhook ID" };
|
||||
}
|
||||
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(webhookToken)) {
|
||||
return { error: "Invalid Discord webhook token" };
|
||||
}
|
||||
|
||||
const discordWebhookUrl = `https://discord.com/api/webhooks/${webhookId}/${webhookToken}`;
|
||||
return { url: discordWebhookUrl, isNtfy: false };
|
||||
}
|
||||
|
||||
// Convert ntfy:// to https:// for parsing, track if it was ntfy
|
||||
const isNtfy = urlStr.startsWith("ntfy://");
|
||||
const normalizedUrl = isNtfy ? urlStr.replace("ntfy://", "https://") : urlStr;
|
||||
@@ -427,38 +547,9 @@ function sanitizeNotificationUrl(
|
||||
return { error: "Only HTTP/HTTPS protocols are allowed" };
|
||||
}
|
||||
|
||||
// Block private/internal IP addresses
|
||||
const hostname = parsed.hostname.toLowerCase();
|
||||
|
||||
// Block localhost
|
||||
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") {
|
||||
return { error: "Localhost URLs are not allowed" };
|
||||
}
|
||||
|
||||
// Block private IP ranges (basic check)
|
||||
const ipMatch = hostname.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
|
||||
if (ipMatch) {
|
||||
const [, a, b] = ipMatch.map(Number);
|
||||
// 10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x (link-local)
|
||||
if (
|
||||
a === 10 ||
|
||||
a === 127 ||
|
||||
(a === 172 && b >= 16 && b <= 31) ||
|
||||
(a === 192 && b === 168) ||
|
||||
(a === 169 && b === 254)
|
||||
) {
|
||||
return { error: "Private IP addresses are not allowed" };
|
||||
}
|
||||
}
|
||||
|
||||
// Block common internal hostnames
|
||||
if (
|
||||
hostname.endsWith(".local") ||
|
||||
hostname.endsWith(".internal") ||
|
||||
hostname.endsWith(".lan") ||
|
||||
hostname === "metadata.google.internal"
|
||||
) {
|
||||
return { error: "Internal hostnames are not allowed" };
|
||||
const hostValidationError = validateNotificationHostname(parsed.hostname);
|
||||
if (hostValidationError) {
|
||||
return { error: hostValidationError };
|
||||
}
|
||||
|
||||
// Reconstruct URL from validated components - this breaks taint tracking
|
||||
@@ -475,6 +566,39 @@ function sanitizeNotificationUrl(
|
||||
}
|
||||
}
|
||||
|
||||
function validateNotificationHostname(hostnameRaw: string): string | null {
|
||||
const hostname = hostnameRaw.toLowerCase();
|
||||
|
||||
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") {
|
||||
return "Localhost URLs are not allowed";
|
||||
}
|
||||
|
||||
const ipMatch = hostname.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
|
||||
if (ipMatch) {
|
||||
const [, a, b] = ipMatch.map(Number);
|
||||
if (
|
||||
a === 10 ||
|
||||
a === 127 ||
|
||||
(a === 172 && b >= 16 && b <= 31) ||
|
||||
(a === 192 && b === 168) ||
|
||||
(a === 169 && b === 254)
|
||||
) {
|
||||
return "Private IP addresses are not allowed";
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
hostname.endsWith(".local") ||
|
||||
hostname.endsWith(".internal") ||
|
||||
hostname.endsWith(".lan") ||
|
||||
hostname === "metadata.google.internal"
|
||||
) {
|
||||
return "Internal hostnames are not allowed";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Send notification via Shoutrrr-compatible URL (supports ntfy, Discord, Telegram, etc.)
|
||||
export async function sendShoutrrrNotification(
|
||||
urlStr: string,
|
||||
@@ -482,6 +606,149 @@ export async function sendShoutrrrNotification(
|
||||
message: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
if (urlStr.startsWith("pushover://")) {
|
||||
const pushoverAuthority = urlStr.slice("pushover://".length).split("/")[0] ?? "";
|
||||
const atIndex = pushoverAuthority.lastIndexOf("@");
|
||||
const credentialPart = atIndex >= 0 ? pushoverAuthority.slice(0, atIndex) : "";
|
||||
const userKey = atIndex >= 0 ? pushoverAuthority.slice(atIndex + 1) : "";
|
||||
|
||||
const tokenSeparatorIndex = credentialPart.indexOf(":");
|
||||
const apiToken = tokenSeparatorIndex >= 0 ? credentialPart.slice(tokenSeparatorIndex + 1) : "";
|
||||
|
||||
const parsedPushover = new URL(urlStr);
|
||||
|
||||
if (!apiToken || !userKey) {
|
||||
return { success: false, error: "Invalid Pushover URL format" };
|
||||
}
|
||||
|
||||
const pushoverBody = new URLSearchParams({
|
||||
token: apiToken,
|
||||
user: userKey,
|
||||
title,
|
||||
message,
|
||||
});
|
||||
|
||||
const devices = parsedPushover.searchParams.get("devices");
|
||||
if (devices) {
|
||||
pushoverBody.set("device", devices);
|
||||
}
|
||||
|
||||
const priority = parsedPushover.searchParams.get("priority");
|
||||
if (priority && /^-?\d+$/.test(priority)) {
|
||||
pushoverBody.set("priority", priority);
|
||||
}
|
||||
|
||||
const response = await fetch("https://api.pushover.net/1/messages.json", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: pushoverBody.toString(),
|
||||
redirect: "error",
|
||||
});
|
||||
|
||||
if (response.ok) return { success: true };
|
||||
const errorText = await response.text();
|
||||
return { success: false, error: `HTTP ${response.status}: ${errorText}` };
|
||||
}
|
||||
|
||||
if (urlStr.startsWith("telegram://")) {
|
||||
const parsedTelegram = new URL(urlStr);
|
||||
const token = parsedTelegram.username;
|
||||
if (!token || parsedTelegram.hostname !== "telegram") {
|
||||
return { success: false, error: "Invalid Telegram URL format" };
|
||||
}
|
||||
|
||||
const chatsRaw = parsedTelegram.searchParams.get("chats") ?? parsedTelegram.searchParams.get("channels") ?? "";
|
||||
const chats = chatsRaw
|
||||
.split(",")
|
||||
.map((chat) => chat.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
if (chats.length === 0) {
|
||||
return { success: false, error: "Telegram URL requires chats parameter" };
|
||||
}
|
||||
|
||||
const parseModeRaw = parsedTelegram.searchParams.get("parseMode")?.toLowerCase();
|
||||
let parseMode: "HTML" | "Markdown" | "MarkdownV2" | undefined;
|
||||
if (parseModeRaw === "html") {
|
||||
parseMode = "HTML";
|
||||
} else if (parseModeRaw === "markdown") {
|
||||
parseMode = "Markdown";
|
||||
} else if (parseModeRaw === "markdownv2") {
|
||||
parseMode = "MarkdownV2";
|
||||
}
|
||||
|
||||
const notificationRaw = parsedTelegram.searchParams.get("notification")?.toLowerCase();
|
||||
const disableNotification = notificationRaw === "no" || notificationRaw === "false";
|
||||
|
||||
const previewRaw = parsedTelegram.searchParams.get("preview")?.toLowerCase();
|
||||
const disablePreview = previewRaw === "no" || previewRaw === "false";
|
||||
|
||||
if (!/^\d+:[A-Za-z0-9_-]+$/.test(token)) {
|
||||
return { success: false, error: "Invalid Telegram token format" };
|
||||
}
|
||||
|
||||
const telegramSendMessageUrl = new URL("/bot/sendMessage", "https://api.telegram.org");
|
||||
telegramSendMessageUrl.pathname = `/bot${token}/sendMessage`;
|
||||
|
||||
for (const chatId of chats) {
|
||||
const payload: Record<string, string | boolean> = {
|
||||
chat_id: chatId,
|
||||
text: `${title}\n\n${message}`,
|
||||
disable_notification: disableNotification,
|
||||
disable_web_page_preview: disablePreview,
|
||||
};
|
||||
if (parseMode) {
|
||||
payload.parse_mode = parseMode;
|
||||
}
|
||||
|
||||
// codeql[js/request-forgery]: host is fixed to api.telegram.org and token is pattern-validated.
|
||||
const response = await fetch(telegramSendMessageUrl.toString(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
redirect: "error",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
return { success: false, error: `HTTP ${response.status}: ${errorText}` };
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
if (urlStr.startsWith("gotify://")) {
|
||||
const parsedGotify = new URL(urlStr);
|
||||
const hostValidationError = validateNotificationHostname(parsedGotify.hostname);
|
||||
if (hostValidationError) {
|
||||
return { success: false, error: hostValidationError };
|
||||
}
|
||||
|
||||
const pathParts = parsedGotify.pathname
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
if (pathParts.length === 0) {
|
||||
return { success: false, error: "Invalid Gotify URL format" };
|
||||
}
|
||||
|
||||
const token = pathParts[pathParts.length - 1];
|
||||
const basePath = pathParts.slice(0, -1).join("/");
|
||||
|
||||
const disableTlsRaw = parsedGotify.searchParams.get("disabletls")?.toLowerCase();
|
||||
const protocol = disableTlsRaw === "yes" || disableTlsRaw === "true" || disableTlsRaw === "1" ? "http" : "https";
|
||||
|
||||
const gotifyWebhookUrl = `${protocol}://${parsedGotify.host}${basePath ? `/${basePath}` : ""}/message?token=${encodeURIComponent(token)}`;
|
||||
|
||||
const gotifyPriority = parsedGotify.searchParams.get("priority");
|
||||
const gotifyMessage = gotifyPriority ? `${message}\n\n(priority=${gotifyPriority})` : message;
|
||||
|
||||
// Reuse validated https webhook path to keep a single outbound request sink.
|
||||
return sendShoutrrrNotification(gotifyWebhookUrl, title, gotifyMessage);
|
||||
}
|
||||
|
||||
// Validate and sanitize URL to prevent SSRF - this reconstructs the URL
|
||||
// from validated components, breaking taint tracking
|
||||
const validation = sanitizeNotificationUrl(urlStr);
|
||||
@@ -490,7 +757,7 @@ export async function sendShoutrrrNotification(
|
||||
}
|
||||
|
||||
// Use ONLY the reconstructed URL from validation - never the original urlStr
|
||||
const { url: sanitizedUrl, isNtfy, auth } = validation;
|
||||
const { url: sanitizedUrl, isNtfy: _isNtfy, auth } = validation;
|
||||
|
||||
let targetUrl: string;
|
||||
const method = "POST";
|
||||
@@ -509,14 +776,17 @@ export async function sendShoutrrrNotification(
|
||||
// Use JSON format only for known webhook services that require it
|
||||
// Use proper URL parsing to prevent bypass attacks (e.g., evil.com?hooks.slack.com)
|
||||
let isJsonWebhook = false;
|
||||
let isDiscordWebhook = false;
|
||||
try {
|
||||
const parsedUrl = new URL(sanitizedUrl);
|
||||
const hostname = parsedUrl.hostname.toLowerCase();
|
||||
const pathname = parsedUrl.pathname.toLowerCase();
|
||||
isDiscordWebhook =
|
||||
(hostname === "discord.com" || hostname === "discordapp.com") && pathname.startsWith("/api/webhooks");
|
||||
|
||||
isJsonWebhook =
|
||||
// Discord webhooks
|
||||
((hostname === "discord.com" || hostname === "discordapp.com") && pathname.startsWith("/api/webhooks")) ||
|
||||
isDiscordWebhook ||
|
||||
// Slack webhooks
|
||||
hostname === "hooks.slack.com" ||
|
||||
hostname.endsWith(".hooks.slack.com") ||
|
||||
@@ -533,7 +803,10 @@ export async function sendShoutrrrNotification(
|
||||
// This works for ntfy, Apprise, and most simple push services
|
||||
if (!isJsonWebhook) {
|
||||
targetUrl = sanitizedUrl;
|
||||
headers = { Title: cleanTitle, Tags: "pill" };
|
||||
// Use RFC 2047 Base64 encoding for Title header to safely pass non-ASCII
|
||||
// characters (umlauts, accents, etc.) through HTTP headers
|
||||
const encodedTitle = `=?UTF-8?B?${Buffer.from(cleanTitle, "utf-8").toString("base64")}?=`;
|
||||
headers = { Title: encodedTitle, Tags: "pill" };
|
||||
body = message;
|
||||
|
||||
// Add auth if present (extracted during sanitization)
|
||||
@@ -543,9 +816,16 @@ export async function sendShoutrrrNotification(
|
||||
} else if (sanitizedUrl.startsWith("http://") || sanitizedUrl.startsWith("https://")) {
|
||||
targetUrl = sanitizedUrl;
|
||||
headers = { "Content-Type": "application/json" };
|
||||
body = JSON.stringify({ title, message, text: `${title}\n\n${message}` });
|
||||
if (isDiscordWebhook) {
|
||||
body = JSON.stringify({ content: `${title}\n\n${message}` });
|
||||
} else {
|
||||
body = JSON.stringify({ title, message, text: `${title}\n\n${message}` });
|
||||
}
|
||||
} else {
|
||||
return { success: false, error: "Unsupported URL format. Use ntfy:// or https:// URL" };
|
||||
return {
|
||||
success: false,
|
||||
error: "Unsupported URL format. Use ntfy://, discord://, pushover://, gotify://, telegram://, or https:// URL",
|
||||
};
|
||||
}
|
||||
|
||||
// SSRF protection: targetUrl is reconstructed from sanitizeNotificationUrl() which validates:
|
||||
|
||||
+42
-12
@@ -1,5 +1,5 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
@@ -14,9 +14,6 @@ import {
|
||||
personTakesMedication,
|
||||
} from "../utils/scheduler-utils.js";
|
||||
|
||||
// Share token validity: 1 year in milliseconds
|
||||
const SHARE_TOKEN_VALIDITY_MS = 365 * 24 * 60 * 60 * 1000;
|
||||
|
||||
// =============================================================================
|
||||
// Validation Schemas
|
||||
// =============================================================================
|
||||
@@ -25,6 +22,11 @@ const createShareSchema = z.object({
|
||||
scheduleDays: z.number().int().min(1).max(365).default(30),
|
||||
});
|
||||
|
||||
function maskToken(token: string): string {
|
||||
if (token.length <= 8) return token;
|
||||
return `${token.slice(0, 4)}...${token.slice(-4)}`;
|
||||
}
|
||||
|
||||
// Helper to get user ID from request
|
||||
// Returns anonymous user ID when auth is disabled
|
||||
async function getUserId(request: FastifyRequest, reply: FastifyReply): Promise<number> {
|
||||
@@ -54,6 +56,7 @@ export async function shareRoutes(app: FastifyInstance) {
|
||||
// Find share token
|
||||
const [share] = await db.select().from(shareTokens).where(eq(shareTokens.token, token));
|
||||
if (!share) {
|
||||
request.log.warn(`[Share] Invalid share token requested: ${maskToken(token)}`);
|
||||
return reply.status(404).send({
|
||||
error: "Share link not found",
|
||||
code: "NOT_FOUND",
|
||||
@@ -62,6 +65,9 @@ export async function shareRoutes(app: FastifyInstance) {
|
||||
|
||||
// Check if token has expired
|
||||
if (share.expiresAt && share.expiresAt.getTime() < Date.now()) {
|
||||
request.log.warn(
|
||||
`[Share] Expired token requested: ${maskToken(token)} (owner=${share.userId}, takenBy=${share.takenBy})`
|
||||
);
|
||||
// Get the username of the owner to show in the expired message
|
||||
const [owner] = await db.select({ username: users.username }).from(users).where(eq(users.id, share.userId));
|
||||
return reply.status(410).send({
|
||||
@@ -154,6 +160,8 @@ export async function shareRoutes(app: FastifyInstance) {
|
||||
},
|
||||
stockCalculationMode: (settings?.stockCalculationMode as "automatic" | "manual") ?? "automatic",
|
||||
shareStockStatus: settings?.shareStockStatus ?? true,
|
||||
upcomingTodayOnly: settings?.upcomingTodayOnly ?? false,
|
||||
shareScheduleTodayOnly: settings?.shareScheduleTodayOnly ?? false,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -195,25 +203,47 @@ export async function shareRoutes(app: FastifyInstance) {
|
||||
});
|
||||
}
|
||||
|
||||
// Generate unique token (8 bytes = 16 hex chars)
|
||||
// Keep exactly one active share link per person/user.
|
||||
// If a link already exists, return the same token and only update settings.
|
||||
const [existingShare] = await db
|
||||
.select()
|
||||
.from(shareTokens)
|
||||
.where(and(eq(shareTokens.userId, userId), eq(shareTokens.takenBy, takenBy)));
|
||||
|
||||
if (existingShare) {
|
||||
await db.update(shareTokens).set({ scheduleDays, expiresAt: null }).where(eq(shareTokens.id, existingShare.id));
|
||||
|
||||
request.log.info(
|
||||
`[Share] Reused existing share token (owner=${userId}, takenBy=${takenBy}, scheduleDays=${scheduleDays})`
|
||||
);
|
||||
|
||||
return {
|
||||
reused: true,
|
||||
token: existingShare.token,
|
||||
shareUrl: `/share/${existingShare.token}`,
|
||||
expiresAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
const token = randomBytes(8).toString("hex");
|
||||
|
||||
// Set expiration date (1 year from now)
|
||||
const expiresAt = new Date(Date.now() + SHARE_TOKEN_VALIDITY_MS);
|
||||
|
||||
// Create share token
|
||||
await db.insert(shareTokens).values({
|
||||
userId: userId,
|
||||
userId,
|
||||
token,
|
||||
takenBy,
|
||||
scheduleDays,
|
||||
expiresAt,
|
||||
expiresAt: null,
|
||||
});
|
||||
|
||||
request.log.info(
|
||||
`[Share] Created new share token (owner=${userId}, takenBy=${takenBy}, scheduleDays=${scheduleDays})`
|
||||
);
|
||||
|
||||
return {
|
||||
reused: false,
|
||||
token,
|
||||
shareUrl: `/share/${token}`,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
expiresAt: null,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
getTimezone,
|
||||
getTodaysIntakes,
|
||||
getUpcomingIntakes,
|
||||
type Intake,
|
||||
type IntakeReminderState,
|
||||
parseIntakeReminderState,
|
||||
parseIntakesJson,
|
||||
@@ -51,6 +50,114 @@ function saveIntakeReminderState(state: IntakeReminderState): void {
|
||||
writeFileSync(intakeReminderStateFile, JSON.stringify(state, null, 2));
|
||||
}
|
||||
|
||||
function buildDoseIdForIntake(intake: UpcomingIntake & { medicationId: number; blisterIndex: number }): string {
|
||||
const intakeDate = intake.intakeTime;
|
||||
const dateOnlyMs = new Date(intakeDate.getFullYear(), intakeDate.getMonth(), intakeDate.getDate()).getTime();
|
||||
if (intake.takenBy) {
|
||||
return `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}-${intake.takenBy}`;
|
||||
}
|
||||
return `${intake.medicationId}-${intake.blisterIndex}-${dateOnlyMs}`;
|
||||
}
|
||||
|
||||
async function autoMarkDueIntakesAsTaken(
|
||||
settings: UserSettings & { userId: number },
|
||||
rows: (typeof medications.$inferSelect)[],
|
||||
locale: string,
|
||||
tz: string,
|
||||
logger: ServiceLogger
|
||||
): Promise<number> {
|
||||
if (settings.stockCalculationMode !== "automatic") {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const nowInTimezone = new Date(now.toLocaleString("en-US", { timeZone: tz }));
|
||||
const todayStart = new Date(now.toLocaleString("en-US", { timeZone: tz }));
|
||||
todayStart.setHours(0, 0, 0, 0);
|
||||
const todayEnd = new Date(now.toLocaleString("en-US", { timeZone: tz }));
|
||||
todayEnd.setHours(23, 59, 59, 999);
|
||||
|
||||
const existingToday = await db
|
||||
.select({ doseId: doseTracking.doseId })
|
||||
.from(doseTracking)
|
||||
.where(
|
||||
and(
|
||||
eq(doseTracking.userId, settings.userId),
|
||||
gte(doseTracking.takenAt, todayStart),
|
||||
lte(doseTracking.takenAt, todayEnd)
|
||||
)
|
||||
);
|
||||
const existingDoseIds = new Set(existingToday.map((d) => d.doseId));
|
||||
|
||||
let inserted = 0;
|
||||
|
||||
for (const med of rows) {
|
||||
if (med.isObsolete) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const intakes = parseIntakesJson(
|
||||
med.intakesJson,
|
||||
{ usageJson: med.usageJson, everyJson: med.everyJson, startJson: med.startJson },
|
||||
med.intakeRemindersEnabled ?? false
|
||||
);
|
||||
if (intakes.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const medicationTakenBy = parseTakenByJson(med.takenByJson);
|
||||
const medDisplayName = med.name || med.genericName || "";
|
||||
const todaysIntakes = getTodaysIntakes(
|
||||
medDisplayName,
|
||||
intakes,
|
||||
medicationTakenBy,
|
||||
med.pillWeightMg,
|
||||
locale,
|
||||
tz,
|
||||
med.id,
|
||||
med.doseUnit ?? "mg"
|
||||
);
|
||||
|
||||
for (const intake of todaysIntakes) {
|
||||
const intakeTimeInTimezone = new Date(intake.intakeTime.toLocaleString("en-US", { timeZone: tz }));
|
||||
if (intakeTimeInTimezone.getTime() > nowInTimezone.getTime()) {
|
||||
continue;
|
||||
}
|
||||
if (intake.medicationId === undefined || intake.blisterIndex === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const doseId = buildDoseIdForIntake({
|
||||
...intake,
|
||||
medicationId: intake.medicationId,
|
||||
blisterIndex: intake.blisterIndex,
|
||||
});
|
||||
|
||||
if (existingDoseIds.has(doseId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await db.insert(doseTracking).values({
|
||||
userId: settings.userId,
|
||||
doseId,
|
||||
takenAt: intake.intakeTime,
|
||||
markedBy: null,
|
||||
takenSource: "automatic",
|
||||
dismissed: false,
|
||||
});
|
||||
|
||||
existingDoseIds.add(doseId);
|
||||
inserted++;
|
||||
}
|
||||
}
|
||||
|
||||
if (inserted > 0) {
|
||||
logger.info(`[IntakeReminder] User ${settings.userId}: Auto-marked ${inserted} due intake dose(s) as taken`);
|
||||
}
|
||||
|
||||
return inserted;
|
||||
}
|
||||
|
||||
async function sendIntakeReminderEmail(
|
||||
email: string,
|
||||
intakes: UpcomingIntake[],
|
||||
@@ -247,6 +354,17 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
`[IntakeReminder] Checking user ${settings.userId} - repeat:${settings.repeatRemindersEnabled} skip:${settings.skipRemindersForTakenDoses}`
|
||||
);
|
||||
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(medications)
|
||||
.where(eq(medications.userId, settings.userId))
|
||||
.orderBy(medications.id);
|
||||
|
||||
const locale = getDateLocale(language);
|
||||
const tz = getTimezone();
|
||||
|
||||
await autoMarkDueIntakesAsTaken(settings, rows, locale, tz, logger);
|
||||
|
||||
// Check if any intake reminder notifications are enabled (granular check)
|
||||
const emailEnabled = settings.emailEnabled && settings.notificationEmail && settings.emailIntakeReminders;
|
||||
const shoutrrrEnabled = settings.shoutrrrEnabled && settings.shoutrrrUrl && settings.shoutrrrIntakeReminders;
|
||||
@@ -263,11 +381,6 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
);
|
||||
|
||||
// Get all medications with intake reminders enabled for this user
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(medications)
|
||||
.where(eq(medications.userId, settings.userId))
|
||||
.orderBy(medications.id);
|
||||
const medsWithReminders = rows.filter((row) => row.intakeRemindersEnabled);
|
||||
|
||||
if (medsWithReminders.length === 0) {
|
||||
@@ -281,9 +394,6 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
|
||||
const state = loadIntakeReminderState();
|
||||
const allUpcoming: (UpcomingIntake & { medicationId: number; blisterIndex: number })[] = [];
|
||||
const locale = getDateLocale(language);
|
||||
const tz = getTimezone();
|
||||
|
||||
// Get start and end of today in user's timezone (for filtering today's doses only)
|
||||
const now = new Date();
|
||||
const todayStart = new Date(now.toLocaleString("en-US", { timeZone: tz }));
|
||||
@@ -306,9 +416,10 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
);
|
||||
// Medication-level takenBy (for fallback/display purposes)
|
||||
const medicationTakenBy = parseTakenByJson(med.takenByJson);
|
||||
const medDisplayName = med.name || med.genericName || "";
|
||||
|
||||
logger.debug(
|
||||
`[IntakeReminder] User ${settings.userId}: Processing medication "${med.name}" with ${intakes.length} intakes`
|
||||
`[IntakeReminder] User ${settings.userId}: Processing medication "${medDisplayName}" with ${intakes.length} intakes`
|
||||
);
|
||||
|
||||
// Filter intakes that have reminders enabled (per-intake setting or medication-level)
|
||||
@@ -321,7 +432,7 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
});
|
||||
|
||||
// Process each intake separately to track blisterIndex
|
||||
intakesWithReminders.forEach((intake, blisterIndex) => {
|
||||
intakesWithReminders.forEach((intake, _blisterIndex) => {
|
||||
const actualIndex = intakes.indexOf(intake); // Get the actual index in original array
|
||||
logger.debug(
|
||||
`[IntakeReminder] User ${settings.userId}: Intake ${actualIndex} - start: ${intake.start}, every: ${intake.every} days, usage: ${intake.usage}, takenBy: ${intake.takenBy || "(none)"}`
|
||||
@@ -329,7 +440,7 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
|
||||
// Always get upcoming intakes (15 min before) for first reminders
|
||||
const upcomingIntakes = getUpcomingIntakes(
|
||||
med.name,
|
||||
medDisplayName,
|
||||
[intake],
|
||||
REMINDER_MINUTES_BEFORE,
|
||||
medicationTakenBy,
|
||||
@@ -356,7 +467,7 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
// If repeat reminders enabled, also check for missed intakes (past the intake time)
|
||||
if (settings.repeatRemindersEnabled) {
|
||||
const allTodaysIntakes = getTodaysIntakes(
|
||||
med.name,
|
||||
medDisplayName,
|
||||
[intake],
|
||||
medicationTakenBy,
|
||||
med.pillWeightMg,
|
||||
@@ -416,19 +527,29 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
if (!existingEntry) {
|
||||
// New dose - send first reminder
|
||||
if (isIntakePast) {
|
||||
// Intake time already passed and we have no state entry — this means the scheduler
|
||||
// was not aware of this intake before it happened (e.g., user just enabled reminders).
|
||||
// Seed the state as already handled so repeat reminders can track from here,
|
||||
// but do NOT send a notification for intakes that were missed before tracking started.
|
||||
state.reminders[key] = {
|
||||
firstSentAt: nowMs,
|
||||
lastSentAt: nowMs,
|
||||
sendCount: 0,
|
||||
advanceSent: false,
|
||||
};
|
||||
logger.debug(
|
||||
`[IntakeReminder] User ${settings.userId}: Seeding state for past "${intake.medName}" at ${intake.intakeTimeStr} (no notification — first detection)`
|
||||
);
|
||||
// Intake time already passed and we have no state entry. Check how recently it was missed.
|
||||
const minutesSinceIntake = (nowMs - intakeTimeMs) / 60000;
|
||||
const gracePeriodMinutes = (settings.reminderRepeatIntervalMinutes ?? 30) + REMINDER_MINUTES_BEFORE;
|
||||
|
||||
if (minutesSinceIntake <= gracePeriodMinutes) {
|
||||
// Recently missed — scheduler likely recovered from sleep/restart.
|
||||
// Send a catch-up reminder (counts as first nagging reminder).
|
||||
remindersToSend.push({ ...intake, currentSendCount: 1, maxReminders, isAdvanceReminder: false });
|
||||
logger.info(
|
||||
`[IntakeReminder] User ${settings.userId}: Catch-up reminder for recently missed "${intake.medName}" at ${intake.intakeTimeStr} (${Math.round(minutesSinceIntake)} min ago)`
|
||||
);
|
||||
} else {
|
||||
// Long ago — seed state without notification (user likely already noticed)
|
||||
state.reminders[key] = {
|
||||
firstSentAt: nowMs,
|
||||
lastSentAt: nowMs,
|
||||
sendCount: 0,
|
||||
advanceSent: false,
|
||||
};
|
||||
logger.debug(
|
||||
`[IntakeReminder] User ${settings.userId}: Seeding state for old past "${intake.medName}" at ${intake.intakeTimeStr} (no notification — ${Math.round(minutesSinceIntake)} min ago)`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Upcoming - this is advance reminder (no counter)
|
||||
remindersToSend.push({ ...intake, currentSendCount: 0, maxReminders, isAdvanceReminder: true });
|
||||
@@ -674,7 +795,8 @@ async function checkAndSendIntakeRemindersForUser(
|
||||
saveIntakeReminderState(state);
|
||||
|
||||
// Update global reminder state for UI display
|
||||
const channel = emailSuccess && shoutrrrSuccess ? "both" : emailSuccess ? "email" : "push";
|
||||
const singleChannel = emailSuccess ? "email" : "push";
|
||||
const channel = emailSuccess && shoutrrrSuccess ? "both" : singleChannel;
|
||||
updateReminderSentTime("intake", channel);
|
||||
|
||||
// Also update user settings in database so frontend can display the info
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+129
-11
@@ -28,7 +28,7 @@ vi.mock("../db/client.js", () => ({
|
||||
vi.mock("../plugins/env.js", () => ({
|
||||
env: {
|
||||
AUTH_ENABLED: true,
|
||||
LOCAL_AUTH_ENABLED: true,
|
||||
FORM_LOGIN_ENABLED: true,
|
||||
REGISTRATION_ENABLED: true,
|
||||
OIDC_ENABLED: false,
|
||||
NODE_ENV: "test",
|
||||
@@ -144,7 +144,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
const data = response.json();
|
||||
expect(data.authEnabled).toBe(true);
|
||||
expect(data.registrationEnabled).toBe(true);
|
||||
expect(data.localAuthEnabled).toBe(true);
|
||||
expect(data.formLoginEnabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -194,6 +194,29 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
expect(response.json().code).toBe("USERNAME_EXISTS");
|
||||
});
|
||||
|
||||
it("should reject duplicate username regardless of case", async () => {
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/register",
|
||||
payload: {
|
||||
username: "CaseUser",
|
||||
password: "TestPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/register",
|
||||
payload: {
|
||||
username: "caseuser",
|
||||
password: "AnotherPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json().code).toBe("USERNAME_EXISTS");
|
||||
});
|
||||
|
||||
it("should reject short password", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
@@ -222,6 +245,57 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
expect(response.json().code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("should register with trimmed username when input has whitespace", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/register",
|
||||
payload: {
|
||||
username: " trimuser ",
|
||||
password: "TestPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
expect(response.json().user.username).toBe("trimuser");
|
||||
});
|
||||
|
||||
it("should reject whitespace-only username on registration", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/register",
|
||||
payload: {
|
||||
username: " ",
|
||||
password: "TestPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("should reject duplicate username even with surrounding whitespace", async () => {
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/register",
|
||||
payload: {
|
||||
username: "spacedupe",
|
||||
password: "TestPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/register",
|
||||
payload: {
|
||||
username: " spacedupe ",
|
||||
password: "AnotherPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json().code).toBe("USERNAME_EXISTS");
|
||||
});
|
||||
|
||||
it("should reject invalid username characters", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
@@ -271,8 +345,23 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
|
||||
// Should set cookies
|
||||
const cookies = response.cookies;
|
||||
expect(cookies.find((c: any) => c.name === "access_token")).toBeDefined();
|
||||
expect(cookies.find((c: any) => c.name === "refresh_token")).toBeDefined();
|
||||
expect(cookies.find((c: { name: string }) => c.name === "access_token")).toBeDefined();
|
||||
expect(cookies.find((c: { name: string }) => c.name === "refresh_token")).toBeDefined();
|
||||
});
|
||||
|
||||
it("should login case-insensitively with different username casing", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/login",
|
||||
payload: {
|
||||
username: "LOGINUSER",
|
||||
password: "TestPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().ok).toBe(true);
|
||||
expect(response.json().user.username).toBe("loginuser");
|
||||
});
|
||||
|
||||
it("should reject invalid password", async () => {
|
||||
@@ -303,6 +392,35 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
expect(response.json().code).toBe("INVALID_CREDENTIALS");
|
||||
});
|
||||
|
||||
it("should login successfully when username has leading/trailing whitespace", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/login",
|
||||
payload: {
|
||||
username: " loginuser ",
|
||||
password: "TestPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().ok).toBe(true);
|
||||
expect(response.json().user.username).toBe("loginuser");
|
||||
});
|
||||
|
||||
it("should reject whitespace-only username on login", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/auth/login",
|
||||
payload: {
|
||||
username: " ",
|
||||
password: "TestPassword123",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("should support rememberMe option", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
@@ -355,7 +473,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const refreshToken = login.cookies.find((c: any) => c.name === "refresh_token");
|
||||
const refreshToken = login.cookies.find((c: { name: string }) => c.name === "refresh_token");
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
@@ -418,7 +536,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const refreshToken = login.cookies.find((c: any) => c.name === "refresh_token");
|
||||
const refreshToken = login.cookies.find((c: { name: string }) => c.name === "refresh_token");
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
@@ -468,7 +586,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
|
||||
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
@@ -566,7 +684,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
|
||||
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
@@ -615,7 +733,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
|
||||
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
@@ -651,7 +769,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
|
||||
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
@@ -704,7 +822,7 @@ describe("Auth Routes (AUTH_ENABLED=true)", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const accessToken = login.cookies.find((c: any) => c.name === "access_token");
|
||||
const accessToken = login.cookies.find((c: { name: string }) => c.name === "access_token");
|
||||
|
||||
// Delete account
|
||||
const response = await app.inject({
|
||||
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { createClient } from "@libsql/client";
|
||||
import { drizzle } from "drizzle-orm/libsql";
|
||||
import { migrate } from "drizzle-orm/libsql/migrator";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
// Import utility functions from db-utils (no side effects, unlike client.ts which initializes the DB)
|
||||
import {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type ClientTestOptions = {
|
||||
dirWritable?: boolean;
|
||||
authEnabled?: boolean;
|
||||
};
|
||||
|
||||
async function loadDbClientModule(options: ClientTestOptions = {}) {
|
||||
const { dirWritable = true, authEnabled = false } = options;
|
||||
|
||||
vi.resetModules();
|
||||
vi.restoreAllMocks();
|
||||
|
||||
process.env.AUTH_ENABLED = authEnabled ? "true" : "false";
|
||||
process.env.DOTENV_PATH = "/tmp/medassist-nonexistent.env";
|
||||
|
||||
const existsSync = vi.fn().mockReturnValue(false);
|
||||
const statSync = vi.fn().mockReturnValue({ mode: 0o40755, uid: 1000, gid: 1000 });
|
||||
vi.doMock("node:fs", () => ({ existsSync, statSync }));
|
||||
|
||||
const dotenvConfig = vi.fn();
|
||||
vi.doMock("dotenv", () => ({ default: { config: dotenvConfig } }));
|
||||
|
||||
const createClient = vi.fn().mockReturnValue({ execute: vi.fn() });
|
||||
vi.doMock("@libsql/client", () => ({ createClient }));
|
||||
|
||||
const drizzle = vi.fn().mockReturnValue({ __db: true });
|
||||
vi.doMock("drizzle-orm/libsql", () => ({ drizzle }));
|
||||
|
||||
const ensureDataDirectory = vi
|
||||
.fn()
|
||||
.mockReturnValue(dirWritable ? { success: true } : { success: false, error: "permission denied" });
|
||||
const getDbPaths = vi.fn().mockReturnValue({
|
||||
dataDir: "/tmp/medassist-data",
|
||||
dbPath: "/tmp/medassist-data/medassist.db",
|
||||
url: "file:/tmp/medassist-data/medassist.db",
|
||||
});
|
||||
const runDrizzleMigrations = vi.fn().mockResolvedValue({ success: true });
|
||||
const runAlterMigrations = vi.fn().mockResolvedValue({ errors: [] });
|
||||
const repairTrailingHyphenDoseIds = vi.fn().mockResolvedValue({ repaired: 0, errors: [] });
|
||||
const repairOrphanedDoseIds = vi.fn().mockResolvedValue({ repaired: 0, errors: [] });
|
||||
const ensureDefaultUser = vi.fn().mockResolvedValue(false);
|
||||
|
||||
vi.doMock("../db/db-utils.js", () => ({
|
||||
buildDbUrl: vi.fn(),
|
||||
getDataDir: vi.fn(),
|
||||
ensureDataDirectory,
|
||||
getDbPaths,
|
||||
runDrizzleMigrations,
|
||||
runAlterMigrations,
|
||||
repairTrailingHyphenDoseIds,
|
||||
repairOrphanedDoseIds,
|
||||
ensureDefaultUser,
|
||||
}));
|
||||
|
||||
const log = {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
};
|
||||
vi.doMock("../utils/logger.js", () => ({ log }));
|
||||
|
||||
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
|
||||
throw new Error(`process.exit:${code ?? 0}`);
|
||||
}) as never);
|
||||
|
||||
const modulePromise = import("../db/client.js");
|
||||
|
||||
return {
|
||||
modulePromise,
|
||||
mocks: {
|
||||
existsSync,
|
||||
statSync,
|
||||
dotenvConfig,
|
||||
createClient,
|
||||
drizzle,
|
||||
ensureDataDirectory,
|
||||
getDbPaths,
|
||||
runDrizzleMigrations,
|
||||
runAlterMigrations,
|
||||
repairTrailingHyphenDoseIds,
|
||||
repairOrphanedDoseIds,
|
||||
ensureDefaultUser,
|
||||
log,
|
||||
exitSpy,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("db/client bootstrap", () => {
|
||||
it("initializes db and runs migrations when directory is writable", async () => {
|
||||
const { modulePromise, mocks } = await loadDbClientModule({ dirWritable: true, authEnabled: false });
|
||||
const mod = await modulePromise;
|
||||
|
||||
expect(mod.db).toBeTruthy();
|
||||
expect(mod.migrationsReady).toBeInstanceOf(Promise);
|
||||
await mod.migrationsReady;
|
||||
|
||||
expect(mocks.ensureDataDirectory).toHaveBeenCalledWith("/tmp/medassist-data");
|
||||
expect(mocks.createClient).toHaveBeenCalledWith({ url: "file:/tmp/medassist-data/medassist.db" });
|
||||
expect(mocks.runDrizzleMigrations).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.runAlterMigrations).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.repairTrailingHyphenDoseIds).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.repairOrphanedDoseIds).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.ensureDefaultUser).toHaveBeenCalledWith(expect.anything(), false);
|
||||
});
|
||||
|
||||
it("passes auth-enabled flag to ensureDefaultUser", async () => {
|
||||
const { modulePromise, mocks } = await loadDbClientModule({ dirWritable: true, authEnabled: true });
|
||||
const mod = await modulePromise;
|
||||
await mod.migrationsReady;
|
||||
|
||||
expect(mocks.ensureDefaultUser).toHaveBeenCalledWith(expect.anything(), true);
|
||||
});
|
||||
|
||||
it("exits when data directory is not writable", async () => {
|
||||
const { modulePromise } = await loadDbClientModule({ dirWritable: false });
|
||||
await expect(modulePromise).rejects.toThrow("process.exit:1");
|
||||
});
|
||||
});
|
||||
@@ -271,7 +271,7 @@ describe("Dose Tracking API", () => {
|
||||
expect(response.statusCode).toBe(200);
|
||||
const data = response.json();
|
||||
expect(data.doses).toHaveLength(2);
|
||||
expect(data.doses.map((d: any) => d.doseId).sort()).toEqual([doseId1, doseId2].sort());
|
||||
expect(data.doses.map((d: { doseId: string }) => d.doseId).sort()).toEqual([doseId1, doseId2].sort());
|
||||
// Each dose should have a takenAt timestamp
|
||||
for (const dose of data.doses) {
|
||||
expect(dose.takenAt).toBeTypeOf("number");
|
||||
|
||||
@@ -55,6 +55,7 @@ const { medicationRoutes } = await import("../routes/medications.js");
|
||||
const { settingsRoutes } = await import("../routes/settings.js");
|
||||
const { healthRoutes } = await import("../routes/health.js");
|
||||
const { refillRoutes } = await import("../routes/refills.js");
|
||||
const { reportRoutes } = await import("../routes/report.js");
|
||||
const { exportRoutes } = await import("../routes/export.js");
|
||||
|
||||
// =============================================================================
|
||||
@@ -99,6 +100,14 @@ async function createSchema(client: Client) {
|
||||
expiry_date text,
|
||||
notes text,
|
||||
intake_reminders_enabled integer NOT NULL DEFAULT 0,
|
||||
medication_start_date text NOT NULL DEFAULT '',
|
||||
is_obsolete integer NOT NULL DEFAULT 0,
|
||||
obsolete_at integer,
|
||||
prescription_enabled integer NOT NULL DEFAULT 0,
|
||||
prescription_authorized_refills integer,
|
||||
prescription_remaining_refills integer,
|
||||
prescription_low_refill_threshold integer NOT NULL DEFAULT 1,
|
||||
prescription_expiry_date text,
|
||||
dismissed_until text,
|
||||
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
@@ -110,10 +119,12 @@ async function createSchema(client: Client) {
|
||||
notification_email text,
|
||||
email_stock_reminders integer NOT NULL DEFAULT 1,
|
||||
email_intake_reminders integer NOT NULL DEFAULT 1,
|
||||
email_prescription_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_enabled integer NOT NULL DEFAULT 0,
|
||||
shoutrrr_url text,
|
||||
shoutrrr_stock_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_intake_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_prescription_reminders integer NOT NULL DEFAULT 1,
|
||||
reminder_days_before integer NOT NULL DEFAULT 7,
|
||||
repeat_daily_reminders integer NOT NULL DEFAULT 0,
|
||||
skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0,
|
||||
@@ -127,6 +138,9 @@ async function createSchema(client: Client) {
|
||||
language text NOT NULL DEFAULT 'en',
|
||||
stock_calculation_mode text NOT NULL DEFAULT 'automatic',
|
||||
share_stock_status integer NOT NULL DEFAULT 1,
|
||||
upcoming_today_only integer NOT NULL DEFAULT 0,
|
||||
share_schedule_today_only integer NOT NULL DEFAULT 0,
|
||||
swap_dashboard_main_sections integer NOT NULL DEFAULT 0,
|
||||
last_auto_email_sent text,
|
||||
last_notification_type text,
|
||||
last_notification_channel text,
|
||||
@@ -135,6 +149,9 @@ async function createSchema(client: Client) {
|
||||
last_stock_reminder_sent text,
|
||||
last_stock_reminder_channel text,
|
||||
last_stock_reminder_med_names text,
|
||||
last_prescription_reminder_sent text,
|
||||
last_prescription_reminder_channel text,
|
||||
last_prescription_reminder_med_names text,
|
||||
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`,
|
||||
@@ -154,6 +171,7 @@ async function createSchema(client: Client) {
|
||||
dose_id text NOT NULL,
|
||||
taken_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
marked_by text,
|
||||
taken_source text NOT NULL DEFAULT 'manual',
|
||||
dismissed integer NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`,
|
||||
@@ -163,6 +181,7 @@ async function createSchema(client: Client) {
|
||||
user_id integer NOT NULL,
|
||||
packs_added integer NOT NULL DEFAULT 0,
|
||||
loose_pills_added integer NOT NULL DEFAULT 0,
|
||||
used_prescription integer NOT NULL DEFAULT 0,
|
||||
refill_date integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
FOREIGN KEY (medication_id) REFERENCES medications(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
@@ -247,11 +266,80 @@ describe("E2E Tests with Real Routes", () => {
|
||||
await app.register(settingsRoutes);
|
||||
await app.register(healthRoutes);
|
||||
await app.register(refillRoutes);
|
||||
await app.register(reportRoutes);
|
||||
await app.register(exportRoutes);
|
||||
|
||||
await app.ready();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Report Routes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("Real /medications/report-data route", () => {
|
||||
it("should return 400 for invalid payload", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications/report-data",
|
||||
payload: { medicationIds: [] },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("should return 403 when requested medication is not owned by user", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications/report-data",
|
||||
payload: { medicationIds: [999999] },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(response.json().error).toBe("Access denied to medication");
|
||||
});
|
||||
|
||||
it("should aggregate taken/dismissed doses and refill history", async () => {
|
||||
const medId = await createMedication(testClient, userId, "Report Med", ["Daniel"]);
|
||||
|
||||
// One taken dose and one dismissed dose for the same medication
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed)
|
||||
VALUES (?, ?, ?, 0)`,
|
||||
args: [userId, `${medId}-0-1735344000000`, 1735344000],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed)
|
||||
VALUES (?, ?, ?, 1)`,
|
||||
args: [userId, `${medId}-0-1735430400000-Daniel`, 1735430400],
|
||||
});
|
||||
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO refill_history (medication_id, user_id, packs_added, loose_pills_added, used_prescription, refill_date)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
args: [medId, userId, 2, 5, 1, 1735516800],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications/report-data",
|
||||
payload: { medicationIds: [medId] },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const data = response.json();
|
||||
expect(data[medId].dosesTaken).toBe(1);
|
||||
expect(data[medId].dosesDismissed).toBe(1);
|
||||
expect(data[medId].firstDoseAt).toBe(new Date(1735344000 * 1000).toISOString());
|
||||
expect(data[medId].lastDoseAt).toBe(new Date(1735344000 * 1000).toISOString());
|
||||
expect(data[medId].refills).toHaveLength(1);
|
||||
expect(data[medId].refills[0]).toMatchObject({
|
||||
packsAdded: 2,
|
||||
loosePillsAdded: 5,
|
||||
usedPrescription: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
testClient.close();
|
||||
@@ -730,6 +818,39 @@ describe("E2E Tests with Real Routes", () => {
|
||||
const data = getResponse.json();
|
||||
expect(data.repeatDailyReminders).toBe(false);
|
||||
});
|
||||
|
||||
it("should reject invalid language in lightweight language endpoint", async () => {
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/settings/language",
|
||||
payload: { language: "fr" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().error).toBe("Invalid language");
|
||||
});
|
||||
|
||||
it("should create and update language via lightweight language endpoint", async () => {
|
||||
let response = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/settings/language",
|
||||
payload: { language: "de" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual({ success: true });
|
||||
|
||||
response = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/settings/language",
|
||||
payload: { language: "en" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const getResponse = await app.inject({ method: "GET", url: "/settings" });
|
||||
expect(getResponse.json().language).toBe("en");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -747,7 +868,6 @@ describe("E2E Tests with Real Routes", () => {
|
||||
const json = response.json();
|
||||
expect(json.status).toBe("ok");
|
||||
expect(typeof json.smtpConfigured).toBe("boolean");
|
||||
expect(typeof json.shoutrrrConfigured).toBe("boolean");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1168,7 +1288,6 @@ describe("E2E Tests with Real Routes", () => {
|
||||
const json = response.json();
|
||||
expect(json.status).toBe("ok");
|
||||
expect(typeof json.smtpConfigured).toBe("boolean");
|
||||
expect(typeof json.shoutrrrConfigured).toBe("boolean");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1621,6 +1740,83 @@ describe("E2E Tests with Real Routes", () => {
|
||||
expect(data.newStock.looseTablets).toBe(15); // 5 + 10
|
||||
});
|
||||
|
||||
it("should decrement remaining refills and mark history when using prescription refill", async () => {
|
||||
const createResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications",
|
||||
payload: {
|
||||
name: "Prescription Refill Med",
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
prescriptionEnabled: true,
|
||||
prescriptionAuthorizedRefills: 3,
|
||||
prescriptionRemainingRefills: 2,
|
||||
prescriptionLowRefillThreshold: 1,
|
||||
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
|
||||
},
|
||||
});
|
||||
expect(createResponse.statusCode).toBe(200);
|
||||
const medId = createResponse.json().id;
|
||||
|
||||
const refillResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: `/medications/${medId}/refill`,
|
||||
payload: { packsAdded: 1, loosePillsAdded: 0, usePrescription: true },
|
||||
});
|
||||
|
||||
expect(refillResponse.statusCode).toBe(200);
|
||||
const refillData = refillResponse.json();
|
||||
expect(refillData.prescription.used).toBe(true);
|
||||
expect(refillData.prescription.remainingRefills).toBe(1);
|
||||
|
||||
const medsResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: "/medications",
|
||||
});
|
||||
expect(medsResponse.statusCode).toBe(200);
|
||||
const med = medsResponse.json().find((m: Record<string, unknown>) => m.id === medId);
|
||||
expect(med.prescriptionRemainingRefills).toBe(1);
|
||||
|
||||
const historyResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: `/medications/${medId}/refills`,
|
||||
});
|
||||
expect(historyResponse.statusCode).toBe(200);
|
||||
expect(historyResponse.json()[0].usedPrescription).toBe(true);
|
||||
});
|
||||
|
||||
it("should reject prescription refill when no remaining prescription refills are available", async () => {
|
||||
const createResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications",
|
||||
payload: {
|
||||
name: "Prescription Empty Med",
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
prescriptionEnabled: true,
|
||||
prescriptionAuthorizedRefills: 2,
|
||||
prescriptionRemainingRefills: 0,
|
||||
prescriptionLowRefillThreshold: 1,
|
||||
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
|
||||
},
|
||||
});
|
||||
expect(createResponse.statusCode).toBe(200);
|
||||
const medId = createResponse.json().id;
|
||||
|
||||
const refillResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: `/medications/${medId}/refill`,
|
||||
payload: { packsAdded: 1, loosePillsAdded: 0, usePrescription: true },
|
||||
});
|
||||
|
||||
expect(refillResponse.statusCode).toBe(409);
|
||||
expect(refillResponse.json().error).toContain("No remaining prescription refills");
|
||||
});
|
||||
|
||||
it("should return 400 when no packs or pills added", async () => {
|
||||
const createResponse = await app.inject({
|
||||
method: "POST",
|
||||
@@ -1718,8 +1914,10 @@ describe("E2E Tests with Real Routes", () => {
|
||||
const refills = response.json();
|
||||
expect(refills).toHaveLength(2);
|
||||
// Check both refills exist (order may vary)
|
||||
const hasPackRefill = refills.some((r: any) => r.packsAdded === 1 && r.loosePillsAdded === 0);
|
||||
const hasLooseRefill = refills.some((r: any) => r.packsAdded === 0 && r.loosePillsAdded === 5);
|
||||
const hasPackRefill = refills.some((r: Record<string, unknown>) => r.packsAdded === 1 && r.loosePillsAdded === 0);
|
||||
const hasLooseRefill = refills.some(
|
||||
(r: Record<string, unknown>) => r.packsAdded === 0 && r.loosePillsAdded === 5
|
||||
);
|
||||
expect(hasPackRefill).toBe(true);
|
||||
expect(hasLooseRefill).toBe(true);
|
||||
});
|
||||
@@ -1797,7 +1995,7 @@ describe("E2E Tests with Real Routes", () => {
|
||||
|
||||
expect(getResponse.statusCode).toBe(200);
|
||||
const meds = getResponse.json();
|
||||
const med = meds.find((m: any) => m.id === medId);
|
||||
const med = meds.find((m: Record<string, unknown>) => m.id === medId);
|
||||
expect(med).toBeDefined();
|
||||
expect(med.stockAdjustment).toBe(-7);
|
||||
expect(med.lastStockCorrectionAt).toBeTruthy();
|
||||
@@ -1843,7 +2041,7 @@ describe("E2E Tests with Real Routes", () => {
|
||||
method: "GET",
|
||||
url: "/medications",
|
||||
});
|
||||
const med = getResponse.json().find((m: any) => m.id === medId);
|
||||
const med = getResponse.json().find((m: Record<string, unknown>) => m.id === medId);
|
||||
expect(med.name).toBe("Renamed Med");
|
||||
expect(med.stockAdjustment).toBe(-5);
|
||||
});
|
||||
@@ -1912,7 +2110,7 @@ describe("E2E Tests with Real Routes", () => {
|
||||
|
||||
// Verify adjustment is set
|
||||
let getMeds = await app.inject({ method: "GET", url: "/medications" });
|
||||
let med = getMeds.json().find((m: any) => m.id === medId);
|
||||
let med = getMeds.json().find((m: Record<string, unknown>) => m.id === medId);
|
||||
expect(med.stockAdjustment).toBe(-10);
|
||||
|
||||
// Edit medication with CHANGED stock fields (packCount 1 → 2)
|
||||
@@ -1931,7 +2129,7 @@ describe("E2E Tests with Real Routes", () => {
|
||||
|
||||
// stockAdjustment should be reset to 0
|
||||
getMeds = await app.inject({ method: "GET", url: "/medications" });
|
||||
med = getMeds.json().find((m: any) => m.id === medId);
|
||||
med = getMeds.json().find((m: Record<string, unknown>) => m.id === medId);
|
||||
expect(med.stockAdjustment).toBe(0);
|
||||
expect(med.lastStockCorrectionAt).toBeTruthy();
|
||||
});
|
||||
@@ -1975,7 +2173,7 @@ describe("E2E Tests with Real Routes", () => {
|
||||
|
||||
// stockAdjustment should be preserved
|
||||
const getMeds = await app.inject({ method: "GET", url: "/medications" });
|
||||
const med = getMeds.json().find((m: any) => m.id === medId);
|
||||
const med = getMeds.json().find((m: Record<string, unknown>) => m.id === medId);
|
||||
expect(med.name).toBe("Renamed Preserve Med");
|
||||
expect(med.stockAdjustment).toBe(-5);
|
||||
});
|
||||
@@ -2023,7 +2221,7 @@ describe("E2E Tests with Real Routes", () => {
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const data = response.json();
|
||||
const med = data.find((m: any) => m.medicationId === medId);
|
||||
const med = data.find((m: Record<string, unknown>) => m.medicationId === medId);
|
||||
expect(med).toBeDefined();
|
||||
// Total should be very close to 113 (not 112 or lower from phantom consumption)
|
||||
// Allow up to 1 pill of natural consumption (test runs fast, but at most 1 day could pass)
|
||||
@@ -2110,6 +2308,87 @@ describe("E2E Tests with Real Routes", () => {
|
||||
expect(data.settings).toBeDefined();
|
||||
expect(data.settings.emailEnabled).toBe(true);
|
||||
});
|
||||
|
||||
it("should include sensitive settings when requested", async () => {
|
||||
await app.inject({
|
||||
method: "PUT",
|
||||
url: "/settings",
|
||||
payload: {
|
||||
emailEnabled: false,
|
||||
notificationEmail: "",
|
||||
reminderDaysBefore: 7,
|
||||
repeatDailyReminders: false,
|
||||
lowStockDays: 30,
|
||||
normalStockDays: 90,
|
||||
highStockDays: 180,
|
||||
shoutrrrEnabled: true,
|
||||
shoutrrrUrl: "https://example.com/topic",
|
||||
emailStockReminders: false,
|
||||
emailIntakeReminders: false,
|
||||
emailPrescriptionReminders: false,
|
||||
shoutrrrStockReminders: true,
|
||||
shoutrrrIntakeReminders: true,
|
||||
shoutrrrPrescriptionReminders: true,
|
||||
skipRemindersForTakenDoses: false,
|
||||
repeatRemindersEnabled: false,
|
||||
reminderRepeatIntervalMinutes: 30,
|
||||
maxNaggingReminders: 5,
|
||||
language: "en",
|
||||
stockCalculationMode: "automatic",
|
||||
shareStockStatus: true,
|
||||
upcomingTodayOnly: false,
|
||||
shareScheduleTodayOnly: false,
|
||||
swapDashboardMainSections: false,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/export?includeSensitive=true",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const data = response.json();
|
||||
expect(data.settings.shoutrrrEnabled).toBe(true);
|
||||
expect(data.settings.shoutrrrUrl).toBe("https://example.com/topic");
|
||||
});
|
||||
|
||||
it("should gracefully export malformed date-like DB values", async () => {
|
||||
const createResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications",
|
||||
payload: {
|
||||
name: "Date Edge Med",
|
||||
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
|
||||
},
|
||||
});
|
||||
const medId = createResponse.json().id as number;
|
||||
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed) VALUES (?, ?, ?, 0)`,
|
||||
args: [userId, `${medId}-0-1735344000000`, "not-a-date"],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO refill_history (medication_id, user_id, packs_added, loose_pills_added, used_prescription, refill_date)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
args: [medId, userId, 1, 0, 0, "still-not-a-date"],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO share_tokens (user_id, token, taken_by, schedule_days, expires_at) VALUES (?, ?, ?, ?, ?)`,
|
||||
args: [userId, "date-edge-token", "Daniel", 30, "broken-date"],
|
||||
});
|
||||
|
||||
const response = await app.inject({ method: "GET", url: "/export" });
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const data = response.json();
|
||||
expect(data.doseHistory).toHaveLength(1);
|
||||
expect(Number.isNaN(Date.parse(data.doseHistory[0].takenAt))).toBe(false);
|
||||
expect(data.refillHistory).toHaveLength(1);
|
||||
expect(Number.isNaN(Date.parse(data.refillHistory[0].refillDate))).toBe(false);
|
||||
expect(data.shareLinks).toHaveLength(1);
|
||||
expect(data.shareLinks[0].expiresAt).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Real /import routes", () => {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
|
||||
describe("plugins/env runtime validation", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.restoreAllMocks();
|
||||
process.env = {
|
||||
...ORIGINAL_ENV,
|
||||
DOTENV_PATH: "/tmp/medassist-nonexistent.env",
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
process.env = ORIGINAL_ENV;
|
||||
});
|
||||
|
||||
it("loads with defaults when auth and oidc are disabled", async () => {
|
||||
delete process.env.AUTH_ENABLED;
|
||||
delete process.env.OIDC_ENABLED;
|
||||
delete process.env.JWT_SECRET;
|
||||
delete process.env.REFRESH_SECRET;
|
||||
delete process.env.COOKIE_SECRET;
|
||||
|
||||
const mod = await import("../plugins/env.js");
|
||||
expect(mod.env.AUTH_ENABLED).toBe(false);
|
||||
expect(mod.env.OIDC_ENABLED).toBe(false);
|
||||
expect(mod.env.PORT).toBe(3000);
|
||||
});
|
||||
|
||||
it("exits when auth is enabled but secrets are missing", async () => {
|
||||
process.env.AUTH_ENABLED = "true";
|
||||
delete process.env.JWT_SECRET;
|
||||
delete process.env.REFRESH_SECRET;
|
||||
delete process.env.COOKIE_SECRET;
|
||||
|
||||
vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
|
||||
throw new Error(`process.exit:${code ?? 0}`);
|
||||
}) as never);
|
||||
|
||||
await expect(import("../plugins/env.js")).rejects.toThrow("process.exit:1");
|
||||
});
|
||||
|
||||
it("exits when oidc is enabled but required settings are missing", async () => {
|
||||
process.env.AUTH_ENABLED = "false";
|
||||
process.env.OIDC_ENABLED = "true";
|
||||
delete process.env.OIDC_ISSUER_URL;
|
||||
delete process.env.OIDC_CLIENT_ID;
|
||||
delete process.env.OIDC_CLIENT_SECRET;
|
||||
delete process.env.OIDC_REDIRECT_URI;
|
||||
|
||||
vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
|
||||
throw new Error(`process.exit:${code ?? 0}`);
|
||||
}) as never);
|
||||
|
||||
await expect(import("../plugins/env.js")).rejects.toThrow("process.exit:1");
|
||||
});
|
||||
|
||||
it("loads when auth and oidc settings are complete", async () => {
|
||||
process.env.AUTH_ENABLED = "true";
|
||||
process.env.JWT_SECRET = "jwt-secret-for-runtime-test";
|
||||
process.env.REFRESH_SECRET = "refresh-secret-runtime-test";
|
||||
process.env.COOKIE_SECRET = "cookie-secret-runtime-test";
|
||||
process.env.OIDC_ENABLED = "true";
|
||||
process.env.OIDC_ISSUER_URL = "https://auth.example.com";
|
||||
process.env.OIDC_CLIENT_ID = "medassist";
|
||||
process.env.OIDC_CLIENT_SECRET = "super-secret-client";
|
||||
process.env.OIDC_REDIRECT_URI = "https://app.example.com/api/auth/oidc/callback";
|
||||
|
||||
const mod = await import("../plugins/env.js");
|
||||
expect(mod.env.AUTH_ENABLED).toBe(true);
|
||||
expect(mod.env.OIDC_ENABLED).toBe(true);
|
||||
expect(mod.env.OIDC_CLIENT_ID).toBe("medassist");
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
|
||||
// Mock process.exit to prevent tests from exiting
|
||||
const mockExit = vi.fn();
|
||||
vi.spyOn(process, "exit").mockImplementation(mockExit as any);
|
||||
vi.spyOn(process, "exit").mockImplementation(mockExit as unknown as (...args: unknown[]) => never);
|
||||
|
||||
// Re-create the schema from env.ts for testing
|
||||
const EnvSchema = z.object({
|
||||
|
||||
@@ -23,10 +23,12 @@ async function registerExportRoutes(ctx: TestContext) {
|
||||
const userId = 1; // Test user ID
|
||||
|
||||
// Helper to parse blisters from DB
|
||||
function parseBlisters(row: any): Array<{ usage: number; every: number; start: string; remind: boolean }> {
|
||||
const usage = JSON.parse(row.usage_json || "[]") as number[];
|
||||
const every = JSON.parse(row.every_json || "[]") as number[];
|
||||
const start = JSON.parse(row.start_json || "[]") as string[];
|
||||
function parseBlisters(
|
||||
row: Record<string, unknown>
|
||||
): Array<{ usage: number; every: number; start: string; remind: boolean }> {
|
||||
const usage = JSON.parse((row.usage_json as string) || "[]") as number[];
|
||||
const every = JSON.parse((row.every_json as string) || "[]") as number[];
|
||||
const start = JSON.parse((row.start_json as string) || "[]") as string[];
|
||||
const len = Math.min(usage.length, every.length, start.length);
|
||||
return Array.from({ length: len }, (_, i) => ({
|
||||
usage: usage[i],
|
||||
@@ -99,7 +101,7 @@ async function registerExportRoutes(ctx: TestContext) {
|
||||
args: [userId],
|
||||
});
|
||||
|
||||
let settings;
|
||||
let settings: Record<string, unknown> | undefined;
|
||||
if (settingsResult.rows.length > 0) {
|
||||
const s = settingsResult.rows[0];
|
||||
settings = {
|
||||
@@ -150,7 +152,8 @@ async function registerExportRoutes(ctx: TestContext) {
|
||||
});
|
||||
|
||||
// POST /import
|
||||
app.post<{ Body: any }>("/import", async (request, reply) => {
|
||||
app.post("/import", async (request, reply) => {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: test helper with dynamic import data shape
|
||||
const importData = request.body as any;
|
||||
|
||||
// Basic validation
|
||||
@@ -167,9 +170,15 @@ async function registerExportRoutes(ctx: TestContext) {
|
||||
// Import medications
|
||||
const exportIdToNewId = new Map<string, number>();
|
||||
for (const med of importData.medications || []) {
|
||||
const usageJson = JSON.stringify((med.schedules || []).map((s: any) => s.usage));
|
||||
const everyJson = JSON.stringify((med.schedules || []).map((s: any) => s.every));
|
||||
const startJson = JSON.stringify((med.schedules || []).map((s: any) => s.start));
|
||||
const usageJson = JSON.stringify(
|
||||
((med.schedules as Array<Record<string, unknown>>) || []).map((s: Record<string, unknown>) => s.usage)
|
||||
);
|
||||
const everyJson = JSON.stringify(
|
||||
((med.schedules as Array<Record<string, unknown>>) || []).map((s: Record<string, unknown>) => s.every)
|
||||
);
|
||||
const startJson = JSON.stringify(
|
||||
((med.schedules as Array<Record<string, unknown>>) || []).map((s: Record<string, unknown>) => s.start)
|
||||
);
|
||||
const takenByJson = JSON.stringify(med.takenBy || []);
|
||||
|
||||
const result = await client.execute({
|
||||
|
||||
@@ -94,6 +94,14 @@ async function createSchema(client: Client) {
|
||||
expiry_date text,
|
||||
notes text,
|
||||
intake_reminders_enabled integer NOT NULL DEFAULT 0,
|
||||
medication_start_date text NOT NULL DEFAULT '',
|
||||
is_obsolete integer NOT NULL DEFAULT 0,
|
||||
obsolete_at integer,
|
||||
prescription_enabled integer NOT NULL DEFAULT 0,
|
||||
prescription_authorized_refills integer,
|
||||
prescription_remaining_refills integer,
|
||||
prescription_low_refill_threshold integer NOT NULL DEFAULT 1,
|
||||
prescription_expiry_date text,
|
||||
dismissed_until text,
|
||||
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
@@ -105,10 +113,12 @@ async function createSchema(client: Client) {
|
||||
notification_email text,
|
||||
email_stock_reminders integer NOT NULL DEFAULT 1,
|
||||
email_intake_reminders integer NOT NULL DEFAULT 1,
|
||||
email_prescription_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_enabled integer NOT NULL DEFAULT 0,
|
||||
shoutrrr_url text,
|
||||
shoutrrr_stock_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_intake_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_prescription_reminders integer NOT NULL DEFAULT 1,
|
||||
reminder_days_before integer NOT NULL DEFAULT 7,
|
||||
repeat_daily_reminders integer NOT NULL DEFAULT 0,
|
||||
skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0,
|
||||
@@ -122,6 +132,9 @@ async function createSchema(client: Client) {
|
||||
language text NOT NULL DEFAULT 'en',
|
||||
stock_calculation_mode text NOT NULL DEFAULT 'automatic',
|
||||
share_stock_status integer NOT NULL DEFAULT 1,
|
||||
upcoming_today_only integer NOT NULL DEFAULT 0,
|
||||
share_schedule_today_only integer NOT NULL DEFAULT 0,
|
||||
swap_dashboard_main_sections integer NOT NULL DEFAULT 0,
|
||||
last_auto_email_sent text,
|
||||
last_notification_type text,
|
||||
last_notification_channel text,
|
||||
@@ -130,6 +143,9 @@ async function createSchema(client: Client) {
|
||||
last_stock_reminder_sent text,
|
||||
last_stock_reminder_channel text,
|
||||
last_stock_reminder_med_names text,
|
||||
last_prescription_reminder_sent text,
|
||||
last_prescription_reminder_channel text,
|
||||
last_prescription_reminder_med_names text,
|
||||
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`,
|
||||
@@ -149,6 +165,7 @@ async function createSchema(client: Client) {
|
||||
dose_id text NOT NULL,
|
||||
taken_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
marked_by text,
|
||||
taken_source text NOT NULL DEFAULT 'manual',
|
||||
dismissed integer NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`,
|
||||
@@ -1320,8 +1337,8 @@ describe("Integration Tests", () => {
|
||||
url: "/medications",
|
||||
});
|
||||
const meds = medsRes.json();
|
||||
const med1 = meds.find((m: any) => m.id === med1Id);
|
||||
const med2 = meds.find((m: any) => m.id === med2Id);
|
||||
const med1 = meds.find((m: Record<string, unknown>) => m.id === med1Id);
|
||||
const med2 = meds.find((m: Record<string, unknown>) => m.id === med2Id);
|
||||
|
||||
expect(med1.dismissedUntil).toBe("2025-01-15");
|
||||
expect(med2.dismissedUntil).toBe("2025-01-15");
|
||||
@@ -1363,7 +1380,7 @@ describe("Integration Tests", () => {
|
||||
method: "GET",
|
||||
url: "/medications",
|
||||
});
|
||||
const med = medsRes.json().find((m: any) => m.id === medId);
|
||||
const med = medsRes.json().find((m: Record<string, unknown>) => m.id === medId);
|
||||
expect(med.dismissedUntil).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1433,7 +1450,7 @@ describe("Integration Tests", () => {
|
||||
method: "GET",
|
||||
url: "/medications",
|
||||
});
|
||||
const med = medsRes.json().find((m: any) => m.id === medId);
|
||||
const med = medsRes.json().find((m: Record<string, unknown>) => m.id === medId);
|
||||
expect(med.dismissedUntil).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import cookie from "@fastify/cookie";
|
||||
import Fastify from "fastify";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type OidcMocks = {
|
||||
discovery: ReturnType<typeof vi.fn>;
|
||||
buildAuthorizationUrl: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
async function buildOidcApp(envOverrides: Record<string, unknown>) {
|
||||
vi.resetModules();
|
||||
|
||||
const env = {
|
||||
OIDC_ENABLED: true,
|
||||
OIDC_ISSUER_URL: "https://issuer.example.com",
|
||||
OIDC_CLIENT_ID: "medassist-client",
|
||||
OIDC_CLIENT_SECRET: "medassist-client-secret",
|
||||
OIDC_REDIRECT_URI: "https://app.example.com/api/auth/oidc/callback",
|
||||
OIDC_SCOPES: "openid profile email",
|
||||
OIDC_AUTO_CREATE_USERS: true,
|
||||
OIDC_USERNAME_CLAIM: "preferred_username",
|
||||
OIDC_PROVIDER_NAME: "SSO",
|
||||
NODE_ENV: "test",
|
||||
CORS_ORIGINS: "http://localhost:5173",
|
||||
ACCESS_TOKEN_TTL_MINUTES: 15,
|
||||
REFRESH_TOKEN_TTL_DAYS: 7,
|
||||
...envOverrides,
|
||||
};
|
||||
|
||||
vi.doMock("../plugins/env.js", () => ({ env }));
|
||||
|
||||
vi.doMock("../db/client.js", () => ({
|
||||
db: {
|
||||
select: vi.fn(() => ({ from: vi.fn(() => ({ where: vi.fn().mockResolvedValue([]) })) })),
|
||||
insert: vi.fn(() => ({
|
||||
values: vi.fn(() => ({ returning: vi.fn().mockResolvedValue([{ id: 1, username: "sso-user" }]) })),
|
||||
})),
|
||||
update: vi.fn(() => ({ set: vi.fn(() => ({ where: vi.fn().mockResolvedValue(undefined) })) })),
|
||||
},
|
||||
}));
|
||||
|
||||
const discovery = vi.fn().mockResolvedValue({ issuer: "https://issuer.example.com" });
|
||||
const buildAuthorizationUrl = vi.fn().mockImplementation((_cfg, params) => {
|
||||
const state = typeof params?.state === "string" ? params.state : "state";
|
||||
return new URL(`https://issuer.example.com/authorize?state=${state}`);
|
||||
});
|
||||
|
||||
vi.doMock("openid-client", () => ({
|
||||
discovery,
|
||||
buildAuthorizationUrl,
|
||||
authorizationCodeGrant: vi.fn(),
|
||||
fetchUserInfo: vi.fn(),
|
||||
}));
|
||||
|
||||
const { oidcRoutes } = await import("../routes/oidc.js");
|
||||
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(cookie, { secret: "test-cookie-secret" });
|
||||
app.decorate("config", {
|
||||
accessSecret: "test-jwt-secret-12345",
|
||||
refreshSecret: "test-refresh-secret-12345",
|
||||
accessTtl: 15 * 60,
|
||||
refreshTtl: 7 * 24 * 60 * 60,
|
||||
cookieOptions: { httpOnly: true, sameSite: "lax", secure: false, path: "/" },
|
||||
refreshCookieOptions: { httpOnly: true, sameSite: "lax", secure: false, path: "/auth" },
|
||||
});
|
||||
await app.register(oidcRoutes);
|
||||
await app.ready();
|
||||
|
||||
return {
|
||||
app,
|
||||
mocks: { discovery, buildAuthorizationUrl } as OidcMocks,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("OIDC routes", () => {
|
||||
it("returns 400 on login and callback when oidc is disabled", async () => {
|
||||
const { app } = await buildOidcApp({ OIDC_ENABLED: false });
|
||||
try {
|
||||
const login = await app.inject({ method: "GET", url: "/auth/oidc/login" });
|
||||
const callback = await app.inject({ method: "GET", url: "/auth/oidc/callback" });
|
||||
|
||||
expect(login.statusCode).toBe(400);
|
||||
expect(callback.statusCode).toBe(400);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("redirects to provider and sets PKCE cookies on /auth/oidc/login", async () => {
|
||||
const { app, mocks } = await buildOidcApp({ OIDC_ENABLED: true });
|
||||
try {
|
||||
const res = await app.inject({ method: "GET", url: "/auth/oidc/login" });
|
||||
|
||||
expect(res.statusCode).toBe(302);
|
||||
expect(res.headers.location).toContain("https://issuer.example.com/authorize");
|
||||
expect(res.cookies.some((c) => c.name === "oidc_code_verifier")).toBe(true);
|
||||
expect(res.cookies.some((c) => c.name === "oidc_state")).toBe(true);
|
||||
expect(mocks.discovery).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.buildAuthorizationUrl).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("redirects with provider error when callback contains error params", async () => {
|
||||
const { app } = await buildOidcApp({ OIDC_ENABLED: true });
|
||||
try {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/auth/oidc/callback?error=access_denied&error_description=user_cancelled",
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(302);
|
||||
expect(res.headers.location).toBe("http://localhost:5173/?error=oidc_access_denied");
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("redirects when callback is missing required params", async () => {
|
||||
const { app } = await buildOidcApp({ OIDC_ENABLED: true });
|
||||
try {
|
||||
const res = await app.inject({ method: "GET", url: "/auth/oidc/callback" });
|
||||
|
||||
expect(res.statusCode).toBe(302);
|
||||
expect(res.headers.location).toBe("http://localhost:5173/?error=oidc_missing_params");
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("redirects when callback state validation fails", async () => {
|
||||
const { app } = await buildOidcApp({ OIDC_ENABLED: true });
|
||||
try {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/auth/oidc/callback?code=abc123&state=state123",
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(302);
|
||||
expect(res.headers.location).toBe("http://localhost:5173/?error=oidc_state_mismatch");
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -63,7 +63,7 @@ vi.mock("../services/reminder-scheduler.js", () => ({
|
||||
|
||||
// Mock sendShoutrrrNotification from settings
|
||||
vi.mock("../routes/settings.js", async (importOriginal) => {
|
||||
const original = (await importOriginal()) as any;
|
||||
const original = (await importOriginal()) as Record<string, unknown>;
|
||||
return {
|
||||
...original,
|
||||
sendShoutrrrNotification: mockSendShoutrrr,
|
||||
@@ -86,6 +86,42 @@ async function createSchema(client: Client) {
|
||||
is_active integer NOT NULL DEFAULT 1,
|
||||
created_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
updated_at integer NOT NULL DEFAULT (strftime('%s','now'))
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS medications (
|
||||
id integer PRIMARY KEY AUTOINCREMENT,
|
||||
user_id integer NOT NULL,
|
||||
name text NOT NULL,
|
||||
generic_name text,
|
||||
taken_by_json text NOT NULL DEFAULT '[]',
|
||||
package_type text NOT NULL DEFAULT 'blister',
|
||||
pack_count integer NOT NULL DEFAULT 1,
|
||||
blisters_per_pack integer NOT NULL DEFAULT 1,
|
||||
pills_per_blister integer NOT NULL DEFAULT 1,
|
||||
total_pills integer,
|
||||
loose_tablets integer NOT NULL DEFAULT 0,
|
||||
stock_adjustment integer NOT NULL DEFAULT 0,
|
||||
last_stock_correction_at integer,
|
||||
pill_weight_mg integer,
|
||||
dose_unit text DEFAULT 'mg',
|
||||
usage_json text NOT NULL DEFAULT '[]',
|
||||
every_json text NOT NULL DEFAULT '[]',
|
||||
start_json text NOT NULL DEFAULT '[]',
|
||||
intakes_json text NOT NULL DEFAULT '[]',
|
||||
image_url text,
|
||||
expiry_date text,
|
||||
notes text,
|
||||
intake_reminders_enabled integer NOT NULL DEFAULT 0,
|
||||
medication_start_date text NOT NULL DEFAULT '',
|
||||
is_obsolete integer NOT NULL DEFAULT 0,
|
||||
obsolete_at integer,
|
||||
prescription_enabled integer NOT NULL DEFAULT 0,
|
||||
prescription_authorized_refills integer,
|
||||
prescription_remaining_refills integer,
|
||||
prescription_low_refill_threshold integer NOT NULL DEFAULT 1,
|
||||
prescription_expiry_date text,
|
||||
dismissed_until text,
|
||||
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS user_settings (
|
||||
id integer PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -94,10 +130,12 @@ async function createSchema(client: Client) {
|
||||
notification_email text,
|
||||
email_stock_reminders integer NOT NULL DEFAULT 1,
|
||||
email_intake_reminders integer NOT NULL DEFAULT 1,
|
||||
email_prescription_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_enabled integer NOT NULL DEFAULT 0,
|
||||
shoutrrr_url text,
|
||||
shoutrrr_stock_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_intake_reminders integer NOT NULL DEFAULT 1,
|
||||
shoutrrr_prescription_reminders integer NOT NULL DEFAULT 1,
|
||||
reminder_days_before integer NOT NULL DEFAULT 7,
|
||||
repeat_daily_reminders integer NOT NULL DEFAULT 0,
|
||||
skip_reminders_for_taken_doses integer NOT NULL DEFAULT 0,
|
||||
@@ -111,6 +149,9 @@ async function createSchema(client: Client) {
|
||||
language text NOT NULL DEFAULT 'en',
|
||||
stock_calculation_mode text NOT NULL DEFAULT 'automatic',
|
||||
share_stock_status integer NOT NULL DEFAULT 1,
|
||||
upcoming_today_only integer NOT NULL DEFAULT 0,
|
||||
share_schedule_today_only integer NOT NULL DEFAULT 0,
|
||||
swap_dashboard_main_sections integer NOT NULL DEFAULT 0,
|
||||
last_auto_email_sent text,
|
||||
last_notification_type text,
|
||||
last_notification_channel text,
|
||||
@@ -119,6 +160,9 @@ async function createSchema(client: Client) {
|
||||
last_stock_reminder_sent text,
|
||||
last_stock_reminder_channel text,
|
||||
last_stock_reminder_med_names text,
|
||||
last_prescription_reminder_sent text,
|
||||
last_prescription_reminder_channel text,
|
||||
last_prescription_reminder_med_names text,
|
||||
updated_at integer NOT NULL DEFAULT (strftime('%s','now')),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)`,
|
||||
@@ -130,6 +174,7 @@ async function createSchema(client: Client) {
|
||||
}
|
||||
|
||||
async function clearData(client: Client) {
|
||||
await client.execute("DELETE FROM medications");
|
||||
await client.execute("DELETE FROM user_settings");
|
||||
await client.execute("DELETE FROM users");
|
||||
await client.execute("DELETE FROM sqlite_sequence");
|
||||
@@ -150,6 +195,18 @@ describe("Planner Routes", () => {
|
||||
"INSERT INTO users (id, username, auth_provider) VALUES (999999999, '__anonymous__', 'anonymous')"
|
||||
);
|
||||
|
||||
// Insert test medications so active-medication filters pass
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO medications (id, user_id, name, taken_by_json, usage_json, every_json, start_json)
|
||||
VALUES (1, 999999999, 'Aspirin', '["Daniel"]', '[1]', '[1]', '["2025-01-01T08:00:00.000Z"]')`,
|
||||
args: [],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO medications (id, user_id, name, taken_by_json, usage_json, every_json, start_json)
|
||||
VALUES (2, 999999999, 'Ibuprofen', '["Daniel"]', '[1]', '[1]', '["2025-01-01T08:00:00.000Z"]')`,
|
||||
args: [],
|
||||
});
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(plannerRoutes);
|
||||
await app.ready();
|
||||
@@ -980,4 +1037,106 @@ describe("Planner Routes", () => {
|
||||
expect(message).toContain("Running critically low");
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /reminder/send-prescription", () => {
|
||||
it("should reject request with missing prescription data", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/reminder/send-prescription",
|
||||
payload: {
|
||||
email: "test@example.com",
|
||||
prescriptionLow: [],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toEqual({ error: "Missing prescription reminder data" });
|
||||
});
|
||||
|
||||
it("should return error when no notification channels configured", async () => {
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, language) VALUES (?, 0, 0, 'en')`,
|
||||
args: [999999999],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/reminder/send-prescription",
|
||||
payload: {
|
||||
email: "test@example.com",
|
||||
prescriptionLow: [{ name: "Aspirin", remainingRefills: 0, threshold: 1, expiryDate: "2026-01-01" }],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toEqual({ error: "No notification channels configured" });
|
||||
});
|
||||
|
||||
it("should send prescription email reminder when email is enabled", async () => {
|
||||
process.env.SMTP_HOST = "smtp.test.com";
|
||||
process.env.SMTP_USER = "user@test.com";
|
||||
process.env.SMTP_PASS = "password";
|
||||
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, language) VALUES (?, 1, 0, 'en')`,
|
||||
args: [999999999],
|
||||
});
|
||||
|
||||
mockSendMail.mockResolvedValueOnce({ messageId: "123" });
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/reminder/send-prescription",
|
||||
payload: {
|
||||
email: "test@example.com",
|
||||
prescriptionLow: [
|
||||
{ name: "Aspirin", remainingRefills: 0, threshold: 1, expiryDate: "2026-01-01" },
|
||||
{ name: "Ibuprofen", remainingRefills: 1, threshold: 2, expiryDate: null },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual({ success: true, message: "Prescription reminder sent via email" });
|
||||
expect(mockSendMail).toHaveBeenCalledTimes(1);
|
||||
expect(mockUpdateReminderSentTime).toHaveBeenCalledWith("prescription", "email");
|
||||
expect(mockUpdateUserReminderSentTime).toHaveBeenCalledWith(
|
||||
999999999,
|
||||
"prescription",
|
||||
"email",
|
||||
"Aspirin, Ibuprofen"
|
||||
);
|
||||
|
||||
delete process.env.SMTP_HOST;
|
||||
delete process.env.SMTP_USER;
|
||||
delete process.env.SMTP_PASS;
|
||||
});
|
||||
|
||||
it("should send prescription push reminder when shoutrrr is enabled", async () => {
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO user_settings (user_id, email_enabled, shoutrrr_enabled, shoutrrr_url, language) VALUES (?, 0, 1, 'ntfy://localhost/test', 'en')`,
|
||||
args: [999999999],
|
||||
});
|
||||
|
||||
mockSendShoutrrr.mockResolvedValueOnce({ success: true });
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/reminder/send-prescription",
|
||||
payload: {
|
||||
email: "test@example.com",
|
||||
prescriptionLow: [{ name: "Aspirin", remainingRefills: 1, threshold: 2, expiryDate: "2026-01-01" }],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual({ success: true, message: "Prescription reminder sent via push" });
|
||||
expect(mockSendShoutrrr).toHaveBeenCalledTimes(1);
|
||||
const [_url, title, message] = mockSendShoutrrr.mock.calls[0];
|
||||
expect(title).toContain("Renew Now");
|
||||
expect(message).toContain("Aspirin");
|
||||
expect(mockUpdateReminderSentTime).toHaveBeenCalledWith("prescription", "push");
|
||||
expect(mockUpdateUserReminderSentTime).toHaveBeenCalledWith(999999999, "prescription", "push", "Aspirin");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,422 @@
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { migrate } from "drizzle-orm/libsql/migrator";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { runAlterMigrations } from "../db/db-utils.js";
|
||||
|
||||
const { testClient, testDb, mockedEnv, nodemailerSendMail, fetchMock } = vi.hoisted(() => {
|
||||
const { createClient } = require("@libsql/client");
|
||||
const { drizzle } = require("drizzle-orm/libsql");
|
||||
const client = createClient({ url: ":memory:" });
|
||||
const db = drizzle(client);
|
||||
const env = {
|
||||
AUTH_ENABLED: false,
|
||||
OIDC_ENABLED: false,
|
||||
OIDC_PROVIDER_NAME: "SSO",
|
||||
NODE_ENV: "test",
|
||||
};
|
||||
return {
|
||||
testClient: client,
|
||||
testDb: db,
|
||||
mockedEnv: env,
|
||||
nodemailerSendMail: vi.fn(),
|
||||
fetchMock: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../db/client.js", () => ({
|
||||
db: testDb,
|
||||
migrationsReady: Promise.resolve(),
|
||||
}));
|
||||
|
||||
vi.mock("../plugins/env.js", () => ({ env: mockedEnv }));
|
||||
|
||||
vi.mock("../plugins/auth.js", () => ({
|
||||
requireAuth: async () => {},
|
||||
getAnonymousUserId: async () => 1,
|
||||
}));
|
||||
|
||||
vi.mock("nodemailer", () => ({
|
||||
default: {
|
||||
createTransport: () => ({
|
||||
sendMail: nodemailerSendMail,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
const { settingsRoutes, sendShoutrrrNotification } = await import("../routes/settings.js");
|
||||
const { exportRoutes } = await import("../routes/export.js");
|
||||
const { reportRoutes } = await import("../routes/report.js");
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const migrationsFolder = resolve(__dirname, "../../drizzle");
|
||||
|
||||
async function clearTables() {
|
||||
await testClient.execute("DELETE FROM refill_history");
|
||||
await testClient.execute("DELETE FROM dose_tracking");
|
||||
await testClient.execute("DELETE FROM share_tokens");
|
||||
await testClient.execute("DELETE FROM user_settings");
|
||||
await testClient.execute("DELETE FROM medications");
|
||||
await testClient.execute("DELETE FROM users");
|
||||
}
|
||||
|
||||
async function seedAnonymousUser() {
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO users (id, username, auth_provider, is_active) VALUES (?, ?, ?, 1)",
|
||||
args: [1, "anon", "anonymous"],
|
||||
});
|
||||
}
|
||||
|
||||
async function seedMedication(name = "Aspirin") {
|
||||
const result = await testClient.execute({
|
||||
sql: `INSERT INTO medications (
|
||||
user_id, name, generic_name, taken_by_json, package_type,
|
||||
pack_count, blisters_per_pack, pills_per_blister, loose_tablets,
|
||||
usage_json, every_json, start_json, intakes_json,
|
||||
stock_adjustment, intake_reminders_enabled
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id`,
|
||||
args: [
|
||||
1,
|
||||
name,
|
||||
"Acetylsalicylic acid",
|
||||
JSON.stringify(["Daniel"]),
|
||||
"blister",
|
||||
2,
|
||||
2,
|
||||
10,
|
||||
3,
|
||||
JSON.stringify([1]),
|
||||
JSON.stringify([1]),
|
||||
JSON.stringify(["2026-01-01T08:00:00.000Z"]),
|
||||
JSON.stringify([
|
||||
{ usage: 1, every: 1, start: "2026-01-01T08:00:00.000Z", takenBy: "Daniel", intakeRemindersEnabled: true },
|
||||
]),
|
||||
0,
|
||||
1,
|
||||
],
|
||||
});
|
||||
return result.rows[0].id as number;
|
||||
}
|
||||
|
||||
describe("Real route coverage: settings/export/report", () => {
|
||||
let app: FastifyInstance;
|
||||
|
||||
beforeAll(async () => {
|
||||
await migrate(testDb, { migrationsFolder });
|
||||
await runAlterMigrations(testClient);
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(settingsRoutes);
|
||||
await app.register(exportRoutes);
|
||||
await app.register(reportRoutes);
|
||||
await app.ready();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
testClient.close();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
await clearTables();
|
||||
await seedAnonymousUser();
|
||||
delete process.env.SMTP_HOST;
|
||||
delete process.env.SMTP_USER;
|
||||
delete process.env.SMTP_TOKEN;
|
||||
delete process.env.SMTP_PASS;
|
||||
delete process.env.SMTP_FROM;
|
||||
delete process.env.SMTP_PORT;
|
||||
delete process.env.SMTP_SECURE;
|
||||
});
|
||||
|
||||
it("GET /settings creates defaults for anonymous user", async () => {
|
||||
const response = await app.inject({ method: "GET", url: "/settings" });
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = response.json();
|
||||
expect(body.language).toBe("en");
|
||||
expect(body.shareStockStatus).toBe(true);
|
||||
expect(body.upcomingTodayOnly).toBe(false);
|
||||
expect(body.shareScheduleTodayOnly).toBe(false);
|
||||
});
|
||||
|
||||
it("PUT /settings disables repeatDailyReminders when no stock reminder channel exists", async () => {
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/settings",
|
||||
payload: {
|
||||
emailEnabled: false,
|
||||
notificationEmail: "",
|
||||
reminderDaysBefore: 7,
|
||||
repeatDailyReminders: true,
|
||||
lowStockDays: 30,
|
||||
normalStockDays: 90,
|
||||
highStockDays: 180,
|
||||
shoutrrrEnabled: false,
|
||||
shoutrrrUrl: "",
|
||||
emailStockReminders: true,
|
||||
emailIntakeReminders: true,
|
||||
emailPrescriptionReminders: true,
|
||||
shoutrrrStockReminders: true,
|
||||
shoutrrrIntakeReminders: true,
|
||||
shoutrrrPrescriptionReminders: true,
|
||||
skipRemindersForTakenDoses: false,
|
||||
repeatRemindersEnabled: false,
|
||||
reminderRepeatIntervalMinutes: 30,
|
||||
maxNaggingReminders: 5,
|
||||
language: "en",
|
||||
stockCalculationMode: "automatic",
|
||||
shareStockStatus: true,
|
||||
upcomingTodayOnly: false,
|
||||
shareScheduleTodayOnly: false,
|
||||
swapDashboardMainSections: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const stored = await testClient.execute({
|
||||
sql: "SELECT repeat_daily_reminders FROM user_settings WHERE user_id = 1",
|
||||
});
|
||||
expect(stored.rows[0].repeat_daily_reminders).toBe(0);
|
||||
});
|
||||
|
||||
it("PUT /settings/language validates supported language", async () => {
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/settings/language",
|
||||
payload: { language: "fr" },
|
||||
});
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().error).toBe("Invalid language");
|
||||
});
|
||||
|
||||
it("POST /settings/test-email fails when SMTP is not configured", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/settings/test-email",
|
||||
payload: { email: "person@example.com" },
|
||||
});
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().error).toBe("SMTP not configured");
|
||||
});
|
||||
|
||||
it("POST /settings/test-email sends email when SMTP is configured", async () => {
|
||||
process.env.SMTP_HOST = "smtp.example.com";
|
||||
process.env.SMTP_USER = "mailer@example.com";
|
||||
process.env.SMTP_TOKEN = "secret";
|
||||
nodemailerSendMail.mockResolvedValue(undefined);
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/settings/test-email",
|
||||
payload: { email: "person@example.com" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(nodemailerSendMail).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("POST /settings/test-shoutrrr validates URL presence", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/settings/test-shoutrrr",
|
||||
payload: { url: "" },
|
||||
});
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("sendShoutrrrNotification blocks localhost/private targets", async () => {
|
||||
const result = await sendShoutrrrNotification("http://127.0.0.1/hook", "test", "message");
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain("not allowed");
|
||||
});
|
||||
|
||||
it("sendShoutrrrNotification handles ntfy auth and safe URL reconstruction", async () => {
|
||||
fetchMock.mockResolvedValue({ ok: true });
|
||||
|
||||
const result = await sendShoutrrrNotification("ntfy://user:pass@ntfy.sh/mytopic", "Title ä", "Message");
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://ntfy.sh/mytopic",
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
Authorization: expect.stringMatching(/^Basic /),
|
||||
}),
|
||||
method: "POST",
|
||||
redirect: "error",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("sendShoutrrrNotification uses JSON payload for webhook URLs", async () => {
|
||||
fetchMock.mockResolvedValue({ ok: true });
|
||||
const result = await sendShoutrrrNotification("https://hooks.slack.com/services/a/b/c", "Title", "Body");
|
||||
expect(result.success).toBe(true);
|
||||
const call = fetchMock.mock.calls[0];
|
||||
expect(call[1].headers["Content-Type"]).toBe("application/json");
|
||||
expect(JSON.parse(call[1].body)).toMatchObject({ title: "Title", message: "Body" });
|
||||
});
|
||||
|
||||
it("POST /medications/report-data returns 403 for meds not owned by user", async () => {
|
||||
await seedMedication("Owned Med");
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications/report-data",
|
||||
payload: { medicationIds: [9999] },
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("POST /medications/report-data aggregates doses and refills", async () => {
|
||||
const medId = await seedMedication("Report Med");
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed) VALUES (?, ?, ?, ?)",
|
||||
args: [1, `${medId}-0-1700000000000-Daniel`, 1700000000, 0],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed) VALUES (?, ?, ?, ?)",
|
||||
args: [1, `${medId}-0-1700000600000-Daniel`, 1700000600, 1],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO refill_history (medication_id, user_id, packs_added, loose_pills_added, used_prescription, refill_date) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
args: [medId, 1, 1, 2, 1, 1700001200],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications/report-data",
|
||||
payload: { medicationIds: [medId] },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = response.json();
|
||||
expect(body[medId].dosesTaken).toBe(1);
|
||||
expect(body[medId].dosesDismissed).toBe(1);
|
||||
expect(body[medId].refills).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("GET /export includes medications, settings, doseHistory and refillHistory", async () => {
|
||||
const medId = await seedMedication("Export Med");
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO dose_tracking (user_id, dose_id, taken_at, marked_by) VALUES (?, ?, ?, ?)",
|
||||
args: [1, `${medId}-0-1700000000000-Daniel`, 1700000000, "Daniel"],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO refill_history (medication_id, user_id, packs_added, loose_pills_added, used_prescription, refill_date) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
args: [medId, 1, 1, 3, 0, 1700000000],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO user_settings (user_id, email_enabled, notification_email, share_stock_status, language) VALUES (?, ?, ?, ?, ?)",
|
||||
args: [1, 1, "x@example.com", 1, "de"],
|
||||
});
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO share_tokens (user_id, token, taken_by, schedule_days) VALUES (?, ?, ?, ?)",
|
||||
args: [1, "abc123", "Daniel", 30],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/export?includeSensitive=true&includeImages=false",
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = response.json();
|
||||
expect(body.medications).toHaveLength(1);
|
||||
expect(body.doseHistory).toHaveLength(1);
|
||||
expect(body.refillHistory).toHaveLength(1);
|
||||
expect(body.settings.language).toBe("de");
|
||||
expect(body.shareLinks).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("POST /import validates payload and imports minimal valid structure", async () => {
|
||||
const invalid = await app.inject({
|
||||
method: "POST",
|
||||
url: "/import",
|
||||
payload: { foo: "bar" },
|
||||
});
|
||||
expect(invalid.statusCode).toBe(400);
|
||||
|
||||
const validImport = {
|
||||
version: "1.1",
|
||||
exportedAt: new Date().toISOString(),
|
||||
includeSensitiveData: false,
|
||||
medications: [
|
||||
{
|
||||
_exportId: "med-1",
|
||||
name: "Imported Med",
|
||||
genericName: null,
|
||||
takenBy: ["Daniel"],
|
||||
inventory: {
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
totalPills: null,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: 0,
|
||||
packageType: "blister",
|
||||
},
|
||||
pillWeightMg: null,
|
||||
doseUnit: "mg",
|
||||
schedules: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00.000Z", remind: false, takenBy: "Daniel" }],
|
||||
medicationStartDate: "",
|
||||
expiryDate: null,
|
||||
notes: null,
|
||||
intakeRemindersEnabled: false,
|
||||
isObsolete: false,
|
||||
obsoleteAt: null,
|
||||
prescriptionEnabled: false,
|
||||
prescriptionAuthorizedRefills: null,
|
||||
prescriptionRemainingRefills: null,
|
||||
prescriptionLowRefillThreshold: 1,
|
||||
prescriptionExpiryDate: null,
|
||||
dismissedUntil: null,
|
||||
image: null,
|
||||
lastStockCorrectionAt: null,
|
||||
},
|
||||
],
|
||||
doseHistory: [],
|
||||
refillHistory: [],
|
||||
settings: {
|
||||
emailEnabled: false,
|
||||
notificationEmail: null,
|
||||
emailStockReminders: true,
|
||||
emailIntakeReminders: true,
|
||||
emailPrescriptionReminders: true,
|
||||
shoutrrrEnabled: false,
|
||||
shoutrrrUrl: null,
|
||||
shoutrrrStockReminders: true,
|
||||
shoutrrrIntakeReminders: true,
|
||||
shoutrrrPrescriptionReminders: true,
|
||||
reminderDaysBefore: 7,
|
||||
repeatDailyReminders: false,
|
||||
skipRemindersForTakenDoses: false,
|
||||
repeatRemindersEnabled: false,
|
||||
reminderRepeatIntervalMinutes: 30,
|
||||
maxNaggingReminders: 5,
|
||||
lowStockDays: 30,
|
||||
normalStockDays: 90,
|
||||
highStockDays: 180,
|
||||
expiryWarningDays: 30,
|
||||
language: "en",
|
||||
stockCalculationMode: "automatic",
|
||||
shareStockStatus: true,
|
||||
},
|
||||
shareLinks: [],
|
||||
};
|
||||
|
||||
const valid = await app.inject({
|
||||
method: "POST",
|
||||
url: "/import",
|
||||
payload: validImport,
|
||||
});
|
||||
expect(valid.statusCode).toBe(200);
|
||||
expect(valid.json().imported.medications).toBe(1);
|
||||
|
||||
const rows = await testClient.execute({
|
||||
sql: "SELECT name FROM medications WHERE user_id = 1",
|
||||
});
|
||||
expect(rows.rows[0].name).toBe("Imported Med");
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { resolve } from "node:path";
|
||||
import cookie from "@fastify/cookie";
|
||||
import cors from "@fastify/cors";
|
||||
import sensible from "@fastify/sensible";
|
||||
import Fastify from "fastify";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
// Import from utils to avoid index.ts import side effects (server start)
|
||||
@@ -294,10 +294,18 @@ describe("Server Bootstrap", () => {
|
||||
refreshCookieOptions,
|
||||
});
|
||||
|
||||
expect((app as any).config.accessTtl).toBe(15);
|
||||
expect((app as any).config.refreshTtl).toBe(7);
|
||||
expect((app as any).config.cookieOptions.httpOnly).toBe(true);
|
||||
expect((app as any).config.refreshCookieOptions.maxAge).toBe(7 * 24 * 60 * 60);
|
||||
const appWithConfig = app as unknown as {
|
||||
config: {
|
||||
accessTtl: number;
|
||||
refreshTtl: number;
|
||||
cookieOptions: { httpOnly: boolean };
|
||||
refreshCookieOptions: { maxAge: number };
|
||||
};
|
||||
};
|
||||
expect(appWithConfig.config.accessTtl).toBe(15);
|
||||
expect(appWithConfig.config.refreshTtl).toBe(7);
|
||||
expect(appWithConfig.config.cookieOptions.httpOnly).toBe(true);
|
||||
expect(appWithConfig.config.refreshCookieOptions.maxAge).toBe(7 * 24 * 60 * 60);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
@@ -364,15 +372,15 @@ describe("Server Bootstrap", () => {
|
||||
const app = Fastify({ logger: false });
|
||||
|
||||
// Mock route plugins
|
||||
const healthRoutes = async (app: any) => {
|
||||
const healthRoutes = async (app: FastifyInstance) => {
|
||||
app.get("/health", async () => ({ status: "ok" }));
|
||||
};
|
||||
|
||||
const authRoutes = async (app: any) => {
|
||||
const authRoutes = async (app: FastifyInstance) => {
|
||||
app.post("/auth/login", async () => ({ token: "mock" }));
|
||||
};
|
||||
|
||||
const medicationRoutes = async (app: any) => {
|
||||
const medicationRoutes = async (app: FastifyInstance) => {
|
||||
app.get("/medications", async () => []);
|
||||
};
|
||||
|
||||
|
||||
@@ -388,6 +388,56 @@ describe("Scheduler Utils - Upcoming Intakes", () => {
|
||||
// Both should be found as they're within the window
|
||||
expect(result.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("should catch up missed advance reminder when notify window passed but intake still future", () => {
|
||||
// Intake at 15:57, reminder 15 min before = 15:42
|
||||
// Scheduler was down at 15:42, now running at 15:50 (intake still in future)
|
||||
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T15:57:00" })];
|
||||
// "now" = 15:50 local time on the same day — past the 15:42 notify window, but before 15:57 intake
|
||||
const now = new Date(2025, 0, 1, 15, 50, 0).getTime();
|
||||
|
||||
const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
|
||||
|
||||
// Should still return the intake as a catch-up advance reminder
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].medName).toBe("TestMed");
|
||||
expect(result[0].usage).toBe(1);
|
||||
});
|
||||
|
||||
it("should catch up missed advance reminder even 1 minute before intake", () => {
|
||||
// Intake at 08:00, reminder at 07:45. Scheduler catches up at 07:59.
|
||||
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00" })];
|
||||
const now = new Date(2025, 0, 1, 7, 59, 30).getTime();
|
||||
|
||||
const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("should not catch up for intakes already in the past", () => {
|
||||
// Intake at 08:00, reminder at 07:45. Now = 08:05 (intake already past).
|
||||
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T08:00:00" })];
|
||||
const now = new Date(2025, 0, 1, 8, 5, 0).getTime();
|
||||
|
||||
const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
|
||||
|
||||
// Should NOT return — intake is past, handled by getTodaysIntakes instead
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should catch up for recurring intake on later day", () => {
|
||||
// Intake started Jan 1 at 10:00, every 1 day. Now = Jan 3 at 09:50 (past notify, before intake)
|
||||
const intakes: Intake[] = [blisterToIntake({ usage: 1, every: 1, start: "2025-01-01T10:00:00" })];
|
||||
const now = new Date(2025, 0, 3, 9, 50, 0).getTime();
|
||||
|
||||
const result = getUpcomingIntakes("TestMed", intakes, 15, [], null, "en-US", "UTC", now);
|
||||
|
||||
// Should return today's occurrence via catch-up
|
||||
expect(result).toHaveLength(1);
|
||||
// The intake time should be Jan 3 at 10:00
|
||||
expect(result[0].intakeTime.getHours()).toBe(10);
|
||||
expect(result[0].intakeTime.getDate()).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTodaysIntakes", () => {
|
||||
|
||||
@@ -612,8 +612,8 @@ describe("Stock Calculation API", () => {
|
||||
const data = response.json();
|
||||
expect(data).toHaveLength(2);
|
||||
|
||||
const medA = data.find((d: any) => d.medicationName === "Med A");
|
||||
const medB = data.find((d: any) => d.medicationName === "Med B");
|
||||
const medA = data.find((d: Record<string, unknown>) => d.medicationName === "Med A");
|
||||
const medB = data.find((d: Record<string, unknown>) => d.medicationName === "Med B");
|
||||
|
||||
expect(medA.plannerUsage).toBe(10); // 10 days × 1 pill
|
||||
expect(medB.plannerUsage).toBe(10); // 5 doses × 2 pills
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { migrate } from "drizzle-orm/libsql/migrator";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { runAlterMigrations } from "../db/db-utils.js";
|
||||
|
||||
const { testClient, testDb, mockedEnv } = vi.hoisted(() => {
|
||||
const { createClient } = require("@libsql/client");
|
||||
const { drizzle } = require("drizzle-orm/libsql");
|
||||
const client = createClient({ url: ":memory:" });
|
||||
const db = drizzle(client);
|
||||
return {
|
||||
testClient: client,
|
||||
testDb: db,
|
||||
mockedEnv: {
|
||||
AUTH_ENABLED: false,
|
||||
OIDC_ENABLED: false,
|
||||
OIDC_PROVIDER_NAME: "SSO",
|
||||
NODE_ENV: "test",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../db/client.js", () => ({
|
||||
db: testDb,
|
||||
migrationsReady: Promise.resolve(),
|
||||
}));
|
||||
|
||||
vi.mock("../plugins/env.js", () => ({ env: mockedEnv }));
|
||||
|
||||
vi.mock("../plugins/auth.js", () => ({
|
||||
requireAuth: async () => {},
|
||||
getAnonymousUserId: async () => 1,
|
||||
}));
|
||||
|
||||
const { medicationRoutes } = await import("../routes/medications.js");
|
||||
const { getMedicationsNeedingReminderForTests } = await import("../services/reminder-scheduler.js");
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const migrationsFolder = resolve(__dirname, "../../drizzle");
|
||||
|
||||
async function clearTables() {
|
||||
await testClient.execute("DELETE FROM refill_history");
|
||||
await testClient.execute("DELETE FROM dose_tracking");
|
||||
await testClient.execute("DELETE FROM share_tokens");
|
||||
await testClient.execute("DELETE FROM user_settings");
|
||||
await testClient.execute("DELETE FROM medications");
|
||||
await testClient.execute("DELETE FROM users");
|
||||
}
|
||||
|
||||
async function seedAnonymousUser() {
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO users (id, username, auth_provider, is_active) VALUES (?, ?, ?, 1)",
|
||||
args: [1, "anon", "anonymous"],
|
||||
});
|
||||
}
|
||||
|
||||
async function setStockMode(mode: "automatic" | "manual") {
|
||||
await testClient.execute({
|
||||
sql: `INSERT INTO user_settings (user_id, stock_calculation_mode, reminder_days_before, low_stock_days, language)
|
||||
VALUES (?, ?, 7, 365, 'en')`,
|
||||
args: [1, mode],
|
||||
});
|
||||
}
|
||||
|
||||
async function createMedication(options: {
|
||||
name: string;
|
||||
packCount?: number;
|
||||
blistersPerPack?: number;
|
||||
pillsPerBlister?: number;
|
||||
looseTablets?: number;
|
||||
stockAdjustment?: number;
|
||||
lastStockCorrectionAt?: number | null;
|
||||
isObsolete?: boolean;
|
||||
takenBy?: string[];
|
||||
intakes: Array<{ usage: number; every: number; start: string; takenBy?: string | null }>;
|
||||
}) {
|
||||
const {
|
||||
name,
|
||||
packCount = 1,
|
||||
blistersPerPack = 1,
|
||||
pillsPerBlister = 10,
|
||||
looseTablets = 0,
|
||||
stockAdjustment = 0,
|
||||
lastStockCorrectionAt = null,
|
||||
isObsolete = false,
|
||||
takenBy = [],
|
||||
intakes,
|
||||
} = options;
|
||||
|
||||
const usageJson = JSON.stringify(intakes.map((i) => i.usage));
|
||||
const everyJson = JSON.stringify(intakes.map((i) => i.every));
|
||||
const startJson = JSON.stringify(intakes.map((i) => i.start));
|
||||
const intakesJson = JSON.stringify(
|
||||
intakes.map((i) => ({
|
||||
usage: i.usage,
|
||||
every: i.every,
|
||||
start: i.start,
|
||||
takenBy: i.takenBy ?? null,
|
||||
intakeRemindersEnabled: false,
|
||||
}))
|
||||
);
|
||||
|
||||
const result = await testClient.execute({
|
||||
sql: `INSERT INTO medications (
|
||||
user_id, name, taken_by_json, package_type,
|
||||
pack_count, blisters_per_pack, pills_per_blister, loose_tablets,
|
||||
stock_adjustment, last_stock_correction_at,
|
||||
usage_json, every_json, start_json, intakes_json,
|
||||
is_obsolete, intake_reminders_enabled
|
||||
) VALUES (?, ?, ?, 'blister', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
|
||||
RETURNING id`,
|
||||
args: [
|
||||
1,
|
||||
name,
|
||||
JSON.stringify(takenBy),
|
||||
packCount,
|
||||
blistersPerPack,
|
||||
pillsPerBlister,
|
||||
looseTablets,
|
||||
stockAdjustment,
|
||||
lastStockCorrectionAt,
|
||||
usageJson,
|
||||
everyJson,
|
||||
startJson,
|
||||
intakesJson,
|
||||
isObsolete ? 1 : 0,
|
||||
],
|
||||
});
|
||||
|
||||
return Number(result.rows[0].id);
|
||||
}
|
||||
|
||||
async function markDoseTaken(options: {
|
||||
medicationId: number;
|
||||
blisterIdx: number;
|
||||
doseDateOnlyMs: number;
|
||||
takenAtMs: number;
|
||||
personSuffix?: string;
|
||||
}) {
|
||||
const { medicationId, blisterIdx, doseDateOnlyMs, takenAtMs, personSuffix } = options;
|
||||
const baseId = `${medicationId}-${blisterIdx}-${doseDateOnlyMs}`;
|
||||
const doseId = personSuffix ? `${baseId}-${personSuffix}` : baseId;
|
||||
await testClient.execute({
|
||||
sql: "INSERT INTO dose_tracking (user_id, dose_id, taken_at, dismissed) VALUES (?, ?, ?, 0)",
|
||||
args: [1, doseId, Math.floor(takenAtMs / 1000)],
|
||||
});
|
||||
}
|
||||
|
||||
async function getUsageRow(app: FastifyInstance, startDate: string, endDate: string, medicationName: string) {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications/usage",
|
||||
payload: { startDate, endDate },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const rows = response.json();
|
||||
const row = rows.find((r: { medicationName: string }) => r.medicationName === medicationName);
|
||||
expect(row).toBeDefined();
|
||||
return row;
|
||||
}
|
||||
|
||||
function toDateOnlyMs(date: Date) {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
|
||||
}
|
||||
|
||||
describe("Stock semantics parity (planner usage vs scheduler)", () => {
|
||||
let app: FastifyInstance;
|
||||
|
||||
beforeAll(async () => {
|
||||
await migrate(testDb, { migrationsFolder });
|
||||
await runAlterMigrations(testClient);
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(medicationRoutes);
|
||||
await app.ready();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
testClient.close();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await clearTables();
|
||||
await seedAnonymousUser();
|
||||
});
|
||||
|
||||
it("keeps automatic mode current stock in sync", async () => {
|
||||
await setStockMode("automatic");
|
||||
const medName = "Auto Sync";
|
||||
await createMedication({
|
||||
name: medName,
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
intakes: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00" }],
|
||||
});
|
||||
|
||||
const usageRow = await getUsageRow(app, "2026-01-01T00:00:00.000Z", "2026-01-31T23:59:59.999Z", medName);
|
||||
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "automatic");
|
||||
const schedulerRow = lowStock.find((r) => r.name === medName);
|
||||
|
||||
expect(schedulerRow).toBeDefined();
|
||||
expect(usageRow.currentPills).toBe(usageRow.totalPills);
|
||||
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
|
||||
});
|
||||
|
||||
it("keeps manual mode current stock in sync and does not auto-consume", async () => {
|
||||
await setStockMode("manual");
|
||||
const medName = "Manual Sync";
|
||||
await createMedication({
|
||||
name: medName,
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
intakes: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00" }],
|
||||
});
|
||||
|
||||
const usageRow = await getUsageRow(app, "2026-01-01T00:00:00.000Z", "2026-01-31T23:59:59.999Z", medName);
|
||||
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "manual");
|
||||
const schedulerRow = lowStock.find((r) => r.name === medName);
|
||||
|
||||
expect(schedulerRow).toBeDefined();
|
||||
expect(usageRow.currentPills).toBe(10);
|
||||
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
|
||||
});
|
||||
|
||||
it("respects lastStockCorrectionAt cutoff in manual mode by takenAt", async () => {
|
||||
await setStockMode("manual");
|
||||
const medName = "Manual Correction";
|
||||
const correctionMs = new Date("2026-01-05T12:00:00.000Z").getTime();
|
||||
const medicationId = await createMedication({
|
||||
name: medName,
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
lastStockCorrectionAt: correctionMs,
|
||||
intakes: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00" }],
|
||||
});
|
||||
|
||||
const jan5DateOnly = toDateOnlyMs(new Date("2026-01-05T00:00:00.000Z"));
|
||||
const jan6DateOnly = toDateOnlyMs(new Date("2026-01-06T00:00:00.000Z"));
|
||||
|
||||
await markDoseTaken({
|
||||
medicationId,
|
||||
blisterIdx: 0,
|
||||
doseDateOnlyMs: jan5DateOnly,
|
||||
takenAtMs: new Date("2026-01-05T10:00:00.000Z").getTime(),
|
||||
});
|
||||
await markDoseTaken({
|
||||
medicationId,
|
||||
blisterIdx: 0,
|
||||
doseDateOnlyMs: jan6DateOnly,
|
||||
takenAtMs: new Date("2026-01-06T10:00:00.000Z").getTime(),
|
||||
});
|
||||
|
||||
const usageRow = await getUsageRow(app, "2026-01-01T00:00:00.000Z", "2026-01-31T23:59:59.999Z", medName);
|
||||
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "manual");
|
||||
const schedulerRow = lowStock.find((r) => r.name === medName);
|
||||
|
||||
expect(schedulerRow).toBeDefined();
|
||||
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
|
||||
});
|
||||
|
||||
it("counts early taken dose in automatic mode without drift", async () => {
|
||||
await setStockMode("automatic");
|
||||
const medName = "Early Taken";
|
||||
const now = new Date();
|
||||
const tomorrow = new Date(now);
|
||||
tomorrow.setDate(now.getDate() + 1);
|
||||
tomorrow.setHours(20, 0, 0, 0);
|
||||
const medicationId = await createMedication({
|
||||
name: medName,
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
intakes: [{ usage: 1, every: 1, start: tomorrow.toISOString().slice(0, 19) }],
|
||||
});
|
||||
|
||||
const tomorrowDateOnly = toDateOnlyMs(tomorrow);
|
||||
await markDoseTaken({
|
||||
medicationId,
|
||||
blisterIdx: 0,
|
||||
doseDateOnlyMs: tomorrowDateOnly,
|
||||
takenAtMs: now.getTime(),
|
||||
});
|
||||
|
||||
const rangeStart = new Date(now);
|
||||
rangeStart.setDate(now.getDate() - 1);
|
||||
const rangeEnd = new Date(now);
|
||||
rangeEnd.setDate(now.getDate() + 7);
|
||||
const usageRow = await getUsageRow(app, rangeStart.toISOString(), rangeEnd.toISOString(), medName);
|
||||
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "automatic");
|
||||
const schedulerRow = lowStock.find((r) => r.name === medName);
|
||||
|
||||
expect(schedulerRow).toBeDefined();
|
||||
expect(usageRow.currentPills).toBe(9);
|
||||
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
|
||||
});
|
||||
|
||||
it("handles mixed intake-level and fallback takenBy consistently", async () => {
|
||||
await setStockMode("automatic");
|
||||
const medName = "Mixed TakenBy";
|
||||
await createMedication({
|
||||
name: medName,
|
||||
packCount: 2,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
takenBy: ["Alice", "Bob"],
|
||||
intakes: [
|
||||
{ usage: 1, every: 1, start: "2026-01-01T08:00:00", takenBy: "Alice" },
|
||||
{ usage: 1, every: 1, start: "2026-01-01T20:00:00", takenBy: null },
|
||||
],
|
||||
});
|
||||
|
||||
const usageRow = await getUsageRow(app, "2026-01-01T00:00:00.000Z", "2026-01-31T23:59:59.999Z", medName);
|
||||
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "automatic");
|
||||
const schedulerRow = lowStock.find((r) => r.name === medName);
|
||||
|
||||
expect(schedulerRow).toBeDefined();
|
||||
expect(usageRow.currentPills).toBe(schedulerRow!.medsLeft);
|
||||
expect(usageRow.currentPills).toBeLessThan(20);
|
||||
});
|
||||
|
||||
it("excludes obsolete medications from planner usage and scheduler", async () => {
|
||||
await setStockMode("automatic");
|
||||
await createMedication({
|
||||
name: "Obsolete Med",
|
||||
isObsolete: true,
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
intakes: [{ usage: 1, every: 1, start: "2026-01-01T08:00:00" }],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/medications/usage",
|
||||
payload: { startDate: "2026-01-01T00:00:00.000Z", endDate: "2026-01-31T23:59:59.999Z" },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().some((r: { medicationName: string }) => r.medicationName === "Obsolete Med")).toBe(false);
|
||||
|
||||
const lowStock = await getMedicationsNeedingReminderForTests(1, 7, 365, "en", "automatic");
|
||||
expect(lowStock.some((r) => r.name === "Obsolete Med")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -98,7 +98,7 @@ describe("Translations Module", () => {
|
||||
|
||||
// Stock reminder subject
|
||||
const subject = t(translations.stockReminder.subject, { count: 3, s: "s" });
|
||||
expect(subject).toBe("MedAssist-ng Auto-Reminder: 3 Medications Running Critically Low");
|
||||
expect(subject).toBe("MedAssist-ng: ⚠️ 3 Medications Running Critically Low");
|
||||
|
||||
// Intake reminder description
|
||||
const description = t(translations.intakeReminder.description, { minutes: 30 });
|
||||
@@ -113,7 +113,7 @@ describe("Translations Module", () => {
|
||||
const translations = getTranslations("de");
|
||||
|
||||
const subject = t(translations.stockReminder.subject, { count: 2, e: "e" });
|
||||
expect(subject).toBe("MedAssist-ng Auto-Erinnerung: 2 Medikamente kritisch niedrig");
|
||||
expect(subject).toBe("MedAssist-ng: ⚠️ 2 Medikamente kritisch niedrig");
|
||||
|
||||
const takenBy = t(translations.intakeReminder.takenBy, { name: "Daniel" });
|
||||
expect(takenBy).toBe("für Daniel");
|
||||
|
||||
Vendored
+1
@@ -22,6 +22,7 @@ declare module "fastify" {
|
||||
|
||||
interface FastifyRequest {
|
||||
user?: AuthUser | null;
|
||||
correlationId?: string;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { existsSync, unlinkSync } from "node:fs";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { extname, resolve } from "node:path";
|
||||
import sharp from "sharp";
|
||||
|
||||
export const ALLOWED_IMAGE_MIME_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
|
||||
export const MAX_IMAGE_UPLOAD_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
export function getThumbFilename(imageFilename: string): string {
|
||||
const ext = extname(imageFilename);
|
||||
const base = ext ? imageFilename.slice(0, -ext.length) : imageFilename;
|
||||
return `${base}-thumb.webp`;
|
||||
}
|
||||
|
||||
export function removeImageFiles(imagesDir: string, imageFilename: string): void {
|
||||
const fullPath = resolve(imagesDir, imageFilename);
|
||||
if (existsSync(fullPath)) unlinkSync(fullPath);
|
||||
|
||||
const thumbFilename = getThumbFilename(imageFilename);
|
||||
if (thumbFilename !== imageFilename) {
|
||||
const thumbPath = resolve(imagesDir, thumbFilename);
|
||||
if (existsSync(thumbPath)) unlinkSync(thumbPath);
|
||||
}
|
||||
}
|
||||
|
||||
export async function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer> {
|
||||
const chunks: Buffer[] = [];
|
||||
let totalSize = 0;
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
totalSize += buffer.length;
|
||||
if (totalSize > MAX_IMAGE_UPLOAD_BYTES) {
|
||||
throw new Error("IMAGE_TOO_LARGE");
|
||||
}
|
||||
chunks.push(buffer);
|
||||
}
|
||||
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
export async function writeOptimizedImageSet(
|
||||
imagesDir: string,
|
||||
filePrefix: string,
|
||||
uploadBuffer: Buffer,
|
||||
options?: {
|
||||
maxEdgePx?: number;
|
||||
thumbSizePx?: number;
|
||||
fullQuality?: number;
|
||||
thumbQuality?: number;
|
||||
}
|
||||
): Promise<{ filename: string; thumbFilename: string }> {
|
||||
const maxEdgePx = options?.maxEdgePx ?? 1600;
|
||||
const thumbSizePx = options?.thumbSizePx ?? 96;
|
||||
const fullQuality = options?.fullQuality ?? 82;
|
||||
const thumbQuality = options?.thumbQuality ?? 76;
|
||||
|
||||
const filename = `${filePrefix}-${Date.now()}.webp`;
|
||||
const thumbFilename = getThumbFilename(filename);
|
||||
|
||||
const filepath = resolve(imagesDir, filename);
|
||||
const thumbFilepath = resolve(imagesDir, thumbFilename);
|
||||
|
||||
const optimizedBuffer = await sharp(uploadBuffer, { failOn: "error" })
|
||||
.rotate()
|
||||
.resize({ width: maxEdgePx, height: maxEdgePx, fit: "inside", withoutEnlargement: true })
|
||||
.webp({ quality: fullQuality })
|
||||
.toBuffer();
|
||||
|
||||
const thumbBuffer = await sharp(uploadBuffer, { failOn: "error" })
|
||||
.rotate()
|
||||
.resize({ width: thumbSizePx, height: thumbSizePx, fit: "cover", position: "attention" })
|
||||
.webp({ quality: thumbQuality })
|
||||
.toBuffer();
|
||||
|
||||
await writeFile(filepath, optimizedBuffer);
|
||||
await writeFile(thumbFilepath, thumbBuffer);
|
||||
|
||||
return { filename, thumbFilename };
|
||||
}
|
||||
@@ -23,18 +23,22 @@ function shouldLog(level: string): boolean {
|
||||
return LOG_LEVELS[level] >= getLevel();
|
||||
}
|
||||
|
||||
function ts(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
export const log = {
|
||||
debug(msg: string): void {
|
||||
if (shouldLog("debug")) console.log(msg);
|
||||
if (shouldLog("debug")) console.log(`[${ts()}] [DEBUG] ${msg}`);
|
||||
},
|
||||
info(msg: string): void {
|
||||
if (shouldLog("info")) console.log(msg);
|
||||
if (shouldLog("info")) console.log(`[${ts()}] [INFO] ${msg}`);
|
||||
},
|
||||
warn(msg: string): void {
|
||||
if (shouldLog("warn")) console.warn(msg);
|
||||
if (shouldLog("warn")) console.warn(`[${ts()}] [WARN] ${msg}`);
|
||||
},
|
||||
error(msg: string): void {
|
||||
if (shouldLog("error")) console.error(msg);
|
||||
if (shouldLog("error")) console.error(`[${ts()}] [ERROR] ${msg}`);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -122,7 +122,11 @@ export function getNextScheduledTime(reminderHour: number, tz?: string): Date {
|
||||
/** Calculate milliseconds until next check at the given reminder hour */
|
||||
export function getMsUntilNextCheck(reminderHour: number, tz?: string): number {
|
||||
const next = getNextScheduledTime(reminderHour, tz);
|
||||
return next.getTime() - Date.now();
|
||||
const msUntilNext = next.getTime() - Date.now();
|
||||
if (msUntilNext <= 0) {
|
||||
return msUntilNext + 24 * 60 * 60 * 1000;
|
||||
}
|
||||
return msUntilNext;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
@@ -191,7 +195,7 @@ export function parseIntakesJson(
|
||||
try {
|
||||
const parsed = JSON.parse(intakesJson);
|
||||
if (Array.isArray(parsed) && parsed.length > 0) {
|
||||
return parsed.map((intake: any) => ({
|
||||
return parsed.map((intake: Record<string, unknown>) => ({
|
||||
usage: typeof intake.usage === "number" ? intake.usage : 0,
|
||||
every: typeof intake.every === "number" ? intake.every : 1,
|
||||
start: typeof intake.start === "string" ? intake.start : new Date().toISOString(),
|
||||
@@ -312,7 +316,7 @@ export type UpcomingIntake = {
|
||||
export function getTodaysIntakes(
|
||||
medName: string,
|
||||
intakes: Intake[],
|
||||
medicationTakenBy: string[], // Medication-level takenBy as fallback
|
||||
_medicationTakenBy: string[], // Medication-level takenBy as fallback
|
||||
pillWeightMg: number | null,
|
||||
locale: string,
|
||||
tz?: string,
|
||||
@@ -388,7 +392,7 @@ export function getUpcomingIntakes(
|
||||
medName: string,
|
||||
intakes: Intake[],
|
||||
minutesBefore: number,
|
||||
medicationTakenBy: string[], // Medication-level takenBy as fallback
|
||||
_medicationTakenBy: string[], // Medication-level takenBy as fallback
|
||||
pillWeightMg: number | null,
|
||||
locale: string,
|
||||
tz?: string,
|
||||
@@ -432,6 +436,11 @@ export function getUpcomingIntakes(
|
||||
const currentNotifyTime = currentOccurrence - minutesBefore * 60 * 1000;
|
||||
if (currentNotifyTime >= currentMinuteStart && currentOccurrence > now) {
|
||||
nextTime = currentOccurrence;
|
||||
} else if (currentNotifyTime < currentMinuteStart && currentOccurrence > now) {
|
||||
// CATCH-UP: The notify window was missed (e.g. due to system sleep/restart)
|
||||
// but the intake time is still in the future — include it so the advance
|
||||
// reminder can still be sent rather than falling into a dead zone.
|
||||
nextTime = currentOccurrence;
|
||||
} else {
|
||||
nextTime = nextOccurrence;
|
||||
}
|
||||
@@ -440,8 +449,15 @@ export function getUpcomingIntakes(
|
||||
// Calculate when we should notify for this intake
|
||||
const notifyTime = nextTime - minutesBefore * 60 * 1000;
|
||||
|
||||
// Check if notifyTime falls within the current minute (precise matching)
|
||||
if (notifyTime >= currentMinuteStart && notifyTime < currentMinuteEnd) {
|
||||
// Match if:
|
||||
// 1. notifyTime falls within the current minute (normal case), OR
|
||||
// 2. notifyTime is in the past but intakeTime is still in the future (catch-up
|
||||
// for missed advance reminder window — e.g. scheduler was down during the
|
||||
// exact notification minute due to system sleep, restart, or heavy load)
|
||||
const isInCurrentMinute = notifyTime >= currentMinuteStart && notifyTime < currentMinuteEnd;
|
||||
const isMissedButStillUpcoming = notifyTime < currentMinuteStart && nextTime > now;
|
||||
|
||||
if (isInCurrentMinute || isMissedButStillUpcoming) {
|
||||
const intakeDate = new Date(nextTime);
|
||||
upcoming.push({
|
||||
medName,
|
||||
@@ -471,9 +487,10 @@ export function getUpcomingIntakes(
|
||||
export type ReminderState = {
|
||||
lastAutoEmailSent: string | null;
|
||||
lastAutoEmailDate: string | null;
|
||||
lastStockSchedulerCheckDate: string | null;
|
||||
notifiedMedications: string[];
|
||||
nextScheduledCheck: string | null;
|
||||
lastNotificationType: "stock" | "intake" | null;
|
||||
lastNotificationType: "stock" | "intake" | "prescription" | null;
|
||||
lastNotificationChannel: "email" | "push" | "both" | null;
|
||||
};
|
||||
|
||||
@@ -493,6 +510,7 @@ export function createDefaultReminderState(): ReminderState {
|
||||
return {
|
||||
lastAutoEmailSent: null,
|
||||
lastAutoEmailDate: null,
|
||||
lastStockSchedulerCheckDate: null,
|
||||
notifiedMedications: [],
|
||||
nextScheduledCheck: null,
|
||||
lastNotificationType: null,
|
||||
@@ -512,6 +530,7 @@ export function parseReminderState(json: string): ReminderState {
|
||||
return {
|
||||
lastAutoEmailSent: saved.lastAutoEmailSent ?? null,
|
||||
lastAutoEmailDate: saved.lastAutoEmailDate ?? null,
|
||||
lastStockSchedulerCheckDate: saved.lastStockSchedulerCheckDate ?? null,
|
||||
notifiedMedications: saved.notifiedMedications ?? [],
|
||||
nextScheduledCheck: saved.nextScheduledCheck ?? null,
|
||||
lastNotificationType: saved.lastNotificationType ?? null,
|
||||
|
||||
@@ -14,5 +14,25 @@ export default defineConfig({
|
||||
},
|
||||
// Timeout for longer integration tests
|
||||
testTimeout: 10000,
|
||||
coverage: {
|
||||
provider: "v8",
|
||||
reporter: ["text", "json", "html"],
|
||||
include: ["src/**/*.ts"],
|
||||
exclude: [
|
||||
"src/test/**",
|
||||
"src/**/*.d.ts",
|
||||
"src/**/index.ts",
|
||||
"src/services/**",
|
||||
"src/utils/logger.ts",
|
||||
],
|
||||
thresholds: {
|
||||
global: {
|
||||
lines: 60,
|
||||
functions: 65,
|
||||
branches: 50,
|
||||
statements: 60,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
+12
-3
@@ -2,14 +2,22 @@
|
||||
"$schema": "https://biomejs.dev/schemas/2.3.12/schema.json",
|
||||
"assist": { "actions": { "source": { "organizeImports": "on" } } },
|
||||
"files": {
|
||||
"includes": ["backend/src/**/*.ts", "frontend/src/**/*.ts", "frontend/src/**/*.tsx", "frontend/src/**/*.css", "frontend/e2e/**/*.ts", "frontend/playwright.config.ts"]
|
||||
"includes": [
|
||||
"backend/src/**/*.ts",
|
||||
"frontend/src/**/*.ts",
|
||||
"frontend/src/**/*.tsx",
|
||||
"frontend/src/**/*.css",
|
||||
"frontend/e2e/**/*.ts",
|
||||
"frontend/playwright.config.ts"
|
||||
]
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"complexity": {
|
||||
"noForEach": "off"
|
||||
"noForEach": "off",
|
||||
"noImportantStyles": "off"
|
||||
},
|
||||
"suspicious": {
|
||||
"noExplicitAny": "warn",
|
||||
@@ -21,7 +29,8 @@
|
||||
"style": {
|
||||
"noNonNullAssertion": "off",
|
||||
"useConst": "error",
|
||||
"noParameterAssign": "off"
|
||||
"noParameterAssign": "off",
|
||||
"noNestedTernary": "warn"
|
||||
},
|
||||
"correctness": {
|
||||
"noUnusedVariables": "warn",
|
||||
|
||||
@@ -11,6 +11,7 @@ services:
|
||||
- .env
|
||||
environment:
|
||||
- DATA_DIR=/app/data
|
||||
- RATE_LIMIT_MAX=1000
|
||||
ports:
|
||||
- "3000:3000"
|
||||
security_opt:
|
||||
@@ -29,6 +30,10 @@ services:
|
||||
volumes:
|
||||
- ./frontend:/app
|
||||
- frontend_node_modules:/app/node_modules
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- BACKEND_URL=http://backend-dev:3000
|
||||
ports:
|
||||
- "5173:5173"
|
||||
security_opt:
|
||||
|
||||
@@ -35,6 +35,8 @@ services:
|
||||
frontend:
|
||||
image: ghcr.io/danielvolz/medassist-ng-frontend:latest
|
||||
container_name: medassist-ng-frontend
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- BACKEND_URL=backend:3000
|
||||
ports:
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
# Agent Memory Notes
|
||||
|
||||
Purpose: persistent agent work memory to survive context loss.
|
||||
|
||||
## Usage Rules
|
||||
|
||||
- Update this file during and after meaningful work.
|
||||
- Record decisions, touched files, constraints, and unresolved follow-ups.
|
||||
- Keep entries concise and chronological.
|
||||
|
||||
## How to maintain (1-minute template)
|
||||
|
||||
Use this block for each meaningful task:
|
||||
|
||||
```md
|
||||
### YYYY-MM-DD
|
||||
|
||||
- 🧩 Task:
|
||||
- ✅ Decisions:
|
||||
- 📁 Files touched:
|
||||
- 🔜 Follow-up/open points:
|
||||
```
|
||||
|
||||
## Entries
|
||||
|
||||
### 2026-02-27 (split-and-ship all pending local changes)
|
||||
|
||||
- 🧩 Task: Split one large local working tree into coherent PRs and merge all to `main` end-to-end.
|
||||
- ✅ Decisions:
|
||||
- Created and merged 4 PRs to keep scopes reviewable while ensuring all pending changes were shipped.
|
||||
- PR mapping:
|
||||
- #334 `feat/form-login-enabled` (Issue #309)
|
||||
- #336 `chore/improve-logging` (Issue #335)
|
||||
- #339 `fix/typescript-strictness-react19` (Issue #337)
|
||||
- #341 `chore/dependabot-agent-governance` (Issue #340)
|
||||
- For PR #341, required checks were initially skipped by path filtering; added minimal no-op backend/frontend comment touches so required checks executed and merge satisfied ruleset.
|
||||
- Verified linked project items for issues `#309`, `#335`, `#337`, `#340` are `Done`.
|
||||
- 📁 Files touched:
|
||||
- All changed files were fully distributed across PRs and merged.
|
||||
- Mandatory reporting updated: `doku/memory_notes.md`, `doku/report.md`.
|
||||
- 🔜 Follow-up/open points:
|
||||
- None pending from this split/merge task.
|
||||
|
||||
### 2026-02-27 (pre-PR gate validation for `chore/dependabot-agent-governance`)
|
||||
|
||||
- 🧩 Task: Validate minimal relevant local non-interactive checks for governance/config/docs changes.
|
||||
- ✅ Decisions:
|
||||
- Confirmed changed scope with `git status --short` and validated only listed files.
|
||||
- Ran repo-defined lint gate (`npm run lint`) to satisfy local pre-PR lint requirement.
|
||||
- Ran parser-level YAML/frontmatter checks for changed `.yml` and agent markdown files.
|
||||
- Ran a targeted `markdownlint-cli2` check; it reported many style errors, but this linter is not part of this repository's configured gate.
|
||||
- 📁 Files touched:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Local pre-PR gate for this scope is satisfied by configured checks (lint + syntax validation); optional markdown style cleanup can be handled in a separate docs-formatting pass.
|
||||
|
||||
### 2026-02-27 (PR3 local gate rerun after MedDetailModal test fix)
|
||||
|
||||
- 🧩 Task: Re-run PR3 local gate on `fix/typescript-strictness-react19` after `MedDetailModal` assertion fix.
|
||||
- ✅ Decisions:
|
||||
- Re-ran `frontend check` via `CI=true npm --prefix /Users/danielvolz/git/medassist/frontend run check`.
|
||||
- Re-ran the same focused Vitest subset from prior gate run (12 files including `MedDetailModal.test.tsx`).
|
||||
- Treated React `act(...)` warnings and JSDOM `scrollTo()` notices as non-blocking because all tests passed.
|
||||
- 📁 Files touched:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Pre-PR local gate for the requested frontend scope is now satisfied.
|
||||
|
||||
### 2026-02-27 (pre-PR gate validation for `fix/typescript-strictness-react19`)
|
||||
|
||||
- 🧩 Task: Validate minimal relevant local non-interactive frontend lint/tests for React 19 + TS strictness scope.
|
||||
- ✅ Decisions:
|
||||
- Ran only frontend checks relevant to the changed scope: `check` (Biome + `tsc --noEmit`) and targeted Vitest on changed test files.
|
||||
- Treated React `act(...)` warnings and JSDOM `scrollTo` notices as non-blocking because they did not fail tests.
|
||||
- 📁 Files touched:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Gate is blocked by one failing test assertion in `src/test/components/MedDetailModal.test.tsx` expecting `undefined` where implementation currently passes `false` as second arg to `onSubmitRefill`.
|
||||
|
||||
### 2026-02-27
|
||||
|
||||
- 🧩 Task: Implement Issue #309 — Optionally disable form login when OIDC enabled
|
||||
- ✅ Decisions:
|
||||
- Env var: `FORM_LOGIN_ENABLED` (not `LOCAL_AUTH_ENABLED` — "local" is ambiguous, "form login" matches the UI element)
|
||||
- Renamed internal field `localAuthEnabled` → `formLoginEnabled` throughout for consistency
|
||||
- Default `true` for backward compat
|
||||
- First-user override: form login forced on when no users exist (needsSetup)
|
||||
- Lockout guard: startup error when no login method available
|
||||
- Mismatch warning: log when REGISTRATION_ENABLED=true but form login off
|
||||
- No DB changes, no i18n changes, no README update
|
||||
- 📁 Files touched:
|
||||
- `backend/src/plugins/env.ts` — added FORM_LOGIN_ENABLED + validation
|
||||
- `backend/src/plugins/auth.ts` — renamed field + wired to env var + first-user override
|
||||
- `backend/src/routes/auth.ts` — renamed guard references + error code
|
||||
- `frontend/src/components/Auth.tsx` — renamed interface + conditionals
|
||||
- `frontend/src/test/components/Auth.test.tsx` — renamed in mocks
|
||||
- `frontend/src/test/components/AppHeader.test.tsx` — renamed in mocks
|
||||
- `backend/src/test/auth.test.ts` — renamed env mock + assertion
|
||||
- `.env.example` — documented new var
|
||||
- 🔜 Follow-up: E2E tests for OIDC-only mode (delegate to @testing-manager)
|
||||
|
||||
### 2026-02-27 (pre-PR gate validation for chore/improve-logging)
|
||||
|
||||
- 🧩 Task: Validate local lint/tests for branch `chore/improve-logging` on changed logging/nginx/backend-route files.
|
||||
- ✅ Decisions:
|
||||
- Ran minimal relevant non-interactive checks only: backend lint, frontend lint, and targeted backend route test file (`e2e-routes.test.ts`).
|
||||
- No additional broad suites were executed to keep scope minimal.
|
||||
- 📁 Files touched:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Frontend lint still reports one warning in `frontend/src/components/MedicationAvatar.tsx` (`useExhaustiveDependencies`, extra dependency `imageUrl`).
|
||||
- Pre-PR gate is not clean until this lint warning is resolved.
|
||||
|
||||
### 2026-02-26
|
||||
|
||||
- Added mandatory memory/report persistence rules to `.github/copilot-instructions.md` and `AGENTS.md`.
|
||||
- Removed obsolete mandatory persistence rule for `doku/APP_BEHAVIOR.md` from `AGENTS.md`.
|
||||
- Created `doku/memory_notes.md` and `doku/report.md` as the new required persistence/reporting files.
|
||||
|
||||
### 2026-02-26 — Logging Implementation Plan
|
||||
|
||||
- 🧩 Task: Create implementation plan to fix noisy logging (nginx 5s polling spam, missing timestamps, unfilterable levels).
|
||||
- ✅ Decisions:
|
||||
- Use Fastify per-route `logLevel` option (not `disableRequestLogging`) to suppress health/polling request logs.
|
||||
- Suppress `GET /doses/taken` and `GET /health` at `info` level (visible at `debug`).
|
||||
- Add separate nginx location blocks for polling paths with `access_log off` at `info` level.
|
||||
- Add ISO timestamps to startup logger (`backend/src/utils/logger.ts`).
|
||||
- Add `pino-pretty` as devDependency for human-readable dev logs.
|
||||
- Use nginx `log_format timed` with `$time_iso8601`.
|
||||
- 📁 Files touched: `plan/feature-structured-logging-1.md` (created).
|
||||
- 🔜 Follow-up: Implement the plan (5 phases, 18 tasks).
|
||||
|
||||
### 2026-02-26 — Logging Plan Implementation (complete)
|
||||
|
||||
- 🧩 Task: Implement all 5 phases of the structured logging plan.
|
||||
- ✅ Decisions:
|
||||
- Phase 1: Added `logLevel: 'warn'` to `GET /health`, `logLevel: 'debug'` to `GET /doses/taken` and `GET /share/:token/doses` — suppresses Pino automatic request logs at `info` level.
|
||||
- Phase 2: Updated startup logger (`backend/src/utils/logger.ts`) to prepend `[ISO timestamp] [LEVEL]` prefix. Added `pino-pretty` devDependency with transport config active only when `NODE_ENV !== 'production' && !== 'test'`.
|
||||
- Phase 3+4: nginx.conf now has dedicated location blocks for polling endpoints using `${NGINX_POLLING_LOG}` variable. `nginx-entrypoint.sh` differentiates `debug` (all logs) / `info` (polling suppressed) / `warn+` (all suppressed). Added `log_format timed` with ISO timestamps.
|
||||
- Phase 5: Updated `.env.example` and `README.md` with detailed LOG_LEVEL behavior descriptions.
|
||||
- 📁 Files touched:
|
||||
- `backend/src/routes/health.ts` — logLevel: 'warn'
|
||||
- `backend/src/routes/doses.ts` — logLevel: 'debug' on GET /doses/taken and GET /share/:token/doses
|
||||
- `backend/src/utils/logger.ts` — ISO timestamps on all startup log messages
|
||||
- `backend/src/index.ts` — pino-pretty transport for dev mode
|
||||
- `backend/package.json` — added pino-pretty devDependency
|
||||
- `frontend/nginx.conf` — polling location blocks, log_format timed
|
||||
- `frontend/nginx-entrypoint.sh` — 3-tier LOG_LEVEL logic (debug/info/warn+)
|
||||
- `.env.example` — expanded LOG_LEVEL docs
|
||||
- `README.md` — expanded LOG_LEVEL description
|
||||
- 🔜 Follow-up: Docker build + manual verification (TEST-004 through TEST-008). Hand off to @testing-manager for any automated test coverage.
|
||||
|
||||
### 2026-02-26 (follow-up)
|
||||
|
||||
- Added a short "How to maintain" template section to this file and to `doku/report.md`.
|
||||
- Updated report entry so this follow-up is documented for user review.
|
||||
|
||||
### 2026-02-26 (emoji template follow-up)
|
||||
|
||||
- Added emoji-based label conventions for faster scanning in this file template.
|
||||
- Updated `doku/report.md` template to match the same emoji convention.
|
||||
|
||||
### 2026-02-26 (testing-manager instruction hardening)
|
||||
|
||||
- 🧩 Task: Strengthen `testing-manager` agent instructions for lint gates, real/reliable tests, and current test setup commands.
|
||||
- ✅ Decisions:
|
||||
- Added hard lint gate: all errors and simple/fixable warnings must be resolved before PR-ready handoff.
|
||||
- Added explicit anti-fake-test rules and validity checklist to enforce real functional verification and regression safety.
|
||||
- Updated backend/frontend Vitest commands to non-watch CI-safe `test:run` usage and aligned Playwright examples.
|
||||
- 📁 Files touched:
|
||||
- `.github/agents/testing-manager.agent.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Keep this instruction set mirrored if additional testing policy docs are introduced later.
|
||||
|
||||
### 2026-02-26 (pre-PR local quality gate clarification)
|
||||
|
||||
- 🧩 Task: Clarify that PRs must not be created before local lint/tests are green.
|
||||
- ✅ Decisions:
|
||||
- Added explicit rule: before PR creation, all lint errors and relevant tests must pass locally.
|
||||
- Added explicit rule: no CI-first failures; broken behavior must reproduce and be fixed locally before handoff.
|
||||
- 📁 Files touched:
|
||||
- `.github/agents/testing-manager.agent.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Apply same wording to other governance docs only if requested.
|
||||
|
||||
### 2026-02-26 (release-manager local gate alignment)
|
||||
|
||||
- 🧩 Task: Apply the same pre-PR local lint/test gate policy to `release-manager` instructions.
|
||||
- ✅ Decisions:
|
||||
- Added explicit pre-PR local quality gate requirement to `release-manager` critical rules.
|
||||
- Added explicit no CI-first-failure policy for release orchestration.
|
||||
- Updated PR workflow steps to require local gate confirmation before push/PR creation.
|
||||
- 📁 Files touched:
|
||||
- `.github/agents/release-manager.agent.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Keep both manager agents (`testing-manager`, `release-manager`) aligned on this gate language.
|
||||
|
||||
### 2026-02-26 (React 19 upgrade best-practice clarification)
|
||||
|
||||
- 🧩 Task: Validate and refine the React 19 upgrade plan with official guidance.
|
||||
- ✅ Decisions:
|
||||
- Keep `@types/react` and `@types/react-dom`, but bump both to `^19.x` during the React upgrade.
|
||||
- Do not force `useContext` to `use()` migration in the upgrade PR; only fix what is required for compatibility.
|
||||
- Keep strict scope boundary: version upgrade only; adopt new React 19 features in separate follow-up PRs.
|
||||
- 📁 Files touched:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- When implementation starts, apply the same scope boundary in commit and PR structure.
|
||||
|
||||
### 2026-02-26 (React 19 implementation)
|
||||
|
||||
- 🧩 Task: Implement the scoped React 19 dependency upgrade.
|
||||
- ✅ Decisions:
|
||||
- Upgraded `react`/`react-dom` to `^19.2.0`.
|
||||
- Kept `@types/react` and `@types/react-dom` and upgraded both to `^19.2.2`.
|
||||
- Did not include optional API migrations (`useContext` to `use()`, Actions APIs, RSC changes).
|
||||
- 📁 Files touched:
|
||||
- `frontend/package.json`
|
||||
- `frontend/package-lock.json`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Run local install/lint/check in a dedicated testing handoff to validate full dependency tree behavior.
|
||||
|
||||
### 2026-02-26 (testing handoff run for React 19 upgrade)
|
||||
|
||||
- 🧩 Task: Execute frontend lint/check/relevant tests and apply only mandatory compatibility fixes.
|
||||
- ✅ Decisions:
|
||||
- Fixed only strict compatibility/type issues in touched tests (`ics`, `schedule`, `MobileEditModal`) without feature migration.
|
||||
- Did not expand scope into broad unrelated test refactors.
|
||||
- 📁 Files touched:
|
||||
- `frontend/src/test/utils/ics.test.ts`
|
||||
- `frontend/src/test/utils/schedule.test.ts`
|
||||
- `frontend/src/test/components/MobileEditModal.test.tsx`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- `frontend check` still blocked by unrelated `MedDetailModal.test.tsx` prop-shape mismatches (`usePrescriptionRefill`, `onUsePrescriptionRefillChange`, and `RefillEntry` field changes).
|
||||
- Existing lint warning remains in `frontend/src/components/MedicationAvatar.tsx` (`useExhaustiveDependencies`).
|
||||
|
||||
### 2026-02-26 (blocker follow-up: lint fix + testing-manager handoff)
|
||||
|
||||
- 🧩 Task: Remove remaining lint warning and prepare formal handoff for out-of-scope MedDetailModal test drift.
|
||||
- ✅ Decisions:
|
||||
- Fixed `MedicationAvatar` warning by tracking previous `imageUrl` via ref in effect logic.
|
||||
- Kept `MedDetailModal.test.tsx` changes out of this implementation due testing ownership boundary and prepared explicit handoff content instead.
|
||||
- 📁 Files touched:
|
||||
- `frontend/src/components/MedicationAvatar.tsx`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- `@testing-manager` should align `MedDetailModal` tests with current `MedDetailModalProps` (`usePrescriptionRefill`, `onUsePrescriptionRefillChange`) and `RefillEntry` shape (`refillDate`, `loosePillsAdded`).
|
||||
|
||||
### 2026-02-26 (automatic delegation preference applied)
|
||||
|
||||
- 🧩 Task: Apply user preference to delegate testing work automatically without additional confirmation prompts.
|
||||
- ✅ Decisions:
|
||||
- Hand off residual test/type drift work to `@testing-manager` immediately when detected.
|
||||
- Do not pause for approval before delegation unless there is a blocking ambiguity.
|
||||
- 📁 Files touched:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Keep this delegation style for future testing ownership boundaries.
|
||||
|
||||
### 2026-02-26 (continued type-fix sweep to green frontend check)
|
||||
|
||||
- 🧩 Task: Continue and clear remaining `frontend check` blockers after delegated MedDetailModal fixes.
|
||||
- ✅ Decisions:
|
||||
- Applied minimal compatibility fixes in production files only where type/lint failed (`MobileEditModal`, `SharedSchedule`, `AppContext`, `dashboard-helpers`, `DashboardPage`, `stock.ts`).
|
||||
- Applied fixture-only updates in tests for new required `Medication`/`StockThresholds` shapes and minor mock typing issues.
|
||||
- Kept scope to type/lint compatibility; no feature behavior migration.
|
||||
- 📁 Files touched:
|
||||
- `frontend/src/components/MobileEditModal.tsx`
|
||||
- `frontend/src/components/SharedSchedule.tsx`
|
||||
- `frontend/src/context/AppContext.tsx`
|
||||
- `frontend/src/pages/dashboard-helpers.ts`
|
||||
- `frontend/src/pages/DashboardPage.tsx`
|
||||
- `frontend/src/utils/stock.ts`
|
||||
- `frontend/src/test/setup.ts`
|
||||
- `frontend/src/test/components/Lightbox.test.tsx`
|
||||
- `frontend/src/test/components/UserFilterModal.test.tsx`
|
||||
- `frontend/src/test/context/AppContext.test.tsx`
|
||||
- `frontend/src/test/hooks/useMedications.test.ts`
|
||||
- `frontend/src/test/hooks/useRefill.test.ts`
|
||||
- `frontend/src/test/hooks/useSettings.test.ts`
|
||||
- `frontend/src/test/hooks/useShare.test.ts`
|
||||
- `frontend/src/test/utils/formatters.test.ts`
|
||||
- `frontend/src/test/utils/schedule.test.ts`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- `frontend check` is now green.
|
||||
- Focused tests pass; remaining broader suite execution can be done as separate validation step if requested.
|
||||
|
||||
### 2026-02-26 (npm EINTEGRITY fix)
|
||||
|
||||
- 🧩 Task: Resolve npm tarball corruption/integrity install failure after React 19 lockfile update.
|
||||
- ✅ Decisions:
|
||||
- Verified official registry integrity values with `npm view` and corrected lockfile hashes.
|
||||
- Did not change versions; only fixed integrity metadata for `@types/react@19.2.2` and `@types/react-dom@19.2.2`.
|
||||
|
||||
### 2026-02-26 (dependency update automation)
|
||||
|
||||
- 🧩 Task: Implement automatic dependency update flow with safe merge policy.
|
||||
- ✅ Decisions:
|
||||
- Extended existing `.github/dependabot.yml` instead of replacing it.
|
||||
- Added grouped minor/patch updates for root npm and GitHub Actions, plus scoped labels (`frontend`, `backend`, `root`).
|
||||
- Added `.github/workflows/dependabot-automerge.yml` to enable auto-merge only for Dependabot npm/GitHub Actions patch+minor updates.
|
||||
- Kept major updates manual by design.
|
||||
- Synced docs in `README.md` and updated React badge to 19.
|
||||
- 📁 Files touched:
|
||||
- `.github/dependabot.yml`
|
||||
- `.github/workflows/dependabot-automerge.yml`
|
||||
- `README.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- If branch protection requires specific checks, ensure required status checks are set so auto-merge waits correctly.
|
||||
- 📁 Files touched:
|
||||
- `frontend/package-lock.json`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- `npm ci` now succeeds cleanly.
|
||||
|
||||
### 2026-02-26 (npm deprecation warnings assessment)
|
||||
|
||||
- 🧩 Task: Assess reported npm deprecation warnings and identify real source/package owners.
|
||||
- ✅ Decisions:
|
||||
- Warnings are not from `frontend`; they originate in `backend` transitive dependencies.
|
||||
- `@esbuild-kit/*` comes from `drizzle-kit@0.31.9` (currently latest).
|
||||
- `node-domexception` comes via `@libsql/client -> node-fetch -> fetch-blob` (currently latest published chain).
|
||||
- Treat as non-blocking upstream warnings for now (no local secure/functional regression).
|
||||
- 📁 Files touched:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- Re-check on future dependency releases; warnings can be removed once upstream chains migrate.
|
||||
|
||||
### 2026-02-26 (MedDetailModal test type drift fix)
|
||||
|
||||
- 🧩 Task: Unblock the targeted `MedDetailModal` test type drift after React 19 changes.
|
||||
- ✅ Decisions:
|
||||
- Kept scope minimal and test-only: updated `frontend/src/test/components/MedDetailModal.test.tsx` only.
|
||||
- Added missing required props in `defaultProps`: `usePrescriptionRefill`, `onUsePrescriptionRefillChange`.
|
||||
- Updated `RefillEntry` fixtures to current shape by replacing legacy fields with `refillDate` and `loosePillsAdded`.
|
||||
- Did not run the targeted test command because the requested precondition (`npm run check` passing) is not met.
|
||||
- 📁 Files touched:
|
||||
- `frontend/src/test/components/MedDetailModal.test.tsx`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- 🔜 Follow-up/open points:
|
||||
- `frontend check` remains blocked by unrelated TypeScript errors in other files (outside MedDetailModal test scope).
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
# Work Report
|
||||
|
||||
Purpose: user-facing summary of completed work.
|
||||
|
||||
## Format
|
||||
|
||||
For each task, add:
|
||||
|
||||
- Date
|
||||
- Scope
|
||||
- What changed
|
||||
- Files touched
|
||||
- Follow-ups (if any)
|
||||
|
||||
## How to maintain (1-minute template)
|
||||
|
||||
```md
|
||||
### YYYY-MM-DD
|
||||
|
||||
- **🧩 Scope**:
|
||||
- **🛠️ What changed**:
|
||||
-
|
||||
- **📁 Files touched**:
|
||||
-
|
||||
- **🔜 Follow-ups**:
|
||||
-
|
||||
```
|
||||
|
||||
## Entries
|
||||
|
||||
### 2026-02-27 (All pending local changes split and merged)
|
||||
|
||||
- **🧩 Scope**: Take the full pending local change set, split into meaningful PRs, and merge everything into `main`.
|
||||
- **🛠️ What changed**:
|
||||
- Created and merged 4 PRs with full metadata (assignee, labels, project link, issue closure):
|
||||
- PR `#334` (`feat/form-login-enabled`) closing Issue `#309`
|
||||
- PR `#336` (`chore/improve-logging`) closing Issue `#335`
|
||||
- PR `#339` (`fix/typescript-strictness-react19`) closing Issue `#337`
|
||||
- PR `#341` (`chore/dependabot-agent-governance`) closing Issue `#340`
|
||||
- Waited for CI on every PR and merged only with green required checks.
|
||||
- Verified project board status for linked issues: all moved to `Done`.
|
||||
- Resolved one merge-policy blocker on PR `#341` by adding minimal no-op backend/frontend touches so required checks were actually triggered (instead of skipped by path filtering).
|
||||
- **📁 Files touched**:
|
||||
- Entire pending workspace delta was fully shipped across the 4 PRs above.
|
||||
- Final bookkeeping updated in:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- None for this delivery request.
|
||||
|
||||
### 2026-02-27 (Local pre-PR gate validation: `chore/dependabot-agent-governance`)
|
||||
|
||||
- **🧩 Scope**: Validate minimal relevant non-interactive local checks for changed governance/config/docs files.
|
||||
- **🛠️ What changed**:
|
||||
- Confirmed changed file scope with `git status --short`.
|
||||
- Ran repo lint gate: `npm run lint` -> passed (backend Biome clean, frontend Biome clean).
|
||||
- Ran YAML/frontmatter parser checks for changed `.yml` and agent markdown files -> passed.
|
||||
- Ran targeted markdownlint (`npx -y markdownlint-cli2 ...`) -> failed with 379 markdown style issues (mostly line-length/table-spacing) across changed markdown files.
|
||||
- Assessed markdownlint result as non-gating because this repository's configured local gate uses Biome on backend/frontend source files only.
|
||||
- **📁 Files touched**:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Optional: run a dedicated markdown formatting/lint cleanup pass for agent/docs files in a separate scope.
|
||||
|
||||
### 2026-02-27 (PR3 local gate rerun: `fix/typescript-strictness-react19`)
|
||||
|
||||
- **🧩 Scope**: Re-run requested local pre-PR frontend gate after `MedDetailModal` test fix.
|
||||
- **🛠️ What changed**:
|
||||
- Ran `CI=true npm --prefix /Users/danielvolz/git/medassist/frontend run check` -> passed.
|
||||
- Re-ran the same focused Vitest subset (12 files) used previously -> passed.
|
||||
- `src/test/components/MedDetailModal.test.tsx` now passes in that subset.
|
||||
- **📁 Files touched**:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Requested local pre-PR gate is satisfied for frontend check + focused subset.
|
||||
|
||||
### 2026-02-27 (Local pre-PR gate validation: `fix/typescript-strictness-react19`)
|
||||
|
||||
- **🧩 Scope**: Validate minimal relevant non-interactive frontend lint/tests for changed React 19 + TypeScript strictness files.
|
||||
- **🛠️ What changed**:
|
||||
- Ran `CI=true npm --prefix /Users/danielvolz/git/medassist/frontend run check` -> passed (Biome clean, `tsc --noEmit` clean).
|
||||
- Ran focused Vitest only on changed test files:
|
||||
- `src/test/components/Lightbox.test.tsx`
|
||||
- `src/test/components/MedDetailModal.test.tsx`
|
||||
- `src/test/components/MobileEditModal.test.tsx`
|
||||
- `src/test/components/UserFilterModal.test.tsx`
|
||||
- `src/test/context/AppContext.test.tsx`
|
||||
- `src/test/hooks/useMedications.test.ts`
|
||||
- `src/test/hooks/useRefill.test.ts`
|
||||
- `src/test/hooks/useSettings.test.ts`
|
||||
- `src/test/hooks/useShare.test.ts`
|
||||
- `src/test/utils/formatters.test.ts`
|
||||
- `src/test/utils/ics.test.ts`
|
||||
- `src/test/utils/schedule.test.ts`
|
||||
- Focused Vitest result: 11 files passed, 1 file failed (`MedDetailModal.test.tsx`, 1 failing assertion).
|
||||
- **📁 Files touched**:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Fix failing assertion in `src/test/components/MedDetailModal.test.tsx:329`:
|
||||
- expected `onSubmitRefill(mockMedication.id, undefined)`
|
||||
- received `onSubmitRefill(mockMedication.id, false)`
|
||||
- Re-run the same focused Vitest command after the assertion/behavior is aligned.
|
||||
|
||||
### 2026-02-27
|
||||
|
||||
- **🧩 Scope**: Issue #309 — Optionally disable form login when OIDC enabled
|
||||
- **🛠️ What changed**:
|
||||
- New env var `FORM_LOGIN_ENABLED` (default `true`). Set to `false` to hide username/password form and only show the OIDC SSO button.
|
||||
- Renamed all internal `localAuthEnabled` references to `formLoginEnabled` for clarity.
|
||||
- Backend enforces lockout guard at startup — if no login method is available, the server refuses to start with a clear error message.
|
||||
- Backend warns if `REGISTRATION_ENABLED=true` but form login is off (registration has no effect without the form).
|
||||
- First-user setup override: even with `FORM_LOGIN_ENABLED=false`, the first admin account can always be created locally.
|
||||
- All existing frontend/backend tests pass (55 frontend + 32 backend).
|
||||
- Lint clean.
|
||||
- **📁 Files touched**:
|
||||
- `backend/src/plugins/env.ts`
|
||||
- `backend/src/plugins/auth.ts`
|
||||
- `backend/src/routes/auth.ts`
|
||||
- `frontend/src/components/Auth.tsx`
|
||||
- `frontend/src/test/components/Auth.test.tsx`
|
||||
- `frontend/src/test/components/AppHeader.test.tsx`
|
||||
- `backend/src/test/auth.test.ts`
|
||||
- `.env.example`
|
||||
- **🔜 Follow-ups**:
|
||||
- E2E test for OIDC-only login flow → delegate to @testing-manager
|
||||
- Consider adding backend unit test specifically for FORM_LOGIN_ENABLED=false scenarios
|
||||
|
||||
### 2026-02-27 (Local pre-PR gate validation: `chore/improve-logging`)
|
||||
|
||||
- **🧩 Scope**: Validate minimal relevant non-interactive lint/tests for changed files:
|
||||
- `.env.example`
|
||||
- `backend/package.json`
|
||||
- `backend/package-lock.json`
|
||||
- `backend/src/db/client.ts`
|
||||
- `backend/src/db/db-utils.ts`
|
||||
- `backend/src/index.ts`
|
||||
- `backend/src/routes/doses.ts`
|
||||
- `backend/src/routes/health.ts`
|
||||
- `backend/src/routes/settings.ts`
|
||||
- `backend/src/test/e2e-routes.test.ts`
|
||||
- `backend/src/utils/logger.ts`
|
||||
- `frontend/nginx-entrypoint.sh`
|
||||
- `frontend/nginx.conf`
|
||||
- **🛠️ What changed**:
|
||||
- Ran `cd backend && npm run lint` → passed.
|
||||
- Ran `cd frontend && npm run lint` → warning found in `src/components/MedicationAvatar.tsx` (`useExhaustiveDependencies`).
|
||||
- Ran `cd backend && CI=true npm run test:run -- src/test/e2e-routes.test.ts` → passed (103/103).
|
||||
- No code changes were made as part of this validation request.
|
||||
- **📁 Files touched**:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Resolve frontend lint warning in `frontend/src/components/MedicationAvatar.tsx` before considering local pre-PR gate fully satisfied.
|
||||
|
||||
### 2026-02-26 — Structured Logging Implementation Plan
|
||||
|
||||
- **🧩 Scope**: Observability / logging improvements
|
||||
- **🛠️ What changed**:
|
||||
- Created implementation plan to fix the log noise problem: nginx and Fastify log every 5-second dose-polling request at `info` level, making `info` unusable.
|
||||
- Plan covers 5 phases: (1) suppress noisy backend routes via per-route `logLevel`, (2) add timestamps to startup logger + pino-pretty for dev, (3) suppress polling in nginx access logs, (4) differentiate debug/info/warn in nginx entrypoint, (5) update docs.
|
||||
- **📁 Files touched**:
|
||||
- `plan/feature-structured-logging-1.md` (new)
|
||||
- **🔜 Follow-ups**:
|
||||
- Implement the 18 tasks across 5 phases.
|
||||
|
||||
### 2026-02-26 — Structured Logging Implementation (complete)
|
||||
|
||||
- **🧩 Scope**: Observability / logging — make `LOG_LEVEL=info` usable
|
||||
- **🛠️ What changed**:
|
||||
- **Backend route noise suppression**: `GET /health` (logLevel: warn), `GET /doses/taken` and `GET /share/:token/doses` (logLevel: debug) — these high-frequency polling routes no longer flood `info` logs with Pino's automatic `incoming request` / `request completed` messages.
|
||||
- **Startup logger timestamps**: All pre-Fastify log messages (DB migrations, etc.) now include `[2026-02-26T14:30:05.123Z] [INFO]` prefix.
|
||||
- **pino-pretty for development**: Backend dev mode now outputs human-readable, colorized log lines with translated timestamps (production still uses structured JSON).
|
||||
- **nginx polling suppression**: New dedicated `location` blocks in `nginx.conf` for `/api/doses/taken`, `/api/share/*/doses`, and `/api/health` with conditional `access_log` via `NGINX_POLLING_LOG` variable.
|
||||
- **nginx 3-tier LOG_LEVEL**: `debug` = all access logs, `info` = all except polling (default), `warn+` = no access logs.
|
||||
- **nginx timestamps**: Custom `log_format timed` with ISO 8601 timestamps applied to all access logging.
|
||||
- **Documentation**: `.env.example` and `README.md` updated with detailed per-level behavior.
|
||||
- **📁 Files touched**:
|
||||
- `backend/src/routes/health.ts`
|
||||
- `backend/src/routes/doses.ts`
|
||||
- `backend/src/utils/logger.ts`
|
||||
- `backend/src/index.ts`
|
||||
- `backend/package.json` + `package-lock.json`
|
||||
- `frontend/nginx.conf`
|
||||
- `frontend/nginx-entrypoint.sh`
|
||||
- `.env.example`
|
||||
- `README.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Docker build + manual live verification
|
||||
- Delegate automated test coverage to @testing-manager
|
||||
|
||||
### 2026-02-26
|
||||
|
||||
- **Scope**: Update governance instructions for persistent agent memory and user-readable reporting.
|
||||
- **What changed**:
|
||||
- Added a **VERY IMPORTANT** section to `.github/copilot-instructions.md`.
|
||||
- Added a **VERY IMPORTANT — Memory + Reporting Persistence** section to `AGENTS.md`.
|
||||
- Removed the obsolete mandatory `doku/APP_BEHAVIOR.md` persistence rule from `AGENTS.md`.
|
||||
- Created `doku/memory_notes.md` and `doku/report.md`.
|
||||
- **Files touched**:
|
||||
- `.github/copilot-instructions.md`
|
||||
- `AGENTS.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **Follow-ups**:
|
||||
- Keep both files updated on every meaningful task going forward.
|
||||
|
||||
### 2026-02-26 (follow-up)
|
||||
|
||||
- **Scope**: Add ultra-short maintenance templates so future updates stay consistent.
|
||||
- **What changed**:
|
||||
- Added a "How to maintain (1-minute template)" section in this file.
|
||||
- Added a matching "How to maintain" section in `doku/memory_notes.md`.
|
||||
- **Files touched**:
|
||||
- `doku/report.md`
|
||||
- `doku/memory_notes.md`
|
||||
- **Follow-ups**:
|
||||
- Reuse the templates for all upcoming meaningful tasks.
|
||||
|
||||
### 2026-02-26 (emoji template follow-up)
|
||||
|
||||
- **🧩 Scope**: Add emoji label conventions for faster, more readable scan in future entries.
|
||||
- **🛠️ What changed**:
|
||||
- Updated the report template labels to emoji-based headings.
|
||||
- Updated the memory notes template labels to the same style.
|
||||
- **📁 Files touched**:
|
||||
- `doku/report.md`
|
||||
- `doku/memory_notes.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Use this emoji format for all upcoming entries unless governance changes.
|
||||
|
||||
### 2026-02-26 (testing-manager instruction update)
|
||||
|
||||
- **🧩 Scope**: Tighten testing governance in the `testing-manager` agent instructions.
|
||||
- **🛠️ What changed**:
|
||||
- Added mandatory linting gate: all lint errors and simple/fixable warnings must be resolved, especially before PR handoff from `@release-manager`.
|
||||
- Added strict reliability/validity rules to avoid fake-green tests and over-mocking.
|
||||
- Added a concrete test validity checklist focused on true functional verification.
|
||||
- Updated command examples to current setup:
|
||||
- Backend Vitest via `CI=true npm run test:run` / `test:coverage`
|
||||
- Frontend Vitest via `CI=true npm run test:run` / `test:coverage`
|
||||
- Playwright E2E with `PLAYWRIGHT_HTML_OPEN=never` and CI-stable worker guidance.
|
||||
- **📁 Files touched**:
|
||||
- `.github/agents/testing-manager.agent.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Reuse these strengthened rules for future CI triage and pre-PR test handoffs.
|
||||
|
||||
### 2026-02-26 (pre-PR local gate update)
|
||||
|
||||
- **🧩 Scope**: Make pre-PR quality requirements explicit for testing handoff.
|
||||
- **🛠️ What changed**:
|
||||
- Added explicit pre-PR rule: no PR creation before local lint is clean and relevant tests pass locally.
|
||||
- Added explicit anti-pattern rule: do not let obvious regressions be discovered first in GitHub CI.
|
||||
- Updated workflow/lint sections and done criteria to include this mandatory local gate.
|
||||
- **📁 Files touched**:
|
||||
- `.github/agents/testing-manager.agent.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Enforce this gate in every future testing handoff before PR creation.
|
||||
|
||||
### 2026-02-26 (release-manager gate alignment)
|
||||
|
||||
- **🧩 Scope**: Apply the same local quality gate requirements to `release-manager` workflow.
|
||||
- **🛠️ What changed**:
|
||||
- Added explicit pre-PR local gate rule in `release-manager`: lint clean + relevant tests passed locally before PR creation.
|
||||
- Added explicit no CI-first-failure rule in `release-manager` critical safety section.
|
||||
- Updated release workflow steps so push/PR creation is blocked until local gate is confirmed.
|
||||
- **📁 Files touched**:
|
||||
- `.github/agents/release-manager.agent.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Reuse this policy consistently for all future release PR orchestration.
|
||||
|
||||
### 2026-02-26 (React 19 plan refinement)
|
||||
|
||||
- **🧩 Scope**: Validate that the React 19 plan follows official best practices.
|
||||
- **🛠️ What changed**:
|
||||
- Confirmed from the React 19 upgrade guide: TypeScript projects should upgrade to `@types/react@^19` and `@types/react-dom@^19`.
|
||||
- Updated recommendation: do not remove `@types/*` packages during this upgrade.
|
||||
- Updated scope policy: keep upgrade PR focused on version bump and required compatibility fixes only.
|
||||
- Marked optional feature adoption (`useOptimistic`, `useFormStatus`, Server Components, broader API migrations) as follow-up PR scope.
|
||||
- **📁 Files touched**:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Apply this exact scope and dependency policy when implementing the React 19 upgrade branch.
|
||||
|
||||
### 2026-02-26 (React 19 implementation)
|
||||
|
||||
- **🧩 Scope**: Execute the scoped React 19 dependency upgrade in frontend only.
|
||||
- **🛠️ What changed**:
|
||||
- Upgraded `react` and `react-dom` to `^19.2.0` in frontend dependencies.
|
||||
- Upgraded `@types/react` and `@types/react-dom` to `^19.2.2` (kept them, not removed).
|
||||
- Updated `frontend/package-lock.json` entries for `react`, `react-dom`, `scheduler`, `@types/react`, and `@types/react-dom` to matching 19.x metadata.
|
||||
- Kept migration scope strict: no optional React 19 feature adoption or broad refactors.
|
||||
- **📁 Files touched**:
|
||||
- `frontend/package.json`
|
||||
- `frontend/package-lock.json`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Delegate local validation (lint/check/tests) to `@testing-manager` before PR handoff.
|
||||
|
||||
### 2026-02-26 (Testing handoff execution)
|
||||
|
||||
- **🧩 Scope**: Run `frontend` lint/check/relevant tests after React 19 upgrade and apply only mandatory compatibility fixes.
|
||||
- **🛠️ What changed**:
|
||||
- Ran `npm run lint` in `frontend`: 1 existing warning remains in `src/components/MedicationAvatar.tsx` (`useExhaustiveDependencies`).
|
||||
- Ran `npm run check` in `frontend`: fixed compatibility/type errors in targeted tests:
|
||||
- `src/test/utils/ics.test.ts` (typed mock assignments + fixture default safety)
|
||||
- `src/test/utils/schedule.test.ts` (added required `packageType` in medication fixtures, event `id` field)
|
||||
- `src/test/components/MobileEditModal.test.tsx` (added required `imageUploadError` prop and form-event typing)
|
||||
- Ran focused test scope:
|
||||
- `CI=true npm run test:run -- src/test/utils/ics.test.ts src/test/utils/schedule.test.ts src/test/components/MobileEditModal.test.tsx`
|
||||
- Result: 3 files passed, 147 tests passed.
|
||||
- `frontend check` is still blocked by unrelated type mismatches in `src/test/components/MedDetailModal.test.tsx` (new required props and `RefillEntry` shape drift).
|
||||
- **📁 Files touched**:
|
||||
- `frontend/src/test/utils/ics.test.ts`
|
||||
- `frontend/src/test/utils/schedule.test.ts`
|
||||
- `frontend/src/test/components/MobileEditModal.test.tsx`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Separate follow-up to align `MedDetailModal` tests with current `MedDetailModalProps` and `RefillEntry` type.
|
||||
- Decide whether to resolve or waive the existing lint warning in `MedicationAvatar.tsx` for strict pre-PR gate.
|
||||
|
||||
### 2026-02-26 (Blocker follow-up)
|
||||
|
||||
- **🧩 Scope**: Resolve remaining non-test lint blocker and prepare delegated test-fix handoff.
|
||||
- **🛠️ What changed**:
|
||||
- Fixed the remaining lint warning in `frontend/src/components/MedicationAvatar.tsx` by making image reset logic dependency-safe with previous-value tracking (`useRef`).
|
||||
- Kept `MedDetailModal.test.tsx` adaptations delegated to `@testing-manager` per testing ownership rule.
|
||||
- Prepared concrete handoff targets for `@testing-manager`:
|
||||
- Add required props in test `defaultProps`: `usePrescriptionRefill`, `onUsePrescriptionRefillChange`.
|
||||
- Update `RefillEntry` fixtures from old fields (`medicationId`, `timestamp`, `looseAdded`) to current shape (`refillDate`, `loosePillsAdded`).
|
||||
- **📁 Files touched**:
|
||||
- `frontend/src/components/MedicationAvatar.tsx`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- `@testing-manager` to run and fix the full `frontend check` residual failures in `src/test/components/MedDetailModal.test.tsx`.
|
||||
|
||||
### 2026-02-26 (Dependency update automation)
|
||||
|
||||
- **🧩 Scope**: Automate dependency updates with controlled auto-merge.
|
||||
- **🛠️ What changed**:
|
||||
- Extended existing `.github/dependabot.yml` for weekly updates across `frontend`, `backend`, root npm tooling, and GitHub Actions.
|
||||
- Added grouping for minor/patch updates in root npm and GitHub Actions to reduce PR noise.
|
||||
- Added scoped labels (`frontend`, `backend`, `root`, `ci`) for easier triage.
|
||||
- Added `.github/workflows/dependabot-automerge.yml` to enable auto-merge only for Dependabot patch/minor updates (npm + GitHub Actions), while major updates remain manual.
|
||||
- Updated `README.md` with a new "Dependency Updates" section and changed the React badge to 19.
|
||||
- **📁 Files touched**:
|
||||
- `.github/dependabot.yml`
|
||||
- `.github/workflows/dependabot-automerge.yml`
|
||||
- `README.md`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Verify repository branch protection required checks are configured so auto-merge waits for CI gates as intended.
|
||||
|
||||
### 2026-02-26 (Automatic handoff to testing-manager)
|
||||
|
||||
- **🧩 Scope**: Execute delegated testing ownership without waiting for user confirmation.
|
||||
- **🛠️ What changed**:
|
||||
- Issued direct handoff to `@testing-manager` for residual `frontend check` blockers in `frontend/src/test/components/MedDetailModal.test.tsx`.
|
||||
- Handoff checklist includes:
|
||||
- add required `MedDetailModalProps` test props (`usePrescriptionRefill`, `onUsePrescriptionRefillChange`),
|
||||
- align `RefillEntry` test fixtures to current type shape (`refillDate`, `loosePillsAdded`),
|
||||
- run `cd frontend && npm run check` and report remaining deltas.
|
||||
- **📁 Files touched**:
|
||||
- `doku/report.md`
|
||||
- `doku/memory_notes.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- After `@testing-manager` completion, continue with PR-ready summary and release handoff.
|
||||
|
||||
### 2026-02-26 (Continued execution: frontend check fully green)
|
||||
|
||||
- **🧩 Scope**: Continue implementation to remove all remaining `frontend` type/lint blockers.
|
||||
- **🛠️ What changed**:
|
||||
- Fixed remaining production type/lint blockers in:
|
||||
- `src/components/MobileEditModal.tsx` (prop destructuring + packageType change handler typing)
|
||||
- `src/components/SharedSchedule.tsx` (critical threshold typing)
|
||||
- `src/context/AppContext.tsx` (import result typing for imported counts)
|
||||
- `src/pages/dashboard-helpers.ts` (strict `PackageType` + null-safe stockAdjustment)
|
||||
- `src/pages/DashboardPage.tsx` (missing `Coverage` type import)
|
||||
- `src/utils/stock.ts` (removed unreachable nullish coalescing)
|
||||
- Fixed remaining test typing drift in:
|
||||
- `src/test/setup.ts`
|
||||
- `src/test/components/Lightbox.test.tsx`
|
||||
- `src/test/components/UserFilterModal.test.tsx`
|
||||
- `src/test/context/AppContext.test.tsx`
|
||||
- `src/test/hooks/useMedications.test.ts`
|
||||
- `src/test/hooks/useRefill.test.ts`
|
||||
- `src/test/hooks/useSettings.test.ts`
|
||||
- `src/test/hooks/useShare.test.ts`
|
||||
- `src/test/utils/formatters.test.ts`
|
||||
- `src/test/utils/schedule.test.ts`
|
||||
- Validation results:
|
||||
- `cd frontend && npm run check` -> **PASS**
|
||||
- `CI=true npm run test:run -- src/test/hooks/useShare.test.ts src/test/hooks/useRefill.test.ts src/test/hooks/useSettings.test.ts src/test/utils/formatters.test.ts` -> **PASS** (4 files, 84 tests)
|
||||
- **📁 Files touched**:
|
||||
- `frontend/src/components/MobileEditModal.tsx`
|
||||
- `frontend/src/components/SharedSchedule.tsx`
|
||||
- `frontend/src/context/AppContext.tsx`
|
||||
- `frontend/src/pages/dashboard-helpers.ts`
|
||||
- `frontend/src/pages/DashboardPage.tsx`
|
||||
- `frontend/src/utils/stock.ts`
|
||||
- `frontend/src/test/setup.ts`
|
||||
- `frontend/src/test/components/Lightbox.test.tsx`
|
||||
- `frontend/src/test/components/UserFilterModal.test.tsx`
|
||||
- `frontend/src/test/context/AppContext.test.tsx`
|
||||
- `frontend/src/test/hooks/useMedications.test.ts`
|
||||
- `frontend/src/test/hooks/useRefill.test.ts`
|
||||
- `frontend/src/test/hooks/useSettings.test.ts`
|
||||
- `frontend/src/test/hooks/useShare.test.ts`
|
||||
- `frontend/src/test/utils/formatters.test.ts`
|
||||
- `frontend/src/test/utils/schedule.test.ts`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Optional: run full frontend test suite as additional confidence step before release handoff.
|
||||
|
||||
### 2026-02-26 (npm integrity issue resolved)
|
||||
|
||||
- **🧩 Scope**: Fix `npm ci` failure caused by tarball integrity mismatch warnings/errors.
|
||||
- **🛠️ What changed**:
|
||||
- Reproduced failure (`EINTEGRITY`) for `@types/react@19.2.2` / `@types/react-dom@19.2.2`.
|
||||
- Pulled authoritative integrity hashes from npm registry via:
|
||||
- `npm view @types/react@19.2.2 dist.integrity`
|
||||
- `npm view @types/react-dom@19.2.2 dist.integrity`
|
||||
- Corrected two integrity strings in `frontend/package-lock.json` to match official registry values.
|
||||
- Re-ran install:
|
||||
- `npm ci --no-audit --no-fund` -> **PASS**.
|
||||
- **📁 Files touched**:
|
||||
- `frontend/package-lock.json`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- None required for this issue; install path is healthy again.
|
||||
|
||||
### 2026-02-26 (Deprecation warnings triage)
|
||||
|
||||
- **🧩 Scope**: Investigate reported npm deprecation warnings and determine if local code changes are required.
|
||||
- **🛠️ What changed**:
|
||||
- Verified warnings are from `backend` transitive deps, not `frontend`:
|
||||
- `drizzle-kit@0.31.9` -> `@esbuild-kit/esm-loader@2.6.5` -> `@esbuild-kit/core-utils@3.3.2`
|
||||
- `@libsql/client@0.17.0` -> `node-fetch@3.3.2` -> `fetch-blob@3.2.0` -> `node-domexception@1.0.0`
|
||||
- Confirmed current installed versions are already latest published for both direct parents (`drizzle-kit`, `@libsql/client`).
|
||||
- Classified as non-blocking upstream deprecation warnings (no immediate local fix available without changing stack/library choices).
|
||||
- **📁 Files touched**:
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Re-evaluate after upstream releases; remove warnings via normal dependency updates when available.
|
||||
|
||||
### 2026-02-26 (MedDetailModal test type drift fix)
|
||||
|
||||
- **🧩 Scope**: Fix only residual prop/type drift in `MedDetailModal` tests to unblock frontend check target area.
|
||||
- **🛠️ What changed**:
|
||||
- Updated `defaultProps` in `frontend/src/test/components/MedDetailModal.test.tsx` with required `MedDetailModalProps` fields:
|
||||
- `usePrescriptionRefill`
|
||||
- `onUsePrescriptionRefillChange`
|
||||
- Updated `RefillEntry` fixtures in the same file to current type shape:
|
||||
- removed legacy fields (`medicationId`, `timestamp`, `looseAdded`)
|
||||
- added current fields (`refillDate`, `loosePillsAdded`)
|
||||
- Ran `cd frontend && npm run check`: the file-specific drift is resolved, but command still fails due unrelated TypeScript errors in other frontend files.
|
||||
- **📁 Files touched**:
|
||||
- `frontend/src/test/components/MedDetailModal.test.tsx`
|
||||
- `doku/memory_notes.md`
|
||||
- `doku/report.md`
|
||||
- **🔜 Follow-ups**:
|
||||
- Resolve remaining unrelated `frontend` TypeScript errors before rerunning full `npm run check` and then the targeted MedDetailModal test command.
|
||||
+5
-1
@@ -41,6 +41,9 @@ RUN sed -i 's|include /etc/nginx/conf.d/\*.conf;|include /tmp/default.conf;|' /e
|
||||
# nginx-unprivileged automatically substitutes env vars in .template files
|
||||
COPY nginx.conf /etc/nginx/templates/default.conf.template
|
||||
|
||||
# Copy entrypoint wrapper (translates LOG_LEVEL → nginx access log control)
|
||||
COPY --chmod=755 nginx-entrypoint.sh /nginx-entrypoint.sh
|
||||
|
||||
# Copy built static files with correct ownership (nginx user = uid 101)
|
||||
COPY --from=builder --chown=101:101 /app/dist /usr/share/nginx/html
|
||||
|
||||
@@ -50,5 +53,6 @@ EXPOSE 8080
|
||||
# Already runs as non-root (nginx user, uid 101)
|
||||
USER nginx
|
||||
|
||||
# Start nginx (entrypoint processes templates automatically)
|
||||
# Use wrapper entrypoint that maps LOG_LEVEL to nginx config
|
||||
ENTRYPOINT ["/nginx-entrypoint.sh"]
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
||||
+82
-45
@@ -1,76 +1,113 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { expect, test as setup } from "@playwright/test";
|
||||
import { TEST_USER } from "./fixtures";
|
||||
import { applyVideoSafetyMode, TEST_USER } from "./fixtures";
|
||||
|
||||
const authFile = path.join(import.meta.dirname, ".auth", "user.json");
|
||||
|
||||
/**
|
||||
* Global setup for authentication
|
||||
* This runs before all tests to ensure a test user exists and stores the authenticated state
|
||||
* Check if a JWT token is still valid (not expired) without making a
|
||||
* network request. Returns `true` when the token has at least 2 minutes
|
||||
* of remaining validity.
|
||||
*/
|
||||
function isTokenValid(token: string): boolean {
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
|
||||
// Require at least 10 minutes of remaining validity to ensure the token
|
||||
// lasts through the entire test run (which can take 7+ minutes)
|
||||
return typeof payload.exp === "number" && Date.now() / 1000 < payload.exp - 600;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Global setup: ensure a test user exists and persist authenticated state.
|
||||
* Runs once before all test projects.
|
||||
*
|
||||
* Strategy:
|
||||
* 1. If a valid auth file exists whose access_token JWT has not expired,
|
||||
* reuse it without any network call (saves rate-limit budget).
|
||||
* 2. If auth is disabled (no login page), save state immediately.
|
||||
* 3. Try to register via API (idempotent — fails silently if user exists).
|
||||
* 4. Log in via the UI.
|
||||
*/
|
||||
setup("authenticate", async ({ page }) => {
|
||||
await applyVideoSafetyMode(page);
|
||||
|
||||
// Create .auth directory if it doesn't exist
|
||||
const authDir = path.dirname(authFile);
|
||||
if (!fs.existsSync(authDir)) {
|
||||
fs.mkdirSync(authDir, { recursive: true });
|
||||
}
|
||||
|
||||
// ---- 1. Try to reuse an existing auth file (offline check) ----
|
||||
if (fs.existsSync(authFile)) {
|
||||
try {
|
||||
const saved = JSON.parse(fs.readFileSync(authFile, "utf-8"));
|
||||
const accessCookie = saved.cookies?.find((c: { name: string }) => c.name === "access_token");
|
||||
if (accessCookie?.value && isTokenValid(accessCookie.value)) {
|
||||
// Token still has enough validity — skip login entirely
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Invalid file — fall through to regular login
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 2. Check if auth is disabled ----
|
||||
await page.goto("/");
|
||||
|
||||
// Wait for the app to fully load (network idle + content visible)
|
||||
await page.waitForLoadState("networkidle");
|
||||
await expect(page.locator("body")).not.toHaveText(/^$/, { timeout: 15000 });
|
||||
|
||||
// Check if auth is disabled (we can access dashboard directly)
|
||||
const dashboardVisible = await page
|
||||
.getByText(/dashboard|medications|schedule/i)
|
||||
const authDisabled = await page
|
||||
.locator("header.hero")
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
if (dashboardVisible) {
|
||||
// Auth is disabled - save empty state and return
|
||||
if (authDisabled) {
|
||||
await page.context().storageState({ path: authFile });
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we need to register (first user setup)
|
||||
const needsSetup = await page
|
||||
.getByText(/create.*first.*user|create.*account|register|first user setup/i)
|
||||
// Wait for auth container
|
||||
await expect(page.locator(".auth-container")).toBeVisible({ timeout: 15000 });
|
||||
|
||||
// ---- 3. Ensure the test user exists ----
|
||||
const baseURL = process.env.PLAYWRIGHT_BASE_URL || "http://localhost:5173";
|
||||
await page.request
|
||||
.post(`${baseURL}/api/auth/register`, {
|
||||
data: { username: TEST_USER.username, password: TEST_USER.password },
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
// ---- 4. Log in via UI ----
|
||||
const usernameField = page.locator("#username");
|
||||
const passwordField = page.locator("#password");
|
||||
|
||||
// Make sure we're on the login form (not register)
|
||||
const isOnRegister = await page
|
||||
.locator(".auth-subtitle")
|
||||
.filter({ hasText: /Create Account/i })
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
|
||||
if (needsSetup) {
|
||||
// Register the test user
|
||||
const usernameField = page.getByLabel(/username/i);
|
||||
const passwordField = page.getByLabel(/password/i).first();
|
||||
|
||||
await usernameField.fill(TEST_USER.username);
|
||||
await passwordField.fill(TEST_USER.password);
|
||||
|
||||
// Look for register/create button
|
||||
const registerButton = page.getByRole("button", { name: /register|create|sign up/i });
|
||||
await registerButton.click();
|
||||
|
||||
// Wait for successful registration and redirect
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 15000 });
|
||||
} else {
|
||||
// Need to login
|
||||
const usernameField = page.getByLabel(/username/i);
|
||||
const passwordField = page.getByLabel(/password/i);
|
||||
|
||||
// Check if we're on login page
|
||||
if (await usernameField.isVisible().catch(() => false)) {
|
||||
await usernameField.fill(TEST_USER.username);
|
||||
await passwordField.fill(TEST_USER.password);
|
||||
|
||||
const loginButton = page.getByRole("button", { name: /sign in|log in|login/i });
|
||||
await loginButton.click();
|
||||
|
||||
// Wait for successful login
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 15000 });
|
||||
if (isOnRegister) {
|
||||
const switchBtn = page.locator("button.auth-link-btn");
|
||||
if (await switchBtn.isVisible().catch(() => false)) {
|
||||
await switchBtn.click();
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
}
|
||||
|
||||
// Save the authenticated state
|
||||
await usernameField.clear();
|
||||
await usernameField.fill(TEST_USER.username);
|
||||
await passwordField.clear();
|
||||
await passwordField.fill(TEST_USER.password);
|
||||
|
||||
// Click the submit button (not the SSO button)
|
||||
await page.locator('button.auth-submit[type="submit"]').click();
|
||||
|
||||
// Wait for successful auth — app header should appear
|
||||
await expect(page.locator("header.hero")).toBeVisible({ timeout: 15000 });
|
||||
|
||||
// Persist authenticated state for all test projects
|
||||
await page.context().storageState({ path: authFile });
|
||||
});
|
||||
|
||||
+82
-87
@@ -1,118 +1,113 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import { expect, type Page, test } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Helper to wait for the app's auth state to be determined
|
||||
* The app shows Loading/Initializing until auth state is fetched
|
||||
*/
|
||||
async function waitForAuthReady(page: import("@playwright/test").Page): Promise<void> {
|
||||
// Wait for the loading indicator to disappear
|
||||
await page.waitForLoadState("networkidle");
|
||||
// The app should have loaded something meaningful
|
||||
await expect(page.locator("body")).not.toHaveText(/^$/, { timeout: 10000 });
|
||||
async function isAuthEnabled(page: Page): Promise<boolean> {
|
||||
try {
|
||||
const response = await page.request.get("/api/auth/state");
|
||||
if (!response.ok()) return true;
|
||||
const state = await response.json();
|
||||
return state?.authEnabled !== false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication E2E Tests
|
||||
*
|
||||
* These tests verify the authentication flow including login, registration,
|
||||
* and logout functionality.
|
||||
* Tests the login/register UI when not authenticated.
|
||||
* Uses empty storage state to simulate unauthenticated access.
|
||||
*
|
||||
* NOTE: This file intentionally imports `test` from @playwright/test
|
||||
* (not from fixtures) because auth tests use empty storageState and
|
||||
* must NOT have the auth-me caching interceptor.
|
||||
*/
|
||||
test.describe("Authentication", () => {
|
||||
// Skip auth dependency for these tests since we're testing auth itself
|
||||
test.use({ storageState: { cookies: [], origins: [] } });
|
||||
|
||||
test("should display login page when not authenticated", async ({ page }) => {
|
||||
test("should show login page for unauthenticated users", async ({ page }) => {
|
||||
test.skip(!(await isAuthEnabled(page)), "Auth is disabled in this environment");
|
||||
|
||||
await page.goto("/");
|
||||
await waitForAuthReady(page);
|
||||
await expect(page.locator(".auth-container")).toBeVisible({ timeout: 15000 });
|
||||
|
||||
// Should show either login form, registration form (first setup), or dashboard (auth disabled)
|
||||
const hasLoginForm = await page
|
||||
.getByLabel(/username/i)
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
const hasDashboard = await page
|
||||
.getByText(/dashboard|medications/i)
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
|
||||
expect(hasLoginForm || hasDashboard).toBeTruthy();
|
||||
// Should have the app title
|
||||
await expect(page.locator(".auth-title")).toContainText("MedAssist-ng");
|
||||
});
|
||||
|
||||
test("should have accessible form fields", async ({ page }) => {
|
||||
test("should have username and password fields", async ({ page }) => {
|
||||
test.skip(!(await isAuthEnabled(page)), "Auth is disabled in this environment");
|
||||
|
||||
await page.goto("/");
|
||||
await waitForAuthReady(page);
|
||||
await expect(page.locator(".auth-container")).toBeVisible({ timeout: 15000 });
|
||||
|
||||
// Check if auth is enabled
|
||||
const hasLoginForm = await page
|
||||
.getByLabel(/username/i)
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
const usernameField = page.locator("#username");
|
||||
const passwordField = page.locator("#password");
|
||||
|
||||
if (hasLoginForm) {
|
||||
// Username field should be accessible
|
||||
const usernameField = page.getByLabel(/username/i);
|
||||
await expect(usernameField).toBeVisible();
|
||||
await expect(usernameField).toBeEnabled();
|
||||
|
||||
// Password field should be accessible
|
||||
const passwordField = page.getByLabel(/password/i);
|
||||
await expect(passwordField).toBeVisible();
|
||||
await expect(passwordField).toBeEnabled();
|
||||
}
|
||||
await expect(usernameField).toBeVisible();
|
||||
await expect(usernameField).toBeEnabled();
|
||||
await expect(passwordField).toBeVisible();
|
||||
await expect(passwordField).toBeEnabled();
|
||||
});
|
||||
|
||||
test("should show validation error for empty credentials", async ({ page }) => {
|
||||
test("should have a submit button", async ({ page }) => {
|
||||
test.skip(!(await isAuthEnabled(page)), "Auth is disabled in this environment");
|
||||
|
||||
await page.goto("/");
|
||||
await waitForAuthReady(page);
|
||||
await expect(page.locator(".auth-container")).toBeVisible({ timeout: 15000 });
|
||||
|
||||
const hasLoginForm = await page
|
||||
.getByLabel(/username/i)
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
|
||||
if (hasLoginForm) {
|
||||
// Try to submit empty form
|
||||
const submitButton = page.getByRole("button", { name: /sign in|log in|login|register|create/i });
|
||||
|
||||
if (await submitButton.isVisible()) {
|
||||
await submitButton.click();
|
||||
|
||||
// Check for validation - either HTML5 validation or custom error
|
||||
const usernameField = page.getByLabel(/username/i);
|
||||
const isInvalid =
|
||||
(await usernameField.evaluate((el) => (el as HTMLInputElement).validity.valueMissing).catch(() => false)) ||
|
||||
(await page
|
||||
.getByText(/required|invalid|error/i)
|
||||
.isVisible()
|
||||
.catch(() => false));
|
||||
|
||||
expect(isInvalid || true).toBeTruthy(); // Validation varies by implementation
|
||||
}
|
||||
}
|
||||
const submitButton = page.locator('button.auth-submit[type="submit"]');
|
||||
await expect(submitButton).toBeVisible();
|
||||
await expect(submitButton).toBeEnabled();
|
||||
});
|
||||
|
||||
test("should toggle password visibility", async ({ page }) => {
|
||||
test("should not navigate to dashboard without credentials", async ({ page }) => {
|
||||
test.skip(!(await isAuthEnabled(page)), "Auth is disabled in this environment");
|
||||
|
||||
await page.goto("/dashboard");
|
||||
|
||||
// Should NOT show the app header (redirected to login)
|
||||
await expect(page.locator("header.hero")).not.toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Should show auth form instead
|
||||
await expect(page.locator(".auth-container")).toBeVisible();
|
||||
});
|
||||
|
||||
test("should show error for invalid credentials", async ({ page }) => {
|
||||
test.skip(!(await isAuthEnabled(page)), "Auth is disabled in this environment");
|
||||
|
||||
await page.goto("/");
|
||||
await waitForAuthReady(page);
|
||||
await expect(page.locator(".auth-container")).toBeVisible({ timeout: 15000 });
|
||||
|
||||
const passwordField = page.getByLabel(/password/i).first();
|
||||
const hasPasswordField = await passwordField.isVisible().catch(() => false);
|
||||
// Fill in invalid credentials
|
||||
await page.locator("#username").fill("nonexistent-user");
|
||||
await page.locator("#password").fill("wrongpassword");
|
||||
await page.locator('button.auth-submit[type="submit"]').click();
|
||||
|
||||
if (hasPasswordField) {
|
||||
// Check initial type is password
|
||||
await expect(passwordField).toHaveAttribute("type", "password");
|
||||
// Should show an error message
|
||||
await expect(page.locator(".auth-error")).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
// Find and click the toggle button (often an eye icon)
|
||||
const toggleButton = page.getByRole("button", { name: /show|hide|toggle.*password/i });
|
||||
const hasToggle = await toggleButton.isVisible().catch(() => false);
|
||||
test("should toggle between login and register forms", async ({ page }) => {
|
||||
test.skip(!(await isAuthEnabled(page)), "Auth is disabled in this environment");
|
||||
|
||||
if (hasToggle) {
|
||||
await toggleButton.click();
|
||||
await expect(passwordField).toHaveAttribute("type", "text");
|
||||
await page.goto("/");
|
||||
await expect(page.locator(".auth-container")).toBeVisible({ timeout: 15000 });
|
||||
|
||||
await toggleButton.click();
|
||||
await expect(passwordField).toHaveAttribute("type", "password");
|
||||
}
|
||||
}
|
||||
const toggleButton = page.locator("button.auth-link-btn");
|
||||
test.skip(
|
||||
!(await toggleButton.isVisible().catch(() => false)),
|
||||
"Registration toggle is unavailable in this environment"
|
||||
);
|
||||
|
||||
// Check current subtitle text
|
||||
const subtitle = page.locator(".auth-subtitle");
|
||||
const initialText = await subtitle.textContent();
|
||||
|
||||
// Click the toggle link (Create account / Already have an account)
|
||||
await toggleButton.click();
|
||||
|
||||
// Subtitle should change
|
||||
const newText = await subtitle.textContent();
|
||||
expect(newText).not.toBe(initialText);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import {
|
||||
authFile,
|
||||
createMedicationViaAPI,
|
||||
deleteAllMedicationsViaAPI,
|
||||
expect,
|
||||
navigateTo,
|
||||
type TestMedication,
|
||||
test,
|
||||
} from "./fixtures";
|
||||
|
||||
/**
|
||||
* Dashboard with Medication Data E2E Tests
|
||||
*
|
||||
* Creates medications via API, then verifies the dashboard
|
||||
* overview table, coverage cards, timeline, and dose tracking.
|
||||
*/
|
||||
test.describe("Dashboard with medications", () => {
|
||||
test.use({ storageState: authFile });
|
||||
test.describe.configure({ timeout: 60000 });
|
||||
|
||||
// Unique medication names to avoid conflicts with parallel workers
|
||||
const MED_1 = "DashData Ibuprofen";
|
||||
const MED_2 = "DashData Vitamin C";
|
||||
|
||||
// Set start to earlier today so doses appear on the timeline
|
||||
const todayMorning = (() => {
|
||||
const d = new Date();
|
||||
d.setHours(8, 0, 0, 0);
|
||||
const pad = (n: number) => n.toString().padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
})();
|
||||
|
||||
const createdMeds: TestMedication[] = [];
|
||||
|
||||
test.beforeAll(async () => {
|
||||
// Clean up any leftover medications from previous test runs
|
||||
await deleteAllMedicationsViaAPI();
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: MED_1,
|
||||
genericName: "Ibuprofen",
|
||||
packageType: "blister",
|
||||
packCount: 2,
|
||||
blistersPerPack: 3,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
intakes: [{ usage: 1, every: 1, start: todayMorning, intakeRemindersEnabled: false }],
|
||||
})
|
||||
);
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: MED_2,
|
||||
packageType: "bottle",
|
||||
totalPills: 90,
|
||||
looseTablets: 90,
|
||||
intakes: [{ usage: 1, every: 1, start: todayMorning, intakeRemindersEnabled: false }],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await deleteAllMedicationsViaAPI();
|
||||
});
|
||||
|
||||
test("should show medication overview table with medications", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const overviewTable = page.locator(".table.table-7");
|
||||
await expect(overviewTable).toBeVisible({ timeout: 10000 });
|
||||
await expect(overviewTable.locator(".table-head")).toBeVisible();
|
||||
|
||||
// Our medications should have rows
|
||||
await expect(overviewTable.getByText(MED_1)).toBeVisible();
|
||||
await expect(overviewTable.getByText(MED_2)).toBeVisible();
|
||||
});
|
||||
|
||||
test("should show status chips in overview table", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const overviewTable = page.locator(".table.table-7");
|
||||
await expect(overviewTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Each medication row should have a status chip
|
||||
const statusChips = overviewTable.locator(".status-chip");
|
||||
expect(await statusChips.count()).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
test("should show stock information in overview", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const overviewTable = page.locator(".table.table-7");
|
||||
await expect(overviewTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// The Ibuprofen row should show stock info (60 pills minus today's usage = 59)
|
||||
const ibuprofenRow = overviewTable.locator(".table-row").filter({ hasText: MED_1 });
|
||||
await expect(ibuprofenRow).toBeVisible();
|
||||
const rowText = await ibuprofenRow.textContent();
|
||||
// Stock should show around 59-60 (60 pills minus today's consumed dose)
|
||||
expect((rowText ?? "").includes("59") || (rowText ?? "").includes("60")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("should show today block in timeline", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const todayBlock = page.locator(".day-block.today");
|
||||
await expect(todayBlock).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
|
||||
test("should show medication names in today's schedule", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const todayBlock = page.locator(".day-block.today");
|
||||
await expect(todayBlock).toBeVisible({ timeout: 10000 });
|
||||
await expect(todayBlock.getByText(MED_1)).toBeVisible();
|
||||
await expect(todayBlock.getByText(MED_2)).toBeVisible();
|
||||
});
|
||||
|
||||
test("should show day summary with dose progress", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const todayBlock = page.locator(".day-block.today");
|
||||
await expect(todayBlock).toBeVisible({ timeout: 10000 });
|
||||
await expect(todayBlock.locator(".day-summary")).toBeVisible();
|
||||
});
|
||||
|
||||
test("should show dose take buttons in today's schedule", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const todayBlock = page.locator(".day-block.today");
|
||||
await expect(todayBlock).toBeVisible({ timeout: 10000 });
|
||||
|
||||
const takeButtons = todayBlock.locator("button.dose-btn.take");
|
||||
expect(await takeButtons.count()).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("should mark a dose as taken and show undo", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const todayBlock = page.locator(".day-block.today");
|
||||
await expect(todayBlock).toBeVisible({ timeout: 10000 });
|
||||
|
||||
const takeBtn = todayBlock.locator("button.dose-btn.take:not([disabled])").first();
|
||||
test.skip(!(await takeBtn.isVisible().catch(() => false)), "No actionable take-dose button is visible for today");
|
||||
|
||||
await takeBtn.click();
|
||||
await expect(todayBlock.locator("button.dose-btn.undo").first()).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test("should undo a taken dose", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
const todayBlock = page.locator(".day-block.today");
|
||||
await expect(todayBlock).toBeVisible({ timeout: 15000 });
|
||||
|
||||
// Normalize state first: if a dose is already taken, undo it so we can
|
||||
// always execute the same take -> undo flow deterministically.
|
||||
const existingUndo = todayBlock.locator("button.dose-btn.undo").first();
|
||||
if (await existingUndo.isVisible().catch(() => false)) {
|
||||
await existingUndo.click();
|
||||
await page.waitForLoadState("networkidle");
|
||||
}
|
||||
|
||||
// Mark a dose as taken first
|
||||
const takeBtn = todayBlock.locator("button.dose-btn.take:not([disabled])").first();
|
||||
await expect(takeBtn).toBeVisible({ timeout: 10000 });
|
||||
await takeBtn.click();
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
// Wait for undo button to appear (confirms the take succeeded)
|
||||
const undoBtn = todayBlock.locator("button.dose-btn.undo").first();
|
||||
await expect(undoBtn).toBeVisible({ timeout: 10000 });
|
||||
await undoBtn.click();
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
// Take button should reappear
|
||||
await expect(todayBlock.locator("button.dose-btn.take:not([disabled])").first()).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
|
||||
test("should show multiple day blocks in timeline", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
// Wait for timeline to fully render
|
||||
await page.waitForLoadState("networkidle");
|
||||
const dayBlocks = page.locator(".day-block");
|
||||
await expect(dayBlocks.first()).toBeVisible({ timeout: 15000 });
|
||||
// With 30-day default, there should be multiple day blocks
|
||||
expect(await dayBlocks.count()).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("should show day header with date text", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const todayBlock = page.locator(".day-block.today");
|
||||
await expect(todayBlock).toBeVisible({ timeout: 10000 });
|
||||
|
||||
const dayDivider = todayBlock.locator(".day-divider");
|
||||
await expect(dayDivider).toBeVisible();
|
||||
expect(await dayDivider.textContent()).toBeTruthy();
|
||||
});
|
||||
|
||||
test("should open medication detail modal from overview table", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const overviewTable = page.locator(".table.table-7");
|
||||
await expect(overviewTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
const medRow = overviewTable.locator(".table-row").filter({ hasText: MED_1 }).first();
|
||||
await medRow.click();
|
||||
|
||||
const modal = page.locator(".modal-overlay");
|
||||
await expect(modal).toBeVisible({ timeout: 5000 });
|
||||
await expect(modal.getByText(MED_1)).toBeVisible();
|
||||
|
||||
await page.locator("button.modal-close").click();
|
||||
await expect(modal).not.toBeVisible();
|
||||
});
|
||||
|
||||
test("should show schedule days selector", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const daysSelect = page.locator("select.schedule-days-select");
|
||||
await expect(daysSelect).toBeVisible();
|
||||
await expect(daysSelect.locator('option[value="30"]')).toBeAttached();
|
||||
await expect(daysSelect.locator('option[value="90"]')).toBeAttached();
|
||||
await expect(daysSelect.locator('option[value="180"]')).toBeAttached();
|
||||
});
|
||||
});
|
||||
+74
-100
@@ -1,122 +1,96 @@
|
||||
import * as path from "node:path";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const authFile = path.join(import.meta.dirname, ".auth", "user.json");
|
||||
import { expect } from "@playwright/test";
|
||||
import { authFile, navigateTo, test } from "./fixtures";
|
||||
|
||||
/**
|
||||
* Dashboard E2E Tests
|
||||
*
|
||||
* These tests verify the main dashboard functionality including
|
||||
* medication overview and upcoming schedules.
|
||||
* Verifies the main dashboard with medication overview (coverage cards)
|
||||
* and upcoming schedules timeline.
|
||||
*/
|
||||
test.describe("Dashboard", () => {
|
||||
test.use({ storageState: authFile });
|
||||
|
||||
test("should display dashboard page", async ({ page }) => {
|
||||
await page.goto("/dashboard");
|
||||
test("should display the dashboard page with header", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
// Wait for app to load
|
||||
await expect(page.locator("body")).not.toContainText(/Loading\.\.\.|Initializing\.\.\./, {
|
||||
timeout: 10000,
|
||||
});
|
||||
// App header with navigation tabs should be visible
|
||||
await expect(page.locator("header.hero")).toBeVisible();
|
||||
await expect(page.locator("header.hero h1")).toBeVisible();
|
||||
|
||||
// Should display navigation
|
||||
await expect(page.getByRole("navigation")).toBeVisible();
|
||||
|
||||
// Should show dashboard content
|
||||
const hasDashboardContent =
|
||||
(await page
|
||||
.getByText(/dashboard|overview|medications/i)
|
||||
.isVisible()
|
||||
.catch(() => false)) ||
|
||||
(await page
|
||||
.getByText(/no medications/i)
|
||||
.isVisible()
|
||||
.catch(() => false));
|
||||
|
||||
expect(hasDashboardContent).toBeTruthy();
|
||||
// Eyebrow should show "Overview"
|
||||
await expect(page.locator(".eyebrow")).toContainText("Overview");
|
||||
});
|
||||
|
||||
test("should have working navigation links", async ({ page }) => {
|
||||
await page.goto("/dashboard");
|
||||
test("should show navigation tabs", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
// All three nav tabs should be visible
|
||||
await expect(page.locator('button.pill:has-text("Dashboard")')).toBeVisible();
|
||||
await expect(page.locator('button.pill:has-text("Medications")')).toBeVisible();
|
||||
await expect(page.locator('button.pill:has-text("Planner")')).toBeVisible();
|
||||
|
||||
// Check for navigation links - these are the common nav items
|
||||
const navLinks = ["dashboard", "medications", "planner", "settings", "schedule"];
|
||||
// Dashboard tab should be active
|
||||
await expect(page.locator('button.pill.primary:has-text("Dashboard")')).toBeVisible();
|
||||
});
|
||||
|
||||
for (const link of navLinks) {
|
||||
const navLink = page.getByRole("link", { name: new RegExp(link, "i") });
|
||||
const isVisible = await navLink.isVisible().catch(() => false);
|
||||
test("should navigate to medications via tab", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
// At least some nav links should be present
|
||||
if (isVisible) {
|
||||
await expect(navLink).toBeEnabled();
|
||||
await page.locator('button.pill:has-text("Medications")').click();
|
||||
await expect(page).toHaveURL(/\/medications/);
|
||||
});
|
||||
|
||||
test("should navigate to planner via tab", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
await page.locator('button.pill:has-text("Planner")').click();
|
||||
await expect(page).toHaveURL(/\/planner/);
|
||||
});
|
||||
|
||||
test("should display medication overview section", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
// Should show either the overview section or "no medications" state
|
||||
const hasOverviewTitle = page.locator("h2").filter({ hasText: /Medication Overview/i });
|
||||
const hasNoMeds = page.getByText(/No medications/i);
|
||||
|
||||
const overviewVisible = await hasOverviewTitle.isVisible().catch(() => false);
|
||||
const noMedsVisible = await hasNoMeds.isVisible().catch(() => false);
|
||||
|
||||
expect(overviewVisible || noMedsVisible).toBeTruthy();
|
||||
});
|
||||
|
||||
test("should display schedules section", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
// Should show the schedules section title or "no medications" state
|
||||
const hasSchedulesTitle = page.locator("h2").filter({ hasText: /Upcoming Schedules/i });
|
||||
const hasNoMeds = page.getByText(/No medications/i);
|
||||
|
||||
const schedulesVisible = await hasSchedulesTitle.isVisible().catch(() => false);
|
||||
const noMedsVisible = await hasNoMeds.isVisible().catch(() => false);
|
||||
|
||||
expect(schedulesVisible || noMedsVisible).toBeTruthy();
|
||||
});
|
||||
|
||||
test("should have schedule days selector when schedules exist", async ({ page }) => {
|
||||
await navigateTo(page, "/dashboard");
|
||||
|
||||
const schedulesTitle = page.locator("h2").filter({ hasText: /Upcoming Schedules/i });
|
||||
if (await schedulesTitle.isVisible().catch(() => false)) {
|
||||
// Days select should be present with 1/3/6 month options
|
||||
const daysSelect = page.locator("select.schedule-days-select");
|
||||
if (await daysSelect.isVisible().catch(() => false)) {
|
||||
await expect(daysSelect).toBeVisible();
|
||||
const options = daysSelect.locator("option");
|
||||
await expect(options).toHaveCount(3);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("should navigate to medications page", async ({ page }) => {
|
||||
await page.goto("/dashboard");
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click medications link
|
||||
const medsLink = page.getByRole("link", { name: /medications/i });
|
||||
if (await medsLink.isVisible()) {
|
||||
await medsLink.click();
|
||||
await expect(page).toHaveURL(/medications/);
|
||||
}
|
||||
});
|
||||
|
||||
test("should navigate to settings page", async ({ page }) => {
|
||||
await page.goto("/dashboard");
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click settings link
|
||||
const settingsLink = page.getByRole("link", { name: /settings/i });
|
||||
if (await settingsLink.isVisible()) {
|
||||
await settingsLink.click();
|
||||
await expect(page).toHaveURL(/settings/);
|
||||
}
|
||||
});
|
||||
|
||||
test("should display medication overview section", async ({ page }) => {
|
||||
await page.goto("/dashboard");
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Look for medication overview or "no medications" message
|
||||
const hasOverview =
|
||||
(await page
|
||||
.getByText(/medication overview|stock/i)
|
||||
.isVisible()
|
||||
.catch(() => false)) ||
|
||||
(await page
|
||||
.getByText(/no medications/i)
|
||||
.isVisible()
|
||||
.catch(() => false));
|
||||
|
||||
expect(hasOverview).toBeTruthy();
|
||||
});
|
||||
|
||||
test("should display upcoming schedules section", async ({ page }) => {
|
||||
await page.goto("/dashboard");
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Look for schedules section or indication that there are no schedules
|
||||
const hasSchedules =
|
||||
(await page
|
||||
.getByText(/upcoming|schedule|1 month|3 months/i)
|
||||
.isVisible()
|
||||
.catch(() => false)) ||
|
||||
(await page
|
||||
.getByText(/no medications/i)
|
||||
.isVisible()
|
||||
.catch(() => false));
|
||||
|
||||
expect(hasSchedules).toBeTruthy();
|
||||
test("should redirect root to dashboard", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
await expect(page.locator("header.hero")).toBeVisible({ timeout: 15000 });
|
||||
await expect(page).toHaveURL(/\/dashboard/);
|
||||
});
|
||||
});
|
||||
|
||||
+317
-88
@@ -2,122 +2,351 @@ import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { test as base, expect, type Page } from "@playwright/test";
|
||||
|
||||
// Storage state path for authenticated sessions
|
||||
const authFile = path.join(import.meta.dirname, "..", ".auth", "user.json");
|
||||
/** Storage state path for authenticated sessions */
|
||||
export const authFile = path.join(import.meta.dirname, "..", ".auth", "user.json");
|
||||
|
||||
/**
|
||||
* Test user credentials for E2E tests
|
||||
* These are used for setting up a test user during the setup phase
|
||||
* Test user credentials for E2E tests.
|
||||
* Override with PLAYWRIGHT_USERNAME / PLAYWRIGHT_PASSWORD env vars.
|
||||
* The setup script registers this user if it doesn't exist and registration is enabled.
|
||||
*/
|
||||
export const TEST_USER = {
|
||||
username: "e2e-test-user",
|
||||
password: "TestPassword123!",
|
||||
username: process.env.PLAYWRIGHT_USERNAME || "e2e-test-user",
|
||||
password: process.env.PLAYWRIGHT_PASSWORD || "TestPassword123!",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Custom test fixture that extends Playwright's base test
|
||||
* Provides utility functions for common testing operations
|
||||
*/
|
||||
export const test = base.extend<{
|
||||
/**
|
||||
* Authenticated page instance - uses stored auth state
|
||||
*/
|
||||
authenticatedPage: Page;
|
||||
}>({
|
||||
authenticatedPage: async ({ page }, use) => {
|
||||
// Load auth state if it exists
|
||||
if (fs.existsSync(authFile)) {
|
||||
const storageState = JSON.parse(fs.readFileSync(authFile, "utf-8"));
|
||||
await page.context().addCookies(storageState.cookies || []);
|
||||
// Note: localStorage must be set after navigating to the page
|
||||
}
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auth-me response mocking
|
||||
// ---------------------------------------------------------------------------
|
||||
// The backend rate-limits /auth/me to 10 req/min. Because every page
|
||||
// navigation triggers the React app's auth-state check (which calls
|
||||
// /auth/me), running 50+ E2E tests in a single suite easily exceeds the
|
||||
// limit.
|
||||
//
|
||||
// Solution: build a synthetic /auth/me response from the JWT payload
|
||||
// stored in the auth file. This avoids all /auth/me network requests
|
||||
// from test pages, completely eliminating rate-limit issues while still
|
||||
// testing the real backend for all other API calls.
|
||||
// ---------------------------------------------------------------------------
|
||||
let mockMeBody: string | null = null;
|
||||
|
||||
function getMockAuthMeBody(): string | null {
|
||||
if (mockMeBody) return mockMeBody;
|
||||
try {
|
||||
const state = JSON.parse(fs.readFileSync(authFile, "utf-8"));
|
||||
const token = state.cookies?.find((c: { name: string }) => c.name === "access_token")?.value;
|
||||
if (!token) return null;
|
||||
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
|
||||
mockMeBody = JSON.stringify({
|
||||
id: payload.sub,
|
||||
username: payload.username,
|
||||
avatarUrl: null,
|
||||
authProvider: "local",
|
||||
createdAt: new Date().toISOString(),
|
||||
lastLoginAt: new Date().toISOString(),
|
||||
});
|
||||
return mockMeBody;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function setupAuthMeMock(page: Page): Promise<void> {
|
||||
const body = getMockAuthMeBody();
|
||||
if (body) {
|
||||
await page.route("**/api/auth/me", (route) =>
|
||||
route.fulfill({ status: 200, contentType: "application/json", body })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce visual flashing in recorded videos by forcing a dark first paint and
|
||||
* disabling most animations/transitions in test mode.
|
||||
*/
|
||||
export async function applyVideoSafetyMode(page: Page): Promise<void> {
|
||||
await page.emulateMedia({ reducedMotion: "reduce", colorScheme: "dark" });
|
||||
await page.addInitScript(() => {
|
||||
const style = document.createElement("style");
|
||||
style.id = "pw-video-safety-style";
|
||||
style.textContent = `
|
||||
html, body {
|
||||
background: #111111 !important;
|
||||
color-scheme: dark !important;
|
||||
}
|
||||
*, *::before, *::after {
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
}
|
||||
`;
|
||||
document.documentElement.appendChild(style);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extended test fixture that automatically mocks /auth/me on every page
|
||||
* using user data from the JWT in the stored auth file.
|
||||
*
|
||||
* Import this `test` (instead of `@playwright/test`) in every spec file
|
||||
* that logs in via `storageState: authFile`.
|
||||
*
|
||||
* auth.spec.ts should keep importing from `@playwright/test` directly
|
||||
* since it tests the unauthenticated flow.
|
||||
*/
|
||||
export const test = base.extend<object>({
|
||||
page: async ({ page }, use) => {
|
||||
await applyVideoSafetyMode(page);
|
||||
await setupAuthMeMock(page);
|
||||
await use(page);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Helper to wait for the app to be fully loaded
|
||||
* Wait for the app to be fully loaded past any loading/initializing screens.
|
||||
* Includes a single retry with page reload to handle transient auth failures
|
||||
* (e.g. brief race between context setup and cookie application).
|
||||
*/
|
||||
export async function waitForAppReady(page: Page): Promise<void> {
|
||||
// Wait for the app to finish loading (no "Loading..." or "Initializing...")
|
||||
await expect(page.getByText(/Loading\.\.\.|Initializing\.\.\./i)).not.toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
const hero = page.locator("header.hero");
|
||||
try {
|
||||
await expect(hero).toBeVisible({ timeout: 15000 });
|
||||
} catch {
|
||||
// Auth might have failed transiently — reload and retry once
|
||||
await page.reload();
|
||||
await expect(hero).toBeVisible({ timeout: 15000 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to login with the test user
|
||||
* Navigate to a page and wait for it to be ready.
|
||||
*/
|
||||
export async function loginTestUser(page: Page): Promise<void> {
|
||||
await page.goto("/");
|
||||
export async function navigateTo(page: Page, path: string): Promise<void> {
|
||||
await page.goto(path);
|
||||
await waitForAppReady(page);
|
||||
|
||||
// Check if we're already logged in
|
||||
const isLoggedIn = await page
|
||||
.getByRole("navigation")
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
if (isLoggedIn) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Fill login form
|
||||
await page.getByLabel(/username/i).fill(TEST_USER.username);
|
||||
await page.getByLabel(/password/i).fill(TEST_USER.password);
|
||||
await page.getByRole("button", { name: /sign in|log in|login/i }).click();
|
||||
|
||||
// Wait for successful login
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
await page.waitForLoadState("networkidle");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to register a new user (for setup)
|
||||
* Click a navigation tab by its text.
|
||||
*/
|
||||
export async function registerTestUser(page: Page): Promise<void> {
|
||||
await page.goto("/");
|
||||
await waitForAppReady(page);
|
||||
|
||||
// Check if we're on the registration page (needs setup)
|
||||
const needsSetup = await page
|
||||
.getByText(/create.*account|register|first user/i)
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
|
||||
if (needsSetup) {
|
||||
// Fill registration form
|
||||
await page.getByLabel(/username/i).fill(TEST_USER.username);
|
||||
await page
|
||||
.getByLabel(/password/i)
|
||||
.first()
|
||||
.fill(TEST_USER.password);
|
||||
|
||||
// Look for confirm password field if present
|
||||
const confirmPassword = page.getByLabel(/confirm.*password/i);
|
||||
if (await confirmPassword.isVisible().catch(() => false)) {
|
||||
await confirmPassword.fill(TEST_USER.password);
|
||||
}
|
||||
|
||||
// Submit registration
|
||||
await page.getByRole("button", { name: /register|create|sign up/i }).click();
|
||||
|
||||
// Wait for successful registration
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
}
|
||||
export async function clickNavTab(page: Page, tabName: string): Promise<void> {
|
||||
await page.locator(`button.pill:has-text("${tabName}")`).click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to logout
|
||||
* Open the user dropdown menu (when auth is enabled).
|
||||
*/
|
||||
export async function logout(page: Page): Promise<void> {
|
||||
// Click on user profile/menu button
|
||||
const userButton = page.getByRole("button", { name: /profile|user|account|menu/i });
|
||||
if (await userButton.isVisible().catch(() => false)) {
|
||||
await userButton.click();
|
||||
await page.getByRole("button", { name: /logout|sign out|log out/i }).click();
|
||||
await expect(page.getByLabel(/username/i)).toBeVisible({ timeout: 5000 });
|
||||
}
|
||||
export async function openUserMenu(page: Page): Promise<void> {
|
||||
await page.locator(".user-menu-btn").click();
|
||||
await expect(page.locator(".user-dropdown")).toBeVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign out via the user dropdown menu.
|
||||
*/
|
||||
export async function signOut(page: Page): Promise<void> {
|
||||
await openUserMenu(page);
|
||||
await page.locator('.dropdown-item:has-text("Sign Out")').click();
|
||||
// Should redirect to login page
|
||||
await expect(page.locator(".auth-container")).toBeVisible({ timeout: 10000 });
|
||||
}
|
||||
|
||||
// Re-export expect for convenience
|
||||
export { expect };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API helpers — create / delete medications via backend API
|
||||
// ---------------------------------------------------------------------------
|
||||
const API_BASE = process.env.PLAYWRIGHT_BASE_URL || "http://localhost:5173";
|
||||
|
||||
function getAuthCookie(): string | null {
|
||||
try {
|
||||
const state = JSON.parse(fs.readFileSync(authFile, "utf-8"));
|
||||
return state.cookies?.find((c: { name: string }) => c.name === "access_token")?.value ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Typed medication response (subset of fields we care about) */
|
||||
export interface TestMedication {
|
||||
id: number;
|
||||
name: string;
|
||||
genericName?: string | null;
|
||||
takenBy?: string[];
|
||||
notes?: string | null;
|
||||
}
|
||||
|
||||
/** Typed share token response */
|
||||
export interface TestShareToken {
|
||||
token: string;
|
||||
takenBy: string;
|
||||
scheduleDays: number;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a medication via the backend API. Returns the created medication
|
||||
* including its `id`. Uses the stored auth cookie from the setup project.
|
||||
* Includes automatic retry for rate-limit (429) responses.
|
||||
*/
|
||||
export async function createMedicationViaAPI(data: {
|
||||
name: string;
|
||||
genericName?: string;
|
||||
takenBy?: string[];
|
||||
notes?: string;
|
||||
expiryDate?: string;
|
||||
packageType?: "blister" | "bottle";
|
||||
packCount?: number;
|
||||
blistersPerPack?: number;
|
||||
pillsPerBlister?: number;
|
||||
looseTablets?: number;
|
||||
totalPills?: number;
|
||||
intakeRemindersEnabled?: boolean;
|
||||
intakes?: {
|
||||
usage: number;
|
||||
every: number;
|
||||
start: string;
|
||||
intakeRemindersEnabled?: boolean;
|
||||
takenBy?: string | null;
|
||||
}[];
|
||||
}): Promise<TestMedication> {
|
||||
const token = getAuthCookie();
|
||||
const isBottle = data.packageType === "bottle";
|
||||
const body = {
|
||||
packageType: isBottle ? "bottle" : "blister",
|
||||
packCount: isBottle ? 1 : (data.packCount ?? 1),
|
||||
blistersPerPack: isBottle ? 1 : (data.blistersPerPack ?? 1),
|
||||
pillsPerBlister: isBottle ? 1 : (data.pillsPerBlister ?? 10),
|
||||
// For bottles: looseTablets IS the current stock. Default to totalPills if not specified.
|
||||
looseTablets: isBottle ? (data.looseTablets ?? data.totalPills ?? 0) : (data.looseTablets ?? 0),
|
||||
totalPills: isBottle ? (data.totalPills ?? null) : null,
|
||||
intakes: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: new Date().toISOString().slice(0, 16),
|
||||
intakeRemindersEnabled: false,
|
||||
},
|
||||
],
|
||||
...data,
|
||||
// Ensure takenBy is always an array (medication-level)
|
||||
takenBy: data.takenBy ?? [],
|
||||
};
|
||||
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
const res = await fetch(`${API_BASE}/api/medications`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(token ? { Cookie: `access_token=${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.status === 429) {
|
||||
// Rate limited — exponential backoff: 3s, 6s, 9s, 12s, 15s
|
||||
await new Promise((r) => setTimeout(r, 3000 * (attempt + 1)));
|
||||
continue;
|
||||
}
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(`Failed to create medication: ${res.status} ${text}`);
|
||||
}
|
||||
return res.json() as Promise<TestMedication>;
|
||||
}
|
||||
throw new Error("Failed to create medication after 5 retries (rate limited)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a medication via the backend API.
|
||||
*/
|
||||
export async function deleteMedicationViaAPI(id: number): Promise<void> {
|
||||
const token = getAuthCookie();
|
||||
await fetch(`${API_BASE}/api/medications/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: token ? { Cookie: `access_token=${token}` } : {},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete ALL medications for the test user via the backend API.
|
||||
* Includes retry logic for rate-limited responses.
|
||||
*/
|
||||
export async function deleteAllMedicationsViaAPI(): Promise<void> {
|
||||
const token = getAuthCookie();
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const res = await fetch(`${API_BASE}/api/medications`, {
|
||||
headers: token ? { Cookie: `access_token=${token}` } : {},
|
||||
});
|
||||
if (res.status === 429) {
|
||||
await new Promise((r) => setTimeout(r, 3000 * (attempt + 1)));
|
||||
continue;
|
||||
}
|
||||
if (!res.ok) return;
|
||||
const meds = (await res.json()) as TestMedication[];
|
||||
for (const med of meds) {
|
||||
for (let delAttempt = 0; delAttempt < 3; delAttempt++) {
|
||||
const delRes = await fetch(`${API_BASE}/api/medications/${med.id}`, {
|
||||
method: "DELETE",
|
||||
headers: token ? { Cookie: `access_token=${token}` } : {},
|
||||
});
|
||||
if (delRes.status === 429) {
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a share token via the backend API.
|
||||
* Requires a medication with takenBy to exist first.
|
||||
*/
|
||||
export async function createShareTokenViaAPI(takenBy: string, scheduleDays = 30): Promise<TestShareToken> {
|
||||
const token = getAuthCookie();
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
const res = await fetch(`${API_BASE}/api/share`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(token ? { Cookie: `access_token=${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({ takenBy, scheduleDays }),
|
||||
});
|
||||
if (res.status === 429) {
|
||||
await new Promise((r) => setTimeout(r, 3000 * (attempt + 1)));
|
||||
continue;
|
||||
}
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(`Failed to create share token: ${res.status} ${text}`);
|
||||
}
|
||||
return res.json() as Promise<TestShareToken>;
|
||||
}
|
||||
throw new Error("Failed to create share token after 5 retries (rate limited)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user settings via the backend API.
|
||||
*/
|
||||
export async function updateSettingsViaAPI(settings: Record<string, unknown>): Promise<void> {
|
||||
const token = getAuthCookie();
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const res = await fetch(`${API_BASE}/api/settings`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(token ? { Cookie: `access_token=${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify(settings),
|
||||
});
|
||||
if (res.status === 429) {
|
||||
await new Promise((r) => setTimeout(r, 3000 * (attempt + 1)));
|
||||
continue;
|
||||
}
|
||||
if (res.ok) return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import {
|
||||
authFile,
|
||||
createMedicationViaAPI,
|
||||
deleteAllMedicationsViaAPI,
|
||||
deleteMedicationViaAPI,
|
||||
expect,
|
||||
navigateTo,
|
||||
type TestMedication,
|
||||
test,
|
||||
} from "./fixtures";
|
||||
|
||||
/**
|
||||
* Medication CRUD E2E Tests
|
||||
*
|
||||
* Tests creating, editing, and deleting medications via the UI form.
|
||||
* Each test cleans up after itself to avoid side effects.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Helper: fill the medication form and save. Waits for the successful
|
||||
* API response and verifies the medication appears in the list.
|
||||
*/
|
||||
async function fillAndSaveMedication(
|
||||
page: Page,
|
||||
opts: {
|
||||
name: string;
|
||||
genericName?: string;
|
||||
packageType?: "blister" | "bottle";
|
||||
packs?: string;
|
||||
blistersPerPack?: string;
|
||||
pillsPerBlister?: string;
|
||||
loosePills?: string;
|
||||
totalCapacity?: string;
|
||||
currentPills?: string;
|
||||
expiryDate?: string;
|
||||
notes?: string;
|
||||
intakes?: { usage: string; every: string }[];
|
||||
}
|
||||
): Promise<void> {
|
||||
const openCreateBtn = page.getByRole("button", { name: /New medication|New entry|form\.newEntry/i }).first();
|
||||
if (await openCreateBtn.isVisible().catch(() => false)) {
|
||||
await openCreateBtn.click();
|
||||
}
|
||||
const form = page.locator("form.form-grid:visible").first();
|
||||
await expect(form.getByLabel(/(Commercial Name|form\.commercialName)/i)).toBeVisible({ timeout: 10000 });
|
||||
await form.getByLabel(/(Commercial Name|form\.commercialName)/i).fill(opts.name);
|
||||
if (opts.genericName) {
|
||||
await form.getByLabel(/(Generic Name|form\.genericName)/i).fill(opts.genericName);
|
||||
}
|
||||
|
||||
const packageTypeSelect = form.locator("select.package-type-select");
|
||||
if (opts.packageType === "bottle") {
|
||||
await packageTypeSelect.selectOption("bottle");
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
if (opts.totalCapacity)
|
||||
await form.getByLabel(/(Total Capacity|form\.totalCapacity|Total \(pills\))/i).fill(opts.totalCapacity);
|
||||
if (opts.currentPills) await form.getByLabel(/(Current Pills|form\.currentPills)/i).fill(opts.currentPills);
|
||||
} else {
|
||||
await packageTypeSelect.selectOption("blister");
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
if (opts.packs) await form.getByLabel(/(^Packs$|form\.packs)/i).fill(opts.packs);
|
||||
if (opts.blistersPerPack)
|
||||
await form.getByLabel(/(Blisters per pack|form\.blistersPerPack)/i).fill(opts.blistersPerPack);
|
||||
if (opts.pillsPerBlister)
|
||||
await form.getByLabel(/(Pills per blister|form\.pillsPerBlister)/i).fill(opts.pillsPerBlister);
|
||||
if (opts.loosePills) {
|
||||
const looseField = form.getByLabel(/(Loose pills|form\.loosePills)/i);
|
||||
if (await looseField.isVisible().catch(() => false)) {
|
||||
await looseField.fill(opts.loosePills);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (opts.expiryDate) await form.getByLabel(/(Expiry Date|form\.expiryDate)/i).fill(opts.expiryDate);
|
||||
if (opts.notes) await form.getByLabel(/(Notes|form\.notes)/i).fill(opts.notes);
|
||||
|
||||
// Fill intake schedules
|
||||
const intakes = opts.intakes ?? [{ usage: "1", every: "1" }];
|
||||
await page.getByRole("tab", { name: /Schedule/i }).click();
|
||||
for (let i = 0; i < intakes.length; i++) {
|
||||
if (i > 0) {
|
||||
await form.getByRole("button", { name: /(Intake|form\.blisters\.addIntake)/i }).click();
|
||||
}
|
||||
const row = form.locator(".blister-row").nth(i);
|
||||
await row.getByLabel(/(Usage \(pills\)|form\.blisters\.usage)/i).fill(intakes[i].usage);
|
||||
await row.getByLabel(/(Every \(days\)|form\.blisters\.everyDays)/i).fill(intakes[i].every);
|
||||
}
|
||||
|
||||
await page.waitForLoadState("networkidle");
|
||||
await form.locator("button[type='submit']").click();
|
||||
|
||||
// Verify the medication appears in the list (may need reload if GET was rate-limited)
|
||||
const medRow = page.locator(".med-row").filter({ hasText: opts.name });
|
||||
try {
|
||||
await expect(medRow).toBeVisible({ timeout: 5000 });
|
||||
} catch {
|
||||
await page.reload();
|
||||
await page.waitForLoadState("networkidle");
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: save after editing (PUT) and wait for success.
|
||||
*/
|
||||
async function saveEdit(page: Page, medName: string): Promise<void> {
|
||||
const form = page.locator("form.form-grid:visible").first();
|
||||
await page.waitForLoadState("networkidle");
|
||||
const submitBtn = form.locator("button[type='submit']");
|
||||
if (
|
||||
(await submitBtn.count()) > 0 &&
|
||||
(await submitBtn
|
||||
.first()
|
||||
.isVisible()
|
||||
.catch(() => false))
|
||||
) {
|
||||
await submitBtn.first().click();
|
||||
} else {
|
||||
const closeBtn = form.getByRole("button", { name: /Close|Cancel/i }).first();
|
||||
if (await closeBtn.isVisible().catch(() => false)) {
|
||||
await closeBtn.click();
|
||||
}
|
||||
}
|
||||
// Wait for the list to update with the new name — retry with reload if rate-limited
|
||||
const medRow = page.locator(".med-row").filter({ hasText: medName });
|
||||
try {
|
||||
await expect(medRow).toBeVisible({ timeout: 15000 });
|
||||
} catch {
|
||||
await page.reload();
|
||||
await page.waitForLoadState("networkidle");
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("Medication CRUD", () => {
|
||||
test.use({ storageState: authFile });
|
||||
|
||||
// Clean up any leftover medications before and after all tests
|
||||
test.beforeAll(async () => {
|
||||
await deleteAllMedicationsViaAPI();
|
||||
});
|
||||
test.afterAll(async () => {
|
||||
await deleteAllMedicationsViaAPI();
|
||||
});
|
||||
|
||||
test.describe("Create medication", () => {
|
||||
// Clean up after each create test to avoid state leakage to later test blocks
|
||||
test.afterEach(async () => {
|
||||
await deleteAllMedicationsViaAPI();
|
||||
});
|
||||
|
||||
test("should create a blister-pack medication via the form", async ({ page }) => {
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await fillAndSaveMedication(page, {
|
||||
name: "Test Ibuprofen",
|
||||
genericName: "Ibuprofen",
|
||||
packageType: "blister",
|
||||
packs: "2",
|
||||
blistersPerPack: "3",
|
||||
pillsPerBlister: "10",
|
||||
loosePills: "5",
|
||||
});
|
||||
|
||||
// Verify medication details in the list
|
||||
const medRow = page.locator(".med-row").filter({ hasText: "Test Ibuprofen" });
|
||||
await expect(medRow.locator(".med-name")).toContainText("Test Ibuprofen");
|
||||
});
|
||||
|
||||
test("should create a bottle medication via the form", async ({ page }) => {
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await fillAndSaveMedication(page, {
|
||||
name: "Test Vitamin D Drops",
|
||||
packageType: "bottle",
|
||||
totalCapacity: "60",
|
||||
currentPills: "45",
|
||||
});
|
||||
});
|
||||
|
||||
test("should create medication with multiple intake schedules", async ({ page }) => {
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await fillAndSaveMedication(page, {
|
||||
name: "Test Multi-Intake Med",
|
||||
packs: "1",
|
||||
blistersPerPack: "2",
|
||||
pillsPerBlister: "14",
|
||||
intakes: [
|
||||
{ usage: "1", every: "1" },
|
||||
{ usage: "0.5", every: "7" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should create medication with notes and expiry date", async ({ page }) => {
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
const expiryDate = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split("T")[0];
|
||||
await fillAndSaveMedication(page, {
|
||||
name: "Test Aspirin",
|
||||
packs: "1",
|
||||
blistersPerPack: "1",
|
||||
pillsPerBlister: "20",
|
||||
expiryDate,
|
||||
notes: "Take with food. Do not exceed 3 per day.",
|
||||
});
|
||||
});
|
||||
|
||||
test("should not save with empty commercial name", async ({ page }) => {
|
||||
await navigateTo(page, "/medications");
|
||||
await page
|
||||
.getByRole("button", { name: /New medication|New entry|form\.newEntry/i })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
// Saving without name should not create a medication row.
|
||||
const saveBtn = page.locator("form.form-grid button[type='submit']");
|
||||
await expect(saveBtn).toBeVisible();
|
||||
await saveBtn.click();
|
||||
await expect(page.locator(".med-row")).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("should reset form after saving a medication", async ({ page }) => {
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await fillAndSaveMedication(page, {
|
||||
name: "Test Reset Check",
|
||||
packs: "1",
|
||||
blistersPerPack: "1",
|
||||
pillsPerBlister: "10",
|
||||
});
|
||||
|
||||
// Opening a fresh form after save should start with an empty commercial name.
|
||||
await page
|
||||
.getByRole("button", { name: /New medication|New entry|form\.newEntry/i })
|
||||
.first()
|
||||
.click();
|
||||
await expect(page.getByLabel(/(Commercial Name|form\.commercialName)/i)).toHaveValue("");
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Edit medication", () => {
|
||||
test.describe.configure({ timeout: 60000 });
|
||||
const createdMeds: TestMedication[] = [];
|
||||
|
||||
test.afterEach(async () => {
|
||||
for (const med of createdMeds) {
|
||||
await deleteMedicationViaAPI(med.id);
|
||||
}
|
||||
createdMeds.length = 0;
|
||||
});
|
||||
|
||||
test("should edit an existing medication", async ({ page }) => {
|
||||
// Create prerequisite via API (faster, no rate-limit issues)
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Before Edit" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
// Click Edit
|
||||
const medRow = page.locator(".med-row").filter({ hasText: "Before Edit" });
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
await medRow.locator("button.info").click();
|
||||
|
||||
// Form title should say "Edit entry" (or legacy "Edit medication").
|
||||
await expect(
|
||||
page.locator("h2").filter({ hasText: /(Edit(:| (entry|medication))|form\.editEntry)/i })
|
||||
).toBeVisible();
|
||||
|
||||
// The name field should have the current value
|
||||
await expect(page.getByLabel(/(Commercial Name|form\.commercialName)/i)).toHaveValue("Before Edit");
|
||||
|
||||
// Change the name
|
||||
await page.getByLabel(/(Commercial Name|form\.commercialName)/i).fill("After Edit");
|
||||
|
||||
// Save the edit
|
||||
await saveEdit(page, "After Edit");
|
||||
|
||||
// Old name should no longer appear
|
||||
await expect(page.locator(".med-row").filter({ hasText: "Before Edit" })).not.toBeVisible();
|
||||
|
||||
// Update tracked ID for cleanup
|
||||
createdMeds[0].name = "After Edit";
|
||||
});
|
||||
|
||||
test("should cancel editing and discard changes", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Cancel Test Med" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
// Click Edit
|
||||
const medRow = page.locator(".med-row").filter({ hasText: "Cancel Test Med" });
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
await medRow.locator("button.info").click();
|
||||
|
||||
// Change the name
|
||||
await page.getByLabel(/(Commercial Name|form\.commercialName)/i).fill("Modified Name");
|
||||
|
||||
// Click Cancel
|
||||
await page
|
||||
.getByRole("button", { name: /Close|Cancel/i })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
// Original name should still be in the list
|
||||
await expect(page.locator(".med-row").filter({ hasText: "Cancel Test Med" })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Delete medication", () => {
|
||||
test.describe.configure({ timeout: 60000 });
|
||||
const createdMeds: TestMedication[] = [];
|
||||
|
||||
test.afterEach(async () => {
|
||||
for (const med of createdMeds) {
|
||||
await deleteMedicationViaAPI(med.id);
|
||||
}
|
||||
createdMeds.length = 0;
|
||||
});
|
||||
|
||||
test("should delete a medication after confirming", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Delete Me Med" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
const medRow = page.locator(".med-row").filter({ hasText: "Delete Me Med" });
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await medRow.locator("button.danger").click();
|
||||
await page
|
||||
.locator(".confirm-modal-overlay, .modal-overlay")
|
||||
.getByRole("button", { name: /Delete/i })
|
||||
.click();
|
||||
|
||||
// Medication should be removed
|
||||
await expect(medRow).toHaveCount(0, { timeout: 10000 });
|
||||
|
||||
// Already deleted via UI — clear tracked list
|
||||
createdMeds.length = 0;
|
||||
});
|
||||
|
||||
test("should not delete when confirm dialog is dismissed", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Keep Me Med" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
const medRow = page.locator(".med-row").filter({ hasText: "Keep Me Med" });
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Dismiss the native confirm()
|
||||
page.on("dialog", (dialog) => dialog.dismiss());
|
||||
await medRow.locator("button.danger").click();
|
||||
|
||||
// Medication should still be there
|
||||
await expect(medRow).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Medication list", () => {
|
||||
test.describe.configure({ timeout: 60000 });
|
||||
const createdMeds: TestMedication[] = [];
|
||||
|
||||
test.afterEach(async () => {
|
||||
for (const med of createdMeds) {
|
||||
await deleteMedicationViaAPI(med.id);
|
||||
}
|
||||
createdMeds.length = 0;
|
||||
});
|
||||
|
||||
test("should display multiple medications in the list", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Med Alpha" }));
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: "Med Beta",
|
||||
packCount: 2,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 14,
|
||||
intakes: [
|
||||
{ usage: 2, every: 1, start: new Date().toISOString().slice(0, 16), intakeRemindersEnabled: false },
|
||||
],
|
||||
})
|
||||
);
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
// Both medications should be in the list
|
||||
await expect(page.locator(".med-row").filter({ hasText: "Med Alpha" })).toBeVisible({ timeout: 10000 });
|
||||
await expect(page.locator(".med-row").filter({ hasText: "Med Beta" })).toBeVisible();
|
||||
expect(await page.locator(".med-row").count()).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
test("should show stock details on medication row", async ({ page }) => {
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: "Stock Detail Med",
|
||||
packCount: 3,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 3,
|
||||
})
|
||||
);
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
const medRow = page.locator(".med-row").filter({ hasText: "Stock Detail Med" });
|
||||
try {
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
} catch {
|
||||
// Reload in case the list didn't include the newly created med
|
||||
await page.reload();
|
||||
await page.waitForLoadState("networkidle");
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
}
|
||||
|
||||
// Should display stock details
|
||||
const medDetails = medRow.locator(".med-details, .med-total");
|
||||
expect(await medDetails.count()).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Intake schedule management", () => {
|
||||
test("should add and remove intake schedule rows", async ({ page }) => {
|
||||
await navigateTo(page, "/medications");
|
||||
await page
|
||||
.getByRole("button", { name: /New medication|New entry|form\.newEntry/i })
|
||||
.first()
|
||||
.click();
|
||||
await page.getByRole("tab", { name: /Schedule/i }).click();
|
||||
const form = page.locator("form.form-grid:visible").first();
|
||||
|
||||
expect(await form.locator(".blister-row").count()).toBe(1);
|
||||
|
||||
await form.getByRole("button", { name: /(Intake|form\.blisters\.addIntake)/i }).click();
|
||||
expect(await form.locator(".blister-row").count()).toBe(2);
|
||||
|
||||
await form.getByRole("button", { name: /(Intake|form\.blisters\.addIntake)/i }).click();
|
||||
expect(await form.locator(".blister-row").count()).toBe(3);
|
||||
|
||||
const removeBtn = page
|
||||
.locator("form.form-grid:visible .blister-row")
|
||||
.last()
|
||||
.getByRole("button", { name: /Remove/i });
|
||||
await removeBtn.click();
|
||||
expect(await form.locator(".blister-row").count()).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,403 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import {
|
||||
authFile,
|
||||
createMedicationViaAPI,
|
||||
deleteAllMedicationsViaAPI,
|
||||
expect,
|
||||
navigateTo,
|
||||
type TestMedication,
|
||||
test,
|
||||
} from "./fixtures";
|
||||
|
||||
/**
|
||||
* Medication Edit E2E Tests
|
||||
*
|
||||
* Tests editing medications: changing fields, adding notes, taken-by persons,
|
||||
* generic name, refill stock, intake reminders, and intake schedule changes.
|
||||
* Each test creates a medication via API, edits it via the UI, and verifies the change.
|
||||
*/
|
||||
|
||||
/** Helper: click Edit button on a medication row */
|
||||
async function clickEditMed(page: Page, medName: string): Promise<void> {
|
||||
const medRow = page.locator(".med-row").filter({ hasText: medName });
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
if (await medRow.isVisible().catch(() => false)) break;
|
||||
await page.reload();
|
||||
await page.waitForLoadState("networkidle");
|
||||
await page.waitForTimeout(1000);
|
||||
}
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
await medRow.locator("button.info").click();
|
||||
await expect(page.locator("h2").filter({ hasText: /(Edit(:| (entry|medication))|form\.editEntry)/i })).toBeVisible({
|
||||
timeout: 5000,
|
||||
});
|
||||
}
|
||||
|
||||
/** Helper: save edit and verify success */
|
||||
async function saveEditAndVerify(page: Page, medName: string): Promise<void> {
|
||||
const form = page.locator("form.form-grid:visible").first();
|
||||
// Wait for any pending network before clicking save
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
const submitBtn = form.locator("button[type='submit']");
|
||||
if (
|
||||
(await submitBtn.count()) > 0 &&
|
||||
(await submitBtn
|
||||
.first()
|
||||
.isVisible()
|
||||
.catch(() => false))
|
||||
) {
|
||||
await submitBtn.first().click();
|
||||
} else {
|
||||
const closeBtn = form.getByRole("button", { name: /Close|Cancel/i }).first();
|
||||
if (await closeBtn.isVisible().catch(() => false)) {
|
||||
await closeBtn.click();
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for save request + re-fetch to complete
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
// Reload page to get fresh data from the backend
|
||||
// This ensures the meds array passed to startEdit has the saved changes
|
||||
await page.reload();
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
// Verify the med row is visible in the list
|
||||
const medRow = page.locator(".med-row").filter({ hasText: medName });
|
||||
await expect(medRow).toBeVisible({ timeout: 10000 });
|
||||
}
|
||||
|
||||
test.describe("Medication Editing", () => {
|
||||
test.use({ storageState: authFile });
|
||||
test.describe.configure({ timeout: 60000 });
|
||||
|
||||
const createdMeds: TestMedication[] = [];
|
||||
|
||||
test.beforeAll(async () => {
|
||||
await deleteAllMedicationsViaAPI();
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await deleteAllMedicationsViaAPI();
|
||||
});
|
||||
|
||||
test("should edit generic name on an existing medication", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Edit GenName Med" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "Edit GenName Med");
|
||||
|
||||
// Generic name should be empty initially
|
||||
const genericField = page.getByLabel(/(Generic Name|form\.genericName)/i);
|
||||
await expect(genericField).toHaveValue("");
|
||||
|
||||
// Add a generic name
|
||||
await genericField.fill("Acetylsalicylic acid");
|
||||
await expect(genericField).toHaveValue("Acetylsalicylic acid");
|
||||
|
||||
await saveEditAndVerify(page, "Edit GenName Med");
|
||||
|
||||
// Click edit again and verify the generic name was saved
|
||||
await clickEditMed(page, "Edit GenName Med");
|
||||
await expect(page.getByLabel(/(Generic Name|form\.genericName)/i)).toHaveValue("Acetylsalicylic acid");
|
||||
});
|
||||
|
||||
test("should add notes to an existing medication", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Edit Notes Med" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "Edit Notes Med");
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
|
||||
// Notes should be empty initially
|
||||
const notesField = page.getByLabel(/(Notes|form\.notes)/i);
|
||||
await expect(notesField).toHaveValue("");
|
||||
|
||||
// Add notes text
|
||||
await notesField.fill("Take with food after breakfast. Do not exceed 3 per day. Store below 25°C.");
|
||||
await expect(notesField).toContainText("Take with food after breakfast");
|
||||
|
||||
await saveEditAndVerify(page, "Edit Notes Med");
|
||||
|
||||
// Verify notes were saved by clicking edit again
|
||||
await clickEditMed(page, "Edit Notes Med");
|
||||
await expect(page.getByLabel(/(Notes|form\.notes)/i)).toContainText("Take with food after breakfast");
|
||||
});
|
||||
|
||||
test("should add taken-by person to a medication", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "TakenBy Med" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "TakenBy Med");
|
||||
|
||||
// Find the taken-by input field inside the tag-input-container
|
||||
const takenByContainer = page.locator(".tag-input-container");
|
||||
await expect(takenByContainer).toBeVisible();
|
||||
const takenByInput = takenByContainer.locator("input");
|
||||
|
||||
// Add a person name
|
||||
await takenByInput.fill("Alice");
|
||||
await takenByInput.press("Enter");
|
||||
|
||||
// Tag should appear
|
||||
await expect(takenByContainer.locator(".tag").filter({ hasText: "Alice" })).toBeVisible();
|
||||
|
||||
// Add another person
|
||||
await takenByInput.fill("Bob");
|
||||
await takenByInput.press("Enter");
|
||||
await expect(takenByContainer.locator(".tag").filter({ hasText: "Bob" })).toBeVisible();
|
||||
|
||||
await saveEditAndVerify(page, "TakenBy Med");
|
||||
|
||||
// Verify tags are persisted
|
||||
await clickEditMed(page, "TakenBy Med");
|
||||
await expect(page.locator(".tag-input-container .tag").filter({ hasText: "Alice" })).toBeVisible();
|
||||
await expect(page.locator(".tag-input-container .tag").filter({ hasText: "Bob" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("should remove a taken-by person from a medication", async ({ page }) => {
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: "Remove TakenBy Med",
|
||||
takenBy: ["Alice", "Bob"],
|
||||
})
|
||||
);
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "Remove TakenBy Med");
|
||||
|
||||
// Both persons should appear as tags
|
||||
const container = page.locator(".tag-input-container");
|
||||
await expect(container.locator(".tag")).toHaveCount(2, { timeout: 5000 });
|
||||
|
||||
// Use Backspace in the empty input to remove the last tag (Bob)
|
||||
// The app handles this: if input empty + backspace → remove last takenBy person
|
||||
const takenByInput = container.locator("input");
|
||||
await takenByInput.click();
|
||||
await takenByInput.press("Backspace");
|
||||
|
||||
// After backspace, Bob (the last tag) should be removed, leaving Alice
|
||||
await expect(container.locator(".tag")).toHaveCount(1, { timeout: 5000 });
|
||||
await expect(container.locator(".tag").filter({ hasText: "Alice" })).toBeVisible();
|
||||
|
||||
await saveEditAndVerify(page, "Remove TakenBy Med");
|
||||
|
||||
// Verify only Alice remains after save
|
||||
await clickEditMed(page, "Remove TakenBy Med");
|
||||
await expect(container.locator(".tag")).toHaveCount(1, { timeout: 5000 });
|
||||
await expect(container.locator(".tag").filter({ hasText: "Alice" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("should add an expiry date to a medication", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Expiry Date Med" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "Expiry Date Med");
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
|
||||
// Set expiry date to 6 months from now
|
||||
const expiryDate = new Date(Date.now() + 180 * 24 * 60 * 60 * 1000).toISOString().split("T")[0];
|
||||
const expiryField = page.getByLabel(/(Expiry Date|form\.expiryDate)/i);
|
||||
await expiryField.fill(expiryDate);
|
||||
await expect(expiryField).toHaveValue(expiryDate);
|
||||
|
||||
// Also touch the name field to ensure form is dirty
|
||||
// Expiry change itself is enough to persist in the current edit flow.
|
||||
|
||||
await saveEditAndVerify(page, "Expiry Date Med");
|
||||
|
||||
// Verify expiry date was saved
|
||||
await clickEditMed(page, "Expiry Date Med");
|
||||
await expect(page.getByLabel(/(Expiry Date|form\.expiryDate)/i)).toHaveValue(expiryDate);
|
||||
});
|
||||
|
||||
test("should edit intake schedule usage and interval", async ({ page }) => {
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: "Edit Intake Med",
|
||||
intakes: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: new Date().toISOString().slice(0, 16),
|
||||
intakeRemindersEnabled: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "Edit Intake Med");
|
||||
await page.getByRole("tab", { name: /Schedule/i }).click();
|
||||
|
||||
// Change intake from 1 pill daily to 2 pills every 7 days
|
||||
const intakeRow = page.locator(".blister-row").first();
|
||||
const usageField = intakeRow.getByLabel(/(Usage \(pills\)|form\.blisters\.usage)/i);
|
||||
const everyField = intakeRow.getByLabel(/(Every \(days\)|form\.blisters\.everyDays)/i);
|
||||
|
||||
await usageField.fill("2");
|
||||
await everyField.fill("7");
|
||||
|
||||
await expect(usageField).toHaveValue("2");
|
||||
await expect(everyField).toHaveValue("7");
|
||||
|
||||
await saveEditAndVerify(page, "Edit Intake Med");
|
||||
|
||||
// Verify the changes persisted
|
||||
await clickEditMed(page, "Edit Intake Med");
|
||||
const savedRow = page.locator(".blister-row").first();
|
||||
await expect(savedRow.getByLabel(/(Usage \(pills\)|form\.blisters\.usage)/i)).toHaveValue("2");
|
||||
await expect(savedRow.getByLabel(/(Every \(days\)|form\.blisters\.everyDays)/i)).toHaveValue("7");
|
||||
});
|
||||
|
||||
test("should add a second intake schedule row", async ({ page }) => {
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: "Add Intake Med",
|
||||
intakes: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: new Date().toISOString().slice(0, 16),
|
||||
intakeRemindersEnabled: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "Add Intake Med");
|
||||
await page.getByRole("tab", { name: /Schedule/i }).click();
|
||||
|
||||
// Should have 1 intake row initially
|
||||
await expect(page.locator(".blister-row")).toHaveCount(1);
|
||||
|
||||
// Add a second intake
|
||||
await page.getByRole("button", { name: /(Intake|form\.blisters\.addIntake)/i }).click();
|
||||
await expect(page.locator(".blister-row")).toHaveCount(2);
|
||||
|
||||
// Fill the new intake row
|
||||
const secondRow = page.locator(".blister-row").nth(1);
|
||||
await secondRow.getByLabel(/(Usage \(pills\)|form\.blisters\.usage)/i).fill("0.5");
|
||||
await secondRow.getByLabel(/(Every \(days\)|form\.blisters\.everyDays)/i).fill("7");
|
||||
|
||||
await saveEditAndVerify(page, "Add Intake Med");
|
||||
|
||||
// Verify 2 intakes persisted
|
||||
await clickEditMed(page, "Add Intake Med");
|
||||
await expect(page.locator(".blister-row")).toHaveCount(2, { timeout: 10000 });
|
||||
});
|
||||
|
||||
test("should toggle intake reminder on a medication", async ({ page }) => {
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: "Reminder Toggle Med",
|
||||
intakes: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: new Date().toISOString().slice(0, 16),
|
||||
intakeRemindersEnabled: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "Reminder Toggle Med");
|
||||
await page.getByRole("tab", { name: /Schedule/i }).click();
|
||||
|
||||
// Find the remind checkbox in the intake row
|
||||
const intakeRow = page.locator(".blister-row").first();
|
||||
const remindCheckbox = intakeRow.locator('input[type="checkbox"]');
|
||||
|
||||
if (await remindCheckbox.isVisible().catch(() => false)) {
|
||||
// Should be unchecked initially
|
||||
await expect(remindCheckbox).not.toBeChecked();
|
||||
|
||||
// Enable it
|
||||
await remindCheckbox.check();
|
||||
await expect(remindCheckbox).toBeChecked();
|
||||
|
||||
await saveEditAndVerify(page, "Reminder Toggle Med");
|
||||
|
||||
// Verify reminder was saved
|
||||
await clickEditMed(page, "Reminder Toggle Med");
|
||||
const savedCheckbox = page.locator(".blister-row").first().locator('input[type="checkbox"]');
|
||||
await expect(savedCheckbox).toBeChecked();
|
||||
}
|
||||
});
|
||||
|
||||
test("should change package type between blister and bottle", async ({ page }) => {
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: "PackType Change Med",
|
||||
packageType: "blister",
|
||||
packCount: 2,
|
||||
blistersPerPack: 3,
|
||||
pillsPerBlister: 10,
|
||||
})
|
||||
);
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "PackType Change Med");
|
||||
const form = page.locator("form.form-grid:visible").first();
|
||||
|
||||
// Should be blister type initially
|
||||
const packageSelect = form.locator("select.package-type-select");
|
||||
await expect(packageSelect).toHaveValue("blister");
|
||||
|
||||
// Blister-specific fields are shown in the Package tab.
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
await expect(form.getByLabel(/(Blisters per pack|form\.blistersPerPack)/i)).toBeVisible();
|
||||
await page.getByRole("tab", { name: /General/i }).click();
|
||||
|
||||
// Switch to bottle
|
||||
await packageSelect.selectOption("bottle");
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
await expect(form.getByLabel(/(Total Capacity|form\.totalCapacity|Total \(pills\))/i)).toBeVisible();
|
||||
|
||||
// Fill bottle-specific fields
|
||||
await form.getByLabel(/(Total Capacity|form\.totalCapacity|Total \(pills\))/i).fill("120");
|
||||
|
||||
await saveEditAndVerify(page, "PackType Change Med");
|
||||
|
||||
// Verify it's still a bottle after reload
|
||||
await clickEditMed(page, "PackType Change Med");
|
||||
await expect(page.locator("select.package-type-select")).toHaveValue("bottle");
|
||||
});
|
||||
|
||||
test("should edit multiple fields at once (name, notes, generic, taken-by)", async ({ page }) => {
|
||||
createdMeds.push(await createMedicationViaAPI({ name: "Multi Edit Med" }));
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await clickEditMed(page, "Multi Edit Med");
|
||||
|
||||
// Change the name
|
||||
await page.getByLabel(/(Commercial Name|form\.commercialName)/i).fill("Fully Edited Med");
|
||||
|
||||
// Add generic name
|
||||
await page.getByLabel(/(Generic Name|form\.genericName)/i).fill("Ibuprofen Lysinate");
|
||||
|
||||
// Add notes
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
await page.getByLabel(/(Notes|form\.notes)/i).fill("Morning dose only. Take with plenty of water.");
|
||||
await page.getByRole("tab", { name: /General/i }).click();
|
||||
|
||||
// Add a taken-by person
|
||||
const takenByInput = page.locator(".tag-input-container input");
|
||||
await takenByInput.fill("Charlie");
|
||||
await takenByInput.press("Enter");
|
||||
await expect(page.locator(".tag-input-container .tag").filter({ hasText: "Charlie" })).toBeVisible();
|
||||
|
||||
await saveEditAndVerify(page, "Fully Edited Med");
|
||||
|
||||
// Verify all changes persisted
|
||||
await clickEditMed(page, "Fully Edited Med");
|
||||
await expect(page.getByLabel(/(Commercial Name|form\.commercialName)/i)).toHaveValue("Fully Edited Med");
|
||||
await expect(page.getByLabel(/(Generic Name|form\.genericName)/i)).toHaveValue("Ibuprofen Lysinate");
|
||||
await expect(page.getByLabel(/(Notes|form\.notes)/i)).toContainText("Morning dose only");
|
||||
await expect(page.locator(".tag-input-container .tag").filter({ hasText: "Charlie" })).toBeVisible();
|
||||
});
|
||||
});
|
||||
+121
-159
@@ -1,200 +1,162 @@
|
||||
import * as path from "node:path";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const authFile = path.join(import.meta.dirname, ".auth", "user.json");
|
||||
|
||||
/**
|
||||
* Helper to wait for the medication form to be visible after clicking add
|
||||
*/
|
||||
async function waitForFormVisible(page: import("@playwright/test").Page): Promise<void> {
|
||||
// Wait for form elements to appear (name field or form container)
|
||||
await page
|
||||
.getByLabel(/commercial.*name|name/i)
|
||||
.first()
|
||||
.waitFor({ state: "visible", timeout: 5000 })
|
||||
.catch(() => {
|
||||
// Form might not be available, that's ok
|
||||
});
|
||||
}
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { authFile, navigateTo, test } from "./fixtures";
|
||||
|
||||
/**
|
||||
* Medications Page E2E Tests
|
||||
*
|
||||
* These tests verify the medications management functionality including
|
||||
* viewing, adding, editing, and deleting medications.
|
||||
* Verifies the medication list, add/edit form, CRUD operations,
|
||||
* and form validation.
|
||||
*/
|
||||
test.describe("Medications Page", () => {
|
||||
test.use({ storageState: authFile });
|
||||
|
||||
const visibleMedForm = (page: Page) => page.locator("form.form-grid:visible").first();
|
||||
|
||||
async function openMedicationForm(page: Page) {
|
||||
await navigateTo(page, "/medications");
|
||||
const nameField = visibleMedForm(page).getByLabel(/(Commercial Name|form\.commercialName)/i);
|
||||
if (await nameField.isVisible().catch(() => false)) return;
|
||||
|
||||
const newEntryButton = page.getByRole("button", { name: /(new (entry|medication)|form\.newEntry)/i });
|
||||
if (await newEntryButton.isVisible().catch(() => false)) {
|
||||
await newEntryButton.click();
|
||||
await expect(nameField).toBeVisible({ timeout: 5000 });
|
||||
}
|
||||
}
|
||||
|
||||
test("should display medications page", async ({ page }) => {
|
||||
await page.goto("/medications");
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
// Wait for app to load
|
||||
await expect(page.locator("body")).not.toContainText(/Loading\.\.\.|Initializing\.\.\./, {
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Should display navigation
|
||||
await expect(page.getByRole("navigation")).toBeVisible();
|
||||
|
||||
// Page should have medications-related content
|
||||
const hasContent =
|
||||
(await page
|
||||
.getByText(/medications|inventory|add/i)
|
||||
.isVisible()
|
||||
.catch(() => false)) ||
|
||||
(await page
|
||||
.getByText(/no medications/i)
|
||||
.isVisible()
|
||||
.catch(() => false));
|
||||
|
||||
expect(hasContent).toBeTruthy();
|
||||
// Medications tab should be active
|
||||
await expect(page.locator('button.pill.primary:has-text("Medications")')).toBeVisible();
|
||||
});
|
||||
|
||||
test("should have medication form fields", async ({ page }) => {
|
||||
await page.goto("/medications");
|
||||
test("should show medication list or empty state", async ({ page }) => {
|
||||
await navigateTo(page, "/medications");
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
// Should show either medication entries or the new medication form
|
||||
const listTitle = page.locator("h2").filter({ hasText: /(Medication list|form\.medicationList)/i });
|
||||
const formTitle = page.locator("h2").filter({ hasText: /(New (entry|medication)|form\.newEntry)/i });
|
||||
|
||||
// Look for the medication form fields (may be visible immediately or after clicking add)
|
||||
const addButton = page.getByRole("button", { name: /add|new|create/i });
|
||||
const hasList = await listTitle.isVisible().catch(() => false);
|
||||
const hasForm = await formTitle.isVisible().catch(() => false);
|
||||
|
||||
if (await addButton.isVisible().catch(() => false)) {
|
||||
// Form might be hidden, click add button
|
||||
await addButton.click();
|
||||
await waitForFormVisible(page);
|
||||
}
|
||||
|
||||
// Check for form fields - commercial name is required
|
||||
const hasNameField =
|
||||
(await page
|
||||
.getByLabel(/commercial.*name|name/i)
|
||||
.isVisible()
|
||||
.catch(() => false)) ||
|
||||
(await page
|
||||
.getByPlaceholder(/ozempic|medication/i)
|
||||
.isVisible()
|
||||
.catch(() => false));
|
||||
|
||||
// The form should have name field at minimum
|
||||
expect(hasNameField).toBeTruthy();
|
||||
expect(hasList || hasForm).toBeTruthy();
|
||||
});
|
||||
|
||||
test("should validate required fields on submit", async ({ page }) => {
|
||||
await page.goto("/medications");
|
||||
test("should display the medication form with required fields", async ({ page }) => {
|
||||
await openMedicationForm(page);
|
||||
const form = visibleMedForm(page);
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
const commercialName = form.getByLabel(/(Commercial Name|form\.commercialName)/i);
|
||||
await expect(commercialName).toBeVisible();
|
||||
|
||||
// Find or trigger the add medication form
|
||||
const addButton = page.getByRole("button", { name: /add|new|create/i });
|
||||
if (await addButton.isVisible().catch(() => false)) {
|
||||
await addButton.click();
|
||||
await waitForFormVisible(page);
|
||||
}
|
||||
// Package type selector should exist
|
||||
await expect(form.getByText(/(Package Type|form\.packageType)/i)).toBeVisible();
|
||||
|
||||
// Try to submit without filling required fields
|
||||
const saveButton = page.getByRole("button", { name: /save|submit|add.*medication/i });
|
||||
if (await saveButton.isVisible().catch(() => false)) {
|
||||
await saveButton.click();
|
||||
// Tabbed form should expose navigation to Package/Schedule sections
|
||||
await expect(page.getByRole("tab", { name: /Package/i })).toBeVisible();
|
||||
await expect(page.getByRole("tab", { name: /Schedule/i })).toBeVisible();
|
||||
});
|
||||
|
||||
// Should show validation error or prevent submission
|
||||
const nameField = page.getByLabel(/commercial.*name|name/i).first();
|
||||
if (await nameField.isVisible().catch(() => false)) {
|
||||
const isInvalid =
|
||||
(await nameField.evaluate((el) => (el as HTMLInputElement).validity.valueMissing).catch(() => false)) ||
|
||||
(await page
|
||||
.getByText(/required|invalid|error/i)
|
||||
.isVisible()
|
||||
.catch(() => false));
|
||||
test("should fill in medication details", async ({ page }) => {
|
||||
await openMedicationForm(page);
|
||||
const form = visibleMedForm(page);
|
||||
|
||||
expect(isInvalid || true).toBeTruthy();
|
||||
}
|
||||
const nameField = form.getByLabel(/(Commercial Name|form\.commercialName)/i);
|
||||
await nameField.fill("Test Aspirin");
|
||||
await expect(nameField).toHaveValue("Test Aspirin");
|
||||
|
||||
const genericField = form.getByLabel(/(Generic Name|form\.genericName)/i);
|
||||
await genericField.fill("Acetylsalicylic acid");
|
||||
await expect(genericField).toHaveValue("Acetylsalicylic acid");
|
||||
});
|
||||
|
||||
test("should have stock inventory fields", async ({ page }) => {
|
||||
await openMedicationForm(page);
|
||||
const form = visibleMedForm(page);
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
|
||||
// Package tab should expose stock-related fields for at least one package mode.
|
||||
const packsField = form.getByLabel(/(^Packs$|form\.packs)/i).first();
|
||||
const totalField = form.getByText(/(Total \(pills\)|Total Capacity|form\.totalCapacity)/i).first();
|
||||
|
||||
const hasPacks = await packsField.isVisible().catch(() => false);
|
||||
const hasTotal = await totalField.isVisible().catch(() => false);
|
||||
|
||||
expect(hasPacks || hasTotal).toBeTruthy();
|
||||
});
|
||||
|
||||
test("should toggle package type between blister and bottle", async ({ page }) => {
|
||||
await openMedicationForm(page);
|
||||
const form = visibleMedForm(page);
|
||||
await page.getByRole("tab", { name: /Package/i }).click();
|
||||
|
||||
// Find the package type radio buttons or selector
|
||||
const blisterOption = form.getByText(/(Blister Pack|form\.packageType\.blister)/i);
|
||||
const bottleOption = form.getByText(/(Pill Bottle|form\.packageType\.bottle)/i);
|
||||
|
||||
if (await blisterOption.isVisible().catch(() => false)) {
|
||||
// Switch to bottle
|
||||
await bottleOption.click();
|
||||
// Bottle-specific fields should appear
|
||||
await expect(form.getByLabel(/(Total Capacity|form\.totalCapacity)/i)).toBeVisible();
|
||||
|
||||
// Switch back to blister
|
||||
await blisterOption.click();
|
||||
await expect(form.getByLabel(/(Blisters per pack|form\.blistersPerPack)/i)).toBeVisible();
|
||||
}
|
||||
});
|
||||
|
||||
test("should allow entering medication details", async ({ page }) => {
|
||||
await page.goto("/medications");
|
||||
test("should have intake schedule with add button", async ({ page }) => {
|
||||
await openMedicationForm(page);
|
||||
const form = visibleMedForm(page);
|
||||
await page.getByRole("tab", { name: /Schedule/i }).click();
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
// Intake schedule section
|
||||
await expect(page.getByRole("tab", { name: /Schedule/i, selected: true })).toBeVisible();
|
||||
|
||||
// Find or trigger the add medication form
|
||||
const addButton = page.getByRole("button", { name: /add|new|create/i });
|
||||
if (await addButton.isVisible().catch(() => false)) {
|
||||
await addButton.click();
|
||||
await waitForFormVisible(page);
|
||||
}
|
||||
// Should have at least one intake entry
|
||||
await expect(
|
||||
form.getByText(/(Usage \(pills\)|Every \(days\)|form\.blisters\.usage|form\.blisters\.everyDays)/i).first()
|
||||
).toBeVisible();
|
||||
|
||||
// Fill in medication details
|
||||
const nameField = page.getByLabel(/commercial.*name|name/i).first();
|
||||
if (await nameField.isVisible().catch(() => false)) {
|
||||
await nameField.fill("Test Medication");
|
||||
|
||||
// Verify the value was entered
|
||||
await expect(nameField).toHaveValue("Test Medication");
|
||||
}
|
||||
|
||||
// Try to fill generic name if available
|
||||
const genericField = page.getByLabel(/generic/i);
|
||||
if (await genericField.isVisible().catch(() => false)) {
|
||||
await genericField.fill("Test Generic");
|
||||
await expect(genericField).toHaveValue("Test Generic");
|
||||
}
|
||||
// Should have an add intake button
|
||||
const addIntake = form.getByRole("button", { name: /(Intake|form\.blisters\.addIntake)/i });
|
||||
await expect(addIntake).toBeVisible();
|
||||
});
|
||||
|
||||
test("should display intake schedule section", async ({ page }) => {
|
||||
await page.goto("/medications");
|
||||
test("should have save and cancel buttons", async ({ page }) => {
|
||||
await openMedicationForm(page);
|
||||
const form = visibleMedForm(page);
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
// Fill in a name to make the form dirty
|
||||
await form.getByLabel(/(Commercial Name|form\.commercialName)/i).fill("Test");
|
||||
|
||||
// Find or trigger the add medication form
|
||||
const addButton = page.getByRole("button", { name: /add|new|create/i });
|
||||
if (await addButton.isVisible().catch(() => false)) {
|
||||
await addButton.click();
|
||||
await waitForFormVisible(page);
|
||||
}
|
||||
|
||||
// Look for intake schedule section
|
||||
const hasScheduleSection =
|
||||
(await page
|
||||
.getByText(/intake.*schedule|dosage|usage/i)
|
||||
.isVisible()
|
||||
.catch(() => false)) ||
|
||||
(await page
|
||||
.getByText(/every.*days|pills/i)
|
||||
.isVisible()
|
||||
.catch(() => false));
|
||||
|
||||
expect(hasScheduleSection).toBeTruthy();
|
||||
// Save button
|
||||
const saveButton = page.getByRole("button", { name: /Save|Add Medication/i });
|
||||
await expect(saveButton).toBeVisible();
|
||||
});
|
||||
|
||||
test("should have cancel functionality", async ({ page }) => {
|
||||
await page.goto("/medications");
|
||||
test("should prevent navigation with unsaved changes", async ({ page }) => {
|
||||
await openMedicationForm(page);
|
||||
const form = visibleMedForm(page);
|
||||
|
||||
await expect(page.getByRole("navigation")).toBeVisible({ timeout: 10000 });
|
||||
// Fill in the form to create unsaved changes
|
||||
await form.getByLabel(/(Commercial Name|form\.commercialName)/i).fill("Unsaved Medication");
|
||||
|
||||
// Find or trigger the add medication form
|
||||
const addButton = page.getByRole("button", { name: /add|new|create/i });
|
||||
if (await addButton.isVisible().catch(() => false)) {
|
||||
await addButton.click();
|
||||
await waitForFormVisible(page);
|
||||
// Try to navigate away
|
||||
await page.locator('button.pill:has-text("Dashboard")').click();
|
||||
|
||||
// Fill in some data
|
||||
const nameField = page.getByLabel(/commercial.*name|name/i).first();
|
||||
if (await nameField.isVisible().catch(() => false)) {
|
||||
await nameField.fill("Test Medication");
|
||||
}
|
||||
// Should show unsaved changes warning modal
|
||||
const modal = page.locator(".confirm-modal-overlay, .modal-overlay");
|
||||
const hasWarning = await modal.isVisible().catch(() => false);
|
||||
|
||||
// Look for cancel button
|
||||
const cancelButton = page.getByRole("button", { name: /cancel|close|discard/i });
|
||||
if (await cancelButton.isVisible().catch(() => false)) {
|
||||
await cancelButton.click();
|
||||
|
||||
// Wait for form to be hidden or reset
|
||||
await expect(nameField)
|
||||
.not.toHaveValue("Test Medication")
|
||||
.catch(() => {
|
||||
// Form might be completely hidden, that's also acceptable
|
||||
});
|
||||
if (hasWarning) {
|
||||
// Cancel to stay on page
|
||||
const cancelBtn = page.getByRole("button", { name: /Cancel|Stay/i });
|
||||
if (await cancelBtn.isVisible().catch(() => false)) {
|
||||
await cancelBtn.click();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import {
|
||||
authFile,
|
||||
createMedicationViaAPI,
|
||||
deleteAllMedicationsViaAPI,
|
||||
expect,
|
||||
navigateTo,
|
||||
type TestMedication,
|
||||
test,
|
||||
} from "./fixtures";
|
||||
|
||||
/**
|
||||
* Helper: navigate to planner, wait for page to be ready, click Calculate,
|
||||
* and wait for results to appear.
|
||||
*/
|
||||
async function calculatePlanner(page: Page): Promise<void> {
|
||||
await page.waitForLoadState("networkidle");
|
||||
await page.locator('form.planner button[type="submit"]').click();
|
||||
// Wait for the results table to appear (more reliable than waitForResponse
|
||||
// since 429 responses would satisfy waitForResponse but not populate results)
|
||||
await expect(page.locator(".table")).toBeVisible({ timeout: 15000 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Planner with Medication Data E2E Tests
|
||||
*
|
||||
* Creates medications via API, then verifies the demand calculator
|
||||
* produces correct results with status chips and usage data.
|
||||
*/
|
||||
test.describe("Planner with medications", () => {
|
||||
test.use({ storageState: authFile });
|
||||
test.describe.configure({ timeout: 60000 });
|
||||
|
||||
const MED_HIGH = "PlanData HighStock";
|
||||
const MED_LOW = "PlanData LowStock";
|
||||
|
||||
const todayMorning = (() => {
|
||||
const d = new Date();
|
||||
d.setHours(8, 0, 0, 0);
|
||||
const pad = (n: number) => n.toString().padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
})();
|
||||
|
||||
const createdMeds: TestMedication[] = [];
|
||||
|
||||
test.beforeAll(async () => {
|
||||
// Clean up any leftover medications from previous test runs
|
||||
await deleteAllMedicationsViaAPI();
|
||||
// Medication with plenty of stock (60 pills)
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: MED_HIGH,
|
||||
packageType: "blister",
|
||||
packCount: 2,
|
||||
blistersPerPack: 3,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
intakes: [{ usage: 1, every: 1, start: todayMorning, intakeRemindersEnabled: false }],
|
||||
})
|
||||
);
|
||||
// Medication with very low stock (3 pills)
|
||||
createdMeds.push(
|
||||
await createMedicationViaAPI({
|
||||
name: MED_LOW,
|
||||
packageType: "blister",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 3,
|
||||
looseTablets: 0,
|
||||
intakes: [{ usage: 1, every: 1, start: todayMorning, intakeRemindersEnabled: false }],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await deleteAllMedicationsViaAPI();
|
||||
});
|
||||
|
||||
test("should show results table after calculating", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
|
||||
test("should show medication names in results", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await expect(resultsTable.getByText(MED_HIGH)).toBeVisible();
|
||||
await expect(resultsTable.getByText(MED_LOW)).toBeVisible();
|
||||
});
|
||||
|
||||
test("should show status chips in results", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
const statusChips = resultsTable.locator(".status-chip");
|
||||
expect(await statusChips.count()).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
test("should show usage data in results rows", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
const rows = resultsTable.locator(".table-row");
|
||||
expect(await rows.count()).toBeGreaterThanOrEqual(2);
|
||||
|
||||
const firstRowText = await rows.first().textContent();
|
||||
expect(firstRowText).toBeTruthy();
|
||||
// Check for "pill" (matches both "pill" and "pills")
|
||||
expect(firstRowText!.toLowerCase()).toContain("pill");
|
||||
});
|
||||
|
||||
test("should show danger status for low-stock medication over 90 days", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
|
||||
// Set the "until" date to 90 days from now
|
||||
const dateInputs = page.locator('form.planner input[type="datetime-local"]');
|
||||
const untilInput = dateInputs.last();
|
||||
const fromValue = await dateInputs.first().inputValue();
|
||||
const fromDate = new Date(fromValue);
|
||||
const untilDate = new Date(fromDate.getTime() + 90 * 24 * 60 * 60 * 1000);
|
||||
const pad = (n: number) => n.toString().padStart(2, "0");
|
||||
const untilValue = `${untilDate.getFullYear()}-${pad(untilDate.getMonth() + 1)}-${pad(untilDate.getDate())}T${pad(untilDate.getHours())}:${pad(untilDate.getMinutes())}`;
|
||||
await untilInput.fill(untilValue);
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Low-stock med (3 pills) should have a danger chip over 90 days
|
||||
const dangerChips = resultsTable.locator(".status-chip.danger");
|
||||
expect(await dangerChips.count()).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("should show Enough status for well-stocked medication over 7 days", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
|
||||
// Set a short date range: 7 days
|
||||
const dateInputs = page.locator('form.planner input[type="datetime-local"]');
|
||||
const untilInput = dateInputs.last();
|
||||
const fromValue = await dateInputs.first().inputValue();
|
||||
const fromDate = new Date(fromValue);
|
||||
const untilDate = new Date(fromDate.getTime() + 7 * 24 * 60 * 60 * 1000);
|
||||
const pad = (n: number) => n.toString().padStart(2, "0");
|
||||
const untilValue = `${untilDate.getFullYear()}-${pad(untilDate.getMonth() + 1)}-${pad(untilDate.getDate())}T${pad(untilDate.getHours())}:${pad(untilDate.getMinutes())}`;
|
||||
await untilInput.fill(untilValue);
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// With 60 pills and 7-day range, high-stock should be "Enough"
|
||||
const successChips = resultsTable.locator(".status-chip.success");
|
||||
expect(await successChips.count()).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("should show table header with correct columns", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
const tableHead = resultsTable.locator(".table-head");
|
||||
await expect(tableHead).toBeVisible();
|
||||
await expect(tableHead.getByText(/Medication/i)).toBeVisible();
|
||||
await expect(tableHead.getByText(/Usage/i)).toBeVisible();
|
||||
await expect(tableHead.getByText(/Status/i)).toBeVisible();
|
||||
});
|
||||
|
||||
test("should reset form and clear results", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click Reset
|
||||
await page.locator("form.planner button.ghost").click();
|
||||
|
||||
// Results should be cleared
|
||||
await expect(resultsTable).not.toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test("should make results rows clickable for medication detail", async ({ page }) => {
|
||||
await navigateTo(page, "/planner");
|
||||
await calculatePlanner(page);
|
||||
|
||||
const resultsTable = page.locator(".table");
|
||||
await expect(resultsTable).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click on a results row
|
||||
await resultsTable.locator(".table-row").first().click();
|
||||
|
||||
const modal = page.locator(".modal-overlay");
|
||||
await expect(modal).toBeVisible({ timeout: 5000 });
|
||||
|
||||
await page.locator("button.modal-close").click();
|
||||
await expect(modal).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user