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
This commit is contained in:
@@ -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 <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
|
||||
```
|
||||
@@ -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",
|
||||
},
|
||||
});
|
||||
|
||||
Generated
+2
-2
@@ -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",
|
||||
|
||||
@@ -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}",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -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,
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Generated
+2
-2
@@ -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",
|
||||
|
||||
@@ -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">✓ {t("about.upToDate", "You are up to date!")}</span>
|
||||
)}
|
||||
{updateCheckResult.status === "update-available" && (
|
||||
<span className="update-status-text">
|
||||
⬆ {t("about.updateAvailable", "Update available")}:{" "}
|
||||
⬆ {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">
|
||||
⚠ {t("about.checkFailed", "Could not check for updates")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -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)}>
|
||||
|
||||
@@ -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")}:{" "}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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>
|
||||
)}
|
||||
|
||||
@@ -526,7 +526,7 @@ export function MedicationsPage() {
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
<label>
|
||||
<label className="full">
|
||||
{t("form.pillWeight")} ({form.doseUnit})
|
||||
<div className="dose-input-group">
|
||||
<input
|
||||
|
||||
@@ -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> {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
@@ -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();
|
||||
|
||||
@@ -184,6 +184,95 @@ describe("useDoses", () => {
|
||||
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());
|
||||
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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[] = [
|
||||
{
|
||||
@@ -1046,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", () => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -117,7 +117,23 @@ 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;
|
||||
|
||||
Reference in New Issue
Block a user