Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8c5deed4c2 | |||
| b19bcf02c2 | |||
| 27a9910dbd | |||
| eb2e445398 | |||
| 61b8812808 | |||
| f7838bd919 | |||
| b0fd3f4187 | |||
| b91717fc19 | |||
| a065adcd82 | |||
| 6edf2fa341 | |||
| 9e3d548536 |
@@ -129,13 +129,26 @@ Apply these rules strictly:
|
|||||||
|
|
||||||
## Task 3: Execute Release
|
## Task 3: Execute Release
|
||||||
|
|
||||||
Use the release script whenever possible:
|
Use the release script — it is **fully non-interactive** (no y/N prompts) and handles the entire flow automatically:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./scripts/release.sh <patch|minor|major>
|
./scripts/release.sh <patch|minor|major|x.y.z>
|
||||||
```
|
```
|
||||||
|
|
||||||
This script handles: branch creation → version bump → PR → CI wait → merge → signed tag → push.
|
The script performs these steps in order:
|
||||||
|
1. Checks out and updates `main`
|
||||||
|
2. Creates release branch `chore/release-X.Y.Z`
|
||||||
|
3. Bumps version in `backend/package.json` and `frontend/package.json`
|
||||||
|
4. Commits, pushes, and creates a PR
|
||||||
|
5. Waits for CI checks (with retry logic — polls every 15s, waits up to 10 minutes)
|
||||||
|
6. Merges the PR (squash + delete branch)
|
||||||
|
7. Creates a signed tag `vX.Y.Z` and pushes it
|
||||||
|
|
||||||
|
**The script auto-detects the git remote** (`origin` or `github`) and uses it consistently.
|
||||||
|
|
||||||
|
**CI wait behavior:** GitHub Actions can take 10-30 seconds before checks appear on a new PR. The script waits 20 seconds initially, then polls every 15 seconds until checks are registered, then watches them to completion. Maximum wait is 10 minutes.
|
||||||
|
|
||||||
|
**On failure:** If CI fails, the script exits with an error. The release branch and PR remain open for inspection. Fix the issue, push to the branch, and the PR will re-run CI. Then merge manually or re-run the script.
|
||||||
|
|
||||||
### Version Files (MANDATORY)
|
### Version Files (MANDATORY)
|
||||||
|
|
||||||
@@ -166,8 +179,8 @@ The version number is displayed in the **About modal** (Settings → About) as a
|
|||||||
|
|
||||||
### After Tagging
|
### After Tagging
|
||||||
|
|
||||||
- The `docker-build.yml` workflow automatically builds and pushes Docker images to GHCR.
|
- 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 `version-bump.yml` workflow automatically updates `package.json` versions if needed.
|
- The `update-test-badges.yml` workflow runs automatically after a successful Docker build to update test count badges in the README.
|
||||||
- Track progress: `https://github.com/DanielVolz/medassist-ng/actions`
|
- Track progress: `https://github.com/DanielVolz/medassist-ng/actions`
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -199,19 +212,20 @@ Read the actual code changes (not just commit messages) to understand what was a
|
|||||||
- Use `### Heading` for sections
|
- Use `### Heading` for sections
|
||||||
- Use **bold** for feature names in bullet points
|
- Use **bold** for feature names in bullet points
|
||||||
- Keep descriptions on the same line as the feature name
|
- Keep descriptions on the same line as the feature name
|
||||||
- Minimal emoji usage (sparingly, not on every line)
|
- **No emojis** — do not use emoji in headings or bullet points
|
||||||
|
- **Include commit references** — each bullet point must end with the PR number (e.g., `(#136)`) or short commit hash (e.g., `(ab12cd3)`) linking to the commit/PR. Use PR numbers when available.
|
||||||
- Always end with "Where to Find It" section
|
- Always end with "Where to Find It" section
|
||||||
- End with: `**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/vPREV...vNEW`
|
- End with: `**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/vPREV...vNEW`
|
||||||
|
|
||||||
**ONLY include user-relevant changes.** DO NOT include:
|
**ONLY include user-relevant changes.** DO NOT include:
|
||||||
- ❌ Technical implementation details (new columns, endpoints, database changes)
|
- Technical implementation details (new columns, endpoints, database changes)
|
||||||
- ❌ Number of tests added
|
- Number of tests added
|
||||||
- ❌ Internal API changes (unless breaking)
|
- Internal API changes (unless breaking)
|
||||||
- ❌ Excessive emoji on every bullet point
|
- Emojis anywhere in the release notes
|
||||||
- ❌ .gitignore changes or other developer-only file changes
|
- .gitignore changes or other developer-only file changes
|
||||||
- ❌ AI/Copilot instruction updates
|
- AI/Copilot instruction updates
|
||||||
- ❌ CI/CD workflow changes (unless affecting users)
|
- CI/CD workflow changes (unless affecting users)
|
||||||
- ❌ Code refactoring without user-visible changes
|
- Code refactoring without user-visible changes
|
||||||
|
|
||||||
### Example: Good Release Notes
|
### Example: Good Release Notes
|
||||||
|
|
||||||
@@ -222,14 +236,14 @@ This release introduces a medication refill tracking feature and improves the mo
|
|||||||
|
|
||||||
### New Features
|
### 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.
|
- **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.
|
- **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.
|
- **Refill History**: Each medication shows a complete history of all refills with timestamps. (#122)
|
||||||
|
|
||||||
### Mobile Improvements
|
### Improvements
|
||||||
|
|
||||||
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability.
|
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability. (#125)
|
||||||
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices.
|
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices. (#125)
|
||||||
|
|
||||||
### Where to Find It
|
### Where to Find It
|
||||||
|
|
||||||
@@ -281,6 +295,30 @@ gh release create vX.Y.Z --title "vX.Y.Z" --notes "RELEASE_NOTES_HERE"
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Task 5: README Update Check (MANDATORY for new features)
|
||||||
|
|
||||||
|
When the release includes **new features** (minor or major version bump), you MUST check whether the `README.md` needs to be updated **before** executing the release.
|
||||||
|
|
||||||
|
### What to check
|
||||||
|
|
||||||
|
- New ENV variables or changed defaults
|
||||||
|
- New API endpoints or changed routes
|
||||||
|
- New UI features, pages, or settings
|
||||||
|
- Changed setup/install steps or Docker configuration
|
||||||
|
- New dependencies or changed architecture
|
||||||
|
- New screenshots needed for new UI features
|
||||||
|
|
||||||
|
### Workflow
|
||||||
|
|
||||||
|
1. Review the changes included in the release
|
||||||
|
2. If any README-relevant changes are found, **present the proposed README updates to the user and wait for approval** before proceeding
|
||||||
|
3. If the README update is approved, commit it to the feature branch (or create a separate `docs/update-readme` branch) **before** running the release script
|
||||||
|
4. Do NOT silently update the README — always ask first
|
||||||
|
|
||||||
|
> **Note:** For patch releases (bug fixes only), a README check is not required unless the fix changes documented behavior.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Complete Workflow Summary
|
## Complete Workflow Summary
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -295,11 +333,12 @@ Ready for release?
|
|||||||
↓
|
↓
|
||||||
5. Check current version (git tag + package.json)
|
5. Check current version (git tag + package.json)
|
||||||
6. Analyze changes → determine SemVer level
|
6. Analyze changes → determine SemVer level
|
||||||
7. Run ./scripts/release.sh <patch|minor|major>
|
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)
|
(or manually: branch → version bump → PR → CI → merge → tag)
|
||||||
↓
|
↓
|
||||||
8. Write release notes (mandatory for minor/major)
|
9. Write release notes (mandatory for minor/major)
|
||||||
9. Publish GitHub release
|
10. Publish GitHub release
|
||||||
↓
|
↓
|
||||||
Docker images built automatically via CI
|
Docker images built automatically via CI
|
||||||
```
|
```
|
||||||
@@ -4,12 +4,13 @@
|
|||||||
|
|
||||||
- **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English.
|
- **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English.
|
||||||
- **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action.
|
- **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action.
|
||||||
- **NEVER create PRs without explicit permission**: Do NOT create Pull Requests, push branches, or merge code unless the user explicitly asks for it. Always present changes and wait for the user to confirm before any git operations that affect the remote repository.
|
- **NEVER create PRs, push, or merge**: Only the **release-manager agent** (`@release-manager`) is allowed to create Pull Requests, push branches to the remote, or merge code. Regular agents and Copilot MUST NOT perform any git operations that affect the remote repository (no `git push`, no `gh pr create`, no `gh pr merge`). Present your local changes and tell the user to invoke `@release-manager` when ready to ship.
|
||||||
- **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository.
|
- **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository.
|
||||||
- **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done.
|
- **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done.
|
||||||
- **Remove old code when re-implementing**: When fixing a bug or re-implementing a feature that didn't work, ALWAYS remove the old/broken code completely. Never leave dead code, unused functions, or obsolete implementations in the codebase.
|
- **Remove old code when re-implementing**: When fixing a bug or re-implementing a feature that didn't work, ALWAYS remove the old/broken code completely. Never leave dead code, unused functions, or obsolete implementations in the codebase.
|
||||||
- **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests. When modifying existing features, update or add tests accordingly. If old tests become obsolete due to code changes, remove or update them.
|
- **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests. When modifying existing features, update or add tests accordingly. If old tests become obsolete due to code changes, remove or update them.
|
||||||
- **Fix bugs, don't test around them**: If you discover incorrect behavior in the code while writing tests, ALWAYS fix the buggy code first, then write tests that verify the correct behavior. NEVER write tests that mimic or assert broken behavior. The user's time is finite and irreplaceable — every bug left unfixed wastes it.
|
- **Fix bugs, don't test around them**: If you discover incorrect behavior in the code while writing tests, ALWAYS fix the buggy code first, then write tests that verify the correct behavior. NEVER write tests that mimic or assert broken behavior. The user's time is finite and irreplaceable — every bug left unfixed wastes it.
|
||||||
|
- **Keep README.md up to date**: After implementing code changes, check whether the `README.md` needs to be updated (e.g., new features, changed ENV variables, new commands, changed architecture, new endpoints, updated screenshots). If changes are relevant to the README, **ask the user for confirmation** before updating it. Do NOT silently update the README — always present the proposed README changes and wait for approval. Examples of README-relevant changes: new ENV variables, new API endpoints, new UI features, changed setup/install steps, new dependencies, changed Docker configuration.
|
||||||
|
|
||||||
## Architecture Overview
|
## Architecture Overview
|
||||||
|
|
||||||
@@ -137,11 +138,16 @@ Push to main / Tag created
|
|||||||
↓
|
↓
|
||||||
┌─────────────────────────────────────┐
|
┌─────────────────────────────────────┐
|
||||||
│ docker-build.yml │
|
│ docker-build.yml │
|
||||||
│ ├─ backend-test (parallel) │
|
│ └─ build-and-push │
|
||||||
│ ├─ frontend-build (parallel) │
|
|
||||||
│ └─ build-and-push (after tests) │
|
|
||||||
│ ├─ Build Docker images │
|
│ ├─ Build Docker images │
|
||||||
│ └─ Push to GHCR │
|
│ └─ Push to GHCR │
|
||||||
|
│ (Tag builds also set "latest") │
|
||||||
|
└─────────────────────────────────────┘
|
||||||
|
↓ After successful build
|
||||||
|
┌─────────────────────────────────────┐
|
||||||
|
│ update-test-badges.yml │
|
||||||
|
│ (workflow_run after docker-build) │
|
||||||
|
│ └─ Run tests, update badge counts │
|
||||||
└─────────────────────────────────────┘
|
└─────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -178,7 +184,9 @@ gh pr merge --squash --delete-branch
|
|||||||
| File | Trigger | Purpose |
|
| File | Trigger | Purpose |
|
||||||
|------|---------|--------|
|
|------|---------|--------|
|
||||||
| `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures |
|
| `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures |
|
||||||
| `.github/workflows/docker-build.yml` | Push to main, Tags | Tests + Build and push Docker images |
|
| `.github/workflows/docker-build.yml` | Push to main, Tags | Build and push Docker images (+ create GitHub release on tags) |
|
||||||
|
| `.github/workflows/update-test-badges.yml` | After successful docker-build | Update test count badges in README |
|
||||||
|
| `.github/workflows/codeql.yml` | Push to main, PRs, Weekly | Security analysis |
|
||||||
|
|
||||||
## Key Patterns
|
## Key Patterns
|
||||||
|
|
||||||
|
|||||||
@@ -25,50 +25,15 @@ env:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Run Tests First
|
# Build and Push Docker Images
|
||||||
# =============================================================================
|
# Tests are NOT run here — branch protection on main requires all PR checks
|
||||||
backend-test:
|
# (backend-test + frontend-build from test.yml) to pass before merge.
|
||||||
name: Backend Tests
|
# Tags are created from main, so code is already tested.
|
||||||
runs-on: ubuntu-latest
|
#
|
||||||
permissions:
|
# Tag builds (v*) always set "latest" in addition to the semver tags.
|
||||||
contents: read
|
# This ensures "latest" always points to the most recent release.
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: backend
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: '22'
|
|
||||||
cache: 'npm'
|
|
||||||
cache-dependency-path: backend/package-lock.json
|
|
||||||
- run: npm ci
|
|
||||||
- run: npx tsc --noEmit
|
|
||||||
- run: npm run test:run
|
|
||||||
|
|
||||||
frontend-build:
|
|
||||||
name: Frontend Build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: frontend
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: '22'
|
|
||||||
cache: 'npm'
|
|
||||||
cache-dependency-path: frontend/package-lock.json
|
|
||||||
- run: npm ci
|
|
||||||
- run: npm run build
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Build and Push Docker Images (only after tests pass)
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
build-and-push:
|
build-and-push:
|
||||||
needs: [backend-test, frontend-build]
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -106,7 +71,7 @@ jobs:
|
|||||||
type=semver,pattern={{version}}
|
type=semver,pattern={{version}}
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }}
|
type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }}
|
||||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
|
|||||||
@@ -1,78 +0,0 @@
|
|||||||
name: Create Release
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags: ['v*']
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
release:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Get version info
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
CURRENT_TAG=${GITHUB_REF#refs/tags/}
|
|
||||||
VERSION=${CURRENT_TAG#v}
|
|
||||||
echo "tag=$CURRENT_TAG" >> $GITHUB_OUTPUT
|
|
||||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
|
||||||
|
|
||||||
# Get previous tag
|
|
||||||
PREV_TAG=$(git tag --sort=-v:refname | grep -A1 "^${CURRENT_TAG}$" | tail -1)
|
|
||||||
if [ "$PREV_TAG" = "$CURRENT_TAG" ]; then
|
|
||||||
PREV_TAG=""
|
|
||||||
fi
|
|
||||||
echo "previous_tag=$PREV_TAG" >> $GITHUB_OUTPUT
|
|
||||||
|
|
||||||
- name: Generate release template
|
|
||||||
run: |
|
|
||||||
cat > release_notes.md << 'EOF'
|
|
||||||
## What's New
|
|
||||||
|
|
||||||
<!--
|
|
||||||
Write 1-2 sentences describing the main changes in this release.
|
|
||||||
Example: This release introduces a medication refill tracking feature and improves the mobile user experience.
|
|
||||||
-->
|
|
||||||
|
|
||||||
### New Features
|
|
||||||
|
|
||||||
<!-- List new features with **bold** names and descriptions -->
|
|
||||||
- **Feature Name**: Description of the feature
|
|
||||||
|
|
||||||
### Improvements
|
|
||||||
|
|
||||||
<!-- List improvements and fixes -->
|
|
||||||
- **Improvement**: Description
|
|
||||||
|
|
||||||
### Where to Find It
|
|
||||||
|
|
||||||
<!-- Tell users where they can access new features -->
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Docker Images
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker pull ghcr.io/danielvolz/medassist-ng-backend:${{ steps.version.outputs.version }}
|
|
||||||
docker pull ghcr.io/danielvolz/medassist-ng-frontend:${{ steps.version.outputs.version }}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/${{ steps.version.outputs.previous_tag }}...${{ steps.version.outputs.tag }}
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Create Draft Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
with:
|
|
||||||
body_path: release_notes.md
|
|
||||||
draft: true
|
|
||||||
generate_release_notes: false
|
|
||||||
name: "Release ${{ steps.version.outputs.tag }}"
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
@@ -2,13 +2,10 @@ name: Update Test Badges
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
push:
|
workflow_run:
|
||||||
|
workflows: ["Build and Push Docker Images"]
|
||||||
|
types: [completed]
|
||||||
branches: [main]
|
branches: [main]
|
||||||
paths:
|
|
||||||
- 'backend/src/**'
|
|
||||||
- 'frontend/src/**'
|
|
||||||
- 'backend/package.json'
|
|
||||||
- 'frontend/package.json'
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -17,6 +14,8 @@ jobs:
|
|||||||
update-badges:
|
update-badges:
|
||||||
name: Update Test Count Badges
|
name: Update Test Count Badges
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
# Only run after successful docker builds, not failed ones
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
|
|||||||
@@ -1,57 +0,0 @@
|
|||||||
name: Version Bump on Release
|
|
||||||
|
|
||||||
on:
|
|
||||||
release:
|
|
||||||
types: [published]
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
version-bump:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: main
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Get version from tag
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
# Extract version from tag (e.g., v1.6.0 -> 1.6.0)
|
|
||||||
VERSION="${GITHUB_REF_NAME#v}"
|
|
||||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
|
||||||
echo "Extracted version: $VERSION"
|
|
||||||
|
|
||||||
- name: Update package.json versions
|
|
||||||
run: |
|
|
||||||
VERSION="${{ steps.version.outputs.version }}"
|
|
||||||
|
|
||||||
# Update backend/package.json
|
|
||||||
jq --arg v "$VERSION" '.version = $v' backend/package.json > backend/package.json.tmp
|
|
||||||
mv backend/package.json.tmp backend/package.json
|
|
||||||
|
|
||||||
# Update frontend/package.json
|
|
||||||
jq --arg v "$VERSION" '.version = $v' frontend/package.json > frontend/package.json.tmp
|
|
||||||
mv frontend/package.json.tmp frontend/package.json
|
|
||||||
|
|
||||||
echo "Updated versions to $VERSION"
|
|
||||||
cat backend/package.json | head -5
|
|
||||||
cat frontend/package.json | head -5
|
|
||||||
|
|
||||||
- name: Commit and push
|
|
||||||
run: |
|
|
||||||
git config user.name "github-actions[bot]"
|
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
|
||||||
|
|
||||||
git add backend/package.json frontend/package.json
|
|
||||||
|
|
||||||
# Only commit if there are changes
|
|
||||||
if git diff --staged --quiet; then
|
|
||||||
echo "No version changes needed"
|
|
||||||
else
|
|
||||||
git commit -m "chore: bump version to ${{ steps.version.outputs.version }} [skip ci]"
|
|
||||||
git push origin main
|
|
||||||
fi
|
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="https://img.shields.io/badge/Backend_Tests-494%2F494-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
|
<img src="https://img.shields.io/badge/Backend_Tests-494%2F494-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
|
||||||
<img src="https://img.shields.io/badge/Frontend_Tests-639%2F639-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
|
<img src="https://img.shields.io/badge/Frontend_Tests-653%2F653-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
### 🤖 AI-Generated Code
|
### 🤖 AI-Generated Code
|
||||||
|
|||||||
@@ -5,6 +5,6 @@ export default defineConfig({
|
|||||||
out: "./drizzle",
|
out: "./drizzle",
|
||||||
dialect: "sqlite",
|
dialect: "sqlite",
|
||||||
dbCredentials: {
|
dbCredentials: {
|
||||||
url: process.env.DATABASE_URL || "./data/medassist.db",
|
url: process.env.DATABASE_URL || "./data/medassist-ng.db",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "medassist-ng-backend",
|
"name": "medassist-ng-backend",
|
||||||
"version": "1.8.3",
|
"version": "1.8.8",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "medassist-ng-backend",
|
"name": "medassist-ng-backend",
|
||||||
"version": "1.8.3",
|
"version": "1.8.8",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fastify/cookie": "^10.0.1",
|
"@fastify/cookie": "^10.0.1",
|
||||||
"@fastify/cors": "^10.0.1",
|
"@fastify/cors": "^10.0.1",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "medassist-ng-backend",
|
"name": "medassist-ng-backend",
|
||||||
"version": "1.8.6",
|
"version": "1.8.8",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -156,7 +156,7 @@ const translations: Record<Language, TranslationKeys> = {
|
|||||||
push: {
|
push: {
|
||||||
stockTitle: "MedAssist-ng: 1 Medication Running Low",
|
stockTitle: "MedAssist-ng: 1 Medication Running Low",
|
||||||
stockTitleMultiple: "MedAssist-ng: {count} Medications Running Low",
|
stockTitleMultiple: "MedAssist-ng: {count} Medications Running Low",
|
||||||
intakeTitle: "💊 Medication Reminder in {minutes} min",
|
intakeTitle: "💊 Reminder: Medication intake in {minutes} min",
|
||||||
pillsLeft: "{count} pills",
|
pillsLeft: "{count} pills",
|
||||||
daysLeft: "{count} days left",
|
daysLeft: "{count} days left",
|
||||||
pillsAt: "{count} pills at {time}",
|
pillsAt: "{count} pills at {time}",
|
||||||
@@ -210,7 +210,7 @@ const translations: Record<Language, TranslationKeys> = {
|
|||||||
push: {
|
push: {
|
||||||
stockTitle: "MedAssist-ng: 1 Medikament wird knapp",
|
stockTitle: "MedAssist-ng: 1 Medikament wird knapp",
|
||||||
stockTitleMultiple: "MedAssist-ng: {count} Medikamente werden knapp",
|
stockTitleMultiple: "MedAssist-ng: {count} Medikamente werden knapp",
|
||||||
intakeTitle: "💊 Einnahme-Erinnerung in {minutes} Min.",
|
intakeTitle: "💊 Erinnerung: Medikamenteneinnahme in {minutes} Min.",
|
||||||
pillsLeft: "{count} Tabletten",
|
pillsLeft: "{count} Tabletten",
|
||||||
daysLeft: "{count} Tage übrig",
|
daysLeft: "{count} Tage übrig",
|
||||||
pillsAt: "{count} Tabletten um {time}",
|
pillsAt: "{count} Tabletten um {time}",
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ const inventorySchema = z.object({
|
|||||||
pillsPerBlister: z.number().int().min(1).default(1),
|
pillsPerBlister: z.number().int().min(1).default(1),
|
||||||
looseTablets: z.number().int().min(0).default(0),
|
looseTablets: z.number().int().min(0).default(0),
|
||||||
stockAdjustment: z.number().int().default(0), // Manual stock correction
|
stockAdjustment: z.number().int().default(0), // Manual stock correction
|
||||||
|
packageType: z.enum(["blister", "bottle"]).default("blister"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const medicationExportSchema = z.object({
|
const medicationExportSchema = z.object({
|
||||||
@@ -276,6 +277,7 @@ export async function exportRoutes(app: FastifyInstance) {
|
|||||||
pillsPerBlister: med.pillsPerBlister ?? 1,
|
pillsPerBlister: med.pillsPerBlister ?? 1,
|
||||||
looseTablets: med.looseTablets ?? 0,
|
looseTablets: med.looseTablets ?? 0,
|
||||||
stockAdjustment: med.stockAdjustment ?? 0,
|
stockAdjustment: med.stockAdjustment ?? 0,
|
||||||
|
packageType: med.packageType ?? "blister",
|
||||||
},
|
},
|
||||||
pillWeightMg: med.pillWeightMg,
|
pillWeightMg: med.pillWeightMg,
|
||||||
doseUnit: med.doseUnit ?? "mg",
|
doseUnit: med.doseUnit ?? "mg",
|
||||||
@@ -490,6 +492,7 @@ export async function exportRoutes(app: FastifyInstance) {
|
|||||||
name: med.name,
|
name: med.name,
|
||||||
genericName: med.genericName || null,
|
genericName: med.genericName || null,
|
||||||
takenByJson,
|
takenByJson,
|
||||||
|
packageType: med.inventory.packageType ?? "blister",
|
||||||
packCount: med.inventory.packCount,
|
packCount: med.inventory.packCount,
|
||||||
blistersPerPack: med.inventory.blistersPerPack,
|
blistersPerPack: med.inventory.blistersPerPack,
|
||||||
pillsPerBlister: med.inventory.pillsPerBlister,
|
pillsPerBlister: med.inventory.pillsPerBlister,
|
||||||
|
|||||||
@@ -656,7 +656,13 @@ export async function medicationRoutes(app: FastifyInstance) {
|
|||||||
const blistersPerPack = row.blistersPerPack ?? 1;
|
const blistersPerPack = row.blistersPerPack ?? 1;
|
||||||
const looseTablets = row.looseTablets ?? 0;
|
const looseTablets = row.looseTablets ?? 0;
|
||||||
const stockAdjustment = row.stockAdjustment ?? 0;
|
const stockAdjustment = row.stockAdjustment ?? 0;
|
||||||
const originalTotalPills = packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
|
const packageType = row.packageType ?? "blister";
|
||||||
|
|
||||||
|
// For bottle type, looseTablets IS the current stock (no blister math)
|
||||||
|
const originalTotalPills =
|
||||||
|
packageType === "bottle"
|
||||||
|
? looseTablets + stockAdjustment
|
||||||
|
: packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
|
||||||
|
|
||||||
// Calculate consumption based on ACTUAL taken doses from dose_tracking
|
// Calculate consumption based on ACTUAL taken doses from dose_tracking
|
||||||
// This ensures Planner shows the same "current stock" as the Dashboard/Modal
|
// This ensures Planner shows the same "current stock" as the Dashboard/Modal
|
||||||
@@ -735,18 +741,27 @@ export async function medicationRoutes(app: FastifyInstance) {
|
|||||||
// Calculate AVAILABLE = stock AFTER the planned period (currentStock - usageTotal)
|
// Calculate AVAILABLE = stock AFTER the planned period (currentStock - usageTotal)
|
||||||
const availableAfterPeriod = Math.max(0, currentStock - usageTotal);
|
const availableAfterPeriod = Math.max(0, currentStock - usageTotal);
|
||||||
|
|
||||||
// Calculate stock breakdown for availableAfterPeriod
|
let fullBlisters: number;
|
||||||
// Consumption order: loose pills first, then from blisters
|
let loosePills: number;
|
||||||
const totalConsumedByEnd = originalTotalPills - availableAfterPeriod;
|
|
||||||
const looseConsumedByEnd = Math.min(totalConsumedByEnd, looseTablets);
|
|
||||||
const loosePillsRemaining = Math.max(0, looseTablets - looseConsumedByEnd);
|
|
||||||
const blisterPillsConsumed = totalConsumedByEnd - looseConsumedByEnd;
|
|
||||||
const originalBlisterPills = originalTotalPills - looseTablets;
|
|
||||||
const blisterPillsRemaining = Math.max(0, originalBlisterPills - blisterPillsConsumed);
|
|
||||||
|
|
||||||
const fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0;
|
if (packageType === "bottle") {
|
||||||
const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0;
|
// Bottle type: no blisters, everything is loose pills
|
||||||
const loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose
|
fullBlisters = 0;
|
||||||
|
loosePills = availableAfterPeriod;
|
||||||
|
} else {
|
||||||
|
// Blister type: calculate stock breakdown
|
||||||
|
// Consumption order: loose pills first, then from blisters
|
||||||
|
const totalConsumedByEnd = originalTotalPills - availableAfterPeriod;
|
||||||
|
const looseConsumedByEnd = Math.min(totalConsumedByEnd, looseTablets);
|
||||||
|
const loosePillsRemaining = Math.max(0, looseTablets - looseConsumedByEnd);
|
||||||
|
const blisterPillsConsumed = totalConsumedByEnd - looseConsumedByEnd;
|
||||||
|
const originalBlisterPills = originalTotalPills - looseTablets;
|
||||||
|
const blisterPillsRemaining = Math.max(0, originalBlisterPills - blisterPillsConsumed);
|
||||||
|
|
||||||
|
fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0;
|
||||||
|
const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0;
|
||||||
|
loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose
|
||||||
|
}
|
||||||
|
|
||||||
const enough = currentStock >= usageTotal;
|
const enough = currentStock >= usageTotal;
|
||||||
return {
|
return {
|
||||||
@@ -759,6 +774,7 @@ export async function medicationRoutes(app: FastifyInstance) {
|
|||||||
fullBlisters,
|
fullBlisters,
|
||||||
loosePills,
|
loosePills,
|
||||||
enough,
|
enough,
|
||||||
|
packageType,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -78,9 +78,13 @@ export async function refillRoutes(app: FastifyInstance) {
|
|||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
// Calculate pills added for response
|
// Calculate pills added for response (packageType-aware)
|
||||||
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister;
|
const isBottle = (med.packageType ?? "blister") === "bottle";
|
||||||
const totalPillsAdded = packsAdded * pillsPerPack + loosePillsAdded;
|
const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
|
||||||
|
const totalPillsAdded = isBottle ? loosePillsAdded : packsAdded * pillsPerPack + loosePillsAdded;
|
||||||
|
const newTotalPills = isBottle
|
||||||
|
? newLooseTablets + (med.stockAdjustment ?? 0)
|
||||||
|
: newPackCount * pillsPerPack + newLooseTablets + (med.stockAdjustment ?? 0);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -94,7 +98,7 @@ export async function refillRoutes(app: FastifyInstance) {
|
|||||||
newStock: {
|
newStock: {
|
||||||
packCount: newPackCount,
|
packCount: newPackCount,
|
||||||
looseTablets: newLooseTablets,
|
looseTablets: newLooseTablets,
|
||||||
totalPills: newPackCount * pillsPerPack + newLooseTablets,
|
totalPills: newTotalPills,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -120,13 +124,14 @@ export async function refillRoutes(app: FastifyInstance) {
|
|||||||
.where(eq(refillHistory.medicationId, medId))
|
.where(eq(refillHistory.medicationId, medId))
|
||||||
.orderBy(desc(refillHistory.refillDate));
|
.orderBy(desc(refillHistory.refillDate));
|
||||||
|
|
||||||
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister;
|
const isBottle = (med.packageType ?? "blister") === "bottle";
|
||||||
|
const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
|
||||||
|
|
||||||
return refills.map((r) => ({
|
return refills.map((r) => ({
|
||||||
id: r.id,
|
id: r.id,
|
||||||
packsAdded: r.packsAdded,
|
packsAdded: r.packsAdded,
|
||||||
loosePillsAdded: r.loosePillsAdded,
|
loosePillsAdded: r.loosePillsAdded,
|
||||||
totalPillsAdded: r.packsAdded * pillsPerPack + r.loosePillsAdded,
|
totalPillsAdded: isBottle ? r.loosePillsAdded : r.packsAdded * pillsPerPack + r.loosePillsAdded,
|
||||||
refillDate: r.refillDate,
|
refillDate: r.refillDate,
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -114,7 +114,9 @@ export async function shareRoutes(app: FastifyInstance) {
|
|||||||
const takenByArray = parseTakenByJson(med.takenByJson);
|
const takenByArray = parseTakenByJson(med.takenByJson);
|
||||||
|
|
||||||
const totalPills =
|
const totalPills =
|
||||||
med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
|
(med.packageType ?? "blister") === "bottle"
|
||||||
|
? med.looseTablets + (med.stockAdjustment ?? 0)
|
||||||
|
: med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
|
||||||
return {
|
return {
|
||||||
id: med.id,
|
id: med.id,
|
||||||
name: med.name,
|
name: med.name,
|
||||||
@@ -123,6 +125,7 @@ export async function shareRoutes(app: FastifyInstance) {
|
|||||||
doseUnit: med.doseUnit ?? "mg",
|
doseUnit: med.doseUnit ?? "mg",
|
||||||
imageUrl: med.imageUrl,
|
imageUrl: med.imageUrl,
|
||||||
totalPills,
|
totalPills,
|
||||||
|
packageType: med.packageType ?? "blister",
|
||||||
packCount: med.packCount,
|
packCount: med.packCount,
|
||||||
blistersPerPack: med.blistersPerPack,
|
blistersPerPack: med.blistersPerPack,
|
||||||
looseTablets: med.looseTablets,
|
looseTablets: med.looseTablets,
|
||||||
|
|||||||
@@ -409,10 +409,18 @@ async function checkAndSendIntakeRemindersForUser(
|
|||||||
if (!existingEntry) {
|
if (!existingEntry) {
|
||||||
// New dose - send first reminder
|
// New dose - send first reminder
|
||||||
if (isIntakePast) {
|
if (isIntakePast) {
|
||||||
// Already missed - this is first nagging reminder (count=1)
|
// Intake time already passed and we have no state entry — this means the scheduler
|
||||||
remindersToSend.push({ ...intake, currentSendCount: 1, maxReminders, isAdvanceReminder: false });
|
// was not aware of this intake before it happened (e.g., user just enabled reminders).
|
||||||
|
// Seed the state as already handled so repeat reminders can track from here,
|
||||||
|
// but do NOT send a notification for intakes that were missed before tracking started.
|
||||||
|
state.reminders[key] = {
|
||||||
|
firstSentAt: nowMs,
|
||||||
|
lastSentAt: nowMs,
|
||||||
|
sendCount: 0,
|
||||||
|
advanceSent: false,
|
||||||
|
};
|
||||||
logger.info(
|
logger.info(
|
||||||
`[IntakeReminder] User ${settings.userId}: First nagging for missed "${intake.medName}" at ${intake.intakeTimeStr} (1/${maxReminders})`
|
`[IntakeReminder] User ${settings.userId}: Seeding state for past "${intake.medName}" at ${intake.intakeTimeStr} (no notification — first detection)`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// Upcoming - this is advance reminder (no counter)
|
// Upcoming - this is advance reminder (no counter)
|
||||||
@@ -551,7 +559,10 @@ async function checkAndSendIntakeRemindersForUser(
|
|||||||
if (hasNaggingReminder && highestSendCount > 0) {
|
if (hasNaggingReminder && highestSendCount > 0) {
|
||||||
// Nagging reminder - show counter
|
// Nagging reminder - show counter
|
||||||
const counterStr = `(${highestSendCount}/${maxReminderCount})`;
|
const counterStr = `(${highestSendCount}/${maxReminderCount})`;
|
||||||
title = language === "de" ? `⚠️ Medikamenten-Erinnerung ${counterStr}` : `⚠️ Medication Reminder ${counterStr}`;
|
title =
|
||||||
|
language === "de"
|
||||||
|
? `⚠️ Erinnerung: Medikamenteneinnahme ${counterStr}`
|
||||||
|
: `⚠️ Reminder: Medication intake ${counterStr}`;
|
||||||
} else {
|
} else {
|
||||||
// Advance reminder - no counter
|
// Advance reminder - no counter
|
||||||
title = t(tr.push.intakeTitle, { minutes: REMINDER_MINUTES_BEFORE });
|
title = t(tr.push.intakeTitle, { minutes: REMINDER_MINUTES_BEFORE });
|
||||||
|
|||||||
@@ -106,7 +106,9 @@ async function getMedicationsNeedingReminder(
|
|||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
const blisters = parseBlistersFromRow(row);
|
const blisters = parseBlistersFromRow(row);
|
||||||
const totalPills =
|
const totalPills =
|
||||||
row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
|
(row.packageType ?? "blister") === "bottle"
|
||||||
|
? row.looseTablets + (row.stockAdjustment ?? 0)
|
||||||
|
: row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
|
||||||
const { daysLeft, depletionDate } = calculateDepletionInfo({ count: totalPills, blisters }, language);
|
const { daysLeft, depletionDate } = calculateDepletionInfo({ count: totalPills, blisters }, language);
|
||||||
|
|
||||||
// Check if medication runs out within reminderDaysBefore days
|
// Check if medication runs out within reminderDaysBefore days
|
||||||
|
|||||||
@@ -2214,4 +2214,250 @@ describe("E2E Tests with Real Routes", () => {
|
|||||||
expect(medsResponse.json()[0].packCount).toBe(10);
|
expect(medsResponse.json()[0].packCount).toBe(10);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Package Type (bottle vs blister) Tests
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("Package type handling (bottle vs blister)", () => {
|
||||||
|
const bottleMedication = {
|
||||||
|
name: "Vitamin D Drops",
|
||||||
|
packageType: "bottle",
|
||||||
|
packCount: 0,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 1,
|
||||||
|
looseTablets: 120,
|
||||||
|
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
|
||||||
|
};
|
||||||
|
|
||||||
|
const blisterMedication = {
|
||||||
|
name: "Aspirin Blister",
|
||||||
|
packageType: "blister",
|
||||||
|
packCount: 2,
|
||||||
|
blistersPerPack: 3,
|
||||||
|
pillsPerBlister: 10,
|
||||||
|
looseTablets: 5,
|
||||||
|
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should create and return bottle type medication", async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/medications",
|
||||||
|
payload: bottleMedication,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const data = response.json();
|
||||||
|
expect(data.packageType).toBe("bottle");
|
||||||
|
expect(data.looseTablets).toBe(120);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return packageType in shared schedule for bottle type", async () => {
|
||||||
|
// Create bottle medication with takenBy
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/medications",
|
||||||
|
payload: { ...bottleMedication, takenBy: ["Daniel"] },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create share token
|
||||||
|
const shareResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/share",
|
||||||
|
payload: { takenBy: "Daniel", scheduleDays: 30 },
|
||||||
|
});
|
||||||
|
expect(shareResponse.statusCode).toBe(200);
|
||||||
|
const { token } = shareResponse.json();
|
||||||
|
|
||||||
|
// Get shared schedule
|
||||||
|
const scheduleResponse = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: `/share/${token}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(scheduleResponse.statusCode).toBe(200);
|
||||||
|
const data = scheduleResponse.json();
|
||||||
|
expect(data.medications).toHaveLength(1);
|
||||||
|
expect(data.medications[0].packageType).toBe("bottle");
|
||||||
|
// Bottle totalPills = looseTablets + stockAdjustment (no blister math)
|
||||||
|
expect(data.medications[0].totalPills).toBe(120);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should calculate correct totalPills for shared blister medication", async () => {
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/medications",
|
||||||
|
payload: { ...blisterMedication, takenBy: ["Daniel"] },
|
||||||
|
});
|
||||||
|
|
||||||
|
const shareResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/share",
|
||||||
|
payload: { takenBy: "Daniel", scheduleDays: 30 },
|
||||||
|
});
|
||||||
|
const { token } = shareResponse.json();
|
||||||
|
|
||||||
|
const scheduleResponse = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: `/share/${token}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(scheduleResponse.statusCode).toBe(200);
|
||||||
|
const data = scheduleResponse.json();
|
||||||
|
expect(data.medications).toHaveLength(1);
|
||||||
|
expect(data.medications[0].packageType).toBe("blister");
|
||||||
|
// Blister totalPills = 2 * 3 * 10 + 5 = 65
|
||||||
|
expect(data.medications[0].totalPills).toBe(65);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should calculate correct refill totalPillsAdded for bottle type", async () => {
|
||||||
|
const createResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/medications",
|
||||||
|
payload: bottleMedication,
|
||||||
|
});
|
||||||
|
const medId = createResponse.json().id;
|
||||||
|
|
||||||
|
// Refill bottle: only loosePillsAdded matters, packs should add 0 pills
|
||||||
|
const refillResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: `/medications/${medId}/refill`,
|
||||||
|
payload: { packsAdded: 0, loosePillsAdded: 30 },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(refillResponse.statusCode).toBe(200);
|
||||||
|
const data = refillResponse.json();
|
||||||
|
expect(data.refill.totalPillsAdded).toBe(30);
|
||||||
|
// newStock.totalPills should be looseTablets only (no blister math)
|
||||||
|
expect(data.newStock.totalPills).toBe(150); // 120 + 30
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should calculate correct refill totalPillsAdded for blister type", async () => {
|
||||||
|
const createResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/medications",
|
||||||
|
payload: blisterMedication,
|
||||||
|
});
|
||||||
|
const medId = createResponse.json().id;
|
||||||
|
|
||||||
|
// Refill blister: 1 pack = 3 blisters * 10 pills = 30 pills + 5 loose
|
||||||
|
const refillResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: `/medications/${medId}/refill`,
|
||||||
|
payload: { packsAdded: 1, loosePillsAdded: 5 },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(refillResponse.statusCode).toBe(200);
|
||||||
|
const data = refillResponse.json();
|
||||||
|
expect(data.refill.totalPillsAdded).toBe(35); // 1*30 + 5
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return correct totalPillsAdded in refill history for bottle type", async () => {
|
||||||
|
const createResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/medications",
|
||||||
|
payload: bottleMedication,
|
||||||
|
});
|
||||||
|
const medId = createResponse.json().id;
|
||||||
|
|
||||||
|
// Add refill
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: `/medications/${medId}/refill`,
|
||||||
|
payload: { packsAdded: 0, loosePillsAdded: 25 },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get refill history
|
||||||
|
const historyResponse = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: `/medications/${medId}/refills`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(historyResponse.statusCode).toBe(200);
|
||||||
|
const refills = historyResponse.json();
|
||||||
|
expect(refills).toHaveLength(1);
|
||||||
|
// For bottle type, totalPillsAdded = loosePillsAdded only
|
||||||
|
expect(refills[0].totalPillsAdded).toBe(25);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should export and import bottle type medication correctly", async () => {
|
||||||
|
// Create bottle medication
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/medications",
|
||||||
|
payload: bottleMedication,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Export
|
||||||
|
const exportResponse = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/export",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(exportResponse.statusCode).toBe(200);
|
||||||
|
const exportData = exportResponse.json();
|
||||||
|
expect(exportData.medications).toHaveLength(1);
|
||||||
|
expect(exportData.medications[0].inventory.packageType).toBe("bottle");
|
||||||
|
expect(exportData.medications[0].inventory.looseTablets).toBe(120);
|
||||||
|
|
||||||
|
// Clear and re-import
|
||||||
|
await clearData(testClient);
|
||||||
|
await testClient.execute(
|
||||||
|
"INSERT INTO users (id, username, auth_provider) VALUES (999999999, '__anonymous__', 'anonymous')"
|
||||||
|
);
|
||||||
|
|
||||||
|
const importResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/import",
|
||||||
|
payload: exportData,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(importResponse.statusCode).toBe(200);
|
||||||
|
expect(importResponse.json().success).toBe(true);
|
||||||
|
|
||||||
|
// Verify imported medication has correct packageType
|
||||||
|
const medsResponse = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/medications",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(medsResponse.json()).toHaveLength(1);
|
||||||
|
const med = medsResponse.json()[0];
|
||||||
|
expect(med.name).toBe("Vitamin D Drops");
|
||||||
|
expect(med.packageType).toBe("bottle");
|
||||||
|
expect(med.looseTablets).toBe(120);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should default to blister when importing without packageType", async () => {
|
||||||
|
const importData = {
|
||||||
|
version: "1.0",
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
medications: [
|
||||||
|
{
|
||||||
|
_exportId: "med-1",
|
||||||
|
name: "Old Export Med",
|
||||||
|
inventory: { packCount: 2, blistersPerPack: 3, pillsPerBlister: 10, looseTablets: 0 },
|
||||||
|
schedules: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const importResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/import",
|
||||||
|
payload: importData,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(importResponse.statusCode).toBe(200);
|
||||||
|
|
||||||
|
const medsResponse = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/medications",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(medsResponse.json()).toHaveLength(1);
|
||||||
|
expect(medsResponse.json()[0].packageType).toBe("blister");
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -52,7 +52,6 @@ services:
|
|||||||
- /tmp:noexec,nosuid,size=64m
|
- /tmp:noexec,nosuid,size=64m
|
||||||
- /var/cache/nginx:noexec,nosuid,size=64m
|
- /var/cache/nginx:noexec,nosuid,size=64m
|
||||||
- /var/run:noexec,nosuid,size=64m
|
- /var/run:noexec,nosuid,size=64m
|
||||||
- /etc/nginx/conf.d:noexec,nosuid,size=1m
|
|
||||||
cap_drop:
|
cap_drop:
|
||||||
- ALL
|
- ALL
|
||||||
|
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "medassist-ng-frontend",
|
"name": "medassist-ng-frontend",
|
||||||
"version": "1.8.3",
|
"version": "1.8.8",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "medassist-ng-frontend",
|
"name": "medassist-ng-frontend",
|
||||||
"version": "1.8.3",
|
"version": "1.8.8",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"i18next": "^24.2.2",
|
"i18next": "^24.2.2",
|
||||||
"i18next-browser-languagedetector": "^8.0.4",
|
"i18next-browser-languagedetector": "^8.0.4",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "medassist-ng-frontend",
|
"name": "medassist-ng-frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.8.6",
|
"version": "1.8.8",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { FRONTEND_VERSION, GITHUB_URL } from "../App";
|
|||||||
interface UpdateCheckResult {
|
interface UpdateCheckResult {
|
||||||
status: "up-to-date" | "update-available" | "error";
|
status: "up-to-date" | "update-available" | "error";
|
||||||
latestVersion?: string;
|
latestVersion?: string;
|
||||||
lastChecked?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AboutModalProps {
|
interface AboutModalProps {
|
||||||
@@ -18,21 +17,10 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
|
|||||||
const [isChecking, setIsChecking] = useState(false);
|
const [isChecking, setIsChecking] = useState(false);
|
||||||
const [updateCheckResult, setUpdateCheckResult] = useState<UpdateCheckResult | null>(null);
|
const [updateCheckResult, setUpdateCheckResult] = useState<UpdateCheckResult | null>(null);
|
||||||
|
|
||||||
// Load cached update check result on mount
|
// Reset check result when modal opens so stale results are never shown
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOpen) return;
|
if (isOpen) {
|
||||||
|
setUpdateCheckResult(null);
|
||||||
// Load cached update check result
|
|
||||||
const cached = sessionStorage.getItem("updateCheckResult");
|
|
||||||
if (cached) {
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(cached);
|
|
||||||
if (parsed && typeof parsed === "object") {
|
|
||||||
setUpdateCheckResult(parsed);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}, [isOpen]);
|
}, [isOpen]);
|
||||||
|
|
||||||
@@ -49,14 +37,10 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
|
|||||||
const latestVersion = (data.tag_name || "").replace(/^v/, "");
|
const latestVersion = (data.tag_name || "").replace(/^v/, "");
|
||||||
const currentVersion = FRONTEND_VERSION.replace(/^v/, "");
|
const currentVersion = FRONTEND_VERSION.replace(/^v/, "");
|
||||||
const isUpToDate = latestVersion === currentVersion;
|
const isUpToDate = latestVersion === currentVersion;
|
||||||
const result: UpdateCheckResult = {
|
setUpdateCheckResult({
|
||||||
status: isUpToDate ? "up-to-date" : "update-available",
|
status: isUpToDate ? "up-to-date" : "update-available",
|
||||||
latestVersion,
|
latestVersion,
|
||||||
lastChecked: new Date().toISOString(),
|
});
|
||||||
};
|
|
||||||
setUpdateCheckResult(result);
|
|
||||||
// Cache the result
|
|
||||||
sessionStorage.setItem("updateCheckResult", JSON.stringify(result));
|
|
||||||
} catch {
|
} catch {
|
||||||
setUpdateCheckResult({ status: "error" });
|
setUpdateCheckResult({ status: "error" });
|
||||||
} finally {
|
} finally {
|
||||||
@@ -114,11 +98,11 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
|
|||||||
{updateCheckResult && (
|
{updateCheckResult && (
|
||||||
<div className={`about-update-result ${updateCheckResult.status}`}>
|
<div className={`about-update-result ${updateCheckResult.status}`}>
|
||||||
{updateCheckResult.status === "up-to-date" && (
|
{updateCheckResult.status === "up-to-date" && (
|
||||||
<span className="update-status-text">✓ {t("about.upToDate", "You are up to date!")}</span>
|
<span className="update-status-text">✓ {t("about.upToDate", "You are up to date!")}</span>
|
||||||
)}
|
)}
|
||||||
{updateCheckResult.status === "update-available" && (
|
{updateCheckResult.status === "update-available" && (
|
||||||
<span className="update-status-text">
|
<span className="update-status-text">
|
||||||
⬆ {t("about.updateAvailable", "Update available")}:{" "}
|
⬆ {t("about.updateAvailable", "Update available")}:{" "}
|
||||||
<strong>v{updateCheckResult.latestVersion}</strong>
|
<strong>v{updateCheckResult.latestVersion}</strong>
|
||||||
<a
|
<a
|
||||||
href={`${GITHUB_URL}/releases/latest`}
|
href={`${GITHUB_URL}/releases/latest`}
|
||||||
@@ -131,11 +115,8 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{updateCheckResult.status === "error" && (
|
{updateCheckResult.status === "error" && (
|
||||||
<span className="update-status-text">⚠ {t("about.checkFailed", "Could not check for updates")}</span>
|
<span className="update-status-text">
|
||||||
)}
|
⚠ {t("about.checkFailed", "Could not check for updates")}
|
||||||
{updateCheckResult.lastChecked && (
|
|
||||||
<span className="update-last-checked">
|
|
||||||
{t("about.lastChecked", "Last checked")}: {new Date(updateCheckResult.lastChecked).toLocaleString()}
|
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
/**
|
/**
|
||||||
* AppHeader - Main application header with navigation and user menu
|
* AppHeader - Main application header with navigation and user menu
|
||||||
*/
|
*/
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useLocation, useNavigate } from "react-router-dom";
|
import { useLocation, useNavigate } from "react-router-dom";
|
||||||
import { useUnsavedChanges } from "../context";
|
import { useUnsavedChanges } from "../context";
|
||||||
|
import type { ThemePreference } from "../hooks";
|
||||||
import { useTheme } from "../hooks";
|
import { useTheme } from "../hooks";
|
||||||
import { useAuth } from "./Auth";
|
import { useAuth } from "./Auth";
|
||||||
|
|
||||||
@@ -19,9 +20,25 @@ export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
|
|||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const currentPath = location.pathname;
|
const currentPath = location.pathname;
|
||||||
const { user, authState, logout } = useAuth();
|
const { user, authState, logout } = useAuth();
|
||||||
const { theme, toggleTheme } = useTheme();
|
const { theme, themePreference, setThemePreference } = useTheme();
|
||||||
const { confirmNavigation } = useUnsavedChanges();
|
const { confirmNavigation } = useUnsavedChanges();
|
||||||
|
|
||||||
|
// Theme dropdown state
|
||||||
|
const [themeMenuOpen, setThemeMenuOpen] = useState(false);
|
||||||
|
const themeMenuRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Close theme dropdown when clicking outside
|
||||||
|
useEffect(() => {
|
||||||
|
if (!themeMenuOpen) return;
|
||||||
|
const handleClickOutside = (e: MouseEvent) => {
|
||||||
|
if (themeMenuRef.current && !themeMenuRef.current.contains(e.target as Node)) {
|
||||||
|
setThemeMenuOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("click", handleClickOutside);
|
||||||
|
return () => document.removeEventListener("click", handleClickOutside);
|
||||||
|
}, [themeMenuOpen]);
|
||||||
|
|
||||||
// Safe navigation that checks for unsaved changes first
|
// Safe navigation that checks for unsaved changes first
|
||||||
const safeNavigate = async (path: string) => {
|
const safeNavigate = async (path: string) => {
|
||||||
if (await confirmNavigation()) {
|
if (await confirmNavigation()) {
|
||||||
@@ -94,13 +111,62 @@ export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
|
|||||||
⚙️
|
⚙️
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
<button
|
<div className={`theme-menu ${themeMenuOpen ? "open" : ""}`} ref={themeMenuRef}>
|
||||||
className="icon-btn"
|
<button className="icon-btn" onClick={() => setThemeMenuOpen(!themeMenuOpen)} title={t("theme.title")}>
|
||||||
onClick={toggleTheme}
|
{theme === "dark" ? "🌙" : "☀️"}
|
||||||
title={theme === "dark" ? t("tooltips.lightMode") : t("tooltips.darkMode")}
|
</button>
|
||||||
>
|
<div className="theme-dropdown">
|
||||||
{theme === "dark" ? "☀️" : "🌙"}
|
<button
|
||||||
</button>
|
className={`theme-dropdown-item${themePreference === "light" ? " active" : ""}`}
|
||||||
|
onClick={() => {
|
||||||
|
setThemePreference("light");
|
||||||
|
setThemeMenuOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<circle cx="12" cy="12" r="5" />
|
||||||
|
<line x1="12" y1="1" x2="12" y2="3" />
|
||||||
|
<line x1="12" y1="21" x2="12" y2="23" />
|
||||||
|
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
|
||||||
|
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
|
||||||
|
<line x1="1" y1="12" x2="3" y2="12" />
|
||||||
|
<line x1="21" y1="12" x2="23" y2="12" />
|
||||||
|
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
|
||||||
|
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
|
||||||
|
</svg>
|
||||||
|
{t("theme.light")}
|
||||||
|
{themePreference === "light" && <span className="theme-check">✓</span>}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`theme-dropdown-item${themePreference === "dark" ? " active" : ""}`}
|
||||||
|
onClick={() => {
|
||||||
|
setThemePreference("dark");
|
||||||
|
setThemeMenuOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
|
||||||
|
</svg>
|
||||||
|
{t("theme.dark")}
|
||||||
|
{themePreference === "dark" && <span className="theme-check">✓</span>}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`theme-dropdown-item${themePreference === "system" ? " active" : ""}`}
|
||||||
|
onClick={() => {
|
||||||
|
setThemePreference("system");
|
||||||
|
setThemeMenuOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
|
||||||
|
<line x1="8" y1="21" x2="16" y2="21" />
|
||||||
|
<line x1="12" y1="17" x2="12" y2="21" />
|
||||||
|
</svg>
|
||||||
|
{t("theme.system")}
|
||||||
|
{themePreference === "system" && <span className="theme-check">✓</span>}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
{authState?.authEnabled && user && (
|
{authState?.authEnabled && user && (
|
||||||
<div className={`user-menu ${userDropdownOpen ? "open" : ""}`}>
|
<div className={`user-menu ${userDropdownOpen ? "open" : ""}`}>
|
||||||
<button className="user-menu-btn" onClick={() => setUserDropdownOpen(!userDropdownOpen)}>
|
<button className="user-menu-btn" onClick={() => setUserDropdownOpen(!userDropdownOpen)}>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// SharedSchedule Component - Public view for shared schedules
|
// SharedSchedule Component - Public view for shared schedules
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useParams } from "react-router-dom";
|
import { useParams } from "react-router-dom";
|
||||||
import type { ExpiredLinkData, SharedScheduleData } from "../types";
|
import type { ExpiredLinkData, SharedScheduleData } from "../types";
|
||||||
@@ -24,23 +24,60 @@ export function SharedSchedule() {
|
|||||||
const [lightboxImage, setLightboxImage] = useState<{ url: string; name: string } | null>(null);
|
const [lightboxImage, setLightboxImage] = useState<{ url: string; name: string } | null>(null);
|
||||||
const [showPastDays, setShowPastDays] = useState(false);
|
const [showPastDays, setShowPastDays] = useState(false);
|
||||||
const [showFutureDays, setShowFutureDays] = useState(false);
|
const [showFutureDays, setShowFutureDays] = useState(false);
|
||||||
const [theme, setTheme] = useState<"light" | "dark">(() => {
|
|
||||||
|
// Theme preference: light, dark, or system
|
||||||
|
type ThemePreference = "light" | "dark" | "system";
|
||||||
|
const [themePreference, setThemePreference] = useState<ThemePreference>(() => {
|
||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
return (localStorage.getItem("theme") as "light" | "dark") || "dark";
|
const stored = localStorage.getItem("theme") as ThemePreference | null;
|
||||||
|
if (stored === "light" || stored === "dark" || stored === "system") return stored;
|
||||||
}
|
}
|
||||||
return "dark";
|
return "dark";
|
||||||
});
|
});
|
||||||
|
|
||||||
// Apply theme to document
|
function getSystemTheme(): "light" | "dark" {
|
||||||
useEffect(() => {
|
if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: light)").matches) {
|
||||||
document.documentElement.setAttribute("data-theme", theme);
|
return "light";
|
||||||
localStorage.setItem("theme", theme);
|
}
|
||||||
}, [theme]);
|
return "dark";
|
||||||
|
|
||||||
function toggleTheme() {
|
|
||||||
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const resolvedTheme = themePreference === "system" ? getSystemTheme() : themePreference;
|
||||||
|
|
||||||
|
// Apply resolved theme to document
|
||||||
|
useEffect(() => {
|
||||||
|
document.documentElement.setAttribute("data-theme", resolvedTheme);
|
||||||
|
localStorage.setItem("theme", themePreference);
|
||||||
|
}, [themePreference, resolvedTheme]);
|
||||||
|
|
||||||
|
// Listen for system theme changes when preference is "system"
|
||||||
|
useEffect(() => {
|
||||||
|
if (themePreference !== "system") return;
|
||||||
|
const mq = window.matchMedia?.("(prefers-color-scheme: light)");
|
||||||
|
if (!mq) return;
|
||||||
|
const handler = () => {
|
||||||
|
const resolved = mq.matches ? "light" : "dark";
|
||||||
|
document.documentElement.setAttribute("data-theme", resolved);
|
||||||
|
};
|
||||||
|
mq.addEventListener("change", handler);
|
||||||
|
return () => mq.removeEventListener("change", handler);
|
||||||
|
}, [themePreference]);
|
||||||
|
|
||||||
|
// Theme dropdown state
|
||||||
|
const [themeMenuOpen, setThemeMenuOpen] = useState(false);
|
||||||
|
const themeMenuRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!themeMenuOpen) return;
|
||||||
|
const handleClickOutside = (e: MouseEvent) => {
|
||||||
|
if (themeMenuRef.current && !themeMenuRef.current.contains(e.target as Node)) {
|
||||||
|
setThemeMenuOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("click", handleClickOutside);
|
||||||
|
return () => document.removeEventListener("click", handleClickOutside);
|
||||||
|
}, [themeMenuOpen]);
|
||||||
|
|
||||||
// Collapsed days state for SharedSchedule (token-specific localStorage)
|
// Collapsed days state for SharedSchedule (token-specific localStorage)
|
||||||
const [manuallyCollapsedDays, setManuallyCollapsedDays] = useState<Set<string>>(new Set());
|
const [manuallyCollapsedDays, setManuallyCollapsedDays] = useState<Set<string>>(new Set());
|
||||||
const [manuallyExpandedDays, setManuallyExpandedDays] = useState<Set<string>>(new Set());
|
const [manuallyExpandedDays, setManuallyExpandedDays] = useState<Set<string>>(new Set());
|
||||||
@@ -522,13 +559,62 @@ export function SharedSchedule() {
|
|||||||
💊 {t("share.scheduleFor")} {data.takenBy}
|
💊 {t("share.scheduleFor")} {data.takenBy}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="shared-schedule-header-actions">
|
<div className="shared-schedule-header-actions">
|
||||||
<button
|
<div className={`theme-menu ${themeMenuOpen ? "open" : ""}`} ref={themeMenuRef}>
|
||||||
className="icon-btn"
|
<button className="icon-btn" onClick={() => setThemeMenuOpen(!themeMenuOpen)} title={t("theme.title")}>
|
||||||
onClick={toggleTheme}
|
{resolvedTheme === "dark" ? "🌙" : "☀️"}
|
||||||
title={theme === "dark" ? t("tooltips.lightMode") : t("tooltips.darkMode")}
|
</button>
|
||||||
>
|
<div className="theme-dropdown">
|
||||||
{theme === "dark" ? "☀️" : "🌙"}
|
<button
|
||||||
</button>
|
className={`theme-dropdown-item${themePreference === "light" ? " active" : ""}`}
|
||||||
|
onClick={() => {
|
||||||
|
setThemePreference("light");
|
||||||
|
setThemeMenuOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<circle cx="12" cy="12" r="5" />
|
||||||
|
<line x1="12" y1="1" x2="12" y2="3" />
|
||||||
|
<line x1="12" y1="21" x2="12" y2="23" />
|
||||||
|
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
|
||||||
|
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
|
||||||
|
<line x1="1" y1="12" x2="3" y2="12" />
|
||||||
|
<line x1="21" y1="12" x2="23" y2="12" />
|
||||||
|
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
|
||||||
|
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
|
||||||
|
</svg>
|
||||||
|
{t("theme.light")}
|
||||||
|
{themePreference === "light" && <span className="theme-check">✓</span>}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`theme-dropdown-item${themePreference === "dark" ? " active" : ""}`}
|
||||||
|
onClick={() => {
|
||||||
|
setThemePreference("dark");
|
||||||
|
setThemeMenuOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
|
||||||
|
</svg>
|
||||||
|
{t("theme.dark")}
|
||||||
|
{themePreference === "dark" && <span className="theme-check">✓</span>}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`theme-dropdown-item${themePreference === "system" ? " active" : ""}`}
|
||||||
|
onClick={() => {
|
||||||
|
setThemePreference("system");
|
||||||
|
setThemeMenuOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
|
||||||
|
<line x1="8" y1="21" x2="16" y2="21" />
|
||||||
|
<line x1="12" y1="17" x2="12" y2="21" />
|
||||||
|
</svg>
|
||||||
|
{t("theme.system")}
|
||||||
|
{themePreference === "system" && <span className="theme-check">✓</span>}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="shared-schedule-period">
|
<p className="shared-schedule-period">
|
||||||
{t("share.period")}:{" "}
|
{t("share.period")}:{" "}
|
||||||
|
|||||||
@@ -278,7 +278,8 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
|||||||
systemLocale,
|
systemLocale,
|
||||||
settingsHook.settings.reminderDaysBefore,
|
settingsHook.settings.reminderDaysBefore,
|
||||||
settingsHook.settings.stockCalculationMode,
|
settingsHook.settings.stockCalculationMode,
|
||||||
doses.takenDoses
|
doses.takenDoses,
|
||||||
|
doses.takenDoseTimestamps
|
||||||
),
|
),
|
||||||
[
|
[
|
||||||
medications.meds,
|
medications.meds,
|
||||||
@@ -287,6 +288,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
|||||||
settingsHook.settings.reminderDaysBefore,
|
settingsHook.settings.reminderDaysBefore,
|
||||||
settingsHook.settings.stockCalculationMode,
|
settingsHook.settings.stockCalculationMode,
|
||||||
doses.takenDoses,
|
doses.takenDoses,
|
||||||
|
doses.takenDoseTimestamps,
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export type { Settings, UseSettingsReturn } from "./useSettings";
|
|||||||
export { useSettings } from "./useSettings";
|
export { useSettings } from "./useSettings";
|
||||||
export type { UseShareReturn } from "./useShare";
|
export type { UseShareReturn } from "./useShare";
|
||||||
export { useShare } from "./useShare";
|
export { useShare } from "./useShare";
|
||||||
export type { Theme, UseThemeReturn } from "./useTheme";
|
export type { Theme, ThemePreference, UseThemeReturn } from "./useTheme";
|
||||||
export { useTheme } from "./useTheme";
|
export { useTheme } from "./useTheme";
|
||||||
export type { UseUnsavedChangesWarningReturn } from "./useUnsavedChangesWarning";
|
export type { UseUnsavedChangesWarningReturn } from "./useUnsavedChangesWarning";
|
||||||
export { useUnsavedChangesWarning } from "./useUnsavedChangesWarning";
|
export { useUnsavedChangesWarning } from "./useUnsavedChangesWarning";
|
||||||
|
|||||||
@@ -2,11 +2,12 @@
|
|||||||
// useDoses Hook - Dose tracking state and operations
|
// useDoses Hook - Dose tracking state and operations
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
export interface UseDosesReturn {
|
export interface UseDosesReturn {
|
||||||
takenDoses: Set<string>;
|
takenDoses: Set<string>;
|
||||||
setTakenDoses: React.Dispatch<React.SetStateAction<Set<string>>>;
|
setTakenDoses: React.Dispatch<React.SetStateAction<Set<string>>>;
|
||||||
|
takenDoseTimestamps: Map<string, number>;
|
||||||
dismissedDoses: Set<string>;
|
dismissedDoses: Set<string>;
|
||||||
showClearMissedConfirm: boolean;
|
showClearMissedConfirm: boolean;
|
||||||
setShowClearMissedConfirm: (show: boolean) => void;
|
setShowClearMissedConfirm: (show: boolean) => void;
|
||||||
@@ -19,25 +20,39 @@ export interface UseDosesReturn {
|
|||||||
|
|
||||||
export function useDoses(): UseDosesReturn {
|
export function useDoses(): UseDosesReturn {
|
||||||
const [takenDoses, setTakenDoses] = useState<Set<string>>(new Set());
|
const [takenDoses, setTakenDoses] = useState<Set<string>>(new Set());
|
||||||
|
const [takenDoseTimestamps, setTakenDoseTimestamps] = useState<Map<string, number>>(new Map());
|
||||||
const [dismissedDoses, setDismissedDoses] = useState<Set<string>>(new Set());
|
const [dismissedDoses, setDismissedDoses] = useState<Set<string>>(new Set());
|
||||||
const [showClearMissedConfirm, setShowClearMissedConfirm] = useState(false);
|
const [showClearMissedConfirm, setShowClearMissedConfirm] = useState(false);
|
||||||
|
|
||||||
|
// Track in-flight mutations to prevent polling from overwriting optimistic updates
|
||||||
|
const mutationInFlightRef = useRef(0);
|
||||||
|
|
||||||
// Load taken doses from server
|
// Load taken doses from server
|
||||||
const loadTakenDoses = useCallback(async () => {
|
const loadTakenDoses = useCallback(async () => {
|
||||||
|
// Skip polling while mutations are in-flight to prevent race conditions
|
||||||
|
// where a poll response with stale data overwrites optimistic updates
|
||||||
|
if (mutationInFlightRef.current > 0) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/doses/taken", { credentials: "include" });
|
const res = await fetch("/api/doses/taken", { credentials: "include" });
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
|
// Double-check no mutation started while we were fetching
|
||||||
|
if (mutationInFlightRef.current > 0) return;
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const taken = new Set<string>();
|
const taken = new Set<string>();
|
||||||
|
const timestamps = new Map<string, number>();
|
||||||
const dismissed = new Set<string>();
|
const dismissed = new Set<string>();
|
||||||
for (const d of data.doses) {
|
for (const d of data.doses) {
|
||||||
if (d.dismissed) {
|
if (d.dismissed) {
|
||||||
dismissed.add(d.doseId);
|
dismissed.add(d.doseId);
|
||||||
} else {
|
} else {
|
||||||
taken.add(d.doseId);
|
taken.add(d.doseId);
|
||||||
|
timestamps.set(d.doseId, d.takenAt);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setTakenDoses(taken);
|
setTakenDoses(taken);
|
||||||
|
setTakenDoseTimestamps(timestamps);
|
||||||
setDismissedDoses(dismissed);
|
setDismissedDoses(dismissed);
|
||||||
}
|
}
|
||||||
// Don't reset on error - keep current state
|
// Don't reset on error - keep current state
|
||||||
@@ -77,59 +92,91 @@ export function useDoses(): UseDosesReturn {
|
|||||||
[takenDoses, getDoseId]
|
[takenDoses, getDoseId]
|
||||||
);
|
);
|
||||||
|
|
||||||
const markDoseTaken = useCallback(async (doseId: string) => {
|
const markDoseTaken = useCallback(
|
||||||
// Optimistic update
|
async (doseId: string) => {
|
||||||
setTakenDoses((prev) => {
|
// Optimistic update
|
||||||
const next = new Set(prev);
|
mutationInFlightRef.current++;
|
||||||
next.add(doseId);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Send to server
|
|
||||||
try {
|
|
||||||
await fetch("/api/doses/taken", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
credentials: "include",
|
|
||||||
body: JSON.stringify({ doseId }),
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// Revert on error
|
|
||||||
setTakenDoses((prev) => {
|
|
||||||
const next = new Set(prev);
|
|
||||||
next.delete(doseId);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const undoDoseTaken = useCallback(async (doseId: string) => {
|
|
||||||
// Optimistic update
|
|
||||||
setTakenDoses((prev) => {
|
|
||||||
const next = new Set(prev);
|
|
||||||
next.delete(doseId);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Send to server
|
|
||||||
try {
|
|
||||||
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
credentials: "include",
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// Revert on error
|
|
||||||
setTakenDoses((prev) => {
|
setTakenDoses((prev) => {
|
||||||
const next = new Set(prev);
|
const next = new Set(prev);
|
||||||
next.add(doseId);
|
next.add(doseId);
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
}
|
setTakenDoseTimestamps((prev) => {
|
||||||
}, []);
|
const next = new Map(prev);
|
||||||
|
next.set(doseId, Date.now());
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send to server
|
||||||
|
try {
|
||||||
|
await fetch("/api/doses/taken", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
credentials: "include",
|
||||||
|
body: JSON.stringify({ doseId }),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Revert on error
|
||||||
|
setTakenDoses((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.delete(doseId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
setTakenDoseTimestamps((prev) => {
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.delete(doseId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
mutationInFlightRef.current--;
|
||||||
|
// Re-sync with server after mutation completes
|
||||||
|
loadTakenDoses();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[loadTakenDoses]
|
||||||
|
);
|
||||||
|
|
||||||
|
const undoDoseTaken = useCallback(
|
||||||
|
async (doseId: string) => {
|
||||||
|
// Optimistic update
|
||||||
|
mutationInFlightRef.current++;
|
||||||
|
setTakenDoses((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.delete(doseId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
setTakenDoseTimestamps((prev) => {
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.delete(doseId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send to server
|
||||||
|
try {
|
||||||
|
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
credentials: "include",
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Revert on error
|
||||||
|
setTakenDoses((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.add(doseId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
mutationInFlightRef.current--;
|
||||||
|
// Re-sync with server after mutation completes
|
||||||
|
loadTakenDoses();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[loadTakenDoses]
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
takenDoses,
|
takenDoses,
|
||||||
setTakenDoses,
|
setTakenDoses,
|
||||||
|
takenDoseTimestamps,
|
||||||
dismissedDoses,
|
dismissedDoses,
|
||||||
showClearMissedConfirm,
|
showClearMissedConfirm,
|
||||||
setShowClearMissedConfirm,
|
setShowClearMissedConfirm,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useCallback, useState } from "react";
|
import { useCallback, useState } from "react";
|
||||||
import type { Coverage, FormState, Medication, RefillEntry } from "../types";
|
import type { Coverage, FormState, Medication, RefillEntry } from "../types";
|
||||||
import { getMedTotal } from "../types";
|
import { getMedTotal, getPackageSize } from "../types";
|
||||||
|
|
||||||
export interface UseRefillReturn {
|
export interface UseRefillReturn {
|
||||||
// Refill state
|
// Refill state
|
||||||
@@ -146,8 +146,8 @@ export function useRefill(): UseRefillReturn {
|
|||||||
const desiredTotal = finalFullBlisters * selectedMed.pillsPerBlister + finalPartialPills;
|
const desiredTotal = finalFullBlisters * selectedMed.pillsPerBlister + finalPartialPills;
|
||||||
|
|
||||||
// The "base" from DB structure (without any stockAdjustment)
|
// The "base" from DB structure (without any stockAdjustment)
|
||||||
const baseTotal =
|
// Use getPackageSize() which handles both blister and bottle types correctly
|
||||||
selectedMed.packCount * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + selectedMed.looseTablets;
|
const baseTotal = getPackageSize(selectedMed);
|
||||||
|
|
||||||
// stockAdjustment = what we need to make getMedTotal() return desiredTotal
|
// stockAdjustment = what we need to make getMedTotal() return desiredTotal
|
||||||
const newStockAdjustment = desiredTotal - baseTotal;
|
const newStockAdjustment = desiredTotal - baseTotal;
|
||||||
|
|||||||
@@ -1,32 +1,80 @@
|
|||||||
// =============================================================================
|
// =============================================================================
|
||||||
// useTheme Hook - Theme (dark/light mode) state management
|
// useTheme Hook - Theme (dark/light/system mode) state management
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
|
||||||
export type Theme = "light" | "dark";
|
export type Theme = "light" | "dark";
|
||||||
|
export type ThemePreference = "light" | "dark" | "system";
|
||||||
|
|
||||||
export interface UseThemeReturn {
|
export interface UseThemeReturn {
|
||||||
|
/** The resolved theme applied to the DOM ("light" | "dark") */
|
||||||
theme: Theme;
|
theme: Theme;
|
||||||
|
/** The user's preference ("light" | "dark" | "system") */
|
||||||
|
themePreference: ThemePreference;
|
||||||
|
/** Set the theme preference */
|
||||||
|
setThemePreference: (pref: ThemePreference) => void;
|
||||||
|
/** Legacy toggle: cycles light → dark → system → light */
|
||||||
toggleTheme: () => void;
|
toggleTheme: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getSystemTheme(): Theme {
|
||||||
|
if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: light)").matches) {
|
||||||
|
return "light";
|
||||||
|
}
|
||||||
|
return "dark";
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveTheme(pref: ThemePreference): Theme {
|
||||||
|
return pref === "system" ? getSystemTheme() : pref;
|
||||||
|
}
|
||||||
|
|
||||||
export function useTheme(): UseThemeReturn {
|
export function useTheme(): UseThemeReturn {
|
||||||
const [theme, setTheme] = useState<Theme>(() => {
|
const [themePreference, setThemePreferenceState] = useState<ThemePreference>(() => {
|
||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
return (localStorage.getItem("theme") as Theme) || "dark";
|
const stored = localStorage.getItem("theme") as ThemePreference | null;
|
||||||
|
if (stored === "light" || stored === "dark" || stored === "system") return stored;
|
||||||
|
return "dark";
|
||||||
}
|
}
|
||||||
return "dark";
|
return "dark";
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
const [theme, setTheme] = useState<Theme>(() => resolveTheme(themePreference));
|
||||||
document.documentElement.setAttribute("data-theme", theme);
|
|
||||||
localStorage.setItem("theme", theme);
|
|
||||||
}, [theme]);
|
|
||||||
|
|
||||||
const toggleTheme = useCallback(() => {
|
// Apply resolved theme to DOM whenever preference or system theme changes
|
||||||
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
|
useEffect(() => {
|
||||||
|
const resolved = resolveTheme(themePreference);
|
||||||
|
setTheme(resolved);
|
||||||
|
document.documentElement.setAttribute("data-theme", resolved);
|
||||||
|
localStorage.setItem("theme", themePreference);
|
||||||
|
}, [themePreference]);
|
||||||
|
|
||||||
|
// Listen for system theme changes when preference is "system"
|
||||||
|
useEffect(() => {
|
||||||
|
if (themePreference !== "system") return;
|
||||||
|
const mq = window.matchMedia?.("(prefers-color-scheme: light)");
|
||||||
|
if (!mq) return;
|
||||||
|
|
||||||
|
const handler = () => {
|
||||||
|
const resolved = resolveTheme("system");
|
||||||
|
setTheme(resolved);
|
||||||
|
document.documentElement.setAttribute("data-theme", resolved);
|
||||||
|
};
|
||||||
|
mq.addEventListener("change", handler);
|
||||||
|
return () => mq.removeEventListener("change", handler);
|
||||||
|
}, [themePreference]);
|
||||||
|
|
||||||
|
const setThemePreference = useCallback((pref: ThemePreference) => {
|
||||||
|
setThemePreferenceState(pref);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return { theme, toggleTheme };
|
const toggleTheme = useCallback(() => {
|
||||||
|
setThemePreferenceState((prev) => {
|
||||||
|
if (prev === "light") return "dark";
|
||||||
|
if (prev === "dark") return "system";
|
||||||
|
return "light";
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { theme, themePreference, setThemePreference, toggleTheme };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -176,7 +176,8 @@
|
|||||||
"badge": "Vorrat planen",
|
"badge": "Vorrat planen",
|
||||||
"from": "Von",
|
"from": "Von",
|
||||||
"until": "Bis",
|
"until": "Bis",
|
||||||
"includeUntilStart": "Verbrauch von heute bis Startdatum einrechnen",
|
"includeUntilStart": "Aktuellen Verbrauch einrechnen",
|
||||||
|
"includeUntilStartTooltip": "Wenn aktiviert, werden die Pillen, die zwischen heute und dem gewählten Startdatum verbraucht werden, vom aktuellen Bestand abgezogen. So erhältst du ein genaueres Bild davon, wie viel du zu Beginn des Planungszeitraums tatsächlich noch übrig hast.",
|
||||||
"calculate": "Berechnen",
|
"calculate": "Berechnen",
|
||||||
"calculating": "Wird berechnet...",
|
"calculating": "Wird berechnet...",
|
||||||
"sendEmail": "📧 Per E-Mail senden",
|
"sendEmail": "📧 Per E-Mail senden",
|
||||||
@@ -290,6 +291,12 @@
|
|||||||
"lightMode": "Zum hellen Modus wechseln",
|
"lightMode": "Zum hellen Modus wechseln",
|
||||||
"darkMode": "Zum dunklen Modus wechseln"
|
"darkMode": "Zum dunklen Modus wechseln"
|
||||||
},
|
},
|
||||||
|
"theme": {
|
||||||
|
"title": "Design",
|
||||||
|
"light": "Hell",
|
||||||
|
"dark": "Dunkel",
|
||||||
|
"system": "System"
|
||||||
|
},
|
||||||
"dose": {
|
"dose": {
|
||||||
"takenBy": "eingenommen von",
|
"takenBy": "eingenommen von",
|
||||||
"markAsTaken": "Als eingenommen markieren"
|
"markAsTaken": "Als eingenommen markieren"
|
||||||
@@ -478,10 +485,9 @@
|
|||||||
"checking": "Prüfe...",
|
"checking": "Prüfe...",
|
||||||
"upToDate": "Du bist auf dem neuesten Stand!",
|
"upToDate": "Du bist auf dem neuesten Stand!",
|
||||||
"updateAvailable": "Update verfügbar",
|
"updateAvailable": "Update verfügbar",
|
||||||
"viewOnGitHub": "Auf GitHub ansehen",
|
|
||||||
"downloadUpdate": "Update herunterladen",
|
"downloadUpdate": "Update herunterladen",
|
||||||
"checkFailed": "Update-Prüfung fehlgeschlagen",
|
"checkFailed": "Update-Prüfung fehlgeschlagen",
|
||||||
"lastChecked": "Zuletzt geprüft",
|
"viewOnGitHub": "Auf GitHub ansehen",
|
||||||
"github": "GitHub",
|
"github": "GitHub",
|
||||||
"license": "MIT-Lizenz",
|
"license": "MIT-Lizenz",
|
||||||
"copyright": "© {{year}} Daniel Volz",
|
"copyright": "© {{year}} Daniel Volz",
|
||||||
|
|||||||
@@ -176,7 +176,8 @@
|
|||||||
"badge": "Plan your supply",
|
"badge": "Plan your supply",
|
||||||
"from": "From",
|
"from": "From",
|
||||||
"until": "Until",
|
"until": "Until",
|
||||||
"includeUntilStart": "Include consumption from today until start date",
|
"includeUntilStart": "Include current consumption",
|
||||||
|
"includeUntilStartTooltip": "When enabled, pills consumed between today and the selected start date are subtracted from your current stock. This gives a more accurate picture of how much you'll actually have left when the planning period begins.",
|
||||||
"calculate": "Calculate",
|
"calculate": "Calculate",
|
||||||
"calculating": "Calculating...",
|
"calculating": "Calculating...",
|
||||||
"sendEmail": "📧 Send via Email",
|
"sendEmail": "📧 Send via Email",
|
||||||
@@ -290,6 +291,12 @@
|
|||||||
"lightMode": "Switch to light mode",
|
"lightMode": "Switch to light mode",
|
||||||
"darkMode": "Switch to dark mode"
|
"darkMode": "Switch to dark mode"
|
||||||
},
|
},
|
||||||
|
"theme": {
|
||||||
|
"title": "Theme",
|
||||||
|
"light": "Light",
|
||||||
|
"dark": "Dark",
|
||||||
|
"system": "System"
|
||||||
|
},
|
||||||
"dose": {
|
"dose": {
|
||||||
"takenBy": "taken by",
|
"takenBy": "taken by",
|
||||||
"markAsTaken": "Mark as taken"
|
"markAsTaken": "Mark as taken"
|
||||||
@@ -478,10 +485,9 @@
|
|||||||
"checking": "Checking...",
|
"checking": "Checking...",
|
||||||
"upToDate": "You're up to date!",
|
"upToDate": "You're up to date!",
|
||||||
"updateAvailable": "Update available",
|
"updateAvailable": "Update available",
|
||||||
"viewOnGitHub": "View on GitHub",
|
|
||||||
"downloadUpdate": "Download Update",
|
"downloadUpdate": "Download Update",
|
||||||
"checkFailed": "Could not check for updates",
|
"checkFailed": "Could not check for updates",
|
||||||
"lastChecked": "Last checked",
|
"viewOnGitHub": "View on GitHub",
|
||||||
"github": "GitHub",
|
"github": "GitHub",
|
||||||
"license": "MIT License",
|
"license": "MIT License",
|
||||||
"copyright": "© {{year}} Daniel Volz",
|
"copyright": "© {{year}} Daniel Volz",
|
||||||
|
|||||||
@@ -34,14 +34,18 @@ function formatOpenBlisterAndLoose(
|
|||||||
return `${openBlisterPills} ${t("common.of")} ${pillsPerBlister} ${t("common.pills")}`;
|
return `${openBlisterPills} ${t("common.of")} ${pillsPerBlister} ${t("common.pills")}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get total pills for a medication
|
// Get total pills for a medication (packageType-aware)
|
||||||
function getMedTotal(med: {
|
function getMedTotal(med: {
|
||||||
packCount: number;
|
packCount: number;
|
||||||
blistersPerPack: number;
|
blistersPerPack: number;
|
||||||
pillsPerBlister: number;
|
pillsPerBlister: number;
|
||||||
looseTablets: number;
|
looseTablets: number;
|
||||||
stockAdjustment?: number | null;
|
stockAdjustment?: number | null;
|
||||||
|
packageType?: string;
|
||||||
}): number {
|
}): number {
|
||||||
|
if (med.packageType === "bottle") {
|
||||||
|
return med.looseTablets + (med.stockAdjustment ?? 0);
|
||||||
|
}
|
||||||
return med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
|
return med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,9 +280,17 @@ export function DashboardPage() {
|
|||||||
<div className="reminder-status-row">
|
<div className="reminder-status-row">
|
||||||
<span className="reminder-status-label">{t("dashboard.reminders.lastSent")}:</span>
|
<span className="reminder-status-label">{t("dashboard.reminders.lastSent")}:</span>
|
||||||
<span className="reminder-status-value">
|
<span className="reminder-status-value">
|
||||||
{reminderData.lastSent.medName && (
|
{reminderData.lastSent.medName &&
|
||||||
<span className="reminder-med-name">{reminderData.lastSent.medName}</span>
|
(() => {
|
||||||
)}
|
const medication = meds.find((m) => m.name === reminderData.lastSent!.medName);
|
||||||
|
return medication ? (
|
||||||
|
<span className="med-link clickable" onClick={() => openMedDetail(medication)}>
|
||||||
|
{reminderData.lastSent!.medName}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="reminder-med-name">{reminderData.lastSent!.medName}</span>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
{reminderData.lastSent.takenBy && (
|
{reminderData.lastSent.takenBy && (
|
||||||
<span className="reminder-taken-by"> ({reminderData.lastSent.takenBy})</span>
|
<span className="reminder-taken-by"> ({reminderData.lastSent.takenBy})</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -526,7 +526,7 @@ export function MedicationsPage() {
|
|||||||
</label>
|
</label>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<label>
|
<label className="full">
|
||||||
{t("form.pillWeight")} ({form.doseUnit})
|
{t("form.pillWeight")} ({form.doseUnit})
|
||||||
<div className="dose-input-group">
|
<div className="dose-input-group">
|
||||||
<input
|
<input
|
||||||
|
|||||||
@@ -178,6 +178,9 @@ export function PlannerPage() {
|
|||||||
onChange={(e) => setIncludeUntilStart(e.target.checked)}
|
onChange={(e) => setIncludeUntilStart(e.target.checked)}
|
||||||
/>
|
/>
|
||||||
{t("planner.includeUntilStart")}
|
{t("planner.includeUntilStart")}
|
||||||
|
<span className="info-tooltip small" data-tooltip={t("planner.includeUntilStartTooltip")}>
|
||||||
|
ⓘ
|
||||||
|
</span>
|
||||||
</label>
|
</label>
|
||||||
<div className="planner-actions">
|
<div className="planner-actions">
|
||||||
<button type="button" className="ghost" onClick={resetRange}>
|
<button type="button" className="ghost" onClick={resetRange}>
|
||||||
@@ -210,11 +213,19 @@ export function PlannerPage() {
|
|||||||
<strong>{row.plannerUsage}</strong> {t("common.pills")}
|
<strong>{row.plannerUsage}</strong> {t("common.pills")}
|
||||||
</span>
|
</span>
|
||||||
<span data-label={t("planner.table.blisters")}>
|
<span data-label={t("planner.table.blisters")}>
|
||||||
{row.blistersNeeded} × {row.blisterSize}
|
{row.packageType === "bottle"
|
||||||
|
? `${row.plannerUsage} ${t("common.pills")}`
|
||||||
|
: `${row.blistersNeeded} × ${row.blisterSize}`}
|
||||||
</span>
|
</span>
|
||||||
<span data-label={t("planner.table.available")}>
|
<span data-label={t("planner.table.available")}>
|
||||||
{row.fullBlisters} {t("common.blisters")}
|
{row.packageType === "bottle" ? (
|
||||||
{row.loosePills > 0 && ` + ${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`}
|
`${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{row.fullBlisters} {t("common.blisters")}
|
||||||
|
{row.loosePills > 0 && ` + ${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
data-label={t("table.status")}
|
data-label={t("table.status")}
|
||||||
|
|||||||
+90
-11
@@ -152,6 +152,90 @@ body.modal-open {
|
|||||||
background: rgba(47, 134, 246, 0.12);
|
background: rgba(47, 134, 246, 0.12);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* =============================================================================
|
||||||
|
Theme Dropdown Menu
|
||||||
|
============================================================================= */
|
||||||
|
.theme-menu {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-dropdown {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 0.5rem);
|
||||||
|
right: 0;
|
||||||
|
min-width: 160px;
|
||||||
|
background: rgba(15, 23, 42, 0.85);
|
||||||
|
backdrop-filter: blur(12px);
|
||||||
|
-webkit-backdrop-filter: blur(12px);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||||
|
border-radius: 12px;
|
||||||
|
box-shadow:
|
||||||
|
0 12px 32px rgba(0, 0, 0, 0.4),
|
||||||
|
inset 0 0 0 1px rgba(255, 255, 255, 0.05);
|
||||||
|
opacity: 0;
|
||||||
|
visibility: hidden;
|
||||||
|
transform: translateY(-6px) scale(0.95);
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
z-index: 1000;
|
||||||
|
overflow: hidden;
|
||||||
|
padding: 0.375rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="light"] .theme-dropdown {
|
||||||
|
background: rgba(255, 255, 255, 0.85);
|
||||||
|
border: 1px solid rgba(0, 0, 0, 0.08);
|
||||||
|
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-menu.open .theme-dropdown {
|
||||||
|
opacity: 1;
|
||||||
|
visibility: visible;
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-dropdown-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.625rem 0.75rem;
|
||||||
|
border: none;
|
||||||
|
background: none;
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
cursor: pointer;
|
||||||
|
border-radius: 8px;
|
||||||
|
transition: background 0.15s ease;
|
||||||
|
text-align: left;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-dropdown-item:hover {
|
||||||
|
background: rgba(59, 130, 246, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-dropdown-item.active {
|
||||||
|
color: var(--accent-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-dropdown-item svg {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-dropdown-item.active svg {
|
||||||
|
opacity: 1;
|
||||||
|
color: var(--accent-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-check {
|
||||||
|
margin-left: auto;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
|
||||||
.hero-title {
|
.hero-title {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -1024,12 +1108,14 @@ textarea.auto-resize {
|
|||||||
|
|
||||||
.dose-input-group input {
|
.dose-input-group input {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 100px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dose-unit-select {
|
.dose-unit-select {
|
||||||
width: auto;
|
width: auto;
|
||||||
min-width: 80px;
|
min-width: unset;
|
||||||
|
max-width: 120px;
|
||||||
|
flex-shrink: 0;
|
||||||
padding: 0.5rem 0.75rem;
|
padding: 0.5rem 0.75rem;
|
||||||
background: var(--bg-primary);
|
background: var(--bg-primary);
|
||||||
border: 1px solid var(--border-primary);
|
border: 1px solid var(--border-primary);
|
||||||
@@ -2019,11 +2105,12 @@ textarea.auto-resize {
|
|||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 0.04em;
|
letter-spacing: 0.04em;
|
||||||
}
|
}
|
||||||
.planner-checkbox {
|
.planner label.planner-checkbox {
|
||||||
grid-column: 1 / -1;
|
grid-column: 1 / -1;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
flex-wrap: nowrap;
|
||||||
gap: 0.75rem;
|
gap: 0.75rem;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
@@ -4614,7 +4701,6 @@ a.about-version-link:hover {
|
|||||||
.about-update-section {
|
.about-update-section {
|
||||||
padding: 1.25rem 1.5rem;
|
padding: 1.25rem 1.5rem;
|
||||||
border-bottom: 1px solid var(--border-primary);
|
border-bottom: 1px solid var(--border-primary);
|
||||||
min-height: 148px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.about-update-btn {
|
.about-update-btn {
|
||||||
@@ -4713,13 +4799,6 @@ a.about-version-link:hover {
|
|||||||
background: var(--accent-hover);
|
background: var(--accent-hover);
|
||||||
}
|
}
|
||||||
|
|
||||||
.update-last-checked {
|
|
||||||
display: block;
|
|
||||||
margin-top: 0.5rem;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
opacity: 0.8;
|
|
||||||
}
|
|
||||||
|
|
||||||
.about-links {
|
.about-links {
|
||||||
padding: 1.25rem 1.5rem;
|
padding: 1.25rem 1.5rem;
|
||||||
border-bottom: 1px solid var(--border-primary);
|
border-bottom: 1px solid var(--border-primary);
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ describe("AppHeader", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("renders theme toggle button", async () => {
|
it("renders theme menu button", async () => {
|
||||||
const mockOnOpenProfile = vi.fn();
|
const mockOnOpenProfile = vi.fn();
|
||||||
const mockOnOpenAbout = vi.fn();
|
const mockOnOpenAbout = vi.fn();
|
||||||
|
|
||||||
@@ -95,12 +95,33 @@ describe("AppHeader", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
const buttons = screen.getAllByRole("button");
|
const themeBtn = screen.getByTitle(/theme\.title/i);
|
||||||
const themeBtn = buttons.find((btn) => btn.textContent?.includes("🌙") || btn.textContent?.includes("☀️"));
|
|
||||||
expect(themeBtn).toBeInTheDocument();
|
expect(themeBtn).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("opens theme dropdown and shows Light/Dark/System options", async () => {
|
||||||
|
const mockOnOpenProfile = vi.fn();
|
||||||
|
const mockOnOpenAbout = vi.fn();
|
||||||
|
|
||||||
|
render(
|
||||||
|
<MemoryRouter initialEntries={["/dashboard"]}>
|
||||||
|
<AuthProvider>
|
||||||
|
<AppHeader onOpenProfile={mockOnOpenProfile} onOpenAbout={mockOnOpenAbout} />
|
||||||
|
</AuthProvider>
|
||||||
|
</MemoryRouter>
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const themeBtn = screen.getByTitle(/theme\.title/i);
|
||||||
|
fireEvent.click(themeBtn);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByText(/theme\.light/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/theme\.dark/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/theme\.system/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
it("renders settings button when auth is disabled", async () => {
|
it("renders settings button when auth is disabled", async () => {
|
||||||
const mockOnOpenProfile = vi.fn();
|
const mockOnOpenProfile = vi.fn();
|
||||||
const mockOnOpenAbout = vi.fn();
|
const mockOnOpenAbout = vi.fn();
|
||||||
|
|||||||
@@ -103,10 +103,14 @@ describe("useDoses", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("marks dose as taken optimistically", async () => {
|
it("marks dose as taken optimistically", async () => {
|
||||||
// First call for initial load, subsequent calls for marking dose
|
// First call for initial load, second for marking dose, third for re-sync
|
||||||
(global.fetch as ReturnType<typeof vi.fn>)
|
(global.fetch as ReturnType<typeof vi.fn>)
|
||||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||||
.mockResolvedValueOnce({ ok: true });
|
.mockResolvedValueOnce({ ok: true })
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: () => Promise.resolve({ doses: [{ doseId: "new-dose", takenAt: Date.now(), dismissed: false }] }),
|
||||||
|
});
|
||||||
|
|
||||||
const { result } = renderHook(() => useDoses());
|
const { result } = renderHook(() => useDoses());
|
||||||
|
|
||||||
@@ -119,7 +123,9 @@ describe("useDoses", () => {
|
|||||||
await result.current.markDoseTaken("new-dose");
|
await result.current.markDoseTaken("new-dose");
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(result.current.takenDoses.has("new-dose")).toBe(true);
|
await waitFor(() => {
|
||||||
|
expect(result.current.takenDoses.has("new-dose")).toBe(true);
|
||||||
|
});
|
||||||
expect(fetch).toHaveBeenCalledWith(
|
expect(fetch).toHaveBeenCalledWith(
|
||||||
"/api/doses/taken",
|
"/api/doses/taken",
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
@@ -130,10 +136,11 @@ describe("useDoses", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("reverts optimistic update on error", async () => {
|
it("reverts optimistic update on error", async () => {
|
||||||
// First call for initial load, second for marking dose fails
|
// First call for initial load, second for marking dose fails, third for re-sync
|
||||||
(global.fetch as ReturnType<typeof vi.fn>)
|
(global.fetch as ReturnType<typeof vi.fn>)
|
||||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||||
.mockRejectedValueOnce(new Error("Network error"));
|
.mockRejectedValueOnce(new Error("Network error"))
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) });
|
||||||
|
|
||||||
const { result } = renderHook(() => useDoses());
|
const { result } = renderHook(() => useDoses());
|
||||||
|
|
||||||
@@ -153,12 +160,13 @@ describe("useDoses", () => {
|
|||||||
|
|
||||||
it("undoes dose taken optimistically", async () => {
|
it("undoes dose taken optimistically", async () => {
|
||||||
const mockDoses = {
|
const mockDoses = {
|
||||||
doses: [{ doseId: "taken-dose", dismissed: false }],
|
doses: [{ doseId: "taken-dose", takenAt: Date.now(), dismissed: false }],
|
||||||
};
|
};
|
||||||
|
|
||||||
(global.fetch as ReturnType<typeof vi.fn>)
|
(global.fetch as ReturnType<typeof vi.fn>)
|
||||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
|
||||||
.mockResolvedValueOnce({ ok: true });
|
.mockResolvedValueOnce({ ok: true })
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) });
|
||||||
|
|
||||||
const { result } = renderHook(() => useDoses());
|
const { result } = renderHook(() => useDoses());
|
||||||
|
|
||||||
@@ -170,10 +178,101 @@ describe("useDoses", () => {
|
|||||||
await result.current.undoDoseTaken("taken-dose");
|
await result.current.undoDoseTaken("taken-dose");
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(result.current.takenDoses.has("taken-dose")).toBe(false);
|
await waitFor(() => {
|
||||||
|
expect(result.current.takenDoses.has("taken-dose")).toBe(false);
|
||||||
|
});
|
||||||
expect(fetch).toHaveBeenCalledWith("/api/doses/taken/taken-dose", expect.objectContaining({ method: "DELETE" }));
|
expect(fetch).toHaveBeenCalledWith("/api/doses/taken/taken-dose", expect.objectContaining({ method: "DELETE" }));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("reverts undo on error by re-adding the dose", async () => {
|
||||||
|
const mockDoses = {
|
||||||
|
doses: [{ doseId: "taken-dose", takenAt: 1710500000000, dismissed: false }],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Initial load returns taken-dose, DELETE fails, re-sync returns taken-dose still there
|
||||||
|
(global.fetch as ReturnType<typeof vi.fn>)
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
|
||||||
|
.mockRejectedValueOnce(new Error("Network error"))
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) });
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useDoses());
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(result.current.takenDoses.has("taken-dose")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.undoDoseTaken("taken-dose");
|
||||||
|
});
|
||||||
|
|
||||||
|
// After error, the dose should be re-added (reverted)
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(result.current.takenDoses.has("taken-dose")).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("populates takenDoseTimestamps from API response", async () => {
|
||||||
|
const takenAt = 1710500000000;
|
||||||
|
const mockDoses = {
|
||||||
|
doses: [{ doseId: "dose-1", takenAt, dismissed: false }],
|
||||||
|
};
|
||||||
|
|
||||||
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: () => Promise.resolve(mockDoses),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useDoses());
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(result.current.takenDoseTimestamps.get("dose-1")).toBe(takenAt);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("markDoseTaken sets takenDoseTimestamp optimistically", async () => {
|
||||||
|
const now = Date.now();
|
||||||
|
vi.setSystemTime(now);
|
||||||
|
|
||||||
|
// Initial load, POST success, re-sync
|
||||||
|
(global.fetch as ReturnType<typeof vi.fn>)
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||||
|
.mockResolvedValueOnce({ ok: true })
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: () => Promise.resolve({ doses: [{ doseId: "new-dose", takenAt: now, dismissed: false }] }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useDoses());
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(result.current.takenDoses.size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.markDoseTaken("new-dose");
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(result.current.takenDoseTimestamps.has("new-dose")).toBe(true);
|
||||||
|
expect(result.current.takenDoseTimestamps.get("new-dose")).toBe(now);
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps state on fetch error during initial load", async () => {
|
||||||
|
// Initial load fails
|
||||||
|
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("Network error"));
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useDoses());
|
||||||
|
|
||||||
|
// Should keep empty state, not crash
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(result.current.takenDoses.size).toBe(0);
|
||||||
|
expect(result.current.dismissedDoses.size).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("setShowClearMissedConfirm works", () => {
|
it("setShowClearMissedConfirm works", () => {
|
||||||
const { result } = renderHook(() => useDoses());
|
const { result } = renderHook(() => useDoses());
|
||||||
|
|
||||||
|
|||||||
@@ -287,6 +287,114 @@ describe("useRefill", () => {
|
|||||||
expect(mockLoadMeds).toHaveBeenCalled();
|
expect(mockLoadMeds).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("stock correction uses correct base for bottle type medications", async () => {
|
||||||
|
// BUG FIX: submitStockCorrection used blister formula (packCount * blistersPerPack * pillsPerBlister + looseTablets)
|
||||||
|
// for ALL medications, but getMedTotal() uses only looseTablets + stockAdjustment for bottles.
|
||||||
|
// This mismatch caused the correction to compute the wrong stockAdjustment.
|
||||||
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
|
||||||
|
|
||||||
|
const bottleMed: Medication = {
|
||||||
|
id: 4,
|
||||||
|
name: "Pills in a Box",
|
||||||
|
packageType: "bottle",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 1,
|
||||||
|
looseTablets: 150,
|
||||||
|
stockAdjustment: -2,
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [{ usage: 1, every: 1, start: "2026-01-31T20:27:00" }],
|
||||||
|
updatedAt: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
// getMedTotal for bottle = looseTablets + stockAdjustment = 150 + (-2) = 148
|
||||||
|
// getPackageSize for bottle = looseTablets = 150
|
||||||
|
|
||||||
|
const mockLoadMeds = vi.fn();
|
||||||
|
const { result } = renderHook(() => useRefill());
|
||||||
|
|
||||||
|
// Pre-fill: user sees 148 pills (148 / 1 = 148 full, 0 partial)
|
||||||
|
act(() => {
|
||||||
|
result.current.openEditStockModal(bottleMed, {
|
||||||
|
all: [{ name: "Pills in a Box", medsLeft: 148, daysLeft: 148 }] as Coverage[],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// User adds +1 → 149 full blisters (pillsPerBlister=1)
|
||||||
|
act(() => {
|
||||||
|
result.current.setEditStockFullBlisters(149);
|
||||||
|
result.current.setEditStockPartialBlisterPills(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.submitStockCorrection(4, bottleMed, mockLoadMeds);
|
||||||
|
});
|
||||||
|
|
||||||
|
// desiredTotal = 149 * 1 + 0 = 149
|
||||||
|
// baseTotal (fixed) = getPackageSize(bottle) = looseTablets = 150
|
||||||
|
// newStockAdjustment = 149 - 150 = -1
|
||||||
|
// → getMedTotal = 150 + (-1) = 149 ✓
|
||||||
|
const fetchCall = (global.fetch as ReturnType<typeof vi.fn>).mock.calls.find(
|
||||||
|
(call: [string, RequestInit]) => call[0] === "/api/medications/4/stock-adjustment"
|
||||||
|
);
|
||||||
|
expect(fetchCall).toBeDefined();
|
||||||
|
const body = JSON.parse(fetchCall![1].body as string);
|
||||||
|
expect(body.stockAdjustment).toBe(-1); // NOT -2 (the old bug)
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stock correction uses correct base for blister type medications", async () => {
|
||||||
|
// Ensure blister type still works correctly after the bottle fix
|
||||||
|
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
|
||||||
|
|
||||||
|
const blisterMed: Medication = {
|
||||||
|
id: 2,
|
||||||
|
name: "Blister Med",
|
||||||
|
packageType: "blister",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 5,
|
||||||
|
pillsPerBlister: 5,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: 1,
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [{ usage: 1, every: 1, start: "2026-01-30T21:07:00" }],
|
||||||
|
updatedAt: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
// getMedTotal for blister = 1*5*5 + 0 + 1 = 26
|
||||||
|
// getPackageSize for blister = 1*5*5 + 0 = 25
|
||||||
|
|
||||||
|
const mockLoadMeds = vi.fn();
|
||||||
|
const { result } = renderHook(() => useRefill());
|
||||||
|
|
||||||
|
// User sees 26 pills → 5 full blisters (5pills each) + 1 partial
|
||||||
|
act(() => {
|
||||||
|
result.current.openEditStockModal(blisterMed, {
|
||||||
|
all: [{ name: "Blister Med", medsLeft: 26, daysLeft: 26 }] as Coverage[],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// User changes to 27 (+1): 5 full + 2 partial
|
||||||
|
act(() => {
|
||||||
|
result.current.setEditStockFullBlisters(5);
|
||||||
|
result.current.setEditStockPartialBlisterPills(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.submitStockCorrection(2, blisterMed, mockLoadMeds);
|
||||||
|
});
|
||||||
|
|
||||||
|
// desiredTotal = 5 * 5 + 2 = 27
|
||||||
|
// baseTotal = getPackageSize(blister) = 1*5*5 + 0 = 25
|
||||||
|
// newStockAdjustment = 27 - 25 = 2
|
||||||
|
// → getMedTotal = 25 + 2 = 27 ✓
|
||||||
|
const fetchCall = (global.fetch as ReturnType<typeof vi.fn>).mock.calls.find(
|
||||||
|
(call: [string, RequestInit]) => call[0] === "/api/medications/2/stock-adjustment"
|
||||||
|
);
|
||||||
|
expect(fetchCall).toBeDefined();
|
||||||
|
const body = JSON.parse(fetchCall![1].body as string);
|
||||||
|
expect(body.stockAdjustment).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
it("allows setting state directly", () => {
|
it("allows setting state directly", () => {
|
||||||
const { result } = renderHook(() => useRefill());
|
const { result } = renderHook(() => useRefill());
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,20 @@ describe("useTheme", () => {
|
|||||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null);
|
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null);
|
||||||
// Reset mock to default behavior
|
// Reset mock to default behavior
|
||||||
(window.localStorage.setItem as ReturnType<typeof vi.fn>).mockImplementation(() => {});
|
(window.localStorage.setItem as ReturnType<typeof vi.fn>).mockImplementation(() => {});
|
||||||
|
// Mock matchMedia to return dark system theme by default
|
||||||
|
Object.defineProperty(window, "matchMedia", {
|
||||||
|
writable: true,
|
||||||
|
value: vi.fn().mockImplementation((query: string) => ({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addEventListener: vi.fn(),
|
||||||
|
removeEventListener: vi.fn(),
|
||||||
|
dispatchEvent: vi.fn(),
|
||||||
|
addListener: vi.fn(),
|
||||||
|
removeListener: vi.fn(),
|
||||||
|
})),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -17,58 +31,76 @@ describe("useTheme", () => {
|
|||||||
it("returns dark as default theme", () => {
|
it("returns dark as default theme", () => {
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
expect(result.current.theme).toBe("dark");
|
expect(result.current.theme).toBe("dark");
|
||||||
|
expect(result.current.themePreference).toBe("dark");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("reads theme from localStorage", () => {
|
it("reads theme preference from localStorage", () => {
|
||||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
|
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
expect(result.current.theme).toBe("light");
|
expect(result.current.theme).toBe("light");
|
||||||
|
expect(result.current.themePreference).toBe("light");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("toggles theme from dark to light", () => {
|
it("toggles theme through light → dark → system → light", () => {
|
||||||
const { result } = renderHook(() => useTheme());
|
|
||||||
|
|
||||||
expect(result.current.theme).toBe("dark");
|
|
||||||
|
|
||||||
act(() => {
|
|
||||||
result.current.toggleTheme();
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.theme).toBe("light");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("toggles theme from light to dark", () => {
|
|
||||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
|
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
|
expect(result.current.themePreference).toBe("light");
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.toggleTheme();
|
||||||
|
});
|
||||||
|
expect(result.current.themePreference).toBe("dark");
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.toggleTheme();
|
||||||
|
});
|
||||||
|
expect(result.current.themePreference).toBe("system");
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.toggleTheme();
|
||||||
|
});
|
||||||
|
expect(result.current.themePreference).toBe("light");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets theme preference directly", () => {
|
||||||
|
const { result } = renderHook(() => useTheme());
|
||||||
|
expect(result.current.themePreference).toBe("dark");
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.setThemePreference("light");
|
||||||
|
});
|
||||||
|
expect(result.current.themePreference).toBe("light");
|
||||||
expect(result.current.theme).toBe("light");
|
expect(result.current.theme).toBe("light");
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
result.current.toggleTheme();
|
result.current.setThemePreference("system");
|
||||||
});
|
});
|
||||||
|
expect(result.current.themePreference).toBe("system");
|
||||||
|
// System resolves to dark (matchMedia returns false for light)
|
||||||
expect(result.current.theme).toBe("dark");
|
expect(result.current.theme).toBe("dark");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("saves theme to localStorage on change", () => {
|
it("saves theme preference to localStorage on change", () => {
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
result.current.toggleTheme();
|
result.current.setThemePreference("light");
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(window.localStorage.setItem).toHaveBeenCalledWith("theme", "light");
|
expect(window.localStorage.setItem).toHaveBeenCalledWith("theme", "light");
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.setThemePreference("system");
|
||||||
|
});
|
||||||
|
expect(window.localStorage.setItem).toHaveBeenCalledWith("theme", "system");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("sets data-theme attribute on document", () => {
|
it("sets data-theme attribute on document", () => {
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
|
|
||||||
expect(document.documentElement.getAttribute("data-theme")).toBe("dark");
|
expect(document.documentElement.getAttribute("data-theme")).toBe("dark");
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
result.current.toggleTheme();
|
result.current.setThemePreference("light");
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(document.documentElement.getAttribute("data-theme")).toBe("light");
|
expect(document.documentElement.getAttribute("data-theme")).toBe("light");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -289,6 +289,113 @@ describe("calculateCoverage", () => {
|
|||||||
expect(result.all[0].daysLeft).toBeNull();
|
expect(result.all[0].daysLeft).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("uses intakes format when available instead of blisters", () => {
|
||||||
|
// The new intakes format should be used for coverage calculation
|
||||||
|
// when med.intakes is present, falling through getBlistersForMed
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "IntakesMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [], // Empty blisters — intakes should be used instead
|
||||||
|
intakes: [
|
||||||
|
{
|
||||||
|
usage: 2,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-10T09:00:00",
|
||||||
|
takenBy: null,
|
||||||
|
intakeRemindersEnabled: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// 30 pills, 2 per day consumed. March 10 09:00 to March 15 12:00 = 6 occurrences × 2 = 12 consumed
|
||||||
|
expect(result.all[0].medsLeft).toBe(18);
|
||||||
|
expect(result.all[0].daysLeft).toBe(9); // 18 pills / 2 per day = 9 days
|
||||||
|
});
|
||||||
|
|
||||||
|
it("per-intake takenBy counts person correctly in automatic mode", () => {
|
||||||
|
// When intakes have per-intake takenBy, each person-intake pair is counted
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "PersonMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 60,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: ["Alice", "Bob"],
|
||||||
|
blisters: [],
|
||||||
|
intakes: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-10T09:00:00",
|
||||||
|
takenBy: "Alice",
|
||||||
|
intakeRemindersEnabled: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-10T09:00:00",
|
||||||
|
takenBy: "Bob",
|
||||||
|
intakeRemindersEnabled: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// 2 intakes × 1 pill/day × 6 occurrences = 12 consumed
|
||||||
|
// dailyRate = 2 (1/day × 2 people)
|
||||||
|
// medsLeft = 60 - 12 = 48, daysLeft = 48 / 2 = 24
|
||||||
|
expect(result.all[0].medsLeft).toBe(48);
|
||||||
|
expect(result.all[0].daysLeft).toBe(24);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("automatic mode without stock correction counts from blister start", () => {
|
||||||
|
// Without stock correction, effectiveStart should be the blisterStart itself.
|
||||||
|
// This tests the `else` branch where effectiveStart = blisterStart.
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "TestMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-13T09:00:00", // 2 days ago + today = 3 occurrences
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
// No lastStockCorrectionAt
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// March 13, 14, 15 at 09:00 — all past (it's 12:00 on March 15) = 3 consumed
|
||||||
|
expect(result.all[0].medsLeft).toBe(27);
|
||||||
|
});
|
||||||
|
|
||||||
it("filters low stock medications", () => {
|
it("filters low stock medications", () => {
|
||||||
const meds: Medication[] = [
|
const meds: Medication[] = [
|
||||||
{
|
{
|
||||||
@@ -409,8 +516,9 @@ describe("calculateCoverage", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("stock correction with dose tracking data also reflects correctly", () => {
|
it("stock correction with dose tracking data also reflects correctly", () => {
|
||||||
// When the user has dose tracking data, the actualConsumed path is used.
|
// In automatic mode, dose tracking data is ignored — stock is always
|
||||||
// Verify that no phantom dose is generated right after a stock correction.
|
// reduced based on the schedule. Verify that tracked doses don't affect
|
||||||
|
// the calculation and that stock correction still resets the baseline.
|
||||||
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
||||||
const march14 = new Date("2024-03-14T00:00:00").getTime();
|
const march14 = new Date("2024-03-14T00:00:00").getTime();
|
||||||
|
|
||||||
@@ -437,20 +545,23 @@ describe("calculateCoverage", () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
// User has tracked a dose yesterday (before the correction)
|
// User has tracked a dose yesterday (before the correction)
|
||||||
|
// In automatic mode, this should be ignored — only the schedule matters.
|
||||||
const takenDoses = new Set([`1-0-${march14}`]);
|
const takenDoses = new Set([`1-0-${march14}`]);
|
||||||
|
|
||||||
const result = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
const result = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
||||||
|
|
||||||
expect(result.all).toHaveLength(1);
|
expect(result.all).toHaveLength(1);
|
||||||
// getMedTotal = 30 - 7 = 23.
|
// getMedTotal = 30 - 7 = 23.
|
||||||
// The taken dose from yesterday should NOT be counted (it's before the correction).
|
// Automatic mode ignores tracking data. After correction, consumption
|
||||||
// No new doses should exist since the correction just happened.
|
// restarts from correctionTime + period, which is in the future.
|
||||||
expect(result.all[0].medsLeft).toBe(23);
|
expect(result.all[0].medsLeft).toBe(23);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("stock correction consumption resumes after one full period", () => {
|
it("stock correction consumption resumes after one full period", () => {
|
||||||
// After 1 day (for daily medication), the next dose should be consumed.
|
// After correction, the next scheduled dose on the blister's grid should
|
||||||
// Set system time to 1 day + 1 hour after correction.
|
// be counted once its time arrives.
|
||||||
|
// Correction at March 14 12:00, blister start 08:00 daily →
|
||||||
|
// next dose after correction = March 15 08:00. Now is 13:00 on March 15 → 1 dose.
|
||||||
const correctionTime = new Date("2024-03-14T12:00:00Z");
|
const correctionTime = new Date("2024-03-14T12:00:00Z");
|
||||||
vi.setSystemTime(new Date("2024-03-15T13:00:00Z")); // 25 hours after correction
|
vi.setSystemTime(new Date("2024-03-15T13:00:00Z")); // 25 hours after correction
|
||||||
|
|
||||||
@@ -483,6 +594,521 @@ describe("calculateCoverage", () => {
|
|||||||
// medsLeft = 23 - 1 = 22
|
// medsLeft = 23 - 1 = 22
|
||||||
expect(result.all[0].medsLeft).toBe(22);
|
expect(result.all[0].medsLeft).toBe(22);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("stock correction aligns to schedule grid, not correction timestamp", () => {
|
||||||
|
// BUG: When correction happened just before a scheduled dose (e.g. 15:40
|
||||||
|
// correction, 15:42 dose), the old code added 1 full period to the correction
|
||||||
|
// time (15:40 + 24h = tomorrow 15:40), missing today's 15:42 dose entirely.
|
||||||
|
// FIX: Align effectiveStart to the blister's schedule grid so that the first
|
||||||
|
// dose counted is the next one on the schedule after the correction.
|
||||||
|
const correctionTime = new Date("2024-03-14T15:40:00Z"); // 2 min before dose
|
||||||
|
vi.setSystemTime(new Date("2024-03-14T15:45:00Z")); // 5 min after correction, 3 min after dose
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "TestMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: -5, // 30 - 5 = 25 pills
|
||||||
|
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-01T15:42:00Z", // Daily at 15:42
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: correctionTime.toISOString(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// Correction at 15:40, dose at 15:42, now at 15:45.
|
||||||
|
// The 15:42 dose is AFTER the correction → should be counted.
|
||||||
|
// medsLeft = 25 - 1 = 24
|
||||||
|
expect(result.all[0].medsLeft).toBe(24);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stock correction shortly after a dose does not count that dose again", () => {
|
||||||
|
// If correction happens shortly AFTER a dose, that dose is already reflected
|
||||||
|
// in the stock count and should NOT be counted again.
|
||||||
|
const correctionTime = new Date("2024-03-14T15:45:00Z"); // 3 min AFTER the 15:42 dose
|
||||||
|
vi.setSystemTime(new Date("2024-03-14T16:00:00Z")); // 15 min after correction
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "TestMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: -5,
|
||||||
|
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-01T15:42:00Z", // Daily at 15:42
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: correctionTime.toISOString(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// Correction at 15:45, after today's 15:42 dose → next dose is TOMORROW 15:42.
|
||||||
|
// Now is 16:00 today → next dose hasn't arrived yet → 0 consumed.
|
||||||
|
// medsLeft = 25
|
||||||
|
expect(result.all[0].medsLeft).toBe(25);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("automatic mode ignores past dose tracking data", () => {
|
||||||
|
// Automatic mode uses time-based expected consumption for past doses.
|
||||||
|
// Even if a user marks only some past doses as taken, the stock should still
|
||||||
|
// decrease for ALL scheduled doses whose time has passed.
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "TestMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-10T09:00:00",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// System time is March 15 12:00, start is 09:00 → 6 occurrences (March 10-15)
|
||||||
|
const march10 = new Date("2024-03-10T00:00:00").getTime();
|
||||||
|
const march11 = new Date("2024-03-11T00:00:00").getTime();
|
||||||
|
|
||||||
|
// User only marked 2 out of 6 past doses as taken
|
||||||
|
const takenDoses = new Set([`1-0-${march10}`, `1-0-${march11}`]);
|
||||||
|
|
||||||
|
const resultWithTracking = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
||||||
|
const resultWithoutTracking = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||||
|
|
||||||
|
// Both should have the same medsLeft — past tracking data doesn't reduce extra
|
||||||
|
expect(resultWithTracking.all[0].medsLeft).toBe(resultWithoutTracking.all[0].medsLeft);
|
||||||
|
// 30 pills - 6 consumed = 24
|
||||||
|
expect(resultWithTracking.all[0].medsLeft).toBe(24);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("automatic mode counts early-taken future doses", () => {
|
||||||
|
// If a user marks a dose as taken BEFORE the scheduled time,
|
||||||
|
// it should count as consumed immediately (early intake).
|
||||||
|
// System time is March 15 12:00, intake at 21:00 → today's dose not yet auto-consumed
|
||||||
|
vi.setSystemTime(new Date("2024-03-15T12:00:00Z"));
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "TestMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-10T21:00:00", // 21:00 = after current time 12:00
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// 5 occurrences auto-consumed: March 10-14 (all at 21:00, which is past)
|
||||||
|
// March 15 at 21:00 hasn't passed yet (it's only 12:00)
|
||||||
|
const resultNoTracking = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||||
|
expect(resultNoTracking.all[0].medsLeft).toBe(25); // 30 - 5 = 25
|
||||||
|
|
||||||
|
// User marks today's (March 15) dose as taken early at 12:00
|
||||||
|
const march15 = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
const takenDoses = new Set([`1-0-${march15}`]);
|
||||||
|
|
||||||
|
const resultEarlyTaken = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
||||||
|
// 5 auto + 1 early = 6 consumed → 30 - 6 = 24
|
||||||
|
expect(resultEarlyTaken.all[0].medsLeft).toBe(24);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("automatic mode does not double-count after intake time passes", () => {
|
||||||
|
// After the scheduled time, the dose is auto-consumed.
|
||||||
|
// If it was also marked as taken (earlier), it should NOT be counted twice.
|
||||||
|
vi.setSystemTime(new Date("2024-03-15T22:00:00Z")); // After 21:00
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "TestMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-10T21:00:00",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// 6 occurrences auto-consumed: March 10-15 (all at 21:00, now it's 22:00)
|
||||||
|
const march15 = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
const march14 = new Date("2024-03-14T00:00:00").getTime();
|
||||||
|
// User marked March 14 and 15 as taken (both already auto-consumed by now)
|
||||||
|
const takenDoses = new Set([`1-0-${march14}`, `1-0-${march15}`]);
|
||||||
|
|
||||||
|
const resultTracked = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
||||||
|
const resultNoTracking = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||||
|
|
||||||
|
// Both should be 24 (30 - 6). No double counting!
|
||||||
|
expect(resultTracked.all[0].medsLeft).toBe(24);
|
||||||
|
expect(resultNoTracking.all[0].medsLeft).toBe(24);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("manual mode: dose taken BEFORE stock correction is excluded", () => {
|
||||||
|
// When a user corrects stock, any dose marked BEFORE the correction
|
||||||
|
// is already reflected in the corrected count and should NOT be counted.
|
||||||
|
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
||||||
|
const todayMidnight = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "DailyMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 14,
|
||||||
|
pillsPerBlister: 14,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: -85, // 196 - 85 = 111 pills
|
||||||
|
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-01-01T08:00:00",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: correctionTime.toISOString(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// User took a dose today at 10am (BEFORE the correction at 12pm)
|
||||||
|
const doseId = `1-0-${todayMidnight}`;
|
||||||
|
const takenDoses = new Set([doseId]);
|
||||||
|
const takenDoseTimestamps = new Map([[doseId, new Date("2024-03-15T10:00:00Z").getTime()]]);
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// getMedTotal = 196 - 85 = 111
|
||||||
|
// Dose was taken BEFORE correction → NOT counted
|
||||||
|
expect(result.all[0].medsLeft).toBe(111);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("manual mode: dose taken AFTER stock correction is counted", () => {
|
||||||
|
// When a user corrects stock and then takes a dose, that dose SHOULD be counted.
|
||||||
|
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
||||||
|
const todayMidnight = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "DailyMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 14,
|
||||||
|
pillsPerBlister: 14,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: -85, // 196 - 85 = 111 pills
|
||||||
|
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-01-01T08:00:00",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: correctionTime.toISOString(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// User took a dose today at 2pm (AFTER the correction at 12pm)
|
||||||
|
const doseId = `1-0-${todayMidnight}`;
|
||||||
|
const takenDoses = new Set([doseId]);
|
||||||
|
const takenDoseTimestamps = new Map([[doseId, new Date("2024-03-15T14:00:00Z").getTime()]]);
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// getMedTotal = 196 - 85 = 111
|
||||||
|
// Dose was taken AFTER correction → counted → 111 - 1 = 110
|
||||||
|
expect(result.all[0].medsLeft).toBe(110);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("manual mode: stock correction counts next-day taken doses", () => {
|
||||||
|
// After a stock correction, doses taken the next day SHOULD be counted.
|
||||||
|
const correctionTime = new Date("2024-03-14T12:00:00Z");
|
||||||
|
const march15Midnight = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "DailyMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: -7, // 30 - 7 = 23 pills
|
||||||
|
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-01T08:00:00",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: correctionTime.toISOString(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// User takes dose on March 15 at 8am (day after correction on March 14)
|
||||||
|
const doseId = `1-0-${march15Midnight}`;
|
||||||
|
const takenDoses = new Set([doseId]);
|
||||||
|
const takenDoseTimestamps = new Map([[doseId, new Date("2024-03-15T08:00:00Z").getTime()]]);
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// getMedTotal = 30 - 7 = 23
|
||||||
|
// March 15 dose should be counted (taken after correction)
|
||||||
|
expect(result.all[0].medsLeft).toBe(22);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("manual mode: no stock correction counts all taken doses", () => {
|
||||||
|
// Without any stock correction, all taken doses should be counted
|
||||||
|
const march14Midnight = new Date("2024-03-14T00:00:00").getTime();
|
||||||
|
const march15Midnight = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "DailyMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-01T08:00:00",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// User took doses on March 14 and 15
|
||||||
|
const doseId1 = `1-0-${march14Midnight}`;
|
||||||
|
const doseId2 = `1-0-${march15Midnight}`;
|
||||||
|
const takenDoses = new Set([doseId1, doseId2]);
|
||||||
|
// No stock correction → takenAt doesn't matter, but provide for completeness
|
||||||
|
const takenDoseTimestamps = new Map([
|
||||||
|
[doseId1, new Date("2024-03-14T08:00:00Z").getTime()],
|
||||||
|
[doseId2, new Date("2024-03-15T08:00:00Z").getTime()],
|
||||||
|
]);
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// Both doses should be counted: medsLeft = 30 - 2 = 28
|
||||||
|
expect(result.all[0].medsLeft).toBe(28);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("manual mode: stock correction with multiple medications", () => {
|
||||||
|
// Regression test: 3 medications (daily, daily, weekly).
|
||||||
|
// Stock correction on all 3. Daily meds have doses taken BEFORE correction.
|
||||||
|
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
||||||
|
const todayMidnight = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "DailyMed1",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 14,
|
||||||
|
pillsPerBlister: 14,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: -85, // 196 - 85 = 111
|
||||||
|
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [{ usage: 1, every: 1, start: "2024-01-01T08:00:00" }],
|
||||||
|
updatedAt: correctionTime.toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
name: "DailyMed2",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: -10, // 30 - 10 = 20
|
||||||
|
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [{ usage: 1, every: 1, start: "2024-01-01T09:00:00" }],
|
||||||
|
updatedAt: correctionTime.toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
name: "WeeklyMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 10,
|
||||||
|
looseTablets: 0,
|
||||||
|
stockAdjustment: -2, // 10 - 2 = 8
|
||||||
|
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||||
|
takenBy: [],
|
||||||
|
blisters: [{ usage: 1, every: 7, start: "2024-01-05T10:00:00" }],
|
||||||
|
updatedAt: correctionTime.toISOString(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// Daily meds have same-day doses taken BEFORE correction (at 8am, correction at 12pm)
|
||||||
|
const doseId1 = `1-0-${todayMidnight}`;
|
||||||
|
const doseId2 = `2-0-${todayMidnight}`;
|
||||||
|
const takenDoses = new Set([doseId1, doseId2]);
|
||||||
|
const takenDoseTimestamps = new Map([
|
||||||
|
[doseId1, new Date("2024-03-15T08:00:00Z").getTime()], // Before correction
|
||||||
|
[doseId2, new Date("2024-03-15T09:00:00Z").getTime()], // Before correction
|
||||||
|
]);
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(3);
|
||||||
|
const daily1 = result.all.find((c) => c.name === "DailyMed1")!;
|
||||||
|
const daily2 = result.all.find((c) => c.name === "DailyMed2")!;
|
||||||
|
const weekly = result.all.find((c) => c.name === "WeeklyMed")!;
|
||||||
|
|
||||||
|
// All three should reflect full stock (doses taken before correction → excluded)
|
||||||
|
expect(daily1.medsLeft).toBe(111);
|
||||||
|
expect(daily2.medsLeft).toBe(20);
|
||||||
|
expect(weekly.medsLeft).toBe(8);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("manual mode: person-suffix dose IDs are counted correctly", () => {
|
||||||
|
// BUG HUNT: In prod (manual mode), dose IDs have a person suffix like
|
||||||
|
// "31-0-1770505200000-Daniel". Does the manual mode code correctly parse
|
||||||
|
// and count these?
|
||||||
|
const march14 = new Date("2024-03-14T00:00:00").getTime();
|
||||||
|
const march15 = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 31,
|
||||||
|
name: "ProdMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: ["Daniel"],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-01T08:00:00",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// Dose IDs with person suffix (as prod generates them)
|
||||||
|
const doseId1 = `31-0-${march14}-Daniel`;
|
||||||
|
const doseId2 = `31-0-${march15}-Daniel`;
|
||||||
|
const takenDoses = new Set([doseId1, doseId2]);
|
||||||
|
// No stock correction → all counted
|
||||||
|
const takenDoseTimestamps = new Map([
|
||||||
|
[doseId1, new Date("2024-03-14T08:00:00Z").getTime()],
|
||||||
|
[doseId2, new Date("2024-03-15T08:00:00Z").getTime()],
|
||||||
|
]);
|
||||||
|
|
||||||
|
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||||
|
|
||||||
|
expect(result.all).toHaveLength(1);
|
||||||
|
// Both doses should be counted: medsLeft = 30 - 2 = 28
|
||||||
|
expect(result.all[0].medsLeft).toBe(28);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("manual mode: future dose taken today counts immediately", () => {
|
||||||
|
// User marks a future dose (later today) as taken.
|
||||||
|
// It should be counted in manual mode immediately.
|
||||||
|
vi.setSystemTime(new Date("2024-03-15T12:00:00Z"));
|
||||||
|
const march15 = new Date("2024-03-15T00:00:00").getTime();
|
||||||
|
|
||||||
|
const meds: Medication[] = [
|
||||||
|
{
|
||||||
|
id: 31,
|
||||||
|
name: "ProdMed",
|
||||||
|
packCount: 1,
|
||||||
|
blistersPerPack: 1,
|
||||||
|
pillsPerBlister: 30,
|
||||||
|
looseTablets: 0,
|
||||||
|
takenBy: ["Daniel"],
|
||||||
|
blisters: [
|
||||||
|
{
|
||||||
|
usage: 1,
|
||||||
|
every: 1,
|
||||||
|
start: "2024-03-01T21:00:00", // 21:00, still in future at 12:00
|
||||||
|
},
|
||||||
|
],
|
||||||
|
updatedAt: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// No doses taken → 30 pills
|
||||||
|
const resultBefore = calculateCoverage(meds, [], "en", 7, "manual", new Set());
|
||||||
|
expect(resultBefore.all[0].medsLeft).toBe(30);
|
||||||
|
|
||||||
|
// Take today's dose (future time) → 29 pills
|
||||||
|
const doseId = `31-0-${march15}-Daniel`;
|
||||||
|
const takenDoses = new Set([doseId]);
|
||||||
|
const takenDoseTimestamps = new Map([[doseId, Date.now()]]);
|
||||||
|
const resultAfter = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||||
|
expect(resultAfter.all[0].medsLeft).toBe(29);
|
||||||
|
|
||||||
|
// Undo → back to 30 pills
|
||||||
|
const resultUndo = calculateCoverage(meds, [], "en", 7, "manual", new Set());
|
||||||
|
expect(resultUndo.all[0].medsLeft).toBe(30);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getStockStatus", () => {
|
describe("getStockStatus", () => {
|
||||||
@@ -527,6 +1153,19 @@ describe("getStockStatus", () => {
|
|||||||
expect(result.level).toBe("normal");
|
expect(result.level).toBe("normal");
|
||||||
expect(result.label).toBe("status.noSchedule");
|
expect(result.label).toBe("status.noSchedule");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("returns critical when daysLeft is at or below criticalStockDays", () => {
|
||||||
|
const thresholdsWithCritical: StockThresholds = {
|
||||||
|
lowStockDays: 30,
|
||||||
|
criticalStockDays: 7,
|
||||||
|
normalStockDays: 90,
|
||||||
|
highStockDays: 180,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = getStockStatus(5, 10, thresholdsWithCritical);
|
||||||
|
expect(result.level).toBe("critical");
|
||||||
|
expect(result.className).toBe("danger");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getNextReminderForMed", () => {
|
describe("getNextReminderForMed", () => {
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ export type PlannerRow = {
|
|||||||
fullBlisters: number;
|
fullBlisters: number;
|
||||||
loosePills: number;
|
loosePills: number;
|
||||||
enough: boolean;
|
enough: boolean;
|
||||||
|
packageType?: PackageType;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type RefillEntry = {
|
export type RefillEntry = {
|
||||||
@@ -170,6 +171,7 @@ export type SharedMedication = {
|
|||||||
doseUnit?: DoseUnit | null;
|
doseUnit?: DoseUnit | null;
|
||||||
imageUrl?: string | null;
|
imageUrl?: string | null;
|
||||||
totalPills: number;
|
totalPills: number;
|
||||||
|
packageType?: PackageType;
|
||||||
packCount: number;
|
packCount: number;
|
||||||
blistersPerPack: number;
|
blistersPerPack: number;
|
||||||
looseTablets: number;
|
looseTablets: number;
|
||||||
|
|||||||
@@ -100,7 +100,8 @@ export function calculateCoverage(
|
|||||||
locale: string,
|
locale: string,
|
||||||
reminderDaysBefore: number,
|
reminderDaysBefore: number,
|
||||||
stockCalculationMode: "automatic" | "manual",
|
stockCalculationMode: "automatic" | "manual",
|
||||||
takenDoses: Set<string>
|
takenDoses: Set<string>,
|
||||||
|
takenDoseTimestamps?: Map<string, number>
|
||||||
): { low: Coverage[]; all: Coverage[] } {
|
): { low: Coverage[]; all: Coverage[] } {
|
||||||
const MS_PER_DAY = 86_400_000;
|
const MS_PER_DAY = 86_400_000;
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -116,66 +117,112 @@ export function calculateCoverage(
|
|||||||
// Also add medication-level takenBy for backward compatibility
|
// Also add medication-level takenBy for backward compatibility
|
||||||
m.takenBy?.forEach((person) => uniquePeople.add(person));
|
m.takenBy?.forEach((person) => uniquePeople.add(person));
|
||||||
const personCount = Math.max(1, uniquePeople.size || m.takenBy?.length || 1);
|
const personCount = Math.max(1, uniquePeople.size || m.takenBy?.length || 1);
|
||||||
const dailyRate = blisters.reduce((sum, s) => sum + (s.every > 0 ? s.usage / s.every : 0), 0) * personCount;
|
|
||||||
|
// Calculate daily consumption rate per intake, accounting for per-intake takenBy.
|
||||||
|
// When an intake has a per-intake takenBy (new format), it represents exactly
|
||||||
|
// one person's dose — do NOT multiply by personCount again.
|
||||||
|
// For legacy intakes (no takenBy), the intake applies to ALL people.
|
||||||
|
let dailyRate = 0;
|
||||||
|
blisters.forEach((s, idx) => {
|
||||||
|
const baseRate = s.every > 0 ? s.usage / s.every : 0;
|
||||||
|
const intake = intakes[idx];
|
||||||
|
if (intake?.takenBy) {
|
||||||
|
// Per-intake takenBy: this intake is for exactly 1 person
|
||||||
|
dailyRate += baseRate;
|
||||||
|
} else {
|
||||||
|
// Legacy: this intake applies to all people
|
||||||
|
dailyRate += baseRate * personCount;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let consumed = 0;
|
let consumed = 0;
|
||||||
const stockCorrectionCutoff = m.lastStockCorrectionAt ? new Date(m.lastStockCorrectionAt).getTime() : 0;
|
const stockCorrectionCutoff = m.lastStockCorrectionAt ? new Date(m.lastStockCorrectionAt).getTime() : 0;
|
||||||
|
|
||||||
if (stockCalculationMode === "automatic") {
|
if (stockCalculationMode === "automatic") {
|
||||||
// In automatic mode, calculate expected consumption based on time
|
// In automatic mode, stock is reduced automatically based on the schedule.
|
||||||
// but also account for manual corrections (doses marked as not taken)
|
// Every scheduled dose counts as consumed once its time has passed.
|
||||||
|
// Additionally, if a user marks a future dose as taken BEFORE the scheduled
|
||||||
|
// time (early intake), that dose is also counted as consumed immediately.
|
||||||
|
// This prevents double-counting: once the scheduled time arrives, the dose
|
||||||
|
// was already counted via the early-taken path, not again via time.
|
||||||
blisters.forEach((s, blisterIdx) => {
|
blisters.forEach((s, blisterIdx) => {
|
||||||
const blisterStart = new Date(s.start).getTime();
|
const blisterStart = new Date(s.start).getTime();
|
||||||
const period = Math.max(1, s.every) * MS_PER_DAY;
|
const period = Math.max(1, s.every) * MS_PER_DAY;
|
||||||
|
|
||||||
// After a stock correction, start counting consumption from the NEXT
|
// After a stock correction, start counting consumption from the NEXT
|
||||||
// scheduled dose, because the user's pill count already reflects all
|
// scheduled dose on this blister's grid, because the user's pill count
|
||||||
// consumption up to the correction time.
|
// already reflects all consumption up to the correction time.
|
||||||
|
// We align to the schedule grid so that e.g. correction at 15:40 with
|
||||||
|
// a daily 15:42 dose counts today's 15:42 dose (2 min later), not
|
||||||
|
// tomorrow's dose (24h later as the old code did).
|
||||||
let effectiveStart: number;
|
let effectiveStart: number;
|
||||||
if (stockCorrectionCutoff > 0 && stockCorrectionCutoff >= blisterStart) {
|
if (stockCorrectionCutoff > 0 && stockCorrectionCutoff >= blisterStart) {
|
||||||
effectiveStart = stockCorrectionCutoff + period;
|
const elapsedSinceStart = stockCorrectionCutoff - blisterStart;
|
||||||
|
const periodsElapsed = Math.floor(elapsedSinceStart / period);
|
||||||
|
effectiveStart = blisterStart + (periodsElapsed + 1) * period;
|
||||||
} else {
|
} else {
|
||||||
effectiveStart = blisterStart;
|
effectiveStart = blisterStart;
|
||||||
}
|
}
|
||||||
if (Number.isNaN(effectiveStart) || effectiveStart > now) return;
|
if (Number.isNaN(effectiveStart)) return;
|
||||||
const occurrences = Math.floor((now - effectiveStart) / period) + 1;
|
|
||||||
const intake = intakes[blisterIdx];
|
const intake = intakes[blisterIdx];
|
||||||
const intakePerson = intake?.takenBy;
|
const intakePerson = intake?.takenBy;
|
||||||
|
|
||||||
// For per-intake takenBy, only count for that person
|
// For per-intake takenBy, only count for that person
|
||||||
// For legacy (no takenBy), count for all people in medication takenBy
|
// For legacy (no takenBy), count for all people in medication takenBy
|
||||||
const peopleForThisIntake = intakePerson ? [intakePerson] : m.takenBy?.length > 0 ? m.takenBy : [null];
|
const peopleForThisIntake = intakePerson ? [intakePerson] : m.takenBy?.length > 0 ? m.takenBy : [null];
|
||||||
const expectedConsumed = occurrences * s.usage * peopleForThisIntake.length;
|
|
||||||
|
|
||||||
// Count how many doses were actually marked as taken for this blister
|
// Time-based: count doses where the scheduled time has already passed
|
||||||
let actualConsumed = 0;
|
let timeBasedConsumed = 0;
|
||||||
|
let lastAutoConsumedDateMs = 0;
|
||||||
|
|
||||||
// Generate all expected dose IDs for this blister up to now
|
if (effectiveStart <= now) {
|
||||||
for (let i = 0; i < occurrences; i++) {
|
const occurrences = Math.floor((now - effectiveStart) / period) + 1;
|
||||||
const doseDate = new Date(effectiveStart + i * period);
|
timeBasedConsumed = occurrences * s.usage * peopleForThisIntake.length;
|
||||||
const dateOnlyMs = new Date(doseDate.getFullYear(), doseDate.getMonth(), doseDate.getDate()).getTime();
|
|
||||||
const baseDoseId = `${m.id}-${blisterIdx}-${dateOnlyMs}`;
|
|
||||||
|
|
||||||
// Check if each person has taken this dose
|
// Date-only timestamp of the last auto-consumed dose
|
||||||
for (const person of peopleForThisIntake) {
|
const lastDoseTime = new Date(effectiveStart + (occurrences - 1) * period);
|
||||||
const doseId = person ? `${baseDoseId}-${person}` : baseDoseId;
|
lastAutoConsumedDateMs = new Date(
|
||||||
if (takenDoses.has(doseId)) {
|
lastDoseTime.getFullYear(),
|
||||||
actualConsumed += s.usage;
|
lastDoseTime.getMonth(),
|
||||||
|
lastDoseTime.getDate()
|
||||||
|
).getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Early intakes: count future doses already marked as taken.
|
||||||
|
// The cutoff is the later of: last auto-consumed date or stock correction date.
|
||||||
|
// This prevents double-counting (time-based + early-taken) and respects corrections.
|
||||||
|
const stockCorrectionDateOnly =
|
||||||
|
stockCorrectionCutoff > 0
|
||||||
|
? new Date(
|
||||||
|
new Date(stockCorrectionCutoff).getFullYear(),
|
||||||
|
new Date(stockCorrectionCutoff).getMonth(),
|
||||||
|
new Date(stockCorrectionCutoff).getDate()
|
||||||
|
).getTime()
|
||||||
|
: 0;
|
||||||
|
const earlyCutoff = Math.max(lastAutoConsumedDateMs, stockCorrectionDateOnly);
|
||||||
|
|
||||||
|
let earlyTakenConsumed = 0;
|
||||||
|
for (const doseId of takenDoses) {
|
||||||
|
const parts = doseId.split("-");
|
||||||
|
if (parts.length >= 3) {
|
||||||
|
const medId = parseInt(parts[0], 10);
|
||||||
|
const bIdx = parseInt(parts[1], 10);
|
||||||
|
const timestamp = parseInt(parts[2], 10);
|
||||||
|
if (medId === m.id && bIdx === blisterIdx && timestamp > earlyCutoff) {
|
||||||
|
earlyTakenConsumed += s.usage;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we have tracking data (any doses marked), use actual consumed
|
consumed += timeBasedConsumed + earlyTakenConsumed;
|
||||||
// Otherwise fall back to expected (for backwards compatibility)
|
|
||||||
const hasTrackingData = Array.from(takenDoses).some((id) => {
|
|
||||||
const parts = id.split("-");
|
|
||||||
return parts.length >= 3 && parseInt(parts[0], 10) === m.id && parseInt(parts[1], 10) === blisterIdx;
|
|
||||||
});
|
|
||||||
|
|
||||||
consumed += hasTrackingData ? actualConsumed : expectedConsumed;
|
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// In manual mode, only count doses that are explicitly marked as taken
|
// In manual mode, only count doses that are explicitly marked as taken.
|
||||||
|
// For stock correction filtering, we use the actual time the dose was marked
|
||||||
|
// as taken (takenAt), not the scheduled date. This correctly handles same-day
|
||||||
|
// scenarios: if a user corrects stock at 3pm, then takes a dose at 4pm,
|
||||||
|
// the dose counts because takenAt (4pm) > correctionTime (3pm).
|
||||||
takenDoses.forEach((doseId) => {
|
takenDoses.forEach((doseId) => {
|
||||||
const parts = doseId.split("-");
|
const parts = doseId.split("-");
|
||||||
if (parts.length >= 3) {
|
if (parts.length >= 3) {
|
||||||
@@ -190,19 +237,17 @@ export function calculateCoverage(
|
|||||||
blisterStartDate.getMonth(),
|
blisterStartDate.getMonth(),
|
||||||
blisterStartDate.getDate()
|
blisterStartDate.getDate()
|
||||||
).getTime();
|
).getTime();
|
||||||
// Convert stock correction cutoff to date-only as well
|
|
||||||
const stockCorrectionDateOnly =
|
// Use actual takenAt timestamp for stock correction comparison.
|
||||||
stockCorrectionCutoff > 0
|
// A dose counts only if it was MARKED after the stock correction,
|
||||||
? new Date(
|
// regardless of what day it was scheduled for.
|
||||||
new Date(stockCorrectionCutoff).getFullYear(),
|
const takenAt = takenDoseTimestamps?.get(doseId) ?? 0;
|
||||||
new Date(stockCorrectionCutoff).getMonth(),
|
const afterCorrectionOrNoCorrectionMs = stockCorrectionCutoff === 0 || takenAt > stockCorrectionCutoff;
|
||||||
new Date(stockCorrectionCutoff).getDate()
|
|
||||||
).getTime()
|
|
||||||
: 0;
|
|
||||||
if (
|
if (
|
||||||
!Number.isNaN(blisterStartDateOnly) &&
|
!Number.isNaN(blisterStartDateOnly) &&
|
||||||
doseTimestamp >= blisterStartDateOnly &&
|
doseTimestamp >= blisterStartDateOnly &&
|
||||||
doseTimestamp >= stockCorrectionDateOnly
|
afterCorrectionOrNoCorrectionMs
|
||||||
) {
|
) {
|
||||||
consumed += blisters[blisterIdx].usage;
|
consumed += blisters[blisterIdx].usage;
|
||||||
}
|
}
|
||||||
|
|||||||
+86
-55
@@ -1,6 +1,6 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# MedAssist Release Script
|
# MedAssist Release Script (non-interactive)
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Usage:
|
# Usage:
|
||||||
# ./scripts/release.sh patch # 1.0.0 -> 1.0.1 (bugfixes)
|
# ./scripts/release.sh patch # 1.0.0 -> 1.0.1 (bugfixes)
|
||||||
@@ -8,8 +8,9 @@
|
|||||||
# ./scripts/release.sh major # 1.0.0 -> 2.0.0 (breaking changes)
|
# ./scripts/release.sh major # 1.0.0 -> 2.0.0 (breaking changes)
|
||||||
# ./scripts/release.sh 1.2.3 # explicit version
|
# ./scripts/release.sh 1.2.3 # explicit version
|
||||||
#
|
#
|
||||||
# This script creates a PR for the version bump (required due to branch protection),
|
# Fully non-interactive: no y/N prompts. Designed to be called by AI agents
|
||||||
# waits for CI, merges it, and then creates a signed tag for the release.
|
# or CI systems. Creates a PR for the version bump (required due to branch
|
||||||
|
# protection), waits for CI with retry logic, merges, and creates a signed tag.
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
@@ -21,45 +22,98 @@ YELLOW='\033[1;33m'
|
|||||||
BLUE='\033[0;34m'
|
BLUE='\033[0;34m'
|
||||||
NC='\033[0m' # No Color
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
# GitHub repo
|
# Configuration
|
||||||
GITHUB_REPO="DanielVolz/medassist-ng"
|
GITHUB_REPO="DanielVolz/medassist-ng"
|
||||||
|
CI_POLL_INTERVAL=15 # seconds between CI status polls
|
||||||
|
CI_INITIAL_DELAY=20 # seconds to wait before first CI check
|
||||||
|
CI_MAX_WAIT=600 # maximum seconds to wait for CI (10 minutes)
|
||||||
|
|
||||||
# Get script directory and project root
|
# Get script directory and project root
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||||
cd "$PROJECT_ROOT"
|
cd "$PROJECT_ROOT"
|
||||||
|
|
||||||
# Check for gh CLI
|
# Detect git remote name (prefer 'origin', fall back to 'github')
|
||||||
|
detect_remote() {
|
||||||
|
if git remote | grep -q '^origin$'; then
|
||||||
|
echo "origin"
|
||||||
|
elif git remote | grep -q '^github$'; then
|
||||||
|
echo "github"
|
||||||
|
else
|
||||||
|
echo -e "${RED}Error: No 'origin' or 'github' remote found.${NC}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
GIT_REMOTE=$(detect_remote)
|
||||||
|
|
||||||
|
# Wait for CI checks on a PR with retry logic
|
||||||
|
# GitHub Actions can take 10-30 seconds before checks are reported.
|
||||||
|
# This function polls until checks appear and then watches them.
|
||||||
|
wait_for_ci() {
|
||||||
|
local pr_number="$1"
|
||||||
|
local elapsed=0
|
||||||
|
|
||||||
|
echo -e "${BLUE}Waiting ${CI_INITIAL_DELAY}s for CI checks to be registered...${NC}"
|
||||||
|
sleep "${CI_INITIAL_DELAY}"
|
||||||
|
elapsed=$CI_INITIAL_DELAY
|
||||||
|
|
||||||
|
while [[ $elapsed -lt $CI_MAX_WAIT ]]; do
|
||||||
|
# Check if any checks have been reported
|
||||||
|
local check_output
|
||||||
|
check_output=$(gh pr checks "${pr_number}" --repo "${GITHUB_REPO}" 2>&1) || true
|
||||||
|
|
||||||
|
if echo "$check_output" | grep -q "no checks reported"; then
|
||||||
|
echo -e "${YELLOW}No checks reported yet (${elapsed}s elapsed). Retrying in ${CI_POLL_INTERVAL}s...${NC}"
|
||||||
|
sleep "${CI_POLL_INTERVAL}"
|
||||||
|
elapsed=$((elapsed + CI_POLL_INTERVAL))
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Checks are registered — use --watch to wait for completion
|
||||||
|
echo -e "${BLUE}CI checks registered. Watching for completion...${NC}"
|
||||||
|
if gh pr checks "${pr_number}" --repo "${GITHUB_REPO}" --watch; then
|
||||||
|
echo -e "${GREEN}CI checks passed!${NC}"
|
||||||
|
return 0
|
||||||
|
else
|
||||||
|
echo -e "${RED}CI checks failed!${NC}"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo -e "${RED}Timed out waiting for CI checks after ${CI_MAX_WAIT}s.${NC}"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# ─── Preflight checks ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
if ! command -v gh &> /dev/null; then
|
if ! command -v gh &> /dev/null; then
|
||||||
echo -e "${RED}Error: GitHub CLI (gh) is required but not installed.${NC}"
|
echo -e "${RED}Error: GitHub CLI (gh) is required but not installed.${NC}"
|
||||||
echo "Install it with: brew install gh"
|
echo "Install it with: brew install gh"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check gh authentication
|
|
||||||
if ! gh auth status &> /dev/null; then
|
if ! gh auth status &> /dev/null; then
|
||||||
echo -e "${RED}Error: Not authenticated with GitHub CLI.${NC}"
|
echo -e "${RED}Error: Not authenticated with GitHub CLI.${NC}"
|
||||||
echo "Run: gh auth login"
|
echo "Run: gh auth login"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check for uncommitted changes
|
|
||||||
if [[ -n $(git status --porcelain) ]]; then
|
if [[ -n $(git status --porcelain) ]]; then
|
||||||
echo -e "${RED}Error: You have uncommitted changes. Commit or stash them first.${NC}"
|
echo -e "${RED}Error: You have uncommitted changes. Commit or stash them first.${NC}"
|
||||||
git status --short
|
git status --short
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Make sure we're on main and up to date
|
# ─── Determine version ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
echo -e "${BLUE}Updating main branch...${NC}"
|
echo -e "${BLUE}Updating main branch...${NC}"
|
||||||
git checkout main
|
git checkout main
|
||||||
git pull origin main 2>/dev/null || git pull github main 2>/dev/null || true
|
git pull "${GIT_REMOTE}" main
|
||||||
|
|
||||||
# Get current version from backend/package.json
|
|
||||||
CURRENT_VERSION=$(grep '"version"' backend/package.json | sed 's/.*"version": "\(.*\)".*/\1/')
|
CURRENT_VERSION=$(grep '"version"' backend/package.json | sed 's/.*"version": "\(.*\)".*/\1/')
|
||||||
echo -e "${BLUE}Current version: ${YELLOW}v${CURRENT_VERSION}${NC}"
|
echo -e "${BLUE}Current version: ${YELLOW}v${CURRENT_VERSION}${NC}"
|
||||||
|
|
||||||
# Calculate new version
|
|
||||||
if [[ -z "$1" ]]; then
|
if [[ -z "$1" ]]; then
|
||||||
echo -e "${RED}Usage: $0 <patch|minor|major|x.y.z>${NC}"
|
echo -e "${RED}Usage: $0 <patch|minor|major|x.y.z>${NC}"
|
||||||
exit 1
|
exit 1
|
||||||
@@ -79,7 +133,6 @@ case "$1" in
|
|||||||
NEW_VERSION="$((major + 1)).0.0"
|
NEW_VERSION="$((major + 1)).0.0"
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
# Assume explicit version (validate format)
|
|
||||||
if [[ ! "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
if [[ ! "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
echo -e "${RED}Invalid version format. Use: x.y.z${NC}"
|
echo -e "${RED}Invalid version format. Use: x.y.z${NC}"
|
||||||
exit 1
|
exit 1
|
||||||
@@ -88,45 +141,31 @@ case "$1" in
|
|||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
echo -e "${GREEN}New version: ${YELLOW}v${NEW_VERSION}${NC}"
|
echo -e "${GREEN}Releasing: ${YELLOW}v${CURRENT_VERSION} → v${NEW_VERSION}${NC}"
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Confirm
|
# ─── Create release branch and PR ────────────────────────────────────────────
|
||||||
read -p "Release v${NEW_VERSION}? (y/N) " -n 1 -r
|
|
||||||
echo ""
|
|
||||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
|
||||||
echo "Aborted."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Branch name for the release
|
|
||||||
RELEASE_BRANCH="chore/release-${NEW_VERSION}"
|
RELEASE_BRANCH="chore/release-${NEW_VERSION}"
|
||||||
|
|
||||||
# Check if branch already exists
|
|
||||||
if git show-ref --verify --quiet "refs/heads/${RELEASE_BRANCH}"; then
|
if git show-ref --verify --quiet "refs/heads/${RELEASE_BRANCH}"; then
|
||||||
echo -e "${YELLOW}Branch ${RELEASE_BRANCH} already exists locally. Deleting...${NC}"
|
echo -e "${YELLOW}Branch ${RELEASE_BRANCH} already exists locally. Deleting...${NC}"
|
||||||
git branch -D "${RELEASE_BRANCH}"
|
git branch -D "${RELEASE_BRANCH}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Create release branch
|
|
||||||
echo -e "${BLUE}Creating release branch...${NC}"
|
echo -e "${BLUE}Creating release branch...${NC}"
|
||||||
git checkout -b "${RELEASE_BRANCH}"
|
git checkout -b "${RELEASE_BRANCH}"
|
||||||
|
|
||||||
# Update version in package.json files
|
|
||||||
echo -e "${BLUE}Updating package.json files...${NC}"
|
echo -e "${BLUE}Updating package.json files...${NC}"
|
||||||
sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" backend/package.json
|
sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" backend/package.json
|
||||||
sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" frontend/package.json 2>/dev/null || true
|
sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" frontend/package.json 2>/dev/null || true
|
||||||
|
|
||||||
# Commit version bump
|
|
||||||
echo -e "${BLUE}Committing version bump...${NC}"
|
echo -e "${BLUE}Committing version bump...${NC}"
|
||||||
git add backend/package.json frontend/package.json 2>/dev/null || git add backend/package.json
|
git add backend/package.json frontend/package.json 2>/dev/null || git add backend/package.json
|
||||||
git commit -m "chore: release v${NEW_VERSION}"
|
git commit -m "chore: release v${NEW_VERSION}"
|
||||||
|
|
||||||
# Push branch to GitHub
|
echo -e "${BLUE}Pushing release branch...${NC}"
|
||||||
echo -e "${BLUE}Pushing release branch to GitHub...${NC}"
|
git push -u "${GIT_REMOTE}" "${RELEASE_BRANCH}"
|
||||||
git push -u origin "${RELEASE_BRANCH}" 2>/dev/null || git push -u github "${RELEASE_BRANCH}"
|
|
||||||
|
|
||||||
# Create PR
|
|
||||||
echo -e "${BLUE}Creating Pull Request...${NC}"
|
echo -e "${BLUE}Creating Pull Request...${NC}"
|
||||||
PR_URL=$(gh pr create \
|
PR_URL=$(gh pr create \
|
||||||
--repo "${GITHUB_REPO}" \
|
--repo "${GITHUB_REPO}" \
|
||||||
@@ -136,57 +175,49 @@ PR_URL=$(gh pr create \
|
|||||||
|
|
||||||
Automated version bump for release v${NEW_VERSION}.
|
Automated version bump for release v${NEW_VERSION}.
|
||||||
|
|
||||||
This PR was created by the release script." \
|
This PR was created by the release script.")
|
||||||
2>&1)
|
|
||||||
|
|
||||||
echo -e "${GREEN}PR created: ${YELLOW}${PR_URL}${NC}"
|
echo -e "${GREEN}PR created: ${YELLOW}${PR_URL}${NC}"
|
||||||
|
|
||||||
# Extract PR number
|
|
||||||
PR_NUMBER=$(echo "$PR_URL" | grep -oE '[0-9]+$')
|
PR_NUMBER=$(echo "$PR_URL" | grep -oE '[0-9]+$')
|
||||||
|
|
||||||
# Wait for CI checks
|
# ─── Wait for CI and merge ────────────────────────────────────────────────────
|
||||||
echo -e "${BLUE}Waiting for CI checks to complete...${NC}"
|
|
||||||
if ! gh pr checks "${PR_NUMBER}" --repo "${GITHUB_REPO}" --watch; then
|
if ! wait_for_ci "${PR_NUMBER}"; then
|
||||||
echo -e "${RED}CI checks failed! Please fix the issues and try again.${NC}"
|
echo -e "${RED}CI checks failed! Please fix the issues and try again.${NC}"
|
||||||
|
echo -e "${RED}Release branch '${RELEASE_BRANCH}' and PR #${PR_NUMBER} are still open.${NC}"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo -e "${GREEN}CI checks passed!${NC}"
|
echo -e "${BLUE}Merging PR #${PR_NUMBER}...${NC}"
|
||||||
|
|
||||||
# Merge PR
|
|
||||||
echo -e "${BLUE}Merging PR...${NC}"
|
|
||||||
gh pr merge "${PR_NUMBER}" --repo "${GITHUB_REPO}" --squash --delete-branch
|
gh pr merge "${PR_NUMBER}" --repo "${GITHUB_REPO}" --squash --delete-branch
|
||||||
|
|
||||||
# Switch back to main and pull
|
echo -e "${BLUE}Updating main branch...${NC}"
|
||||||
echo -e "${BLUE}Updating main branch with merged changes...${NC}"
|
|
||||||
git checkout main
|
git checkout main
|
||||||
git pull origin main 2>/dev/null || git pull github main 2>/dev/null || true
|
git pull "${GIT_REMOTE}" main
|
||||||
|
|
||||||
|
# ─── Create and push signed tag ──────────────────────────────────────────────
|
||||||
|
|
||||||
# Check if tag exists and delete it
|
|
||||||
if git rev-parse "v${NEW_VERSION}" >/dev/null 2>&1; then
|
if git rev-parse "v${NEW_VERSION}" >/dev/null 2>&1; then
|
||||||
echo -e "${YELLOW}Tag v${NEW_VERSION} already exists locally. Deleting...${NC}"
|
echo -e "${YELLOW}Tag v${NEW_VERSION} already exists locally. Deleting...${NC}"
|
||||||
git tag -d "v${NEW_VERSION}"
|
git tag -d "v${NEW_VERSION}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check if remote tag exists
|
if git ls-remote --tags "${GIT_REMOTE}" "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}"; then
|
||||||
if git ls-remote --tags origin "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}" || \
|
|
||||||
git ls-remote --tags github "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}"; then
|
|
||||||
echo -e "${YELLOW}Tag v${NEW_VERSION} exists on remote. Deleting...${NC}"
|
echo -e "${YELLOW}Tag v${NEW_VERSION} exists on remote. Deleting...${NC}"
|
||||||
git push origin ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
|
git push "${GIT_REMOTE}" ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
|
||||||
git push github ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Create signed tag
|
|
||||||
echo -e "${BLUE}Creating signed tag v${NEW_VERSION}...${NC}"
|
echo -e "${BLUE}Creating signed tag v${NEW_VERSION}...${NC}"
|
||||||
git tag -s "v${NEW_VERSION}" -m "Release v${NEW_VERSION}"
|
git tag -s "v${NEW_VERSION}" -m "Release v${NEW_VERSION}"
|
||||||
|
|
||||||
# Push tag
|
echo -e "${BLUE}Pushing tag...${NC}"
|
||||||
echo -e "${BLUE}Pushing tag to GitHub...${NC}"
|
git push "${GIT_REMOTE}" "v${NEW_VERSION}"
|
||||||
git push origin "v${NEW_VERSION}" 2>/dev/null || git push github "v${NEW_VERSION}"
|
|
||||||
|
# ─── Done ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
|
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
|
||||||
echo -e "${GREEN}✓ Released v${NEW_VERSION}${NC}"
|
echo -e "${GREEN} ✓ Released v${NEW_VERSION}${NC}"
|
||||||
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
|
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
|
||||||
echo ""
|
echo ""
|
||||||
echo -e "${BLUE}GitHub Actions will now build and publish Docker images.${NC}"
|
echo -e "${BLUE}GitHub Actions will now build and publish Docker images.${NC}"
|
||||||
|
|||||||
Reference in New Issue
Block a user