Compare commits

...

17 Commits

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

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

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

Docker image builds now start immediately after merge.
2026-02-08 15:05:33 +01:00
Daniel Volz 6edf2fa341 docs: add rule to keep README.md up to date after code changes (#131) 2026-02-08 14:45:30 +01:00
Daniel Volz 9e3d548536 chore: make release script non-interactive with CI retry logic (#130)
- Remove y/N confirmation prompt for automation
- Add wait_for_ci() with retry logic (polls until checks appear)
- Auto-detect git remote (origin or github)
- Remove unused /etc/nginx/conf.d tmpfs from compose
- Update release-manager agent docs to match
2026-02-08 14:13:11 +01:00
Daniel Volz e55e415a50 chore: release v1.8.6 (#129) 2026-02-08 14:06:03 +01:00
Daniel Volz 5253d14af7 fix: make frontend image self-contained for read-only filesystems (#128)
Revert Dockerfile to use /tmp redirect for envsubst output, so the image
works regardless of docker-compose.yml tmpfs configuration. Removes the
uid=101,gid=101 requirement from compose that was a breaking change.
2026-02-08 14:03:53 +01:00
github-actions[bot] 4f75d78a2b chore: update test count badges [skip ci] 2026-02-08 12:54:19 +00:00
Daniel Volz 8f9b65147b fix: use PAT for badge workflow to bypass branch protection (#127) 2026-02-08 13:53:19 +01:00
Daniel Volz 571ab00918 chore: release v1.8.5 (#126) 2026-02-08 13:35:52 +01:00
Daniel Volz 27f5478dad fix: clean up nginx read-only filesystem approach (#125)
Remove Dockerfile /tmp workaround hacks (NGINX_ENVSUBST_OUTPUT_DIR and sed).
Use tmpfs with uid=101,gid=101 in docker-compose.yml instead, so the
nginx user can write to /etc/nginx/conf.d directly under read_only: true.
2026-02-08 13:33:40 +01:00
43 changed files with 2006 additions and 524 deletions
+62 -23
View File
@@ -129,13 +129,26 @@ Apply these rules strictly:
## 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
./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)
@@ -166,8 +179,8 @@ The version number is displayed in the **About modal** (Settings → About) as a
### After Tagging
- The `docker-build.yml` workflow automatically builds and pushes Docker images to GHCR.
- The `version-bump.yml` workflow automatically updates `package.json` versions if needed.
- The `docker-build.yml` workflow automatically builds and pushes Docker images to GHCR with both versioned tags (`1.8.7`, `1.8`) and `latest`.
- The `update-test-badges.yml` workflow runs automatically after a successful Docker build to update test count badges in the README.
- Track progress: `https://github.com/DanielVolz/medassist-ng/actions`
---
@@ -199,19 +212,20 @@ Read the actual code changes (not just commit messages) to understand what was a
- Use `### Heading` for sections
- Use **bold** for feature names in bullet points
- Keep descriptions on the same line as the feature name
- Minimal emoji usage (sparingly, not on every line)
- **No emojis** — do not use emoji in headings or bullet points
- **Include commit references** — each bullet point must end with the PR number (e.g., `(#136)`) or short commit hash (e.g., `(ab12cd3)`) linking to the commit/PR. Use PR numbers when available.
- Always end with "Where to Find It" section
- End with: `**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/vPREV...vNEW`
**ONLY include user-relevant changes.** DO NOT include:
- Technical implementation details (new columns, endpoints, database changes)
- Number of tests added
- Internal API changes (unless breaking)
- ❌ Excessive emoji on every bullet point
- .gitignore changes or other developer-only file changes
- AI/Copilot instruction updates
- CI/CD workflow changes (unless affecting users)
- Code refactoring without user-visible changes
- Technical implementation details (new columns, endpoints, database changes)
- Number of tests added
- Internal API changes (unless breaking)
- Emojis anywhere in the release notes
- .gitignore changes or other developer-only file changes
- AI/Copilot instruction updates
- CI/CD workflow changes (unless affecting users)
- Code refactoring without user-visible changes
### Example: Good Release Notes
@@ -222,14 +236,14 @@ This release introduces a medication refill tracking feature and improves the mo
### New Features
- **Medication Refill**: Track when you refill your medications with a single click. Add full packs or individual pills and view complete refill history.
- **Automatic Stock Updates**: Stock levels are automatically recalculated after each refill.
- **Refill History**: Each medication shows a complete history of all refills with timestamps.
- **Medication Refill**: Track when you refill your medications with a single click. Add full packs or individual pills and view complete refill history. (#120)
- **Automatic Stock Updates**: Stock levels are automatically recalculated after each refill. (#120)
- **Refill History**: Each medication shows a complete history of all refills with timestamps. (#122)
### Mobile Improvements
### Improvements
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability.
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices.
- **Centered Tooltips**: Info tooltips now display centered on screen for better readability. (#125)
- **Touch-friendly**: Tooltips close automatically when scrolling on touch devices. (#125)
### Where to Find It
@@ -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
```
@@ -295,11 +333,12 @@ Ready for release?
5. Check current version (git tag + package.json)
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)
8. Write release notes (mandatory for minor/major)
9. Publish GitHub release
9. Write release notes (mandatory for minor/major)
10. Publish GitHub release
Docker images built automatically via CI
```
+13 -5
View File
@@ -4,12 +4,13 @@
- **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English.
- **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action.
- **NEVER create PRs without explicit permission**: Do NOT create Pull Requests, push branches, or merge code unless the user explicitly asks for it. Always present changes and wait for the user to confirm before any git operations that affect the remote repository.
- **NEVER create PRs, push, or merge**: Only the **release-manager agent** (`@release-manager`) is allowed to create Pull Requests, push branches to the remote, or merge code. Regular agents and Copilot MUST NOT perform any git operations that affect the remote repository (no `git push`, no `gh pr create`, no `gh pr merge`). Present your local changes and tell the user to invoke `@release-manager` when ready to ship.
- **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository.
- **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done.
- **Remove old code when re-implementing**: When fixing a bug or re-implementing a feature that didn't work, ALWAYS remove the old/broken code completely. Never leave dead code, unused functions, or obsolete implementations in the codebase.
- **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests. When modifying existing features, update or add tests accordingly. If old tests become obsolete due to code changes, remove or update them.
- **Fix bugs, don't test around them**: If you discover incorrect behavior in the code while writing tests, ALWAYS fix the buggy code first, then write tests that verify the correct behavior. NEVER write tests that mimic or assert broken behavior. The user's time is finite and irreplaceable — every bug left unfixed wastes it.
- **Keep README.md up to date**: After implementing code changes, check whether the `README.md` needs to be updated (e.g., new features, changed ENV variables, new commands, changed architecture, new endpoints, updated screenshots). If changes are relevant to the README, **ask the user for confirmation** before updating it. Do NOT silently update the README — always present the proposed README changes and wait for approval. Examples of README-relevant changes: new ENV variables, new API endpoints, new UI features, changed setup/install steps, new dependencies, changed Docker configuration.
## Architecture Overview
@@ -137,11 +138,16 @@ Push to main / Tag created
┌─────────────────────────────────────┐
│ docker-build.yml │
─ backend-test (parallel)
│ ├─ frontend-build (parallel) │
│ └─ build-and-push (after tests) │
─ build-and-push
│ ├─ Build Docker images │
│ └─ Push to GHCR │
│ (Tag builds also set "latest") │
└─────────────────────────────────────┘
↓ After successful build
┌─────────────────────────────────────┐
│ update-test-badges.yml │
│ (workflow_run after docker-build) │
│ └─ Run tests, update badge counts │
└─────────────────────────────────────┘
```
@@ -178,7 +184,9 @@ gh pr merge --squash --delete-branch
| File | Trigger | Purpose |
|------|---------|--------|
| `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures |
| `.github/workflows/docker-build.yml` | Push to main, Tags | Tests + Build and push Docker images |
| `.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
+8 -43
View File
@@ -25,50 +25,15 @@ env:
jobs:
# =============================================================================
# Run Tests First
# =============================================================================
backend-test:
name: Backend Tests
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: backend/package-lock.json
- run: npm ci
- run: npx tsc --noEmit
- run: npm run test:run
frontend-build:
name: Frontend Build
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- run: npm ci
- run: npm run build
# =============================================================================
# Build and Push Docker Images (only after tests pass)
# Build and Push Docker Images
# Tests are NOT run here — branch protection on main requires all PR checks
# (backend-test + frontend-build from test.yml) to pass before merge.
# Tags are created from main, so code is already tested.
#
# Tag builds (v*) always set "latest" in addition to the semver tags.
# This ensures "latest" always points to the most recent release.
# =============================================================================
build-and-push:
needs: [backend-test, frontend-build]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -106,7 +71,7 @@ jobs:
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
- name: Build and push
uses: docker/build-push-action@v5
-78
View File
@@ -1,78 +0,0 @@
name: Create Release
on:
push:
tags: ['v*']
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get version info
id: version
run: |
CURRENT_TAG=${GITHUB_REF#refs/tags/}
VERSION=${CURRENT_TAG#v}
echo "tag=$CURRENT_TAG" >> $GITHUB_OUTPUT
echo "version=$VERSION" >> $GITHUB_OUTPUT
# Get previous tag
PREV_TAG=$(git tag --sort=-v:refname | grep -A1 "^${CURRENT_TAG}$" | tail -1)
if [ "$PREV_TAG" = "$CURRENT_TAG" ]; then
PREV_TAG=""
fi
echo "previous_tag=$PREV_TAG" >> $GITHUB_OUTPUT
- name: Generate release template
run: |
cat > release_notes.md << 'EOF'
## What's New
<!--
Write 1-2 sentences describing the main changes in this release.
Example: This release introduces a medication refill tracking feature and improves the mobile user experience.
-->
### New Features
<!-- List new features with **bold** names and descriptions -->
- **Feature Name**: Description of the feature
### Improvements
<!-- List improvements and fixes -->
- **Improvement**: Description
### Where to Find It
<!-- Tell users where they can access new features -->
---
## Docker Images
```bash
docker pull ghcr.io/danielvolz/medassist-ng-backend:${{ steps.version.outputs.version }}
docker pull ghcr.io/danielvolz/medassist-ng-frontend:${{ steps.version.outputs.version }}
```
**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/${{ steps.version.outputs.previous_tag }}...${{ steps.version.outputs.tag }}
EOF
- name: Create Draft Release
uses: softprops/action-gh-release@v1
with:
body_path: release_notes.md
draft: true
generate_release_notes: false
name: "Release ${{ steps.version.outputs.tag }}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+6 -7
View File
@@ -2,13 +2,10 @@ name: Update Test Badges
on:
workflow_dispatch:
push:
workflow_run:
workflows: ["Build and Push Docker Images"]
types: [completed]
branches: [main]
paths:
- 'backend/src/**'
- 'frontend/src/**'
- 'backend/package.json'
- 'frontend/package.json'
permissions:
contents: write
@@ -17,12 +14,14 @@ jobs:
update-badges:
name: Update Test Count Badges
runs-on: ubuntu-latest
# Only run after successful docker builds, not failed ones
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ secrets.BADGE_TOKEN || secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
-57
View File
@@ -1,57 +0,0 @@
name: Version Bump on Release
on:
release:
types: [published]
permissions:
contents: write
jobs:
version-bump:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: main
token: ${{ secrets.GITHUB_TOKEN }}
- name: Get version from tag
id: version
run: |
# Extract version from tag (e.g., v1.6.0 -> 1.6.0)
VERSION="${GITHUB_REF_NAME#v}"
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "Extracted version: $VERSION"
- name: Update package.json versions
run: |
VERSION="${{ steps.version.outputs.version }}"
# Update backend/package.json
jq --arg v "$VERSION" '.version = $v' backend/package.json > backend/package.json.tmp
mv backend/package.json.tmp backend/package.json
# Update frontend/package.json
jq --arg v "$VERSION" '.version = $v' frontend/package.json > frontend/package.json.tmp
mv frontend/package.json.tmp frontend/package.json
echo "Updated versions to $VERSION"
cat backend/package.json | head -5
cat frontend/package.json | head -5
- name: Commit and push
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add backend/package.json frontend/package.json
# Only commit if there are changes
if git diff --staged --quiet; then
echo "No version changes needed"
else
git commit -m "chore: bump version to ${{ steps.version.outputs.version }} [skip ci]"
git push origin main
fi
+2 -2
View File
@@ -18,8 +18,8 @@
</p>
<p align="center">
<img src="https://img.shields.io/badge/Backend_Tests-454%2F454-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
<img src="https://img.shields.io/badge/Frontend_Tests-611%2F611-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
<img src="https://img.shields.io/badge/Backend_Tests-494%2F494-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
<img src="https://img.shields.io/badge/Frontend_Tests-653%2F653-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
</p>
### 🤖 AI-Generated Code
+1 -1
View File
@@ -5,6 +5,6 @@ export default defineConfig({
out: "./drizzle",
dialect: "sqlite",
dbCredentials: {
url: process.env.DATABASE_URL || "./data/medassist.db",
url: process.env.DATABASE_URL || "./data/medassist-ng.db",
},
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "medassist-ng-backend",
"version": "1.8.3",
"version": "1.8.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "medassist-ng-backend",
"version": "1.8.3",
"version": "1.8.8",
"dependencies": {
"@fastify/cookie": "^10.0.1",
"@fastify/cors": "^10.0.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "medassist-ng-backend",
"version": "1.8.4",
"version": "1.8.8",
"private": true,
"type": "module",
"scripts": {
+2 -2
View File
@@ -156,7 +156,7 @@ const translations: Record<Language, TranslationKeys> = {
push: {
stockTitle: "MedAssist-ng: 1 Medication 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",
daysLeft: "{count} days left",
pillsAt: "{count} pills at {time}",
@@ -210,7 +210,7 @@ const translations: Record<Language, TranslationKeys> = {
push: {
stockTitle: "MedAssist-ng: 1 Medikament wird knapp",
stockTitleMultiple: "MedAssist-ng: {count} Medikamente werden knapp",
intakeTitle: "💊 Einnahme-Erinnerung in {minutes} Min.",
intakeTitle: "💊 Erinnerung: Medikamenteneinnahme in {minutes} Min.",
pillsLeft: "{count} Tabletten",
daysLeft: "{count} Tage übrig",
pillsAt: "{count} Tabletten um {time}",
+3
View File
@@ -37,6 +37,7 @@ const inventorySchema = z.object({
pillsPerBlister: z.number().int().min(1).default(1),
looseTablets: z.number().int().min(0).default(0),
stockAdjustment: z.number().int().default(0), // Manual stock correction
packageType: z.enum(["blister", "bottle"]).default("blister"),
});
const medicationExportSchema = z.object({
@@ -276,6 +277,7 @@ export async function exportRoutes(app: FastifyInstance) {
pillsPerBlister: med.pillsPerBlister ?? 1,
looseTablets: med.looseTablets ?? 0,
stockAdjustment: med.stockAdjustment ?? 0,
packageType: med.packageType ?? "blister",
},
pillWeightMg: med.pillWeightMg,
doseUnit: med.doseUnit ?? "mg",
@@ -490,6 +492,7 @@ export async function exportRoutes(app: FastifyInstance) {
name: med.name,
genericName: med.genericName || null,
takenByJson,
packageType: med.inventory.packageType ?? "blister",
packCount: med.inventory.packCount,
blistersPerPack: med.inventory.blistersPerPack,
pillsPerBlister: med.inventory.pillsPerBlister,
+28 -12
View File
@@ -656,7 +656,13 @@ export async function medicationRoutes(app: FastifyInstance) {
const blistersPerPack = row.blistersPerPack ?? 1;
const looseTablets = row.looseTablets ?? 0;
const stockAdjustment = row.stockAdjustment ?? 0;
const originalTotalPills = packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
const packageType = row.packageType ?? "blister";
// For bottle type, looseTablets IS the current stock (no blister math)
const originalTotalPills =
packageType === "bottle"
? looseTablets + stockAdjustment
: packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
// Calculate consumption based on ACTUAL taken doses from dose_tracking
// This ensures Planner shows the same "current stock" as the Dashboard/Modal
@@ -735,18 +741,27 @@ export async function medicationRoutes(app: FastifyInstance) {
// Calculate AVAILABLE = stock AFTER the planned period (currentStock - usageTotal)
const availableAfterPeriod = Math.max(0, currentStock - usageTotal);
// Calculate stock breakdown for availableAfterPeriod
// 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);
let fullBlisters: number;
let loosePills: number;
const fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0;
const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0;
const loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose
if (packageType === "bottle") {
// Bottle type: no blisters, everything is loose pills
fullBlisters = 0;
loosePills = availableAfterPeriod;
} else {
// Blister type: calculate stock breakdown
// Consumption order: loose pills first, then from blisters
const totalConsumedByEnd = originalTotalPills - availableAfterPeriod;
const looseConsumedByEnd = Math.min(totalConsumedByEnd, looseTablets);
const loosePillsRemaining = Math.max(0, looseTablets - looseConsumedByEnd);
const blisterPillsConsumed = totalConsumedByEnd - looseConsumedByEnd;
const originalBlisterPills = originalTotalPills - looseTablets;
const blisterPillsRemaining = Math.max(0, originalBlisterPills - blisterPillsConsumed);
fullBlisters = pillsPerBlister > 0 ? Math.floor(blisterPillsRemaining / pillsPerBlister) : 0;
const openBlisterPills = pillsPerBlister > 0 ? blisterPillsRemaining % pillsPerBlister : 0;
loosePills = loosePillsRemaining + openBlisterPills; // Combine open blister + remaining loose
}
const enough = currentStock >= usageTotal;
return {
@@ -759,6 +774,7 @@ export async function medicationRoutes(app: FastifyInstance) {
fullBlisters,
loosePills,
enough,
packageType,
};
});
+11 -6
View File
@@ -78,9 +78,13 @@ export async function refillRoutes(app: FastifyInstance) {
})
.returning();
// Calculate pills added for response
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister;
const totalPillsAdded = packsAdded * pillsPerPack + loosePillsAdded;
// Calculate pills added for response (packageType-aware)
const isBottle = (med.packageType ?? "blister") === "bottle";
const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
const totalPillsAdded = isBottle ? loosePillsAdded : packsAdded * pillsPerPack + loosePillsAdded;
const newTotalPills = isBottle
? newLooseTablets + (med.stockAdjustment ?? 0)
: newPackCount * pillsPerPack + newLooseTablets + (med.stockAdjustment ?? 0);
return {
success: true,
@@ -94,7 +98,7 @@ export async function refillRoutes(app: FastifyInstance) {
newStock: {
packCount: newPackCount,
looseTablets: newLooseTablets,
totalPills: newPackCount * pillsPerPack + newLooseTablets,
totalPills: newTotalPills,
},
};
});
@@ -120,13 +124,14 @@ export async function refillRoutes(app: FastifyInstance) {
.where(eq(refillHistory.medicationId, medId))
.orderBy(desc(refillHistory.refillDate));
const pillsPerPack = med.blistersPerPack * med.pillsPerBlister;
const isBottle = (med.packageType ?? "blister") === "bottle";
const pillsPerPack = isBottle ? 0 : med.blistersPerPack * med.pillsPerBlister;
return refills.map((r) => ({
id: r.id,
packsAdded: r.packsAdded,
loosePillsAdded: r.loosePillsAdded,
totalPillsAdded: r.packsAdded * pillsPerPack + r.loosePillsAdded,
totalPillsAdded: isBottle ? r.loosePillsAdded : r.packsAdded * pillsPerPack + r.loosePillsAdded,
refillDate: r.refillDate,
}));
});
+4 -1
View File
@@ -114,7 +114,9 @@ export async function shareRoutes(app: FastifyInstance) {
const takenByArray = parseTakenByJson(med.takenByJson);
const totalPills =
med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
(med.packageType ?? "blister") === "bottle"
? med.looseTablets + (med.stockAdjustment ?? 0)
: med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
return {
id: med.id,
name: med.name,
@@ -123,6 +125,7 @@ export async function shareRoutes(app: FastifyInstance) {
doseUnit: med.doseUnit ?? "mg",
imageUrl: med.imageUrl,
totalPills,
packageType: med.packageType ?? "blister",
packCount: med.packCount,
blistersPerPack: med.blistersPerPack,
looseTablets: med.looseTablets,
@@ -409,10 +409,18 @@ async function checkAndSendIntakeRemindersForUser(
if (!existingEntry) {
// New dose - send first reminder
if (isIntakePast) {
// Already missed - this is first nagging reminder (count=1)
remindersToSend.push({ ...intake, currentSendCount: 1, maxReminders, isAdvanceReminder: false });
// Intake time already passed and we have no state entry — this means the scheduler
// was not aware of this intake before it happened (e.g., user just enabled reminders).
// Seed the state as already handled so repeat reminders can track from here,
// but do NOT send a notification for intakes that were missed before tracking started.
state.reminders[key] = {
firstSentAt: nowMs,
lastSentAt: nowMs,
sendCount: 0,
advanceSent: false,
};
logger.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 {
// Upcoming - this is advance reminder (no counter)
@@ -551,7 +559,10 @@ async function checkAndSendIntakeRemindersForUser(
if (hasNaggingReminder && highestSendCount > 0) {
// Nagging reminder - show counter
const counterStr = `(${highestSendCount}/${maxReminderCount})`;
title = language === "de" ? `⚠️ Medikamenten-Erinnerung ${counterStr}` : `⚠️ Medication Reminder ${counterStr}`;
title =
language === "de"
? `⚠️ Erinnerung: Medikamenteneinnahme ${counterStr}`
: `⚠️ Reminder: Medication intake ${counterStr}`;
} else {
// Advance reminder - no counter
title = t(tr.push.intakeTitle, { minutes: REMINDER_MINUTES_BEFORE });
+3 -1
View File
@@ -106,7 +106,9 @@ async function getMedicationsNeedingReminder(
for (const row of rows) {
const blisters = parseBlistersFromRow(row);
const totalPills =
row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
(row.packageType ?? "blister") === "bottle"
? row.looseTablets + (row.stockAdjustment ?? 0)
: row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
const { daysLeft, depletionDate } = calculateDepletionInfo({ count: totalPills, blisters }, language);
// Check if medication runs out within reminderDaysBefore days
+246
View File
@@ -2214,4 +2214,250 @@ describe("E2E Tests with Real Routes", () => {
expect(medsResponse.json()[0].packCount).toBe(10);
});
});
// ---------------------------------------------------------------------------
// Package Type (bottle vs blister) Tests
// ---------------------------------------------------------------------------
describe("Package type handling (bottle vs blister)", () => {
const bottleMedication = {
name: "Vitamin D Drops",
packageType: "bottle",
packCount: 0,
blistersPerPack: 1,
pillsPerBlister: 1,
looseTablets: 120,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
};
const blisterMedication = {
name: "Aspirin Blister",
packageType: "blister",
packCount: 2,
blistersPerPack: 3,
pillsPerBlister: 10,
looseTablets: 5,
blisters: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
};
it("should create and return bottle type medication", async () => {
const response = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
expect(response.statusCode).toBe(200);
const data = response.json();
expect(data.packageType).toBe("bottle");
expect(data.looseTablets).toBe(120);
});
it("should return packageType in shared schedule for bottle type", async () => {
// Create bottle medication with takenBy
await app.inject({
method: "POST",
url: "/medications",
payload: { ...bottleMedication, takenBy: ["Daniel"] },
});
// Create share token
const shareResponse = await app.inject({
method: "POST",
url: "/share",
payload: { takenBy: "Daniel", scheduleDays: 30 },
});
expect(shareResponse.statusCode).toBe(200);
const { token } = shareResponse.json();
// Get shared schedule
const scheduleResponse = await app.inject({
method: "GET",
url: `/share/${token}`,
});
expect(scheduleResponse.statusCode).toBe(200);
const data = scheduleResponse.json();
expect(data.medications).toHaveLength(1);
expect(data.medications[0].packageType).toBe("bottle");
// Bottle totalPills = looseTablets + stockAdjustment (no blister math)
expect(data.medications[0].totalPills).toBe(120);
});
it("should calculate correct totalPills for shared blister medication", async () => {
await app.inject({
method: "POST",
url: "/medications",
payload: { ...blisterMedication, takenBy: ["Daniel"] },
});
const shareResponse = await app.inject({
method: "POST",
url: "/share",
payload: { takenBy: "Daniel", scheduleDays: 30 },
});
const { token } = shareResponse.json();
const scheduleResponse = await app.inject({
method: "GET",
url: `/share/${token}`,
});
expect(scheduleResponse.statusCode).toBe(200);
const data = scheduleResponse.json();
expect(data.medications).toHaveLength(1);
expect(data.medications[0].packageType).toBe("blister");
// Blister totalPills = 2 * 3 * 10 + 5 = 65
expect(data.medications[0].totalPills).toBe(65);
});
it("should calculate correct refill totalPillsAdded for bottle type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
const medId = createResponse.json().id;
// Refill bottle: only loosePillsAdded matters, packs should add 0 pills
const refillResponse = await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 0, loosePillsAdded: 30 },
});
expect(refillResponse.statusCode).toBe(200);
const data = refillResponse.json();
expect(data.refill.totalPillsAdded).toBe(30);
// newStock.totalPills should be looseTablets only (no blister math)
expect(data.newStock.totalPills).toBe(150); // 120 + 30
});
it("should calculate correct refill totalPillsAdded for blister type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: blisterMedication,
});
const medId = createResponse.json().id;
// Refill blister: 1 pack = 3 blisters * 10 pills = 30 pills + 5 loose
const refillResponse = await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 1, loosePillsAdded: 5 },
});
expect(refillResponse.statusCode).toBe(200);
const data = refillResponse.json();
expect(data.refill.totalPillsAdded).toBe(35); // 1*30 + 5
});
it("should return correct totalPillsAdded in refill history for bottle type", async () => {
const createResponse = await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
const medId = createResponse.json().id;
// Add refill
await app.inject({
method: "POST",
url: `/medications/${medId}/refill`,
payload: { packsAdded: 0, loosePillsAdded: 25 },
});
// Get refill history
const historyResponse = await app.inject({
method: "GET",
url: `/medications/${medId}/refills`,
});
expect(historyResponse.statusCode).toBe(200);
const refills = historyResponse.json();
expect(refills).toHaveLength(1);
// For bottle type, totalPillsAdded = loosePillsAdded only
expect(refills[0].totalPillsAdded).toBe(25);
});
it("should export and import bottle type medication correctly", async () => {
// Create bottle medication
await app.inject({
method: "POST",
url: "/medications",
payload: bottleMedication,
});
// Export
const exportResponse = await app.inject({
method: "GET",
url: "/export",
});
expect(exportResponse.statusCode).toBe(200);
const exportData = exportResponse.json();
expect(exportData.medications).toHaveLength(1);
expect(exportData.medications[0].inventory.packageType).toBe("bottle");
expect(exportData.medications[0].inventory.looseTablets).toBe(120);
// Clear and re-import
await clearData(testClient);
await testClient.execute(
"INSERT INTO users (id, username, auth_provider) VALUES (999999999, '__anonymous__', 'anonymous')"
);
const importResponse = await app.inject({
method: "POST",
url: "/import",
payload: exportData,
});
expect(importResponse.statusCode).toBe(200);
expect(importResponse.json().success).toBe(true);
// Verify imported medication has correct packageType
const medsResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(medsResponse.json()).toHaveLength(1);
const med = medsResponse.json()[0];
expect(med.name).toBe("Vitamin D Drops");
expect(med.packageType).toBe("bottle");
expect(med.looseTablets).toBe(120);
});
it("should default to blister when importing without packageType", async () => {
const importData = {
version: "1.0",
exportedAt: new Date().toISOString(),
medications: [
{
_exportId: "med-1",
name: "Old Export Med",
inventory: { packCount: 2, blistersPerPack: 3, pillsPerBlister: 10, looseTablets: 0 },
schedules: [{ usage: 1, every: 1, start: "2025-01-01T08:00:00.000Z" }],
},
],
};
const importResponse = await app.inject({
method: "POST",
url: "/import",
payload: importData,
});
expect(importResponse.statusCode).toBe(200);
const medsResponse = await app.inject({
method: "GET",
url: "/medications",
});
expect(medsResponse.json()).toHaveLength(1);
expect(medsResponse.json()[0].packageType).toBe("blister");
});
});
});
-1
View File
@@ -52,7 +52,6 @@ services:
- /tmp:noexec,nosuid,size=64m
- /var/cache/nginx:noexec,nosuid,size=64m
- /var/run:noexec,nosuid,size=64m
- /etc/nginx/conf.d:noexec,nosuid,size=1m
cap_drop:
- ALL
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "medassist-ng-frontend",
"version": "1.8.3",
"version": "1.8.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "medassist-ng-frontend",
"version": "1.8.3",
"version": "1.8.8",
"dependencies": {
"i18next": "^24.2.2",
"i18next-browser-languagedetector": "^8.0.4",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "medassist-ng-frontend",
"private": true,
"version": "1.8.4",
"version": "1.8.8",
"type": "module",
"scripts": {
"dev": "vite",
+9 -28
View File
@@ -5,7 +5,6 @@ import { FRONTEND_VERSION, GITHUB_URL } from "../App";
interface UpdateCheckResult {
status: "up-to-date" | "update-available" | "error";
latestVersion?: string;
lastChecked?: string;
}
interface AboutModalProps {
@@ -18,21 +17,10 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
const [isChecking, setIsChecking] = useState(false);
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(() => {
if (!isOpen) return;
// Load cached update check result
const cached = sessionStorage.getItem("updateCheckResult");
if (cached) {
try {
const parsed = JSON.parse(cached);
if (parsed && typeof parsed === "object") {
setUpdateCheckResult(parsed);
}
} catch {
// ignore
}
if (isOpen) {
setUpdateCheckResult(null);
}
}, [isOpen]);
@@ -49,14 +37,10 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
const latestVersion = (data.tag_name || "").replace(/^v/, "");
const currentVersion = FRONTEND_VERSION.replace(/^v/, "");
const isUpToDate = latestVersion === currentVersion;
const result: UpdateCheckResult = {
setUpdateCheckResult({
status: isUpToDate ? "up-to-date" : "update-available",
latestVersion,
lastChecked: new Date().toISOString(),
};
setUpdateCheckResult(result);
// Cache the result
sessionStorage.setItem("updateCheckResult", JSON.stringify(result));
});
} catch {
setUpdateCheckResult({ status: "error" });
} finally {
@@ -114,11 +98,11 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
{updateCheckResult && (
<div className={`about-update-result ${updateCheckResult.status}`}>
{updateCheckResult.status === "up-to-date" && (
<span className="update-status-text"> {t("about.upToDate", "You are up to date!")}</span>
<span className="update-status-text">&#10003; {t("about.upToDate", "You are up to date!")}</span>
)}
{updateCheckResult.status === "update-available" && (
<span className="update-status-text">
{t("about.updateAvailable", "Update available")}:{" "}
&#11014; {t("about.updateAvailable", "Update available")}:{" "}
<strong>v{updateCheckResult.latestVersion}</strong>
<a
href={`${GITHUB_URL}/releases/latest`}
@@ -131,11 +115,8 @@ export default function AboutModal({ isOpen, onClose }: AboutModalProps) {
</span>
)}
{updateCheckResult.status === "error" && (
<span className="update-status-text"> {t("about.checkFailed", "Could not check for updates")}</span>
)}
{updateCheckResult.lastChecked && (
<span className="update-last-checked">
{t("about.lastChecked", "Last checked")}: {new Date(updateCheckResult.lastChecked).toLocaleString()}
<span className="update-status-text">
&#9888; {t("about.checkFailed", "Could not check for updates")}
</span>
)}
</div>
+75 -9
View File
@@ -1,10 +1,11 @@
/**
* AppHeader - Main application header with navigation and user menu
*/
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import { useUnsavedChanges } from "../context";
import type { ThemePreference } from "../hooks";
import { useTheme } from "../hooks";
import { useAuth } from "./Auth";
@@ -19,9 +20,25 @@ export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
const location = useLocation();
const currentPath = location.pathname;
const { user, authState, logout } = useAuth();
const { theme, toggleTheme } = useTheme();
const { theme, themePreference, setThemePreference } = useTheme();
const { confirmNavigation } = useUnsavedChanges();
// Theme dropdown state
const [themeMenuOpen, setThemeMenuOpen] = useState(false);
const themeMenuRef = useRef<HTMLDivElement>(null);
// Close theme dropdown when clicking outside
useEffect(() => {
if (!themeMenuOpen) return;
const handleClickOutside = (e: MouseEvent) => {
if (themeMenuRef.current && !themeMenuRef.current.contains(e.target as Node)) {
setThemeMenuOpen(false);
}
};
document.addEventListener("click", handleClickOutside);
return () => document.removeEventListener("click", handleClickOutside);
}, [themeMenuOpen]);
// Safe navigation that checks for unsaved changes first
const safeNavigate = async (path: string) => {
if (await confirmNavigation()) {
@@ -94,13 +111,62 @@ export function AppHeader({ onOpenProfile, onOpenAbout }: AppHeaderProps) {
</button>
)}
<button
className="icon-btn"
onClick={toggleTheme}
title={theme === "dark" ? t("tooltips.lightMode") : t("tooltips.darkMode")}
>
{theme === "dark" ? "☀️" : "🌙"}
</button>
<div className={`theme-menu ${themeMenuOpen ? "open" : ""}`} ref={themeMenuRef}>
<button className="icon-btn" onClick={() => setThemeMenuOpen(!themeMenuOpen)} title={t("theme.title")}>
{theme === "dark" ? "🌙" : "☀️"}
</button>
<div className="theme-dropdown">
<button
className={`theme-dropdown-item${themePreference === "light" ? " active" : ""}`}
onClick={() => {
setThemePreference("light");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" />
<line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" />
<line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</svg>
{t("theme.light")}
{themePreference === "light" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "dark" ? " active" : ""}`}
onClick={() => {
setThemePreference("dark");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
{t("theme.dark")}
{themePreference === "dark" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "system" ? " active" : ""}`}
onClick={() => {
setThemePreference("system");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>
{t("theme.system")}
{themePreference === "system" && <span className="theme-check"></span>}
</button>
</div>
</div>
{authState?.authEnabled && user && (
<div className={`user-menu ${userDropdownOpen ? "open" : ""}`}>
<button className="user-menu-btn" onClick={() => setUserDropdownOpen(!userDropdownOpen)}>
+104 -18
View File
@@ -2,7 +2,7 @@
// 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 { useParams } from "react-router-dom";
import type { ExpiredLinkData, SharedScheduleData } from "../types";
@@ -24,23 +24,60 @@ export function SharedSchedule() {
const [lightboxImage, setLightboxImage] = useState<{ url: string; name: string } | null>(null);
const [showPastDays, setShowPastDays] = 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") {
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";
});
// Apply theme to document
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
}, [theme]);
function toggleTheme() {
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
function getSystemTheme(): "light" | "dark" {
if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: light)").matches) {
return "light";
}
return "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)
const [manuallyCollapsedDays, setManuallyCollapsedDays] = 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}
</h1>
<div className="shared-schedule-header-actions">
<button
className="icon-btn"
onClick={toggleTheme}
title={theme === "dark" ? t("tooltips.lightMode") : t("tooltips.darkMode")}
>
{theme === "dark" ? "☀️" : "🌙"}
</button>
<div className={`theme-menu ${themeMenuOpen ? "open" : ""}`} ref={themeMenuRef}>
<button className="icon-btn" onClick={() => setThemeMenuOpen(!themeMenuOpen)} title={t("theme.title")}>
{resolvedTheme === "dark" ? "🌙" : "☀️"}
</button>
<div className="theme-dropdown">
<button
className={`theme-dropdown-item${themePreference === "light" ? " active" : ""}`}
onClick={() => {
setThemePreference("light");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" />
<line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" />
<line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</svg>
{t("theme.light")}
{themePreference === "light" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "dark" ? " active" : ""}`}
onClick={() => {
setThemePreference("dark");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
{t("theme.dark")}
{themePreference === "dark" && <span className="theme-check"></span>}
</button>
<button
className={`theme-dropdown-item${themePreference === "system" ? " active" : ""}`}
onClick={() => {
setThemePreference("system");
setThemeMenuOpen(false);
}}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>
{t("theme.system")}
{themePreference === "system" && <span className="theme-check"></span>}
</button>
</div>
</div>
</div>
<p className="shared-schedule-period">
{t("share.period")}:{" "}
+3 -1
View File
@@ -278,7 +278,8 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
systemLocale,
settingsHook.settings.reminderDaysBefore,
settingsHook.settings.stockCalculationMode,
doses.takenDoses
doses.takenDoses,
doses.takenDoseTimestamps
),
[
medications.meds,
@@ -287,6 +288,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
settingsHook.settings.reminderDaysBefore,
settingsHook.settings.stockCalculationMode,
doses.takenDoses,
doses.takenDoseTimestamps,
]
);
+1 -1
View File
@@ -14,7 +14,7 @@ export type { Settings, UseSettingsReturn } from "./useSettings";
export { useSettings } from "./useSettings";
export type { UseShareReturn } from "./useShare";
export { useShare } from "./useShare";
export type { Theme, UseThemeReturn } from "./useTheme";
export type { Theme, ThemePreference, UseThemeReturn } from "./useTheme";
export { useTheme } from "./useTheme";
export type { UseUnsavedChangesWarningReturn } from "./useUnsavedChangesWarning";
export { useUnsavedChangesWarning } from "./useUnsavedChangesWarning";
+92 -45
View File
@@ -2,11 +2,12 @@
// useDoses Hook - Dose tracking state and operations
// =============================================================================
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
export interface UseDosesReturn {
takenDoses: Set<string>;
setTakenDoses: React.Dispatch<React.SetStateAction<Set<string>>>;
takenDoseTimestamps: Map<string, number>;
dismissedDoses: Set<string>;
showClearMissedConfirm: boolean;
setShowClearMissedConfirm: (show: boolean) => void;
@@ -19,25 +20,39 @@ export interface UseDosesReturn {
export function useDoses(): UseDosesReturn {
const [takenDoses, setTakenDoses] = useState<Set<string>>(new Set());
const [takenDoseTimestamps, setTakenDoseTimestamps] = useState<Map<string, number>>(new Map());
const [dismissedDoses, setDismissedDoses] = useState<Set<string>>(new Set());
const [showClearMissedConfirm, setShowClearMissedConfirm] = useState(false);
// Track in-flight mutations to prevent polling from overwriting optimistic updates
const mutationInFlightRef = useRef(0);
// Load taken doses from server
const loadTakenDoses = useCallback(async () => {
// Skip polling while mutations are in-flight to prevent race conditions
// where a poll response with stale data overwrites optimistic updates
if (mutationInFlightRef.current > 0) return;
try {
const res = await fetch("/api/doses/taken", { credentials: "include" });
if (res.ok) {
// Double-check no mutation started while we were fetching
if (mutationInFlightRef.current > 0) return;
const data = await res.json();
const taken = new Set<string>();
const timestamps = new Map<string, number>();
const dismissed = new Set<string>();
for (const d of data.doses) {
if (d.dismissed) {
dismissed.add(d.doseId);
} else {
taken.add(d.doseId);
timestamps.set(d.doseId, d.takenAt);
}
}
setTakenDoses(taken);
setTakenDoseTimestamps(timestamps);
setDismissedDoses(dismissed);
}
// Don't reset on error - keep current state
@@ -77,59 +92,91 @@ export function useDoses(): UseDosesReturn {
[takenDoses, getDoseId]
);
const markDoseTaken = useCallback(async (doseId: string) => {
// Optimistic update
setTakenDoses((prev) => {
const next = new Set(prev);
next.add(doseId);
return next;
});
// Send to server
try {
await fetch("/api/doses/taken", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ doseId }),
});
} catch {
// Revert on error
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
}
}, []);
const undoDoseTaken = useCallback(async (doseId: string) => {
// Optimistic update
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
// Send to server
try {
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
method: "DELETE",
credentials: "include",
});
} catch {
// Revert on error
const markDoseTaken = useCallback(
async (doseId: string) => {
// Optimistic update
mutationInFlightRef.current++;
setTakenDoses((prev) => {
const next = new Set(prev);
next.add(doseId);
return next;
});
}
}, []);
setTakenDoseTimestamps((prev) => {
const next = new Map(prev);
next.set(doseId, Date.now());
return next;
});
// Send to server
try {
await fetch("/api/doses/taken", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ doseId }),
});
} catch {
// Revert on error
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
setTakenDoseTimestamps((prev) => {
const next = new Map(prev);
next.delete(doseId);
return next;
});
} finally {
mutationInFlightRef.current--;
// Re-sync with server after mutation completes
loadTakenDoses();
}
},
[loadTakenDoses]
);
const undoDoseTaken = useCallback(
async (doseId: string) => {
// Optimistic update
mutationInFlightRef.current++;
setTakenDoses((prev) => {
const next = new Set(prev);
next.delete(doseId);
return next;
});
setTakenDoseTimestamps((prev) => {
const next = new Map(prev);
next.delete(doseId);
return next;
});
// Send to server
try {
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
method: "DELETE",
credentials: "include",
});
} catch {
// Revert on error
setTakenDoses((prev) => {
const next = new Set(prev);
next.add(doseId);
return next;
});
} finally {
mutationInFlightRef.current--;
// Re-sync with server after mutation completes
loadTakenDoses();
}
},
[loadTakenDoses]
);
return {
takenDoses,
setTakenDoses,
takenDoseTimestamps,
dismissedDoses,
showClearMissedConfirm,
setShowClearMissedConfirm,
+3 -3
View File
@@ -1,6 +1,6 @@
import { useCallback, useState } from "react";
import type { Coverage, FormState, Medication, RefillEntry } from "../types";
import { getMedTotal } from "../types";
import { getMedTotal, getPackageSize } from "../types";
export interface UseRefillReturn {
// Refill state
@@ -146,8 +146,8 @@ export function useRefill(): UseRefillReturn {
const desiredTotal = finalFullBlisters * selectedMed.pillsPerBlister + finalPartialPills;
// The "base" from DB structure (without any stockAdjustment)
const baseTotal =
selectedMed.packCount * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + selectedMed.looseTablets;
// Use getPackageSize() which handles both blister and bottle types correctly
const baseTotal = getPackageSize(selectedMed);
// stockAdjustment = what we need to make getMedTotal() return desiredTotal
const newStockAdjustment = desiredTotal - baseTotal;
+58 -10
View File
@@ -1,32 +1,80 @@
// =============================================================================
// useTheme Hook - Theme (dark/light mode) state management
// useTheme Hook - Theme (dark/light/system mode) state management
// =============================================================================
import { useCallback, useEffect, useState } from "react";
export type Theme = "light" | "dark";
export type ThemePreference = "light" | "dark" | "system";
export interface UseThemeReturn {
/** The resolved theme applied to the DOM ("light" | "dark") */
theme: Theme;
/** The user's preference ("light" | "dark" | "system") */
themePreference: ThemePreference;
/** Set the theme preference */
setThemePreference: (pref: ThemePreference) => void;
/** Legacy toggle: cycles light → dark → system → light */
toggleTheme: () => void;
}
function getSystemTheme(): Theme {
if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: light)").matches) {
return "light";
}
return "dark";
}
function resolveTheme(pref: ThemePreference): Theme {
return pref === "system" ? getSystemTheme() : pref;
}
export function useTheme(): UseThemeReturn {
const [theme, setTheme] = useState<Theme>(() => {
const [themePreference, setThemePreferenceState] = useState<ThemePreference>(() => {
if (typeof window !== "undefined") {
return (localStorage.getItem("theme") as Theme) || "dark";
const stored = localStorage.getItem("theme") as ThemePreference | null;
if (stored === "light" || stored === "dark" || stored === "system") return stored;
return "dark";
}
return "dark";
});
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
}, [theme]);
const [theme, setTheme] = useState<Theme>(() => resolveTheme(themePreference));
const toggleTheme = useCallback(() => {
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
// Apply resolved theme to DOM whenever preference or system theme changes
useEffect(() => {
const resolved = resolveTheme(themePreference);
setTheme(resolved);
document.documentElement.setAttribute("data-theme", resolved);
localStorage.setItem("theme", themePreference);
}, [themePreference]);
// Listen for system theme changes when preference is "system"
useEffect(() => {
if (themePreference !== "system") return;
const mq = window.matchMedia?.("(prefers-color-scheme: light)");
if (!mq) return;
const handler = () => {
const resolved = resolveTheme("system");
setTheme(resolved);
document.documentElement.setAttribute("data-theme", resolved);
};
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, [themePreference]);
const setThemePreference = useCallback((pref: ThemePreference) => {
setThemePreferenceState(pref);
}, []);
return { theme, toggleTheme };
const toggleTheme = useCallback(() => {
setThemePreferenceState((prev) => {
if (prev === "light") return "dark";
if (prev === "dark") return "system";
return "light";
});
}, []);
return { theme, themePreference, setThemePreference, toggleTheme };
}
+9 -3
View File
@@ -176,7 +176,8 @@
"badge": "Vorrat planen",
"from": "Von",
"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",
"calculating": "Wird berechnet...",
"sendEmail": "📧 Per E-Mail senden",
@@ -290,6 +291,12 @@
"lightMode": "Zum hellen Modus wechseln",
"darkMode": "Zum dunklen Modus wechseln"
},
"theme": {
"title": "Design",
"light": "Hell",
"dark": "Dunkel",
"system": "System"
},
"dose": {
"takenBy": "eingenommen von",
"markAsTaken": "Als eingenommen markieren"
@@ -478,10 +485,9 @@
"checking": "Prüfe...",
"upToDate": "Du bist auf dem neuesten Stand!",
"updateAvailable": "Update verfügbar",
"viewOnGitHub": "Auf GitHub ansehen",
"downloadUpdate": "Update herunterladen",
"checkFailed": "Update-Prüfung fehlgeschlagen",
"lastChecked": "Zuletzt geprüft",
"viewOnGitHub": "Auf GitHub ansehen",
"github": "GitHub",
"license": "MIT-Lizenz",
"copyright": "© {{year}} Daniel Volz",
+9 -3
View File
@@ -176,7 +176,8 @@
"badge": "Plan your supply",
"from": "From",
"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",
"calculating": "Calculating...",
"sendEmail": "📧 Send via Email",
@@ -290,6 +291,12 @@
"lightMode": "Switch to light mode",
"darkMode": "Switch to dark mode"
},
"theme": {
"title": "Theme",
"light": "Light",
"dark": "Dark",
"system": "System"
},
"dose": {
"takenBy": "taken by",
"markAsTaken": "Mark as taken"
@@ -478,10 +485,9 @@
"checking": "Checking...",
"upToDate": "You're up to date!",
"updateAvailable": "Update available",
"viewOnGitHub": "View on GitHub",
"downloadUpdate": "Download Update",
"checkFailed": "Could not check for updates",
"lastChecked": "Last checked",
"viewOnGitHub": "View on GitHub",
"github": "GitHub",
"license": "MIT License",
"copyright": "© {{year}} Daniel Volz",
+16 -4
View File
@@ -34,14 +34,18 @@ function formatOpenBlisterAndLoose(
return `${openBlisterPills} ${t("common.of")} ${pillsPerBlister} ${t("common.pills")}`;
}
// Get total pills for a medication
// Get total pills for a medication (packageType-aware)
function getMedTotal(med: {
packCount: number;
blistersPerPack: number;
pillsPerBlister: number;
looseTablets: number;
stockAdjustment?: number | null;
packageType?: string;
}): number {
if (med.packageType === "bottle") {
return med.looseTablets + (med.stockAdjustment ?? 0);
}
return med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
}
@@ -276,9 +280,17 @@ export function DashboardPage() {
<div className="reminder-status-row">
<span className="reminder-status-label">{t("dashboard.reminders.lastSent")}:</span>
<span className="reminder-status-value">
{reminderData.lastSent.medName && (
<span className="reminder-med-name">{reminderData.lastSent.medName}</span>
)}
{reminderData.lastSent.medName &&
(() => {
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 && (
<span className="reminder-taken-by"> ({reminderData.lastSent.takenBy})</span>
)}
+1 -1
View File
@@ -526,7 +526,7 @@ export function MedicationsPage() {
</label>
</>
)}
<label>
<label className="full">
{t("form.pillWeight")} ({form.doseUnit})
<div className="dose-input-group">
<input
+14 -3
View File
@@ -178,6 +178,9 @@ export function PlannerPage() {
onChange={(e) => setIncludeUntilStart(e.target.checked)}
/>
{t("planner.includeUntilStart")}
<span className="info-tooltip small" data-tooltip={t("planner.includeUntilStartTooltip")}>
</span>
</label>
<div className="planner-actions">
<button type="button" className="ghost" onClick={resetRange}>
@@ -210,11 +213,19 @@ export function PlannerPage() {
<strong>{row.plannerUsage}</strong>&nbsp;{t("common.pills")}
</span>
<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 data-label={t("planner.table.available")}>
{row.fullBlisters} {t("common.blisters")}
{row.loosePills > 0 && ` + ${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`}
{row.packageType === "bottle" ? (
`${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`
) : (
<>
{row.fullBlisters} {t("common.blisters")}
{row.loosePills > 0 && ` + ${Math.round(row.loosePills * 10) / 10} ${t("common.pills")}`}
</>
)}
</span>
<span
data-label={t("table.status")}
+90 -11
View File
@@ -152,6 +152,90 @@ body.modal-open {
background: rgba(47, 134, 246, 0.12);
}
/* =============================================================================
Theme Dropdown Menu
============================================================================= */
.theme-menu {
position: relative;
}
.theme-dropdown {
position: absolute;
top: calc(100% + 0.5rem);
right: 0;
min-width: 160px;
background: rgba(15, 23, 42, 0.85);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px;
box-shadow:
0 12px 32px rgba(0, 0, 0, 0.4),
inset 0 0 0 1px rgba(255, 255, 255, 0.05);
opacity: 0;
visibility: hidden;
transform: translateY(-6px) scale(0.95);
transition: all 0.2s ease;
z-index: 1000;
overflow: hidden;
padding: 0.375rem;
}
[data-theme="light"] .theme-dropdown {
background: rgba(255, 255, 255, 0.85);
border: 1px solid rgba(0, 0, 0, 0.08);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
}
.theme-menu.open .theme-dropdown {
opacity: 1;
visibility: visible;
transform: translateY(0) scale(1);
}
.theme-dropdown-item {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
padding: 0.625rem 0.75rem;
border: none;
background: none;
color: var(--text-primary);
font-size: 0.875rem;
cursor: pointer;
border-radius: 8px;
transition: background 0.15s ease;
text-align: left;
box-shadow: none;
}
.theme-dropdown-item:hover {
background: rgba(59, 130, 246, 0.15);
}
.theme-dropdown-item.active {
color: var(--accent-primary);
}
.theme-dropdown-item svg {
width: 18px;
height: 18px;
flex-shrink: 0;
opacity: 0.7;
}
.theme-dropdown-item.active svg {
opacity: 1;
color: var(--accent-primary);
}
.theme-check {
margin-left: auto;
font-size: 0.8rem;
opacity: 0.8;
}
.hero-title {
display: flex;
align-items: center;
@@ -1024,12 +1108,14 @@ textarea.auto-resize {
.dose-input-group input {
flex: 1;
min-width: 0;
min-width: 100px;
}
.dose-unit-select {
width: auto;
min-width: 80px;
min-width: unset;
max-width: 120px;
flex-shrink: 0;
padding: 0.5rem 0.75rem;
background: var(--bg-primary);
border: 1px solid var(--border-primary);
@@ -2019,11 +2105,12 @@ textarea.auto-resize {
text-transform: uppercase;
letter-spacing: 0.04em;
}
.planner-checkbox {
.planner label.planner-checkbox {
grid-column: 1 / -1;
display: flex;
flex-direction: row;
align-items: center;
flex-wrap: nowrap;
gap: 0.75rem;
color: var(--text-secondary);
font-size: 0.875rem;
@@ -4614,7 +4701,6 @@ a.about-version-link:hover {
.about-update-section {
padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--border-primary);
min-height: 148px;
}
.about-update-btn {
@@ -4713,13 +4799,6 @@ a.about-version-link:hover {
background: var(--accent-hover);
}
.update-last-checked {
display: block;
margin-top: 0.5rem;
font-size: 0.75rem;
opacity: 0.8;
}
.about-links {
padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--border-primary);
@@ -82,7 +82,7 @@ describe("AppHeader", () => {
});
});
it("renders theme toggle button", async () => {
it("renders theme menu button", async () => {
const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn();
@@ -95,12 +95,33 @@ describe("AppHeader", () => {
);
await waitFor(() => {
const buttons = screen.getAllByRole("button");
const themeBtn = buttons.find((btn) => btn.textContent?.includes("🌙") || btn.textContent?.includes("☀️"));
const themeBtn = screen.getByTitle(/theme\.title/i);
expect(themeBtn).toBeInTheDocument();
});
});
it("opens theme dropdown and shows Light/Dark/System options", async () => {
const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn();
render(
<MemoryRouter initialEntries={["/dashboard"]}>
<AuthProvider>
<AppHeader onOpenProfile={mockOnOpenProfile} onOpenAbout={mockOnOpenAbout} />
</AuthProvider>
</MemoryRouter>
);
await waitFor(() => {
const themeBtn = screen.getByTitle(/theme\.title/i);
fireEvent.click(themeBtn);
});
expect(screen.getByText(/theme\.light/i)).toBeInTheDocument();
expect(screen.getByText(/theme\.dark/i)).toBeInTheDocument();
expect(screen.getByText(/theme\.system/i)).toBeInTheDocument();
});
it("renders settings button when auth is disabled", async () => {
const mockOnOpenProfile = vi.fn();
const mockOnOpenAbout = vi.fn();
+107 -8
View File
@@ -103,10 +103,14 @@ describe("useDoses", () => {
});
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>)
.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());
@@ -119,7 +123,9 @@ describe("useDoses", () => {
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(
"/api/doses/taken",
expect.objectContaining({
@@ -130,10 +136,11 @@ describe("useDoses", () => {
});
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>)
.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());
@@ -153,12 +160,13 @@ describe("useDoses", () => {
it("undoes dose taken optimistically", async () => {
const mockDoses = {
doses: [{ doseId: "taken-dose", dismissed: false }],
doses: [{ doseId: "taken-dose", takenAt: Date.now(), dismissed: false }],
};
(global.fetch as ReturnType<typeof vi.fn>)
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
.mockResolvedValueOnce({ ok: true });
.mockResolvedValueOnce({ ok: true })
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) });
const { result } = renderHook(() => useDoses());
@@ -170,10 +178,101 @@ describe("useDoses", () => {
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" }));
});
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", () => {
const { result } = renderHook(() => useDoses());
+108
View File
@@ -287,6 +287,114 @@ describe("useRefill", () => {
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", () => {
const { result } = renderHook(() => useRefill());
+54 -22
View File
@@ -8,6 +8,20 @@ describe("useTheme", () => {
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null);
// Reset mock to default behavior
(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(() => {
@@ -17,58 +31,76 @@ describe("useTheme", () => {
it("returns dark as default theme", () => {
const { result } = renderHook(() => useTheme());
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");
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe("light");
expect(result.current.themePreference).toBe("light");
});
it("toggles theme from dark to 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", () => {
it("toggles theme through light → dark → system → light", () => {
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
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");
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");
});
it("saves theme to localStorage on change", () => {
it("saves theme preference to localStorage on change", () => {
const { result } = renderHook(() => useTheme());
act(() => {
result.current.toggleTheme();
result.current.setThemePreference("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", () => {
const { result } = renderHook(() => useTheme());
expect(document.documentElement.getAttribute("data-theme")).toBe("dark");
act(() => {
result.current.toggleTheme();
result.current.setThemePreference("light");
});
expect(document.documentElement.getAttribute("data-theme")).toBe("light");
});
});
+645 -6
View File
@@ -289,6 +289,113 @@ describe("calculateCoverage", () => {
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", () => {
const meds: Medication[] = [
{
@@ -409,8 +516,9 @@ describe("calculateCoverage", () => {
});
it("stock correction with dose tracking data also reflects correctly", () => {
// When the user has dose tracking data, the actualConsumed path is used.
// Verify that no phantom dose is generated right after a stock correction.
// In automatic mode, dose tracking data is ignored — stock is always
// 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 march14 = new Date("2024-03-14T00:00:00").getTime();
@@ -437,20 +545,23 @@ describe("calculateCoverage", () => {
];
// 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 result = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
expect(result.all).toHaveLength(1);
// getMedTotal = 30 - 7 = 23.
// The taken dose from yesterday should NOT be counted (it's before the correction).
// No new doses should exist since the correction just happened.
// Automatic mode ignores tracking data. After correction, consumption
// restarts from correctionTime + period, which is in the future.
expect(result.all[0].medsLeft).toBe(23);
});
it("stock correction consumption resumes after one full period", () => {
// After 1 day (for daily medication), the next dose should be consumed.
// Set system time to 1 day + 1 hour after correction.
// After correction, the next scheduled dose on the blister's grid should
// 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");
vi.setSystemTime(new Date("2024-03-15T13:00:00Z")); // 25 hours after correction
@@ -483,6 +594,521 @@ describe("calculateCoverage", () => {
// medsLeft = 23 - 1 = 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", () => {
@@ -527,6 +1153,19 @@ describe("getStockStatus", () => {
expect(result.level).toBe("normal");
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", () => {
+2
View File
@@ -67,6 +67,7 @@ export type PlannerRow = {
fullBlisters: number;
loosePills: number;
enough: boolean;
packageType?: PackageType;
};
export type RefillEntry = {
@@ -170,6 +171,7 @@ export type SharedMedication = {
doseUnit?: DoseUnit | null;
imageUrl?: string | null;
totalPills: number;
packageType?: PackageType;
packCount: number;
blistersPerPack: number;
looseTablets: number;
+86 -41
View File
@@ -100,7 +100,8 @@ export function calculateCoverage(
locale: string,
reminderDaysBefore: number,
stockCalculationMode: "automatic" | "manual",
takenDoses: Set<string>
takenDoses: Set<string>,
takenDoseTimestamps?: Map<string, number>
): { low: Coverage[]; all: Coverage[] } {
const MS_PER_DAY = 86_400_000;
const now = Date.now();
@@ -116,66 +117,112 @@ export function calculateCoverage(
// Also add medication-level takenBy for backward compatibility
m.takenBy?.forEach((person) => uniquePeople.add(person));
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;
const stockCorrectionCutoff = m.lastStockCorrectionAt ? new Date(m.lastStockCorrectionAt).getTime() : 0;
if (stockCalculationMode === "automatic") {
// In automatic mode, calculate expected consumption based on time
// but also account for manual corrections (doses marked as not taken)
// In automatic mode, stock is reduced automatically based on the schedule.
// 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) => {
const blisterStart = new Date(s.start).getTime();
const period = Math.max(1, s.every) * MS_PER_DAY;
// After a stock correction, start counting consumption from the NEXT
// scheduled dose, because the user's pill count already reflects all
// consumption up to the correction time.
// scheduled dose on this blister's grid, because the user's pill count
// already reflects all consumption up to the correction time.
// We align to the schedule grid so that e.g. correction at 15:40 with
// a daily 15:42 dose counts today's 15:42 dose (2 min later), not
// tomorrow's dose (24h later as the old code did).
let effectiveStart: number;
if (stockCorrectionCutoff > 0 && stockCorrectionCutoff >= blisterStart) {
effectiveStart = stockCorrectionCutoff + period;
const elapsedSinceStart = stockCorrectionCutoff - blisterStart;
const periodsElapsed = Math.floor(elapsedSinceStart / period);
effectiveStart = blisterStart + (periodsElapsed + 1) * period;
} else {
effectiveStart = blisterStart;
}
if (Number.isNaN(effectiveStart) || effectiveStart > now) return;
const occurrences = Math.floor((now - effectiveStart) / period) + 1;
if (Number.isNaN(effectiveStart)) return;
const intake = intakes[blisterIdx];
const intakePerson = intake?.takenBy;
// For per-intake takenBy, only count for that person
// For legacy (no takenBy), count for all people in medication takenBy
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
let actualConsumed = 0;
// Time-based: count doses where the scheduled time has already passed
let timeBasedConsumed = 0;
let lastAutoConsumedDateMs = 0;
// Generate all expected dose IDs for this blister up to now
for (let i = 0; i < occurrences; i++) {
const doseDate = new Date(effectiveStart + i * period);
const dateOnlyMs = new Date(doseDate.getFullYear(), doseDate.getMonth(), doseDate.getDate()).getTime();
const baseDoseId = `${m.id}-${blisterIdx}-${dateOnlyMs}`;
if (effectiveStart <= now) {
const occurrences = Math.floor((now - effectiveStart) / period) + 1;
timeBasedConsumed = occurrences * s.usage * peopleForThisIntake.length;
// Check if each person has taken this dose
for (const person of peopleForThisIntake) {
const doseId = person ? `${baseDoseId}-${person}` : baseDoseId;
if (takenDoses.has(doseId)) {
actualConsumed += s.usage;
// Date-only timestamp of the last auto-consumed dose
const lastDoseTime = new Date(effectiveStart + (occurrences - 1) * period);
lastAutoConsumedDateMs = new Date(
lastDoseTime.getFullYear(),
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
// 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;
consumed += timeBasedConsumed + earlyTakenConsumed;
});
} 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) => {
const parts = doseId.split("-");
if (parts.length >= 3) {
@@ -190,19 +237,17 @@ export function calculateCoverage(
blisterStartDate.getMonth(),
blisterStartDate.getDate()
).getTime();
// Convert stock correction cutoff to date-only as well
const stockCorrectionDateOnly =
stockCorrectionCutoff > 0
? new Date(
new Date(stockCorrectionCutoff).getFullYear(),
new Date(stockCorrectionCutoff).getMonth(),
new Date(stockCorrectionCutoff).getDate()
).getTime()
: 0;
// Use actual takenAt timestamp for stock correction comparison.
// A dose counts only if it was MARKED after the stock correction,
// regardless of what day it was scheduled for.
const takenAt = takenDoseTimestamps?.get(doseId) ?? 0;
const afterCorrectionOrNoCorrectionMs = stockCorrectionCutoff === 0 || takenAt > stockCorrectionCutoff;
if (
!Number.isNaN(blisterStartDateOnly) &&
doseTimestamp >= blisterStartDateOnly &&
doseTimestamp >= stockCorrectionDateOnly
afterCorrectionOrNoCorrectionMs
) {
consumed += blisters[blisterIdx].usage;
}
+86 -55
View File
@@ -1,6 +1,6 @@
#!/bin/bash
# =============================================================================
# MedAssist Release Script
# MedAssist Release Script (non-interactive)
# =============================================================================
# Usage:
# ./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 1.2.3 # explicit version
#
# This script creates a PR for the version bump (required due to branch protection),
# waits for CI, merges it, and then creates a signed tag for the release.
# Fully non-interactive: no y/N prompts. Designed to be called by AI agents
# 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
@@ -21,45 +22,98 @@ YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# GitHub repo
# Configuration
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
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
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
echo -e "${RED}Error: GitHub CLI (gh) is required but not installed.${NC}"
echo "Install it with: brew install gh"
exit 1
fi
# Check gh authentication
if ! gh auth status &> /dev/null; then
echo -e "${RED}Error: Not authenticated with GitHub CLI.${NC}"
echo "Run: gh auth login"
exit 1
fi
# Check for uncommitted changes
if [[ -n $(git status --porcelain) ]]; then
echo -e "${RED}Error: You have uncommitted changes. Commit or stash them first.${NC}"
git status --short
exit 1
fi
# Make sure we're on main and up to date
# ─── Determine version ───────────────────────────────────────────────────────
echo -e "${BLUE}Updating main branch...${NC}"
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/')
echo -e "${BLUE}Current version: ${YELLOW}v${CURRENT_VERSION}${NC}"
# Calculate new version
if [[ -z "$1" ]]; then
echo -e "${RED}Usage: $0 <patch|minor|major|x.y.z>${NC}"
exit 1
@@ -79,7 +133,6 @@ case "$1" in
NEW_VERSION="$((major + 1)).0.0"
;;
*)
# Assume explicit version (validate format)
if [[ ! "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo -e "${RED}Invalid version format. Use: x.y.z${NC}"
exit 1
@@ -88,45 +141,31 @@ case "$1" in
;;
esac
echo -e "${GREEN}New version: ${YELLOW}v${NEW_VERSION}${NC}"
echo ""
echo -e "${GREEN}Releasing: ${YELLOW}v${CURRENT_VERSION} → v${NEW_VERSION}${NC}"
# Confirm
read -p "Release v${NEW_VERSION}? (y/N) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Aborted."
exit 1
fi
# ─── Create release branch and PR ────────────────────────────────────────────
# Branch name for the release
RELEASE_BRANCH="chore/release-${NEW_VERSION}"
# Check if branch already exists
if git show-ref --verify --quiet "refs/heads/${RELEASE_BRANCH}"; then
echo -e "${YELLOW}Branch ${RELEASE_BRANCH} already exists locally. Deleting...${NC}"
git branch -D "${RELEASE_BRANCH}"
fi
# Create release branch
echo -e "${BLUE}Creating release branch...${NC}"
git checkout -b "${RELEASE_BRANCH}"
# Update version in package.json files
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}\"/" frontend/package.json 2>/dev/null || true
# Commit version bump
echo -e "${BLUE}Committing version bump...${NC}"
git add backend/package.json frontend/package.json 2>/dev/null || git add backend/package.json
git commit -m "chore: release v${NEW_VERSION}"
# Push branch to GitHub
echo -e "${BLUE}Pushing release branch to GitHub...${NC}"
git push -u origin "${RELEASE_BRANCH}" 2>/dev/null || git push -u github "${RELEASE_BRANCH}"
echo -e "${BLUE}Pushing release branch...${NC}"
git push -u "${GIT_REMOTE}" "${RELEASE_BRANCH}"
# Create PR
echo -e "${BLUE}Creating Pull Request...${NC}"
PR_URL=$(gh pr create \
--repo "${GITHUB_REPO}" \
@@ -136,57 +175,49 @@ PR_URL=$(gh pr create \
Automated version bump for release v${NEW_VERSION}.
This PR was created by the release script." \
2>&1)
This PR was created by the release script.")
echo -e "${GREEN}PR created: ${YELLOW}${PR_URL}${NC}"
# Extract PR number
PR_NUMBER=$(echo "$PR_URL" | grep -oE '[0-9]+$')
# Wait for CI checks
echo -e "${BLUE}Waiting for CI checks to complete...${NC}"
if ! gh pr checks "${PR_NUMBER}" --repo "${GITHUB_REPO}" --watch; then
# ─── Wait for CI and merge ────────────────────────────────────────────────────
if ! wait_for_ci "${PR_NUMBER}"; then
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
fi
echo -e "${GREEN}CI checks passed!${NC}"
# Merge PR
echo -e "${BLUE}Merging PR...${NC}"
echo -e "${BLUE}Merging PR #${PR_NUMBER}...${NC}"
gh pr merge "${PR_NUMBER}" --repo "${GITHUB_REPO}" --squash --delete-branch
# Switch back to main and pull
echo -e "${BLUE}Updating main branch with merged changes...${NC}"
echo -e "${BLUE}Updating main branch...${NC}"
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
echo -e "${YELLOW}Tag v${NEW_VERSION} already exists locally. Deleting...${NC}"
git tag -d "v${NEW_VERSION}"
fi
# Check if remote tag exists
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
if git ls-remote --tags "${GIT_REMOTE}" "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}"; then
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 github ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
git push "${GIT_REMOTE}" ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
fi
# Create signed tag
echo -e "${BLUE}Creating signed tag v${NEW_VERSION}...${NC}"
git tag -s "v${NEW_VERSION}" -m "Release v${NEW_VERSION}"
# Push tag
echo -e "${BLUE}Pushing tag to GitHub...${NC}"
git push origin "v${NEW_VERSION}" 2>/dev/null || git push github "v${NEW_VERSION}"
echo -e "${BLUE}Pushing tag...${NC}"
git push "${GIT_REMOTE}" "v${NEW_VERSION}"
# ─── Done ─────────────────────────────────────────────────────────────────────
echo ""
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 ""
echo -e "${BLUE}GitHub Actions will now build and publish Docker images.${NC}"