From 8c5deed4c26d9fdefb17e4e292e131b4b3930df5 Mon Sep 17 00:00:00 2001 From: Daniel Volz Date: Sun, 8 Feb 2026 20:32:40 +0100 Subject: [PATCH] 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 --- .github/agents/release-manager.agent.md | 62 +++-- backend/drizzle.config.ts | 2 +- backend/package-lock.json | 4 +- backend/src/i18n/translations.ts | 4 +- backend/src/routes/export.ts | 3 + backend/src/routes/medications.ts | 40 ++- backend/src/routes/refills.ts | 17 +- backend/src/routes/share.ts | 5 +- .../src/services/intake-reminder-scheduler.ts | 19 +- backend/src/services/reminder-scheduler.ts | 4 +- backend/src/test/e2e-routes.test.ts | 246 ++++++++++++++++++ frontend/package-lock.json | 4 +- frontend/src/components/AboutModal.tsx | 37 +-- frontend/src/components/AppHeader.tsx | 84 +++++- frontend/src/components/SharedSchedule.tsx | 122 +++++++-- frontend/src/hooks/index.ts | 2 +- frontend/src/hooks/useTheme.ts | 68 ++++- frontend/src/i18n/de.json | 12 +- frontend/src/i18n/en.json | 12 +- frontend/src/pages/DashboardPage.tsx | 20 +- frontend/src/pages/MedicationsPage.tsx | 2 +- frontend/src/pages/PlannerPage.tsx | 17 +- frontend/src/styles.css | 101 ++++++- .../src/test/components/AppHeader.test.tsx | 27 +- frontend/src/test/hooks/useDoses.test.ts | 89 +++++++ frontend/src/test/hooks/useTheme.test.ts | 76 ++++-- frontend/src/test/utils/schedule.test.ts | 120 +++++++++ frontend/src/types/index.ts | 2 + frontend/src/utils/schedule.ts | 18 +- 29 files changed, 1053 insertions(+), 166 deletions(-) diff --git a/.github/agents/release-manager.agent.md b/.github/agents/release-manager.agent.md index ca2c1d5..1bb622b 100644 --- a/.github/agents/release-manager.agent.md +++ b/.github/agents/release-manager.agent.md @@ -212,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 @@ -235,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 @@ -294,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 ``` @@ -308,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 +7. If minor/major: check README.md for needed updates (Task 5) +8. Run ./scripts/release.sh (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 ``` \ No newline at end of file diff --git a/backend/drizzle.config.ts b/backend/drizzle.config.ts index 31054b1..a05172d 100644 --- a/backend/drizzle.config.ts +++ b/backend/drizzle.config.ts @@ -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", }, }); diff --git a/backend/package-lock.json b/backend/package-lock.json index 61c6c3d..3f348fb 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -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", diff --git a/backend/src/i18n/translations.ts b/backend/src/i18n/translations.ts index f98deeb..de885c1 100644 --- a/backend/src/i18n/translations.ts +++ b/backend/src/i18n/translations.ts @@ -156,7 +156,7 @@ const translations: Record = { 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 = { 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}", diff --git a/backend/src/routes/export.ts b/backend/src/routes/export.ts index 9c4efee..6a4aa7e 100644 --- a/backend/src/routes/export.ts +++ b/backend/src/routes/export.ts @@ -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, diff --git a/backend/src/routes/medications.ts b/backend/src/routes/medications.ts index 38e7010..db2160f 100644 --- a/backend/src/routes/medications.ts +++ b/backend/src/routes/medications.ts @@ -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, }; }); diff --git a/backend/src/routes/refills.ts b/backend/src/routes/refills.ts index 0f36026..dde6676 100644 --- a/backend/src/routes/refills.ts +++ b/backend/src/routes/refills.ts @@ -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, })); }); diff --git a/backend/src/routes/share.ts b/backend/src/routes/share.ts index 0565859..10d2dc1 100644 --- a/backend/src/routes/share.ts +++ b/backend/src/routes/share.ts @@ -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, diff --git a/backend/src/services/intake-reminder-scheduler.ts b/backend/src/services/intake-reminder-scheduler.ts index cd602b5..cee3569 100644 --- a/backend/src/services/intake-reminder-scheduler.ts +++ b/backend/src/services/intake-reminder-scheduler.ts @@ -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 }); diff --git a/backend/src/services/reminder-scheduler.ts b/backend/src/services/reminder-scheduler.ts index 0f1ee62..7b20e5a 100644 --- a/backend/src/services/reminder-scheduler.ts +++ b/backend/src/services/reminder-scheduler.ts @@ -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 diff --git a/backend/src/test/e2e-routes.test.ts b/backend/src/test/e2e-routes.test.ts index 0669a17..eb69470 100644 --- a/backend/src/test/e2e-routes.test.ts +++ b/backend/src/test/e2e-routes.test.ts @@ -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"); + }); + }); }); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index a240f3b..476f43e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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", diff --git a/frontend/src/components/AboutModal.tsx b/frontend/src/components/AboutModal.tsx index dd222d2..df6592a 100644 --- a/frontend/src/components/AboutModal.tsx +++ b/frontend/src/components/AboutModal.tsx @@ -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(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 && (
{updateCheckResult.status === "up-to-date" && ( - ✓ {t("about.upToDate", "You are up to date!")} + ✓ {t("about.upToDate", "You are up to date!")} )} {updateCheckResult.status === "update-available" && ( - ⬆ {t("about.updateAvailable", "Update available")}:{" "} + ⬆ {t("about.updateAvailable", "Update available")}:{" "} v{updateCheckResult.latestVersion} )} {updateCheckResult.status === "error" && ( - ⚠ {t("about.checkFailed", "Could not check for updates")} - )} - {updateCheckResult.lastChecked && ( - - {t("about.lastChecked", "Last checked")}: {new Date(updateCheckResult.lastChecked).toLocaleString()} + + ⚠ {t("about.checkFailed", "Could not check for updates")} )}
diff --git a/frontend/src/components/AppHeader.tsx b/frontend/src/components/AppHeader.tsx index 622946e..fe06748 100644 --- a/frontend/src/components/AppHeader.tsx +++ b/frontend/src/components/AppHeader.tsx @@ -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(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) { ⚙️ )} - +
+ +
+ + + +
+
{authState?.authEnabled && user && (
+
+ +
+ + + +
+

{t("share.period")}:{" "} diff --git a/frontend/src/hooks/index.ts b/frontend/src/hooks/index.ts index 7015c17..af87b01 100644 --- a/frontend/src/hooks/index.ts +++ b/frontend/src/hooks/index.ts @@ -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"; diff --git a/frontend/src/hooks/useTheme.ts b/frontend/src/hooks/useTheme.ts index 8df4cc6..a13787f 100644 --- a/frontend/src/hooks/useTheme.ts +++ b/frontend/src/hooks/useTheme.ts @@ -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(() => { + const [themePreference, setThemePreferenceState] = useState(() => { 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(() => 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 }; } diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.json index cad2e07..29d7fdc 100644 --- a/frontend/src/i18n/de.json +++ b/frontend/src/i18n/de.json @@ -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", diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.json index b672a10..0b95fbd 100644 --- a/frontend/src/i18n/en.json +++ b/frontend/src/i18n/en.json @@ -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", diff --git a/frontend/src/pages/DashboardPage.tsx b/frontend/src/pages/DashboardPage.tsx index c2440e8..a1e5489 100644 --- a/frontend/src/pages/DashboardPage.tsx +++ b/frontend/src/pages/DashboardPage.tsx @@ -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() {

{t("dashboard.reminders.lastSent")}: - {reminderData.lastSent.medName && ( - {reminderData.lastSent.medName} - )} + {reminderData.lastSent.medName && + (() => { + const medication = meds.find((m) => m.name === reminderData.lastSent!.medName); + return medication ? ( + openMedDetail(medication)}> + {reminderData.lastSent!.medName} + + ) : ( + {reminderData.lastSent!.medName} + ); + })()} {reminderData.lastSent.takenBy && ( ({reminderData.lastSent.takenBy}) )} diff --git a/frontend/src/pages/MedicationsPage.tsx b/frontend/src/pages/MedicationsPage.tsx index 3d1a09a..f698a96 100644 --- a/frontend/src/pages/MedicationsPage.tsx +++ b/frontend/src/pages/MedicationsPage.tsx @@ -526,7 +526,7 @@ export function MedicationsPage() { )} -