feat(mental-health): accept client source + externalId with durable dedup

The screener POST hardcoded source=WEB and ignored any client-supplied
externalId, so the native client could not tag provenance and an outbox
replay beyond the 24h idempotency-key window minted duplicate
administrations plus duplicate trend points.

Accept an optional closed source enum (WEB|IOS, default WEB) and an optional
bounded externalId, and persist both. Deduplicate on (userId, externalId)
when present: the route returns the existing administration on replay, and a
partial unique index over (user_id, external_id) WHERE external_id IS NOT
NULL (migration 0221) backstops a concurrent insert race (P2002 resolved to
the winner). The derived *_SCORE measurement keeps its stable per-assessment
externalId, so dedup at the assessment level prevents duplicate trend points.
Item answers stay encrypted and out of AI/MCP/export. Regenerate OpenAPI.
This commit is contained in:
Marc-André Bombeck committed 2026-06-28 19:06:21 +02:00
1 parent e93f74381e
commit 930cb227eb
6 files changed
+250 -32

No files matched your search

+19
View File
@@ -12,6 +12,15 @@ import {
export const assessmentInstrumentEnum = z.enum(["PHQ9", "GAD7"]);
/**
* Client provenance for an administration. Closed enum so the column can never
* carry a free-form label. `WEB` is the in-app questionnaire (the DB default);
* `IOS` is the native client. Distinct from `MeasurementSource` on purpose — a
* screener is questionnaire input, not a device sample, so it keeps its own
* narrow vocabulary.
*/
export const assessmentSourceEnum = z.enum(["WEB", "IOS"]);
const itemAnswer = z.number().int().min(0).max(3);
export const createAssessmentSchema = z
@@ -26,6 +35,16 @@ export const createAssessmentSchema = z
tz: z.string().max(64).optional(),
/** Locale of the validated wording actually presented. */
locale: z.string().max(16).optional(),
/** Client provenance; defaults to WEB. */
source: assessmentSourceEnum.optional().default("WEB"),
/**
* Optional client-supplied idempotency anchor. When present, a repeat with
* the same value returns the existing administration instead of minting a
* duplicate — durable replay protection beyond the 24h idempotency-key
* window (the native client's outbox). Bounded to the 120-char measurement
* externalId cap.
*/
externalId: z.string().min(1).max(120).optional(),
})
.superRefine((val, ctx) => {
const def = INSTRUMENTS[val.instrument as InstrumentId];