mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 08:02:12 +00:00
release: v1.32.0 — hardening and scalability (#580)
* release: prepare v1.32.0 * test: stabilize water capture re-entry
This commit is contained in:
1 parent
b01822be48
commit
62eb431d66
372 files changed
+25178
-8561
No files matched your search
@@ -0,0 +1,102 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
medicationIntakeImportJob: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
|
||||
const request = new NextRequest(
|
||||
"http://localhost/api/medications/med-1/intake/import/job-1",
|
||||
);
|
||||
const context = {
|
||||
params: Promise.resolve({ id: "med-1", jobId: "job-1" }),
|
||||
};
|
||||
const session = {
|
||||
session: { id: "session-1", expiresAt: new Date(Date.now() + 60_000) },
|
||||
user: { id: "user-1", username: "owner", role: "USER" as const },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(session as never);
|
||||
});
|
||||
|
||||
describe("GET medication intake import status", () => {
|
||||
it("rejects unauthenticated polling", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
|
||||
const response = await GET(request, context);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(prisma.medicationIntakeImportJob.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses a single owner-and-medication-scoped lookup and hides foreign jobs", async () => {
|
||||
vi.mocked(prisma.medicationIntakeImportJob.findFirst).mockResolvedValue(
|
||||
null,
|
||||
);
|
||||
|
||||
const response = await GET(request, context);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(prisma.medicationIntakeImportJob.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "job-1", medicationId: "med-1", userId: "user-1" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["queued", "running", "done", "failed"])(
|
||||
"returns the owner-visible %s state",
|
||||
async (status) => {
|
||||
vi.mocked(prisma.medicationIntakeImportJob.findFirst).mockResolvedValue({
|
||||
id: "job-1",
|
||||
status,
|
||||
progress: { processed: status === "queued" ? 0 : 2, total: 2 },
|
||||
result: status === "done" ? { imported: 2 } : null,
|
||||
failureReason:
|
||||
status === "failed" ? "Medication intake import failed" : null,
|
||||
createdAt: new Date("2026-07-21T10:00:00.000Z"),
|
||||
startedAt:
|
||||
status === "queued" ? null : new Date("2026-07-21T10:00:01.000Z"),
|
||||
completedAt:
|
||||
status === "done" || status === "failed"
|
||||
? new Date("2026-07-21T10:00:02.000Z")
|
||||
: null,
|
||||
} as never);
|
||||
|
||||
const response = await GET(request, context);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.data).toEqual(
|
||||
expect.objectContaining({
|
||||
jobId: "job-1",
|
||||
status,
|
||||
progress: expect.any(Object),
|
||||
}),
|
||||
);
|
||||
expect(JSON.stringify(body)).not.toContain("user-1");
|
||||
expect(JSON.stringify(body)).not.toContain("med-1");
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiError, apiSuccess } from "@/lib/api-response";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string; jobId: string }>;
|
||||
}
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, { params }: RouteContext) => {
|
||||
const { user } = await requireAuth();
|
||||
const { id: medicationId, jobId } = await params;
|
||||
annotate({
|
||||
action: { name: "medication.intake.import.status" },
|
||||
meta: { job_id: jobId, medication_id: medicationId },
|
||||
});
|
||||
|
||||
const row = await prisma.medicationIntakeImportJob.findFirst({
|
||||
where: { id: jobId, medicationId, userId: user.id },
|
||||
});
|
||||
if (!row) return apiError("Import job not found", 404);
|
||||
|
||||
return apiSuccess({
|
||||
jobId: row.id,
|
||||
status: row.status,
|
||||
progress: row.progress,
|
||||
result: row.result,
|
||||
failureReason: row.failureReason,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
startedAt: row.startedAt?.toISOString() ?? null,
|
||||
completedAt: row.completedAt?.toISOString() ?? null,
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,42 +1,44 @@
|
||||
/**
|
||||
* v1.4.43 W6 — multi-issue 422 envelope on POST
|
||||
* /api/medications/[id]/intake/import. Preserves the
|
||||
* `medication.intake.import.invalid_format` errorCode meta so the CSV
|
||||
* import client UI can branch on the prefix semantics.
|
||||
* Durable medication-intake import kickoff contracts.
|
||||
*
|
||||
* v1.29 perf fix — the per-row `findUnique` duplicate probe was replaced by
|
||||
* one indexed `findMany` existence read over every row's idempotencyKey
|
||||
* before the write loop. `create` + `consumeForIntake` stay per-row.
|
||||
* The request process validates and persists the complete payload, then
|
||||
* returns a polling handle without performing intake writes itself.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
vi.mock("@/lib/db", () => {
|
||||
const prismaMock = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([{ id: "m1" }]),
|
||||
medication: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
medicationIntakeEvent: {
|
||||
findMany: vi.fn(),
|
||||
medicationIntakeImportJob: {
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
auditLog: { create: vi.fn() },
|
||||
},
|
||||
}));
|
||||
};
|
||||
return {
|
||||
prisma: {
|
||||
...prismaMock,
|
||||
$transaction: vi.fn((callback: (tx: typeof prismaMock) => unknown) =>
|
||||
callback(prismaMock),
|
||||
),
|
||||
},
|
||||
toJson: (value: unknown) => value,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/cache/invalidate", () => ({
|
||||
invalidateUserMedications: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/medications/inventory/consumption", () => ({
|
||||
consumeForIntake: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/rollups/medication-compliance-rollups", () => ({
|
||||
recomputeMedicationComplianceForDay: vi.fn().mockResolvedValue(undefined),
|
||||
dayKeyForScheduledFor: vi.fn().mockReturnValue("2026-01-01"),
|
||||
|
||||
vi.mock("@/lib/jobs/boss-instance", () => ({
|
||||
getGlobalBoss: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
@@ -51,18 +53,14 @@ vi.mock("next/headers", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
// (#22) — silent cross-device intake sync. Mocked so the route test can
|
||||
// assert the hook without reaching the APNs senders or the coalescing
|
||||
// timers.
|
||||
vi.mock("@/lib/notifications/medication-intake-sync", () => ({
|
||||
queueMedicationIntakeSync: vi.fn(),
|
||||
}));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { queueMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { consumeForIntake } from "@/lib/medications/inventory/consumption";
|
||||
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
|
||||
import {
|
||||
MEDICATION_INTAKE_IMPORT_QUEUE,
|
||||
MEDICATION_INTAKE_IMPORT_STALE_AFTER_MS,
|
||||
} from "@/lib/jobs/medication-intake-import";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
@@ -79,16 +77,28 @@ function postReq(body: unknown): NextRequest {
|
||||
|
||||
const ROUTE_CTX = { params: Promise.resolve({ id: "m1" }) };
|
||||
|
||||
/** Mirrors the route's own dedup-key derivation for a zaehler-less row. */
|
||||
function keyFor(medId: string, datum: string, uhrzeit: string): string {
|
||||
const takenAt = new Date(`${datum}T${uhrzeit}`);
|
||||
return `import-${medId}-${takenAt.getTime()}`;
|
||||
}
|
||||
const CREATED_JOB = {
|
||||
id: "job-1",
|
||||
status: "queued",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
|
||||
vi.mocked(getGlobalBoss).mockReturnValue({
|
||||
send: vi.fn().mockResolvedValue("boss-1"),
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeImportJob.create).mockResolvedValue(
|
||||
CREATED_JOB as never,
|
||||
);
|
||||
vi.mocked(prisma.medicationIntakeImportJob.update).mockResolvedValue(
|
||||
CREATED_JOB as never,
|
||||
);
|
||||
vi.mocked(prisma.medicationIntakeImportJob.updateMany).mockResolvedValue({
|
||||
count: 0,
|
||||
});
|
||||
vi.mocked(prisma.medicationIntakeImportJob.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
|
||||
id: "m1",
|
||||
userId: "user-1",
|
||||
@@ -176,72 +186,161 @@ describe("POST /api/medications/[id]/intake/import — 422 multi-issue (v1.4.43
|
||||
postReq([{ datum: "not-a-date", uhrzeit: "07:00:00" }]),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
it("rejects an impossible calendar timestamp before creating a job", async () => {
|
||||
const res = await POST(
|
||||
postReq([{ datum: "2026-02-30", uhrzeit: "07:00:00" }]),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
expect(prisma.medicationIntakeImportJob.create).not.toHaveBeenCalled();
|
||||
expect(getGlobalBoss).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/medications/[id]/intake/import — inventory consumption", () => {
|
||||
beforeEach(() => {
|
||||
// Fresh imports: the batched existence read finds no prior rows, and
|
||||
// create echoes an id.
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([]);
|
||||
let n = 0;
|
||||
vi.mocked(prisma.medicationIntakeEvent.create).mockImplementation(
|
||||
(async () => ({ id: `evt-${++n}`, takenAt: new Date() })) as never,
|
||||
);
|
||||
});
|
||||
|
||||
it("consumes stock once per freshly imported taken dose", async () => {
|
||||
describe("POST /api/medications/[id]/intake/import — durable kickoff", () => {
|
||||
it("returns 202 with an owner-pollable job handle", async () => {
|
||||
const res = await POST(
|
||||
postReq([
|
||||
{ datum: "2026-01-01", uhrzeit: "07:00:00" },
|
||||
{ datum: "2026-01-01", uhrzeit: "19:00:00" },
|
||||
{ datum: "2026-01-02", uhrzeit: "07:00:00" },
|
||||
]),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
const body = (await res.json()) as { data: { imported: number } };
|
||||
expect(body.data.imported).toBe(3);
|
||||
expect(consumeForIntake).toHaveBeenCalledTimes(3);
|
||||
const call = vi.mocked(consumeForIntake).mock.calls[0]?.[0];
|
||||
expect(call?.medicationId).toBe("m1");
|
||||
expect(call?.userId).toBe("user-1");
|
||||
expect(call?.eventId).toBe("evt-1");
|
||||
|
||||
// The three-row import reads existence in ONE indexed query, not one
|
||||
// findUnique probe per row.
|
||||
expect(prisma.medicationIntakeEvent.findMany).toHaveBeenCalledTimes(1);
|
||||
const findManyArg = vi.mocked(prisma.medicationIntakeEvent.findMany).mock
|
||||
.calls[0]?.[0] as { where: { idempotencyKey: { in: string[] } } };
|
||||
expect(findManyArg.where.idempotencyKey.in).toHaveLength(3);
|
||||
|
||||
// (#22) — the whole import queues exactly ONE cross-device sync
|
||||
// fan-out, not one per imported row.
|
||||
expect(queueMedicationIntakeSync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not consume for duplicate (already-imported) rows", async () => {
|
||||
// First entry's key is already present — the batched existence read
|
||||
// reports it, the second entry's key is absent (fresh).
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
|
||||
{ idempotencyKey: keyFor("m1", "2026-01-01", "07:00:00") },
|
||||
] as never);
|
||||
const res = await POST(
|
||||
postReq([
|
||||
{ datum: "2026-01-01", uhrzeit: "07:00:00" },
|
||||
{ datum: "2026-01-01", uhrzeit: "07:00:00", zaehler: 41 },
|
||||
{ datum: "2026-01-01", uhrzeit: "19:00:00" },
|
||||
]),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
const body = (await res.json()) as {
|
||||
data: { imported: number; skippedDuplicates: number };
|
||||
|
||||
expect(res.status).toBe(202);
|
||||
await expect(res.json()).resolves.toEqual({
|
||||
data: {
|
||||
jobId: "job-1",
|
||||
status: "queued",
|
||||
statusUrl: "/api/medications/m1/intake/import/job-1/status",
|
||||
},
|
||||
error: null,
|
||||
});
|
||||
|
||||
expect(prisma.medicationIntakeImportJob.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
userId: "user-1",
|
||||
medicationId: "m1",
|
||||
status: "queued",
|
||||
payload: {
|
||||
entries: [
|
||||
{
|
||||
idempotencyKey: "import-m1-41",
|
||||
takenAt: expect.any(String),
|
||||
},
|
||||
{
|
||||
idempotencyKey: expect.stringMatching(/^import-m1-\d+$/),
|
||||
takenAt: expect.any(String),
|
||||
},
|
||||
],
|
||||
},
|
||||
progress: expect.objectContaining({
|
||||
processed: 0,
|
||||
imported: 0,
|
||||
skippedDuplicates: 0,
|
||||
total: 2,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
const boss = vi.mocked(getGlobalBoss).mock.results[0]?.value as {
|
||||
send: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
expect(body.data.imported).toBe(1);
|
||||
expect(body.data.skippedDuplicates).toBe(1);
|
||||
// Only the fresh row consumes — the duplicate never re-creates an event,
|
||||
// so re-import cannot double-decrement.
|
||||
expect(consumeForIntake).toHaveBeenCalledTimes(1);
|
||||
expect(boss.send).toHaveBeenCalledWith(
|
||||
MEDICATION_INTAKE_IMPORT_QUEUE,
|
||||
{ jobId: "job-1" },
|
||||
expect.objectContaining({ retryLimit: expect.any(Number) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails stale abandoned work and admits a replacement job", async () => {
|
||||
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(now);
|
||||
|
||||
try {
|
||||
vi.mocked(prisma.medicationIntakeImportJob.updateMany).mockResolvedValue({
|
||||
count: 1,
|
||||
});
|
||||
|
||||
const res = await POST(
|
||||
postReq([{ datum: "2026-01-01", uhrzeit: "07:00:00" }]),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(202);
|
||||
expect(prisma.medicationIntakeImportJob.updateMany).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({
|
||||
medicationId: "m1",
|
||||
userId: "user-1",
|
||||
status: { in: ["queued", "running"] },
|
||||
OR: expect.arrayContaining([
|
||||
{
|
||||
heartbeatAt: {
|
||||
lt: new Date(
|
||||
now.getTime() - MEDICATION_INTAKE_IMPORT_STALE_AFTER_MS,
|
||||
),
|
||||
},
|
||||
},
|
||||
]),
|
||||
}),
|
||||
data: expect.objectContaining({
|
||||
status: "failed",
|
||||
failureReason: "Medication intake import abandoned",
|
||||
completedAt: now,
|
||||
}),
|
||||
});
|
||||
expect(prisma.medicationIntakeImportJob.create).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a fresh queued or running job as the single active import", async () => {
|
||||
vi.mocked(prisma.medicationIntakeImportJob.findFirst).mockResolvedValue({
|
||||
id: "active-job",
|
||||
status: "running",
|
||||
} as never);
|
||||
|
||||
const res = await POST(
|
||||
postReq([{ datum: "2026-01-01", uhrzeit: "07:00:00" }]),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
await expect(res.json()).resolves.toEqual({
|
||||
data: null,
|
||||
error: "Medication intake import already in progress",
|
||||
});
|
||||
expect(prisma.medicationIntakeImportJob.create).not.toHaveBeenCalled();
|
||||
expect(getGlobalBoss).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("marks enqueue failure terminal and never exposes the queue error", async () => {
|
||||
const queueError = "postgres://queue-user:secret@example.test exploded";
|
||||
const send = vi.fn().mockRejectedValue(new Error(queueError));
|
||||
vi.mocked(getGlobalBoss).mockReturnValue({ send } as never);
|
||||
|
||||
const res = await POST(
|
||||
postReq([{ datum: "2026-01-01", uhrzeit: "07:00:00" }]),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(503);
|
||||
const body = await res.text();
|
||||
expect(body).not.toContain(queueError);
|
||||
expect(body).not.toContain("secret");
|
||||
expect(prisma.medicationIntakeImportJob.update).toHaveBeenCalledWith({
|
||||
where: { id: "job-1" },
|
||||
data: expect.objectContaining({
|
||||
status: "failed",
|
||||
failureReason: "Background worker enqueue failed",
|
||||
completedAt: expect.any(Date),
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,27 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
sanitiseZodIssues,
|
||||
} from "@/lib/api-response";
|
||||
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
|
||||
import { consumeForIntake } from "@/lib/medications/inventory/consumption";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import { queueMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma, toJson } from "@/lib/db";
|
||||
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
|
||||
import {
|
||||
recomputeMedicationComplianceForDay,
|
||||
dayKeyForScheduledFor,
|
||||
} from "@/lib/rollups/medication-compliance-rollups";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
MEDICATION_INTAKE_IMPORT_QUEUE,
|
||||
MEDICATION_INTAKE_IMPORT_SEND_OPTIONS,
|
||||
MEDICATION_INTAKE_IMPORT_STALE_AFTER_MS,
|
||||
type MedicationImportPayload,
|
||||
type MedicationImportProgress,
|
||||
} from "@/lib/jobs/medication-intake-import";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
|
||||
|
||||
const importEntrySchema = z.object({
|
||||
datum: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
@@ -26,7 +29,29 @@ const importEntrySchema = z.object({
|
||||
zaehler: z.union([z.number().int(), z.string()]).optional(),
|
||||
});
|
||||
|
||||
const importSchema = z.array(importEntrySchema).min(1).max(1000);
|
||||
function isValidImportTimestamp(datum: string, uhrzeit: string): boolean {
|
||||
const [year, month, day] = datum.split("-").map(Number);
|
||||
const [hour, minute, second] = uhrzeit.split(":").map(Number);
|
||||
const value = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
|
||||
return (
|
||||
value.getUTCFullYear() === year &&
|
||||
value.getUTCMonth() === month - 1 &&
|
||||
value.getUTCDate() === day &&
|
||||
value.getUTCHours() === hour &&
|
||||
value.getUTCMinutes() === minute &&
|
||||
value.getUTCSeconds() === second
|
||||
);
|
||||
}
|
||||
|
||||
const validatedImportEntrySchema = importEntrySchema.refine(
|
||||
({ datum, uhrzeit }) => isValidImportTimestamp(datum, uhrzeit),
|
||||
{ message: "Invalid date or time" },
|
||||
);
|
||||
|
||||
const validatedImportSchema = z
|
||||
.array(validatedImportEntrySchema)
|
||||
.min(1)
|
||||
.max(1000);
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
@@ -53,7 +78,7 @@ export const POST = apiHandler(
|
||||
? Object.values(body).find((value) => Array.isArray(value))
|
||||
: null;
|
||||
|
||||
const parsed = importSchema.safeParse(payload);
|
||||
const parsed = validatedImportSchema.safeParse(payload);
|
||||
if (!parsed.success) {
|
||||
// v1.4.43 W6 — CSV import; preserve the `Invalid format:` prefix
|
||||
// semantics for the existing client-side branch by setting the
|
||||
@@ -92,161 +117,152 @@ export const POST = apiHandler(
|
||||
}
|
||||
|
||||
const entries = parsed.data;
|
||||
let imported = 0;
|
||||
let skippedDuplicates = 0;
|
||||
let skippedInvalid = 0;
|
||||
// v1.4.39 W-MED — collect distinct day-keys touched by the import
|
||||
// so the rollup pass fires once per day rather than once per row.
|
||||
const touchedDays = new Set<string>();
|
||||
|
||||
// Perf — a CSV import can carry up to 1000 rows; the pre-fix loop ran a
|
||||
// `findUnique` duplicate probe before every single `create`, up to 2000
|
||||
// sequential round trips. Resolve `takenAt` + the dedup key for every
|
||||
// row first, then read every key's existence in ONE indexed query
|
||||
// (`idempotencyKey` carries its own unique index) before the write
|
||||
// loop. `create` + `consumeForIntake` (inventory decrement) stay
|
||||
// per-row — each has a real side effect keyed off the freshly-created
|
||||
// event's id, so they aren't safely batchable without a deeper change
|
||||
// to the inventory-consumption path.
|
||||
interface PreparedIntake {
|
||||
takenAt: Date;
|
||||
idempotencyKey: string;
|
||||
}
|
||||
const prepared: PreparedIntake[] = [];
|
||||
for (const entry of entries) {
|
||||
// Parse as local datetime first; if invalid, fall back to CET offset.
|
||||
let takenAt = new Date(`${entry.datum}T${entry.uhrzeit}`);
|
||||
if (isNaN(takenAt.getTime())) {
|
||||
takenAt = new Date(`${entry.datum}T${entry.uhrzeit}+01:00`);
|
||||
}
|
||||
if (isNaN(takenAt.getTime())) {
|
||||
skippedInvalid++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Prefer explicit counter; otherwise use timestamp-based dedup key.
|
||||
const idempotencyKey = entry.zaehler
|
||||
? `import-${id}-${String(entry.zaehler)}`
|
||||
: `import-${id}-${takenAt.getTime()}`;
|
||||
|
||||
prepared.push({ takenAt, idempotencyKey });
|
||||
}
|
||||
|
||||
const existingRows =
|
||||
prepared.length > 0
|
||||
? await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
idempotencyKey: { in: prepared.map((p) => p.idempotencyKey) },
|
||||
const normalized: MedicationImportPayload = {
|
||||
entries: entries.map((entry) => {
|
||||
const takenAt = new Date(`${entry.datum}T${entry.uhrzeit}`);
|
||||
const idempotencyKey = entry.zaehler
|
||||
? `import-${id}-${String(entry.zaehler)}`
|
||||
: `import-${id}-${takenAt.getTime()}`;
|
||||
return { takenAt: takenAt.toISOString(), idempotencyKey };
|
||||
}),
|
||||
};
|
||||
const progress: MedicationImportProgress = {
|
||||
processed: 0,
|
||||
total: normalized.entries.length,
|
||||
imported: 0,
|
||||
skippedDuplicates: 0,
|
||||
touchedDays: [],
|
||||
rollupProcessed: 0,
|
||||
};
|
||||
const admission = await prisma.$transaction(async (tx) => {
|
||||
await tx.$queryRaw`
|
||||
SELECT "id"
|
||||
FROM "medications"
|
||||
WHERE "id" = ${id}
|
||||
AND "user_id" = ${user.id}
|
||||
FOR UPDATE
|
||||
`;
|
||||
const now = new Date();
|
||||
const staleBefore = new Date(
|
||||
now.getTime() - MEDICATION_INTAKE_IMPORT_STALE_AFTER_MS,
|
||||
);
|
||||
await tx.medicationIntakeImportJob.updateMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
status: { in: ["queued", "running"] },
|
||||
OR: [
|
||||
{ heartbeatAt: { lt: staleBefore } },
|
||||
{
|
||||
heartbeatAt: null,
|
||||
startedAt: { lt: staleBefore },
|
||||
},
|
||||
select: { idempotencyKey: true },
|
||||
})
|
||||
: [];
|
||||
const existingKeys = new Set(
|
||||
existingRows
|
||||
.map((r) => r.idempotencyKey)
|
||||
.filter((k): k is string => k !== null),
|
||||
);
|
||||
{
|
||||
heartbeatAt: null,
|
||||
startedAt: null,
|
||||
createdAt: { lt: staleBefore },
|
||||
},
|
||||
],
|
||||
},
|
||||
data: {
|
||||
status: "failed",
|
||||
failureReason: "Medication intake import abandoned",
|
||||
heartbeatAt: now,
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
const activeJob = await tx.medicationIntakeImportJob.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
status: { in: ["queued", "running"] },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (activeJob) return { active: true as const };
|
||||
|
||||
for (const { takenAt, idempotencyKey } of prepared) {
|
||||
if (existingKeys.has(idempotencyKey)) {
|
||||
skippedDuplicates++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const created = await prisma.medicationIntakeEvent.create({
|
||||
const importJob = await tx.medicationIntakeImportJob.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
scheduledFor: takenAt,
|
||||
takenAt,
|
||||
skipped: false,
|
||||
source: "IMPORT",
|
||||
idempotencyKey,
|
||||
status: "queued",
|
||||
payload: toJson(normalized),
|
||||
progress: toJson(progress),
|
||||
},
|
||||
});
|
||||
imported++;
|
||||
// v1.16.13 — CSV import was the one intake seam that recorded a taken
|
||||
// dose without decrementing tracked stock, so runway / days-left
|
||||
// overstated. Consume exactly like the other taken paths: the stamp on
|
||||
// the freshly-created event makes it exactly-once, the duplicate skip
|
||||
// above means a re-import never re-creates the row (no double-decrement),
|
||||
// and `consumeForIntake` no-ops for as-needed / no-inventory medications.
|
||||
await consumeForIntake({
|
||||
client: prisma,
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
eventId: created.id,
|
||||
intakeAt: created.takenAt ?? takenAt,
|
||||
return { active: false as const, importJob };
|
||||
});
|
||||
if (admission.active) {
|
||||
return apiError("Medication intake import already in progress", 409);
|
||||
}
|
||||
const { importJob } = admission;
|
||||
|
||||
let bossJobId: string | null = null;
|
||||
try {
|
||||
const boss = getGlobalBoss();
|
||||
if (!boss) throw new Error("worker unavailable");
|
||||
bossJobId = await boss.send(
|
||||
MEDICATION_INTAKE_IMPORT_QUEUE,
|
||||
{ jobId: importJob.id },
|
||||
MEDICATION_INTAKE_IMPORT_SEND_OPTIONS,
|
||||
);
|
||||
if (!bossJobId) throw new Error("queue rejected job");
|
||||
await prisma.medicationIntakeImportJob.update({
|
||||
where: { id: importJob.id },
|
||||
data: { pgBossJobId: bossJobId },
|
||||
});
|
||||
touchedDays.add(dayKeyForScheduledFor(takenAt, user.timezone));
|
||||
} catch {
|
||||
const completedAt = new Date();
|
||||
await prisma.medicationIntakeImportJob.update({
|
||||
where: { id: importJob.id },
|
||||
data: {
|
||||
status: "failed",
|
||||
failureReason: "Background worker enqueue failed",
|
||||
heartbeatAt: completedAt,
|
||||
completedAt,
|
||||
},
|
||||
});
|
||||
await auditLog("medication.intake.import.kickoff.denied", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
jobId: importJob.id,
|
||||
medicationId: id,
|
||||
reason: "enqueue_failed",
|
||||
},
|
||||
});
|
||||
return apiError("Background worker is not available", 503);
|
||||
}
|
||||
|
||||
// v1.4.39 W-MED — fold the touched days into rollup rows after the
|
||||
// insert loop completes. Best-effort: a populator failure logs but
|
||||
// never rolls back the imported events.
|
||||
for (const dayKey of touchedDays) {
|
||||
try {
|
||||
await recomputeMedicationComplianceForDay(
|
||||
user.id,
|
||||
id,
|
||||
dayKey,
|
||||
user.timezone,
|
||||
);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
annotate({
|
||||
meta: {
|
||||
medication_compliance_rollup_import_failed: true,
|
||||
medication_compliance_rollup_import_error: message,
|
||||
medication_compliance_rollup_day: dayKey,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// v1.15.20 — imported intakes change every cached medication read
|
||||
// (list, intake caches, compliance payload). This write path was the
|
||||
// one intake surface missing the flush.
|
||||
if (imported > 0) {
|
||||
invalidateUserMedications(user.id, { evict: true });
|
||||
}
|
||||
|
||||
await auditLog("medication.intake.import", {
|
||||
await auditLog("medication.intake.import.kickoff", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
jobId: importJob.id,
|
||||
bossJobId,
|
||||
medicationId: id,
|
||||
imported,
|
||||
skippedDuplicates,
|
||||
skippedInvalid,
|
||||
total: entries.length,
|
||||
total: normalized.entries.length,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.intake.import",
|
||||
name: "medication.intake.import.kickoff",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: {
|
||||
imported,
|
||||
skippedDuplicates,
|
||||
skippedInvalid,
|
||||
total: entries.length,
|
||||
job_id: importJob.id,
|
||||
total: normalized.entries.length,
|
||||
},
|
||||
});
|
||||
|
||||
// (#22) — silent cross-device intake sync: imported rows change the
|
||||
// intake state the user's other iOS devices render. Coalesced per
|
||||
// user, best-effort — never affects the response.
|
||||
if (imported > 0) {
|
||||
queueMedicationIntakeSync({
|
||||
userId: user.id,
|
||||
originDeviceToken: request.headers.get("x-device-id"),
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess({ imported, skippedDuplicates, skippedInvalid }, 201);
|
||||
return apiSuccess(
|
||||
{
|
||||
jobId: importJob.id,
|
||||
status: "queued" as const,
|
||||
statusUrl: `/api/medications/${id}/intake/import/${importJob.id}/status`,
|
||||
},
|
||||
202,
|
||||
);
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user