mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
feat(mood): derive pleasantness on every write path
- one helper resolves the level-A values for a write; the five writers call it instead of carrying their own copy of the derivation - the create schema takes a1 to a5, and a value the user set wins over the derived one; the batch request shape is untouched - both arms of both upserts restate the values, so a re-post cannot leave a stale reading beside a mood that has since changed - the JSON import derives from the row's own label rather than the file's score, which is the one place the two can disagree - correcting an entry's label re-derives pleasantness the way it re-derives the score; an explicit null takes an answer back - a round trip through all five writers against real Postgres asserts the rows agree and that nothing invents the other four values
This commit is contained in:
1 parent
ad4f5c04f0
commit
a1c78eceef
9 files changed
+555
-1
No files matched your search
@@ -0,0 +1,343 @@
|
||||
/**
|
||||
* v1.37 — every mood writer resolves the same pleasantness value.
|
||||
*
|
||||
* Five paths write a `MoodEntry`, and only one of them is the web form. If
|
||||
* the derivation lived at the call site, a mood tapped in a chat and the same
|
||||
* mood typed into the form would drift apart the first time one of the five
|
||||
* was edited without the others. This test posts the identical mood through
|
||||
* all five and asserts the rows agree, against real Postgres and the real
|
||||
* handlers:
|
||||
*
|
||||
* 1. POST /api/mood-entries (web + iOS single)
|
||||
* 2. POST /api/mood-entries/bulk (iOS backfill)
|
||||
* 3. logTelegramMood (the bot)
|
||||
* 4. POST /api/import (JSON restore)
|
||||
* 5. logMcpMood (the assistant tool)
|
||||
*
|
||||
* It also pins the three rules the columns exist for: a re-post refreshes the
|
||||
* value rather than leaving a stale one beside a fresh mood, an explicit
|
||||
* client value beats the derivation, and nothing ever invents A2 to A5.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { cookieJar } from "./mock-next-headers";
|
||||
import { getPrismaClient, truncateAllTables } from "./setup";
|
||||
|
||||
const USER = "user-mood-writers-agree";
|
||||
|
||||
vi.mock("next/headers", async () => {
|
||||
const { cookieJar, headerJar } = await import("./mock-next-headers");
|
||||
return {
|
||||
headers: vi.fn(async () => ({
|
||||
get: (name: string) => headerJar.get(name.toLowerCase()) ?? null,
|
||||
})),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: (name: string) => {
|
||||
const value = cookieJar.get(name);
|
||||
return value ? { name, value } : undefined;
|
||||
},
|
||||
set: (name: string, value: string) => {
|
||||
cookieJar.set(name, value);
|
||||
},
|
||||
delete: (name: string) => {
|
||||
cookieJar.delete(name);
|
||||
},
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
async function createUserSession() {
|
||||
await getPrismaClient().user.create({
|
||||
data: {
|
||||
id: USER,
|
||||
username: "mood-writers-agree",
|
||||
email: "mood-writers-agree@example.test",
|
||||
timezone: "Europe/Berlin",
|
||||
},
|
||||
});
|
||||
const session = await getPrismaClient().session.create({
|
||||
data: {
|
||||
userId: USER,
|
||||
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
cookieJar.set("healthlog_session", session.id);
|
||||
}
|
||||
|
||||
function jsonRequest(path: string, body: unknown): NextRequest {
|
||||
return new NextRequest(`http://localhost${path}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await truncateAllTables(getPrismaClient());
|
||||
cookieJar.clear();
|
||||
});
|
||||
|
||||
describe("mood writers agree on the derived level-A value", () => {
|
||||
it("writes the same moodA1 through all five writers for the same mood", async () => {
|
||||
await createUserSession();
|
||||
|
||||
const { POST: postSingle } = await import("@/app/api/mood-entries/route");
|
||||
const { POST: postBulk } =
|
||||
await import("@/app/api/mood-entries/bulk/route");
|
||||
const { POST: postImport } = await import("@/app/api/import/route");
|
||||
const { logTelegramMood } = await import("@/lib/mood/create-from-telegram");
|
||||
const { logMcpMood } = await import("@/lib/mcp/writes");
|
||||
|
||||
// 1 — single create.
|
||||
const single = await postSingle(
|
||||
jsonRequest("/api/mood-entries", {
|
||||
mood: "GUT",
|
||||
moodLoggedAt: "2026-05-16T08:00:00.000Z",
|
||||
externalId: "writer-single",
|
||||
}),
|
||||
);
|
||||
expect(single.status).toBe(201);
|
||||
|
||||
// 2 — bulk backfill. The request shape carries no level-A field; the
|
||||
// server derives it, which is the whole point of this phase being
|
||||
// invisible on the wire.
|
||||
const bulk = await postBulk(
|
||||
jsonRequest("/api/mood-entries/bulk", {
|
||||
entries: [
|
||||
{
|
||||
mood: "GUT",
|
||||
moodLoggedAt: "2026-05-16T09:00:00.000Z",
|
||||
externalId: "writer-bulk",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(bulk.status).toBe(200);
|
||||
|
||||
// 3 — the bot. Its input is the 1-5 score; it resolves the label itself.
|
||||
const telegram = await logTelegramMood({
|
||||
userId: USER,
|
||||
score: 4,
|
||||
tz: "Europe/Berlin",
|
||||
externalId: "telegram:mood:1:2:4",
|
||||
});
|
||||
expect(telegram.created).toBe(true);
|
||||
|
||||
// 4 — the JSON import. Deliberately carries a `score` that disagrees with
|
||||
// its own label: this is the one writer whose score comes out of the file
|
||||
// rather than out of the label, and the self-assessment column has to
|
||||
// follow the label the user picked, not the number the file asserts.
|
||||
const imported = await postImport(
|
||||
jsonRequest("/api/import", {
|
||||
moodEntries: [
|
||||
{
|
||||
date: "2026-05-16",
|
||||
mood: "GUT",
|
||||
score: 2,
|
||||
loggedAt: "2026-05-16T10:00:00.000Z",
|
||||
externalId: "writer-import",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(imported.status).toBe(200);
|
||||
|
||||
// 5 — the assistant tool.
|
||||
const mcp = await logMcpMood({
|
||||
userId: USER,
|
||||
score: 4,
|
||||
tz: "Europe/Berlin",
|
||||
idempotencyKey: "writer-mcp-1",
|
||||
});
|
||||
expect(mcp.status).toBe("written");
|
||||
|
||||
const rows = await getPrismaClient().moodEntry.findMany({
|
||||
where: { userId: USER },
|
||||
orderBy: { source: "asc" },
|
||||
select: {
|
||||
source: true,
|
||||
mood: true,
|
||||
score: true,
|
||||
moodA1: true,
|
||||
stressA2: true,
|
||||
energyA3: true,
|
||||
connectionA4: true,
|
||||
stabilityA5: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Five writers, five rows — and one of them is the bulk path, which must
|
||||
// not have been folded into the single path's row.
|
||||
expect(rows).toHaveLength(5);
|
||||
expect(rows.map((r) => r.source).sort()).toEqual([
|
||||
"IMPORT",
|
||||
"MANUAL",
|
||||
"MANUAL",
|
||||
"MCP",
|
||||
"TELEGRAM",
|
||||
]);
|
||||
|
||||
for (const row of rows) {
|
||||
expect(row.mood).toBe("GUT");
|
||||
// GUT sits at 7 on the level-A scale. Asserted by value on every row,
|
||||
// not by comparing the rows to each other: five rows agreeing on a
|
||||
// wrong number would pass a same-value assertion.
|
||||
expect(row.moodA1).toBe(7);
|
||||
// Nothing derives the other four, on any path.
|
||||
expect(row.stressA2).toBeNull();
|
||||
expect(row.energyA3).toBeNull();
|
||||
expect(row.connectionA4).toBeNull();
|
||||
expect(row.stabilityA5).toBeNull();
|
||||
}
|
||||
|
||||
// The imported row keeps the file's own score while its level-A value
|
||||
// follows the label — the disagreement the file carried is not copied
|
||||
// into the new column.
|
||||
const importedRow = rows.find((r) => r.source === "IMPORT");
|
||||
expect(importedRow?.score).toBe(2);
|
||||
expect(importedRow?.moodA1).toBe(7);
|
||||
});
|
||||
|
||||
it("refreshes moodA1 when an externalId is re-posted with a different mood", async () => {
|
||||
await createUserSession();
|
||||
const { POST: postSingle } = await import("@/app/api/mood-entries/route");
|
||||
const { POST: postBulk } =
|
||||
await import("@/app/api/mood-entries/bulk/route");
|
||||
|
||||
await postSingle(
|
||||
jsonRequest("/api/mood-entries", {
|
||||
mood: "LAUSIG",
|
||||
moodLoggedAt: "2026-05-16T08:00:00.000Z",
|
||||
externalId: "repost-single",
|
||||
}),
|
||||
);
|
||||
await postSingle(
|
||||
jsonRequest("/api/mood-entries", {
|
||||
mood: "SUPER_GUT",
|
||||
moodLoggedAt: "2026-05-16T08:10:00.000Z",
|
||||
externalId: "repost-single",
|
||||
}),
|
||||
);
|
||||
|
||||
await postBulk(
|
||||
jsonRequest("/api/mood-entries/bulk", {
|
||||
entries: [
|
||||
{
|
||||
mood: "LAUSIG",
|
||||
moodLoggedAt: "2026-05-16T11:00:00.000Z",
|
||||
externalId: "repost-bulk",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
await postBulk(
|
||||
jsonRequest("/api/mood-entries/bulk", {
|
||||
entries: [
|
||||
{
|
||||
mood: "SUPER_GUT",
|
||||
moodLoggedAt: "2026-05-16T11:10:00.000Z",
|
||||
externalId: "repost-bulk",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const rows = await getPrismaClient().moodEntry.findMany({
|
||||
where: { userId: USER },
|
||||
orderBy: { externalId: "asc" },
|
||||
select: { externalId: true, mood: true, score: true, moodA1: true },
|
||||
});
|
||||
|
||||
// One row per externalId — the re-post updated in place, as before.
|
||||
expect(rows).toHaveLength(2);
|
||||
for (const row of rows) {
|
||||
expect(row.mood).toBe("SUPER_GUT");
|
||||
expect(row.score).toBe(5);
|
||||
// The update arm of both upserts restates the value. Without it the row
|
||||
// would carry LAUSIG's 1 beside SUPER_GUT's 5.
|
||||
expect(row.moodA1).toBe(9);
|
||||
}
|
||||
});
|
||||
|
||||
it("lets an explicit client value win over the derivation, and stores the other four literally", async () => {
|
||||
await createUserSession();
|
||||
const { POST: postSingle } = await import("@/app/api/mood-entries/route");
|
||||
|
||||
const res = await postSingle(
|
||||
jsonRequest("/api/mood-entries", {
|
||||
mood: "OKAY",
|
||||
moodLoggedAt: "2026-05-16T12:00:00.000Z",
|
||||
// A day that felt middling overall but was genuinely stressful: the
|
||||
// whole reason five values beat one.
|
||||
a1: 4,
|
||||
a2: 9,
|
||||
a3: 2,
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
const json = (await res.json()) as {
|
||||
data: { a1: number; a2: number; a3: number; a4: null; a5: null };
|
||||
};
|
||||
// The response echoes the values under the keys the request used.
|
||||
expect(json.data.a1).toBe(4);
|
||||
expect(json.data.a2).toBe(9);
|
||||
expect(json.data.a5).toBeNull();
|
||||
|
||||
const row = await getPrismaClient().moodEntry.findFirstOrThrow({
|
||||
where: { userId: USER },
|
||||
});
|
||||
// Not 5 — OKAY's derived value lost to the number the user set.
|
||||
expect(row.moodA1).toBe(4);
|
||||
// Stored literally, higher meaning more stress. A value flipped on the
|
||||
// way in could never be recovered.
|
||||
expect(row.stressA2).toBe(9);
|
||||
expect(row.energyA3).toBe(2);
|
||||
// Untouched sliders write nothing at all.
|
||||
expect(row.connectionA4).toBeNull();
|
||||
expect(row.stabilityA5).toBeNull();
|
||||
// The five-point axis is untouched by any of this.
|
||||
expect(row.score).toBe(3);
|
||||
});
|
||||
|
||||
it("re-derives A1 when an entry's mood is corrected, and clears a value on an explicit null", async () => {
|
||||
await createUserSession();
|
||||
const { POST: postSingle } = await import("@/app/api/mood-entries/route");
|
||||
const { PUT } = await import("@/app/api/mood-entries/[id]/route");
|
||||
|
||||
const created = await postSingle(
|
||||
jsonRequest("/api/mood-entries", {
|
||||
mood: "SCHLECHT",
|
||||
moodLoggedAt: "2026-05-16T13:00:00.000Z",
|
||||
a2: 8,
|
||||
}),
|
||||
);
|
||||
const createdJson = (await created.json()) as { data: { id: string } };
|
||||
const id = createdJson.data.id;
|
||||
|
||||
const corrected = await PUT(
|
||||
new NextRequest(`http://localhost/api/mood-entries/${id}`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ mood: "GUT", a2: null }),
|
||||
}),
|
||||
{ params: Promise.resolve({ id }) },
|
||||
);
|
||||
expect(corrected.status).toBe(200);
|
||||
|
||||
const row = await getPrismaClient().moodEntry.findUniqueOrThrow({
|
||||
where: { id },
|
||||
});
|
||||
expect(row.mood).toBe("GUT");
|
||||
expect(row.score).toBe(4);
|
||||
// The label moved, so pleasantness moved with it — the same way `score`
|
||||
// does. A stale 3 here would contradict the entry's own label.
|
||||
expect(row.moodA1).toBe(7);
|
||||
// An explicit null takes back an answer.
|
||||
expect(row.stressA2).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user