fix(medications): identify an imported dose by when it was taken

The intake import built its replay key from the row's optional `zaehler`
field. That reads as a per-row counter — the documented example showed one —
but nothing required it to be unique and nothing checked. A reported export
carried the dose quantity there instead: 1 tablet, on all 28 rows. Every entry
queued under the same key, one dose reached the ledger, and the other 27 came
back reported as duplicates of a dose they had nothing to do with.

The key is the instant now, and `zaehler` is out of the contract rather than
accepted-and-ignored. Nothing is lost by dropping it: the live-row unique on
`(user_id, medication_id, scheduled_for, source)` already makes an imported
dose unique per instant, so a re-import of a file first imported under the old
key still dedups.

The telling is the other half. Two different facts were counted as one number:
entries of a submission that collide with each other, and doses the ledger
already holds. They are separate reasons now, grouped with a count, and the
dialog renders them through the same classifier and the same outcome line as
the CSV and JSON import cards — so an import that wrote nothing can no longer
answer in success tone. That rule shipped for the settings import panel and
this surface was not part of it; the guard now lists every import surface by
path, so a fourth one has to be added deliberately. `skippedInvalid` is gone:
it was hardcoded to zero on every path and reported a capability the importer
never had.

Alongside it, the other half of the environment report — a scheduled job that
fails every run has to say so. `recordError()` increments one unnamed counter,
so the admin status page could show a number and not which queue produced it,
and the module's own screen showed a zero day count with nothing to
distinguish "nothing stored yet" from "every run failed". pg-boss has held the
answer the whole time: a job that exhausts its retries keeps its queue name,
its error and its timestamp. The admin status now names the failing queues
with counts and the last error, the environment overview reports its own
account's failed runs, and neither needed a change at any of the thirty
`recordError()` call sites — a visibility fix that has to be remembered per
call site is the same failure one level up.

Refs #650, #646
This commit is contained in:
Marc-André Bombeck committed 2026-07-26 14:37:57 +02:00
1 parent a8d798442f
commit f0c5b5ae94
27 files changed
+1626 -154

No files matched your search

@@ -28,6 +28,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useAuth } from "@/hooks/use-auth";
import { ConfirmButton } from "@/components/settings/confirm-button";
import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { apiDelete, apiGet, apiPost, apiPut } from "@/lib/api/api-fetch";
import { queryKeys } from "@/lib/query-keys";
@@ -64,6 +65,10 @@ interface EnvironmentOverview {
latestDate: string | null;
latestFetchedAt: string | null;
};
/** Set when the background weather fetch for this account recently gave up.
* A zero day count alone cannot distinguish "nothing to store yet" from
* "every run failed", so the count is never rendered on its own. */
lastFetchFailure: { lastFailedAt: string; failures: number } | null;
attribution: string;
}
@@ -72,7 +77,7 @@ function todayKey(): string {
}
export function EnvironmentSection() {
const { t } = useTranslations();
const { t, tCount } = useTranslations();
const { user } = useAuth();
const queryClient = useQueryClient();
@@ -500,6 +505,22 @@ export function EnvironmentSection() {
})}
</p>
)}
{data?.lastFetchFailure && (
<p
role="status"
data-testid="environment-fetch-failed"
className="text-destructive mt-1 pl-7 text-xs"
>
{tCount(
"settings.sections.environment.fetchFailed",
data.lastFetchFailure.failures,
{
count: data.lastFetchFailure.failures,
when: formatDateTime(data.lastFetchFailure.lastFailedAt),
},
)}
</p>
)}
</SettingsCard>
{/* Attribution (CC BY 4.0, required) */}
@@ -7,6 +7,13 @@
* exactly one key of the outcome table, and no card reaches for them
* directly. A future card that hand-rolls a green tick fails here rather than
* shipping and lying to a self-hoster about their sensor history.
*
* #650 widened it. The medication intake import is a third import surface, in
* another directory, and it was not covered when the rule landed — it kept its
* own success/error tone and reported a run that wrote one row out of
* twenty-eight as a success. "Every import surface" now means every one of
* them, listed by path, so a fourth surface has to be added here deliberately
* rather than inheriting the old behaviour by being somewhere else.
*/
import { describe, it, expect } from "vitest";
import { readFileSync, readdirSync } from "node:fs";
@@ -14,6 +21,34 @@ import { join } from "node:path";
const PANEL_DIR = join(__dirname, "..");
const PRESENTATION_FILE = "import-result-view.tsx";
const REPO_ROOT = join(__dirname, "..", "..", "..", "..", "..");
/**
* Every surface that reports an import result, and the module each one must
* render its outcome through. Paths from the repository root.
*/
const IMPORT_SURFACES: ReadonlyArray<{ path: string; through: RegExp }> = [
{
path: "src/components/settings/import-panel/csv-import-card.tsx",
through: /CsvImportResultView|ImportOutcomeLine/,
},
{
path: "src/components/settings/import-panel/json-import-card.tsx",
through: /CsvImportResultView|ImportOutcomeLine/,
},
{
path: "src/components/settings/import-panel/apple-health-import-card.tsx",
through: /CsvImportResultView|ImportOutcomeLine/,
},
{
path: "src/components/medications/intake-import-result.tsx",
through: /ImportOutcomeLine/,
},
{
path: "src/components/medications/intake-import-dialog.tsx",
through: /IntakeImportResultView/,
},
];
/** The success affordance: the tick component and the success colour token. */
const SUCCESS_MARKERS = ["CheckCircle2", "text-success"] as const;
@@ -25,10 +60,16 @@ function panelSourceFiles(): string[] {
}
/** Code only — a comment naming the marker is prose, not an affordance. */
function stripComments(source: string): string {
return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
}
function readCode(name: string): string {
return readFileSync(join(PANEL_DIR, name), "utf8")
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/^\s*\/\/.*$/gm, "");
return stripComments(readFileSync(join(PANEL_DIR, name), "utf8"));
}
function readRepoCode(relativePath: string): string {
return stripComments(readFileSync(join(REPO_ROOT, relativePath), "utf8"));
}
describe("import panel — success affordance is owned by the outcome table", () => {
@@ -63,13 +104,27 @@ describe("import panel — success affordance is owned by the outcome table", ()
}
});
it("routes every card's result line through the shared outcome line", () => {
for (const name of [
"csv-import-card.tsx",
"json-import-card.tsx",
"apple-health-import-card.tsx",
]) {
expect(readCode(name)).toMatch(/CsvImportResultView|ImportOutcomeLine/);
it("routes every import surface's result line through the shared outcome line", () => {
for (const surface of IMPORT_SURFACES) {
expect(
readRepoCode(surface.path),
`${surface.path} must render its outcome through the shared line`,
).toMatch(surface.through);
}
});
it("keeps the success markers out of every import surface", () => {
const offenders = IMPORT_SURFACES.filter((surface) =>
SUCCESS_MARKERS.some((marker) =>
readRepoCode(surface.path).includes(marker),
),
).map((surface) => surface.path);
expect(
offenders,
offenders.length > 0
? `Import surface(s) hand-rolling the success affordance instead of ` +
`classifying the counts: ${offenders.join(", ")}`
: undefined,
).toEqual([]);
});
});