feat(mood): add rated mood factors (ingestion + write contract)

Extend the structured mood taxonomy so a tag can carry a magnitude. A
rated factor is a MoodTag of kind RATED that the user scores per entry;
the score persists on MoodEntryTagLink.rating. Binary tags keep
kind BINARY and a null rating, so every existing row and read path stays
byte-identical.

Migration 0119 is additive: four marker columns on mood_tags (kind,
scale_min, scale_max, inverse), a nullable rating on mood_entry_tag_links,
and a seeded factors category with five MVP factors (work, social, sleep
quality, stress, conflict). Stress and conflict are inverse-scaled
(higher means worse); conflict is a 1..2 Yes/No factor.

Write contract: POST /api/mood-entries and the bulk route accept an
optional ratedFactors: [{ key, rating }] array parallel to the binary
tagKeys. The resolver builds the join rows field-by-field, drops unknown
and non-RATED keys silently, and rejects a rating outside the factor's
own scaleMin..scaleMax (422 on the single-entry path, per-entry skipped
on bulk). Create and list responses surface the persisted factors split
from binary keys so a client hydrates without a refetch. GET
/api/mood/tags now emits kind, scaleMin, scaleMax, and inverse so a
client can render factors versus tags.

This is the ingestion half; analytics over rated factors follow later.
Factor labels ship in all six locales.
This commit is contained in:
Marc-André Bombeck committed 2026-06-04 23:09:03 +02:00
1 parent 793602f464
commit 81096b9553
20 files changed
+1100 -43

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
/**
* v1.12.0 — rated mood factors: resolver + write-path unit coverage.
*
* `resolveRatedFactors` resolves catalog keys, drops unknown / non-RATED
* keys, and rejects an out-of-scale rating. `createTagLinks` persists the
* rating onto the join and de-dupes a key passed both as a binary key and
* a rated factor.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
const moodTagFindMany = vi.fn();
const linkCreateMany = vi.fn().mockResolvedValue({ count: 0 });
vi.mock("@/lib/db", () => ({
prisma: {
moodTag: { findMany: (...a: unknown[]) => moodTagFindMany(...a) },
moodEntryTagLink: { createMany: (...a: unknown[]) => linkCreateMany(...a) },
},
}));
import {
resolveRatedFactors,
createTagLinks,
RatedFactorOutOfRangeError,
} from "@/lib/mood/tag-links";
beforeEach(() => {
moodTagFindMany.mockReset();
linkCreateMany.mockReset().mockResolvedValue({ count: 0 });
});
describe("resolveRatedFactors", () => {
it("resolves a valid factor to its catalog id + rating", async () => {
moodTagFindMany.mockResolvedValue([
{ id: "mt_factor_work", key: "factor_work", scaleMin: 1, scaleMax: 5 },
]);
const out = await resolveRatedFactors([{ key: "factor_work", rating: 4 }]);
expect(out).toEqual([{ moodTagId: "mt_factor_work", rating: 4 }]);
});
it("drops unknown / non-RATED keys (catalog is the source of truth)", async () => {
// The query already filters by `kind: 'RATED'` + `isActive`, so an
// unknown / binary key simply doesn't come back.
moodTagFindMany.mockResolvedValue([]);
const out = await resolveRatedFactors([{ key: "happy", rating: 3 }]);
expect(out).toEqual([]);
});
it("rejects a rating above the factor's scaleMax", async () => {
moodTagFindMany.mockResolvedValue([
{
id: "mt_factor_conflict",
key: "factor_conflict",
scaleMin: 1,
scaleMax: 2,
},
]);
await expect(
resolveRatedFactors([{ key: "factor_conflict", rating: 4 }]),
).rejects.toBeInstanceOf(RatedFactorOutOfRangeError);
});
it("rejects a rating below the factor's scaleMin", async () => {
moodTagFindMany.mockResolvedValue([
{ id: "mt_factor_work", key: "factor_work", scaleMin: 1, scaleMax: 5 },
]);
await expect(
resolveRatedFactors([{ key: "factor_work", rating: 0 }]),
).rejects.toBeInstanceOf(RatedFactorOutOfRangeError);
});
it("is a no-op on an empty input", async () => {
const out = await resolveRatedFactors([]);
expect(out).toEqual([]);
expect(moodTagFindMany).not.toHaveBeenCalled();
});
});
describe("createTagLinks with rated factors", () => {
it("persists the rating onto the join row", async () => {
moodTagFindMany.mockResolvedValue([
{ id: "mt_factor_work", key: "factor_work", scaleMin: 1, scaleMax: 5 },
]);
await createTagLinks("entry-1", [], undefined, [
{ key: "factor_work", rating: 5 },
]);
expect(linkCreateMany).toHaveBeenCalledWith(
expect.objectContaining({
data: [{ moodEntryId: "entry-1", moodTagId: "mt_factor_work", rating: 5 }],
}),
);
});
it("propagates the out-of-range error before any write", async () => {
moodTagFindMany.mockResolvedValue([
{
id: "mt_factor_conflict",
key: "factor_conflict",
scaleMin: 1,
scaleMax: 2,
},
]);
await expect(
createTagLinks("entry-1", [], undefined, [
{ key: "factor_conflict", rating: 5 },
]),
).rejects.toBeInstanceOf(RatedFactorOutOfRangeError);
expect(linkCreateMany).not.toHaveBeenCalled();
});
});
+148 -1
View File
@@ -20,6 +20,84 @@ import { prisma } from "@/lib/db";
*/
type TagLinkDb = PrismaClient | Prisma.TransactionClient;
/**
* v1.12.0 — a rated factor as it arrives on the wire: a catalog
* (`mood_tags.key`) + the user's score for this entry.
*/
export interface RatedFactorInput {
key: string;
rating: number;
}
/**
* v1.12.0 — a rated factor resolved to its catalog row id, ready to
* write onto the `mood_entry_tag_links` join.
*/
interface ResolvedRatedFactor {
moodTagId: string;
rating: number;
}
/**
* v1.12.0 — thrown when a submitted factor rating falls outside the
* resolved `MoodTag`'s own `scaleMin..scaleMax`. The route maps this to a
* 422 (the per-tag scale is the real gate; the Zod schema only enforces
* the outer 1..5 envelope). Unknown / non-RATED keys are NOT an error —
* they are dropped silently, matching the binary `tagKeys` posture.
*/
export class RatedFactorOutOfRangeError extends Error {
constructor(
public readonly key: string,
public readonly rating: number,
public readonly scaleMin: number,
public readonly scaleMax: number,
) {
super(
`Rating ${rating} for factor "${key}" is outside its scale ${scaleMin}..${scaleMax}`,
);
this.name = "RatedFactorOutOfRangeError";
}
}
/**
* Resolve rated-factor inputs against the catalog. Unknown keys, inactive
* tags, and `kind = 'BINARY'` keys are dropped silently (the catalog is
* the source of truth, same posture as `resolveTagKeysToIds`). A rating
* outside the resolved tag's `scaleMin..scaleMax` throws
* `RatedFactorOutOfRangeError` so the route returns 422. The last value
* wins on a duplicate key in the same payload.
*/
export async function resolveRatedFactors(
factors: RatedFactorInput[],
db: TagLinkDb = prisma,
): Promise<ResolvedRatedFactor[]> {
if (factors.length === 0) return [];
// Last-writer-wins on a duplicate key in the same submission.
const byKey = new Map<string, number>();
for (const f of factors) byKey.set(f.key, f.rating);
const rows = await db.moodTag.findMany({
where: { key: { in: [...byKey.keys()] }, isActive: true, kind: "RATED" },
select: { id: true, key: true, scaleMin: true, scaleMax: true },
});
const resolved: ResolvedRatedFactor[] = [];
for (const row of rows) {
const rating = byKey.get(row.key);
if (rating === undefined) continue;
if (rating < row.scaleMin || rating > row.scaleMax) {
throw new RatedFactorOutOfRangeError(
row.key,
rating,
row.scaleMin,
row.scaleMax,
);
}
resolved.push({ moodTagId: row.id, rating });
}
return resolved;
}
/**
* Resolve catalog tag keys to ids, dropping unknown / inactive keys.
* Returns the ids in catalog order (deduped).
@@ -40,13 +118,44 @@ export async function resolveTagKeysToIds(
/**
* Create the structured-tag links for a freshly-created entry. No-op on
* an empty / all-unknown key set.
*
* v1.12.0 — optionally also writes rated-factor links (`kind = 'RATED'`
* catalog tags carrying a per-entry `rating`). Binary keys leave `rating`
* NULL; rated factors persist their score. A factor key passed in both
* `keys` and `ratedFactors` resolves to a single link carrying the
* rating (the rated insert wins via `skipDuplicates`, which is why the
* rated rows are written first). Throws `RatedFactorOutOfRangeError` (→
* route 422) when a rating is out of the factor's scale.
*/
export async function createTagLinks(
moodEntryId: string,
keys: string[],
db: TagLinkDb = prisma,
ratedFactors: RatedFactorInput[] = [],
): Promise<void> {
const tagIds = await resolveTagKeysToIds(keys, db);
// Resolve rated factors FIRST so an out-of-range rating aborts before
// any write, and so the rated rows (which carry a value) take priority
// over a bare binary row for the same tag id under `skipDuplicates`.
const resolvedFactors = await resolveRatedFactors(ratedFactors, db);
const ratedTagIds = new Set(resolvedFactors.map((f) => f.moodTagId));
if (resolvedFactors.length > 0) {
await db.moodEntryTagLink.createMany({
// Field-by-field — no mass assignment of the wire object.
data: resolvedFactors.map((f) => ({
moodEntryId,
moodTagId: f.moodTagId,
rating: f.rating,
})),
skipDuplicates: true,
});
}
const tagIds = (await resolveTagKeysToIds(keys, db)).filter(
// A key already written as a rated link is not re-inserted as a
// bare binary row (that would lose the rating to `skipDuplicates`).
(id) => !ratedTagIds.has(id),
);
if (tagIds.length === 0) return;
await db.moodEntryTagLink.createMany({
data: tagIds.map((moodTagId) => ({ moodEntryId, moodTagId })),
@@ -87,3 +196,41 @@ export async function replaceTagLinks(
});
}
}
/**
* v1.12.0 — replace the full rated-factor link set for an entry. A
* changed rating on the same factor is a real change (not a no-op), so
* the simplest correct shape is "delete every RATED link for the entry,
* re-insert the desired set". Binary links are left untouched. Passing an
* empty array clears every rated link. Throws `RatedFactorOutOfRangeError`
* (→ route 422) before any write when a rating is out of scale.
*
* Not wired into a route yet (the POST + bulk ingestion contract is the
* v1.12.0 scope); exported for the PATCH edit path a later wave adds.
*/
export async function replaceRatedFactorLinks(
moodEntryId: string,
factors: RatedFactorInput[],
db: TagLinkDb = prisma,
): Promise<void> {
// Resolve (and range-check) before mutating so an out-of-range rating
// aborts the replace cleanly.
const resolved = await resolveRatedFactors(factors, db);
// Drop every existing RATED link for the entry (a `rating IS NOT NULL`
// row is, by construction, a rated-factor link).
await db.moodEntryTagLink.deleteMany({
where: { moodEntryId, rating: { not: null } },
});
if (resolved.length > 0) {
await db.moodEntryTagLink.createMany({
data: resolved.map((f) => ({
moodEntryId,
moodTagId: f.moodTagId,
rating: f.rating,
})),
skipDuplicates: true,
});
}
}
+25
View File
@@ -83,6 +83,23 @@ export function getScoreForMood(mood: string): number {
// Bounded so a single create can't fan out an unbounded link set.
const structuredTagKeys = z.array(z.string().max(60)).max(30);
// v1.12.0 — rated mood factors. A factor is a catalog `MoodTag` of
// `kind = 'RATED'`; the user scores it per entry, and the score persists
// on `MoodEntryTagLink.rating`. The wire shape is a parallel array to
// `tagKeys` (binary), keeping the binary contract byte-identical and the
// iOS Codable model simple (`[{ key, rating }]`).
//
// The Zod `rating` bound here is the OUTER envelope (1..5 covers every
// seeded factor's scale). The REAL gate is per-tag: after resolving each
// key to its `MoodTag`, the server rejects a rating outside the tag's own
// `scaleMin..scaleMax` (e.g. 1..2 for `factor_conflict`). See
// `resolveRatedFactors` in `src/lib/mood/tag-links.ts`.
const ratedFactor = z.object({
key: z.string().max(60),
rating: z.number().int().min(1).max(5),
});
const ratedFactors = z.array(ratedFactor).max(30);
export const createMoodEntrySchema = z.object({
mood: moodLevelEnum,
tags: z.array(z.string().max(50)).max(20).optional(),
@@ -91,6 +108,11 @@ export const createMoodEntrySchema = z.object({
// unknown keys are dropped silently (the catalog is the source of
// truth, a stale client can't mint a tag).
tagKeys: structuredTagKeys.optional(),
// v1.12.0 — rated factors scored 1..5 (or the factor's own scale).
// Parallel to the binary `tagKeys`; persisted on
// `MoodEntryTagLink.rating`. Out-of-scale or non-RATED keys are
// rejected (422) / dropped server-side per the catalog.
ratedFactors: ratedFactors.optional(),
// v1.4.30 H-5 — first-class free-text note. Replaces the
// `tags: ["note:<text>"]` workaround. Capped at 500 chars so the
// Coach evidence shelf renders cleanly without truncating chips.
@@ -105,6 +127,9 @@ export const updateMoodEntrySchema = z.object({
// v1.8.5 — full replacement of the structured-tag set when present.
// `null` clears every link; omit to leave links untouched.
tagKeys: structuredTagKeys.nullable().optional(),
// v1.12.0 — full replacement of the rated-factor set when present.
// `null` clears every rated link; omit to leave them untouched.
ratedFactors: ratedFactors.nullable().optional(),
note: z.string().max(500).nullable().optional(),
moodLoggedAt: z.iso
.datetime({ offset: true })