mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
fix(mood): honour externalId for idempotent re-import on the native entry routes
Migration 0122 added MoodEntry.externalId plus the NULL-distinct @@unique([userId, source, externalId]) and wired the moodLog webhook and sync importer onto it, but the iOS-facing native routes never used it: POST /api/mood-entries dropped externalId entirely (the schema did not declare it) and POST /api/mood-entries/bulk accepted it in its Zod schema yet parsed-and-ignored it, still upserting on the legacy (userId, date, moodLoggedAt) key. The dedup index existed but nothing on the native write path reached it, so the idempotent re-import the client needs was not functional. Declare externalId on createMoodEntrySchema (bounded to match the bulk schema), persist it, and — when present — upsert the single-entry write on (userId, source, externalId) so a re-post with the same id updates the existing row in place instead of 409-ing or minting a duplicate. When absent, keep the legacy first-write create and its 409-on-conflict behaviour untouched. On the bulk path, branch the per-entry probe and upsert onto the same compound key when an entry carries an externalId, refreshing date and moodLoggedAt in the update so a re-zoned re-import lands the corrected wall-clock on the same row; absent ids keep the legacy wall-clock key. Both paths resolve source once so the dedup key and the row write agree. Echo externalId back on the single response (via the row) and on each bulk per-entry result so the client can map server ids onto its local rows. Cover the present-vs-absent upsert key, cross-user isolation, and the echo with unit tests on both routes plus a real-Postgres integration test proving a re-posted externalId resolves to one row updated in place, a null externalId keeps wall-clock behaviour, and the same id under two users stays isolated. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> (cherry picked from commit 6a65de22bc436daeeb73dd2a1cb612336c74a928)
This commit is contained in:
1 parent
53e87ba345
commit
b64f48bce3
6 files changed
+685
-34
No files matched your search
@@ -11,6 +11,10 @@ import { NextRequest } from "next/server";
|
||||
const txClient = {
|
||||
moodEntry: {
|
||||
create: vi.fn(),
|
||||
// v1.12.1 — the create path upserts on `(userId, source, externalId)`
|
||||
// when the body carries a source-stable id, so the tx client must
|
||||
// expose `upsert` too.
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
moodEntryTagLink: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
@@ -392,3 +396,127 @@ describe("POST /api/mood-entries — rated factors (v1.12.0)", () => {
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/mood-entries — externalId idempotent re-import (v1.12.1)", () => {
|
||||
it("upserts on (userId, source, externalId) when externalId is present", async () => {
|
||||
txClient.moodEntry.upsert.mockResolvedValue({
|
||||
id: "mood-ext",
|
||||
tags: null,
|
||||
moodLoggedAt: new Date("2026-06-01T08:00:00.000Z"),
|
||||
mood: "GUT",
|
||||
note: null,
|
||||
source: "MANUAL",
|
||||
externalId: "ios-uuid-1",
|
||||
date: "2026-06-01",
|
||||
});
|
||||
|
||||
const res = await POST(
|
||||
postReq({
|
||||
mood: "GUT",
|
||||
moodLoggedAt: "2026-06-01T08:00:00.000Z",
|
||||
externalId: "ios-uuid-1",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
// The legacy `create` path is NOT taken when externalId is present.
|
||||
expect(txClient.moodEntry.create).not.toHaveBeenCalled();
|
||||
expect(txClient.moodEntry.upsert).toHaveBeenCalledTimes(1);
|
||||
const call = txClient.moodEntry.upsert.mock.calls[0]?.[0] as {
|
||||
where: {
|
||||
userId_source_externalId: {
|
||||
userId: string;
|
||||
source: string;
|
||||
externalId: string;
|
||||
};
|
||||
};
|
||||
create: { externalId: string; source: string };
|
||||
};
|
||||
expect(call.where.userId_source_externalId).toEqual({
|
||||
userId: "user-1",
|
||||
source: "MANUAL",
|
||||
externalId: "ios-uuid-1",
|
||||
});
|
||||
expect(call.create.externalId).toBe("ios-uuid-1");
|
||||
});
|
||||
|
||||
it("echoes externalId back in the create response", async () => {
|
||||
txClient.moodEntry.upsert.mockResolvedValue({
|
||||
id: "mood-ext",
|
||||
tags: null,
|
||||
moodLoggedAt: new Date("2026-06-01T08:00:00.000Z"),
|
||||
mood: "GUT",
|
||||
note: null,
|
||||
source: "MANUAL",
|
||||
externalId: "ios-uuid-2",
|
||||
date: "2026-06-01",
|
||||
});
|
||||
const res = await POST(
|
||||
postReq({
|
||||
mood: "GUT",
|
||||
moodLoggedAt: "2026-06-01T08:00:00.000Z",
|
||||
externalId: "ios-uuid-2",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
const out = (await res.json()) as { data: { externalId: string } };
|
||||
expect(out.data.externalId).toBe("ios-uuid-2");
|
||||
});
|
||||
|
||||
it("threads the upserted source into the dedup key for a non-MANUAL source", async () => {
|
||||
txClient.moodEntry.upsert.mockResolvedValue({
|
||||
id: "mood-ext",
|
||||
tags: null,
|
||||
moodLoggedAt: new Date("2026-06-01T08:00:00.000Z"),
|
||||
mood: "GUT",
|
||||
note: null,
|
||||
source: "DAYLIO",
|
||||
externalId: "daylio-7",
|
||||
date: "2026-06-01",
|
||||
});
|
||||
const res = await POST(
|
||||
postReq({
|
||||
mood: "GUT",
|
||||
moodLoggedAt: "2026-06-01T08:00:00.000Z",
|
||||
source: "DAYLIO",
|
||||
externalId: "daylio-7",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
const call = txClient.moodEntry.upsert.mock.calls[0]?.[0] as {
|
||||
where: { userId_source_externalId: { source: string } };
|
||||
};
|
||||
expect(call.where.userId_source_externalId.source).toBe("DAYLIO");
|
||||
});
|
||||
|
||||
it("falls back to the legacy create when externalId is absent", async () => {
|
||||
txClient.moodEntry.create.mockResolvedValue({
|
||||
id: "mood-legacy",
|
||||
tags: null,
|
||||
moodLoggedAt: new Date("2026-06-01T08:00:00.000Z"),
|
||||
mood: "GUT",
|
||||
note: null,
|
||||
source: "MANUAL",
|
||||
externalId: null,
|
||||
date: "2026-06-01",
|
||||
});
|
||||
const res = await POST(
|
||||
postReq({ mood: "GUT", moodLoggedAt: "2026-06-01T08:00:00.000Z" }),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
expect(txClient.moodEntry.create).toHaveBeenCalledTimes(1);
|
||||
expect(txClient.moodEntry.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an over-long externalId at the Zod layer (422)", async () => {
|
||||
const res = await POST(
|
||||
postReq({
|
||||
mood: "GUT",
|
||||
moodLoggedAt: "2026-06-01T08:00:00.000Z",
|
||||
externalId: "x".repeat(121),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
expect(txClient.moodEntry.upsert).not.toHaveBeenCalled();
|
||||
expect(txClient.moodEntry.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -265,6 +265,112 @@ describe("POST /api/mood-entries/bulk — structured tagKeys (v1.12.0)", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("dedups on (userId, source, externalId) when an entry carries externalId", async () => {
|
||||
vi.mocked(prisma.moodEntry.findUnique).mockResolvedValue(null as never);
|
||||
vi.mocked(prisma.moodEntry.upsert).mockResolvedValue({
|
||||
id: "entry-ext",
|
||||
} as never);
|
||||
const res = await POST(
|
||||
postReq({
|
||||
entries: [
|
||||
{
|
||||
mood: "GUT",
|
||||
moodLoggedAt: "2026-05-16T08:00:00.000Z",
|
||||
externalId: "ios-uuid-1",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: { inserted: number; entries: Array<{ externalId?: string }> };
|
||||
};
|
||||
expect(json.data.inserted).toBe(1);
|
||||
// The probe + upsert both key on the externalId compound, not the
|
||||
// legacy wall-clock tuple.
|
||||
const probeWhere = vi.mocked(prisma.moodEntry.findUnique).mock.calls[0]?.[0]
|
||||
?.where as Record<string, unknown>;
|
||||
expect(probeWhere).toHaveProperty("userId_source_externalId");
|
||||
const upsertArg = vi.mocked(prisma.moodEntry.upsert).mock.calls[0]?.[0] as {
|
||||
where: Record<string, unknown>;
|
||||
create: { externalId: string | null; source: string };
|
||||
};
|
||||
expect(upsertArg.where).toHaveProperty("userId_source_externalId");
|
||||
expect(upsertArg.create.externalId).toBe("ios-uuid-1");
|
||||
// The per-entry result echoes the externalId back for iOS hydration.
|
||||
expect(json.data.entries[0].externalId).toBe("ios-uuid-1");
|
||||
});
|
||||
|
||||
it("uses the legacy wall-clock key and omits externalId when none is sent", async () => {
|
||||
vi.mocked(prisma.moodEntry.findUnique).mockResolvedValue(null as never);
|
||||
vi.mocked(prisma.moodEntry.upsert).mockResolvedValue({
|
||||
id: "entry-legacy",
|
||||
} as never);
|
||||
const res = await POST(
|
||||
postReq({
|
||||
entries: [{ mood: "OKAY", moodLoggedAt: "2026-05-16T08:00:00.000Z" }],
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: { entries: Array<{ externalId?: string }> };
|
||||
};
|
||||
const probeWhere = vi.mocked(prisma.moodEntry.findUnique).mock.calls[0]?.[0]
|
||||
?.where as Record<string, unknown>;
|
||||
expect(probeWhere).toHaveProperty("userId_date_moodLoggedAt");
|
||||
expect(json.data.entries[0].externalId).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reports a re-posted externalId entry as a duplicate (idempotent)", async () => {
|
||||
// Probe finds the row → the response classifies it duplicate, not
|
||||
// inserted, and the upsert update branch refreshes it in place.
|
||||
vi.mocked(prisma.moodEntry.findUnique).mockResolvedValue({
|
||||
id: "entry-ext",
|
||||
} as never);
|
||||
vi.mocked(prisma.moodEntry.upsert).mockResolvedValue({
|
||||
id: "entry-ext",
|
||||
} as never);
|
||||
const res = await POST(
|
||||
postReq({
|
||||
entries: [
|
||||
{
|
||||
mood: "SUPER_GUT",
|
||||
moodLoggedAt: "2026-05-16T08:00:00.000Z",
|
||||
externalId: "ios-uuid-1",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: { inserted: number; duplicates: number };
|
||||
};
|
||||
expect(json.data.inserted).toBe(0);
|
||||
expect(json.data.duplicates).toBe(1);
|
||||
const upsertArg = vi.mocked(prisma.moodEntry.upsert).mock.calls[0]?.[0] as {
|
||||
update: Record<string, unknown>;
|
||||
};
|
||||
// The externalId update branch also refreshes date + moodLoggedAt.
|
||||
expect(upsertArg.update).toHaveProperty("date");
|
||||
expect(upsertArg.update).toHaveProperty("moodLoggedAt");
|
||||
});
|
||||
|
||||
it("rejects an over-long externalId at the Zod boundary (422)", async () => {
|
||||
const res = await POST(
|
||||
postReq({
|
||||
entries: [
|
||||
{
|
||||
mood: "OKAY",
|
||||
moodLoggedAt: "2026-05-16T08:00:00.000Z",
|
||||
externalId: "x".repeat(121),
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
expect(prisma.moodEntry.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("marks the single entry skipped (not the batch) on an out-of-scale rating", async () => {
|
||||
const { RatedFactorOutOfRangeError } = await import("@/lib/mood/tag-links");
|
||||
// First entry's factor write throws; the loop catch records it skipped.
|
||||
|
||||
@@ -106,6 +106,10 @@ interface EntryResult {
|
||||
status: EntryStatus;
|
||||
reason?: string;
|
||||
id?: string;
|
||||
// v1.12.1 — echo the client-supplied source-stable id back on each
|
||||
// result so iOS can map a server row id onto its local SwiftData row
|
||||
// without re-deriving it. Omitted when the entry sent no externalId.
|
||||
externalId?: string;
|
||||
}
|
||||
|
||||
export const POST = apiHandler(withIdempotency<[NextRequest]>(postBulk));
|
||||
@@ -185,30 +189,43 @@ async function postBulk(request: NextRequest): Promise<Response> {
|
||||
const score = getScoreForMood(entry.mood);
|
||||
|
||||
try {
|
||||
// v1.12.1 — when the entry carries a source-stable `externalId`,
|
||||
// dedup on the NULL-distinct `(userId, source, externalId)` key so a
|
||||
// re-post with the same id (an iOS retry after a network hiccup, or a
|
||||
// second adopt-on-pair backfill) updates the existing row in place
|
||||
// instead of minting a duplicate when `moodLoggedAt` re-rounds /
|
||||
// re-zones. Absent → the legacy `(userId, date, moodLoggedAt)` key.
|
||||
// `source` carries a schema default of "MANUAL"; resolve it once so
|
||||
// the probe, upsert key, and create write all agree on the value.
|
||||
const resolvedSource = entry.source;
|
||||
const probeWhere = entry.externalId
|
||||
? {
|
||||
userId_source_externalId: {
|
||||
userId: user.id,
|
||||
source: resolvedSource,
|
||||
externalId: entry.externalId,
|
||||
},
|
||||
}
|
||||
: {
|
||||
userId_date_moodLoggedAt: {
|
||||
userId: user.id,
|
||||
date,
|
||||
moodLoggedAt: entry.moodLoggedAt,
|
||||
},
|
||||
};
|
||||
|
||||
// Probe-then-upsert so the response reliably distinguishes
|
||||
// "inserted" from "duplicate". Two round-trips per entry is
|
||||
// acceptable given the 500-entry cap; a more cache-friendly
|
||||
// shape (batched probe) is a v1.4.31 optimisation if the cap
|
||||
// grows.
|
||||
const existing = await prisma.moodEntry.findUnique({
|
||||
where: {
|
||||
userId_date_moodLoggedAt: {
|
||||
userId: user.id,
|
||||
date,
|
||||
moodLoggedAt: entry.moodLoggedAt,
|
||||
},
|
||||
},
|
||||
where: probeWhere,
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const result = await prisma.moodEntry.upsert({
|
||||
where: {
|
||||
userId_date_moodLoggedAt: {
|
||||
userId: user.id,
|
||||
date,
|
||||
moodLoggedAt: entry.moodLoggedAt,
|
||||
},
|
||||
},
|
||||
where: probeWhere,
|
||||
create: {
|
||||
userId: user.id,
|
||||
date,
|
||||
@@ -217,17 +234,24 @@ async function postBulk(request: NextRequest): Promise<Response> {
|
||||
score,
|
||||
tags: entry.tags ? JSON.stringify(entry.tags) : null,
|
||||
note: entry.note ?? null,
|
||||
source: entry.source,
|
||||
source: resolvedSource,
|
||||
externalId: entry.externalId ?? null,
|
||||
moodLoggedAt: entry.moodLoggedAt,
|
||||
},
|
||||
update: {
|
||||
// Last-writer-wins on the mood + tags + note triple. The
|
||||
// iOS client only re-posts an existing entry when it has
|
||||
// new data; the server trusts that decision.
|
||||
// new data; the server trusts that decision. When the dedup
|
||||
// key is `externalId`, also refresh `date` / `moodLoggedAt`
|
||||
// so a re-zoned re-import lands the corrected wall-clock on
|
||||
// the same row.
|
||||
mood: entry.mood,
|
||||
score,
|
||||
tags: entry.tags ? JSON.stringify(entry.tags) : null,
|
||||
note: entry.note ?? null,
|
||||
...(entry.externalId
|
||||
? { date, moodLoggedAt: entry.moodLoggedAt }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -258,16 +282,31 @@ async function postBulk(request: NextRequest): Promise<Response> {
|
||||
|
||||
if (existing) {
|
||||
duplicates += 1;
|
||||
results.push({ index: i, status: "duplicate", id: result.id });
|
||||
results.push({
|
||||
index: i,
|
||||
status: "duplicate",
|
||||
id: result.id,
|
||||
...(entry.externalId ? { externalId: entry.externalId } : {}),
|
||||
});
|
||||
} else {
|
||||
inserted += 1;
|
||||
results.push({ index: i, status: "inserted", id: result.id });
|
||||
results.push({
|
||||
index: i,
|
||||
status: "inserted",
|
||||
id: result.id,
|
||||
...(entry.externalId ? { externalId: entry.externalId } : {}),
|
||||
});
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const reason =
|
||||
err instanceof Error ? err.message.slice(0, 120) : "upsert_failed";
|
||||
skipped.push({ index: i, reason });
|
||||
results.push({ index: i, status: "skipped", reason });
|
||||
results.push({
|
||||
index: i,
|
||||
status: "skipped",
|
||||
reason,
|
||||
...(entry.externalId ? { externalId: entry.externalId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -173,8 +173,16 @@ async function postMoodEntry(request: NextRequest) {
|
||||
return returnAllZodIssues(parsed.error, 422);
|
||||
}
|
||||
|
||||
const { mood, tags, tagKeys, ratedFactors, note, moodLoggedAt, source } =
|
||||
parsed.data;
|
||||
const {
|
||||
mood,
|
||||
tags,
|
||||
tagKeys,
|
||||
ratedFactors,
|
||||
note,
|
||||
moodLoggedAt,
|
||||
source,
|
||||
externalId,
|
||||
} = parsed.data;
|
||||
// v1.4.25 W7b (Decision A) — anchor the `date` string to the user's
|
||||
// current displayTimezone and store the resolved zone on the row.
|
||||
// Legacy rows with `tz IS NULL` continue to read as Europe/Berlin
|
||||
@@ -182,6 +190,10 @@ async function postMoodEntry(request: NextRequest) {
|
||||
const tz = user.timezone ?? DEFAULT_TIMEZONE;
|
||||
const date = moodDateKey(moodLoggedAt, tz);
|
||||
const score = getScoreForMood(mood);
|
||||
// v1.12.1 — `source` carries a schema default of "MANUAL"; resolve it
|
||||
// once so the externalId upsert key (`(userId, source, externalId)`)
|
||||
// and the row write agree on the exact value.
|
||||
const resolvedSource = source ?? "MANUAL";
|
||||
|
||||
try {
|
||||
// v1.8.5 — write the entry and its structured-tag links in one
|
||||
@@ -191,19 +203,57 @@ async function postMoodEntry(request: NextRequest) {
|
||||
// through the helper so both writes commit (or abort) together.
|
||||
const { entry, persistedTagKeys, persistedRatedFactors } =
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const created = await tx.moodEntry.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
date,
|
||||
tz,
|
||||
mood,
|
||||
score,
|
||||
tags: tags ? JSON.stringify(tags) : null,
|
||||
note: note ?? null,
|
||||
source: source ?? "MANUAL",
|
||||
moodLoggedAt,
|
||||
},
|
||||
});
|
||||
// v1.12.1 — when the client supplies a source-stable `externalId`,
|
||||
// upsert on the NULL-distinct `(userId, source, externalId)` key so
|
||||
// a re-post with the same id updates the existing row in place
|
||||
// (idempotent re-import) instead of minting a duplicate or 409-ing.
|
||||
// Without an `externalId`, fall back to the legacy first-write
|
||||
// `create` exactly as before — a same-tuple re-post then trips the
|
||||
// `(userId, date, moodLoggedAt)` unique and surfaces as a 409 below.
|
||||
const created = externalId
|
||||
? await tx.moodEntry.upsert({
|
||||
where: {
|
||||
userId_source_externalId: {
|
||||
userId: user.id,
|
||||
source: resolvedSource,
|
||||
externalId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
date,
|
||||
tz,
|
||||
mood,
|
||||
score,
|
||||
tags: tags ? JSON.stringify(tags) : null,
|
||||
note: note ?? null,
|
||||
source: resolvedSource,
|
||||
externalId,
|
||||
moodLoggedAt,
|
||||
},
|
||||
update: {
|
||||
date,
|
||||
tz,
|
||||
mood,
|
||||
score,
|
||||
tags: tags ? JSON.stringify(tags) : null,
|
||||
note: note ?? null,
|
||||
moodLoggedAt,
|
||||
},
|
||||
})
|
||||
: await tx.moodEntry.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
date,
|
||||
tz,
|
||||
mood,
|
||||
score,
|
||||
tags: tags ? JSON.stringify(tags) : null,
|
||||
note: note ?? null,
|
||||
source: resolvedSource,
|
||||
moodLoggedAt,
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
(tagKeys && tagKeys.length > 0) ||
|
||||
|
||||
Reference in new issue
Block a user