fix(3b): delad kompletteringsväg för legacy /cook + deterministiska cooking-assumptions

- cookRecipeInputSchema utökas med actualPortionsEaten, leftoverEstimatePortions, leftoverNote
- completeCookingSession-wrapper i apps/api/src/lib/cooking.ts hanterar summavalidering,
  persistens av svar, profiluppdateringar och analytics (started+completed) för båda vägarna
- Legacy POST /v1/recipes/:id/cook använder wrappern med emitStartedEvent
- GET /v1/recipes/:id/cooking-assumptions väljer deterministiskt bland icke-valfria ingredienser
- i18n: nyckel cooked.portionsSumExceedsPlanned i samtliga 12 lokaler + server-i18n
- Nya tester för legacy /cook och cooking-assumptions med valfri första ingrediens

Refs: steg 3b-fix, granskningsrunda 2026-08-07
This commit is contained in:
Sven (AAMOS AI)
2026-08-07 05:13:35 +07:00
parent e46281b9b5
commit bbe7526ef3
18 changed files with 457 additions and 162 deletions
+27 -115
View File
@@ -1,5 +1,5 @@
import type { FastifyInstance } from "fastify";
import { and, eq, lt } from "drizzle-orm";
import { and, eq, inArray, lt } from "drizzle-orm";
import { schema, markMilestone } from "@app/database";
import {
cookingSessionStartInputSchema,
@@ -8,14 +8,9 @@ import {
} from "@app/validation";
import { errors, parse } from "../lib/errors.js";
import { requireActiveHousehold, requireMembership } from "../lib/helpers.js";
import {
cookingSessionStarted,
cookingSessionCompleted,
cookingSessionCancelled,
} from "@app/analytics";
import { cookingSessionStarted, cookingSessionCancelled } from "@app/analytics";
import { trackProductAnalytics } from "../lib/helpers.js";
import { completeCookingSessionCore } from "../lib/cooking.js";
import { updateCookingAssumptionProfile } from "@app/inventory-engine";
import { completeCookingSession } from "../lib/cooking.js";
import { z } from "zod";
/**
@@ -137,8 +132,8 @@ export async function cookingSessionRoutes(app: FastifyInstance) {
/**
* Complete en session.
* I steg 3a: anropar samma logik som gamla /cook, men länkar allt till cookingSessionId.
* I steg 3b: sparar svar på max 23 frågor och uppdaterar hushållsantagandeprofiler.
* Delad kompletteringsväg via completeCookingSession hanterar summavalidering,
* persistens, profiluppdateringar och analytics.
*/
app.post("/v1/cooking-sessions/:id/complete", auth, async (req) => {
const { id } = parse(idParamSchema, req.params);
@@ -148,107 +143,9 @@ export async function cookingSessionRoutes(app: FastifyInstance) {
throw errors.conflict("Sessionen måste vara startad för att avslutas.");
}
const mealBoxPortions = input.mealBoxPortions ?? 0;
const plannedPortions = input.portionsCooked ?? session.plannedPortions;
const actualPortionsEaten = input.actualPortionsEaten ?? Math.max(0, plannedPortions - mealBoxPortions);
const leftoverEstimatePortions = input.leftoverEstimatePortions ?? mealBoxPortions;
const result = await completeCookingSession(app, session, req.userId, input, req.correlationId);
if (actualPortionsEaten + leftoverEstimatePortions > plannedPortions) {
throw errors.badRequest("Åtna portioner + rester får inte överstiga totalt antal portioner.");
}
const result = await completeCookingSessionCore(
app,
session,
req.userId,
{ ...input, portionsCooked: plannedPortions, mealBoxPortions },
req.correlationId,
);
await app.db
.update(schema.cookingSessions)
.set({
actualPortionsEaten,
leftoverEstimatePortions,
leftoverNote: input.leftoverNote ?? null,
updatedAt: new Date(),
})
.where(eq(schema.cookingSessions.id, id));
// Uppdatera antagandeprofiler per ingrediens (hushållsnivå).
const date = new Date().toISOString().slice(0, 10);
for (const ing of result.recipeIngredients) {
if (ing.optional) continue;
const [existing] = await app.db
.select()
.from(schema.cookingAssumptionProfiles)
.where(
and(
eq(schema.cookingAssumptionProfiles.householdId, session.householdId),
eq(schema.cookingAssumptionProfiles.canonicalIngredientId, ing.canonicalIngredientId),
),
)
.limit(1);
const updatedProfile = updateCookingAssumptionProfile(
{
householdId: session.householdId,
canonicalIngredientId: ing.canonicalIngredientId,
plannedPortions,
actualPortionsEaten,
leftoverEstimatePortions,
sessionId: id,
date,
},
existing ?? { averageEatenPortions: null, averageLeftoverPortions: null, observationCount: 0 },
);
await app.db
.insert(schema.cookingAssumptionProfiles)
.values({
householdId: session.householdId,
canonicalIngredientId: ing.canonicalIngredientId,
...updatedProfile,
updatedAt: new Date(),
})
.onConflictDoUpdate({
target: [
schema.cookingAssumptionProfiles.householdId,
schema.cookingAssumptionProfiles.canonicalIngredientId,
],
set: {
averageEatenPortions: updatedProfile.averageEatenPortions,
averageLeftoverPortions: updatedProfile.averageLeftoverPortions,
observationCount: updatedProfile.observationCount,
lastSessionAnswers: updatedProfile.lastSessionAnswers,
updatedAt: new Date(),
},
});
}
const [updated] = await app.db
.select()
.from(schema.cookingSessions)
.where(eq(schema.cookingSessions.id, id))
.limit(1);
await trackProductAnalytics(
app.db,
req.userId,
cookingSessionCompleted({
householdId: session.householdId,
properties: {
cookingSessionId: id,
recipeId: session.recipeId,
portionsCooked: plannedPortions,
actualPortionsEaten,
leftoverEstimatePortions,
mealBoxPortions,
},
}),
);
return { ...result, session: updated };
return result;
});
/** Hämta antagandeprofil för ett recept (per hushåll + ingrediens). */
@@ -258,23 +155,38 @@ export async function cookingSessionRoutes(app: FastifyInstance) {
await requireMembership(app.db, householdId, req.userId);
const ings = await app.db
.select({ canonicalIngredientId: schema.recipeIngredients.canonicalIngredientId })
.select({
canonicalIngredientId: schema.recipeIngredients.canonicalIngredientId,
optional: schema.recipeIngredients.optional,
})
.from(schema.recipeIngredients)
.where(eq(schema.recipeIngredients.recipeId, id));
if (ings.length === 0) throw errors.notFound("Receptet finns inte.");
const nonOptionalIds = ings.filter((i) => !i.optional).map((i) => i.canonicalIngredientId);
if (nonOptionalIds.length === 0) {
return {
householdId,
recipeId: id,
defaultActualPortionsEaten: null,
defaultLeftoverEstimatePortions: null,
observationCount: 0,
};
}
const profiles = await app.db
.select()
.from(schema.cookingAssumptionProfiles)
.where(
and(
eq(schema.cookingAssumptionProfiles.householdId, householdId),
eq(schema.cookingAssumptionProfiles.canonicalIngredientId, ings[0]!.canonicalIngredientId),
inArray(schema.cookingAssumptionProfiles.canonicalIngredientId, nonOptionalIds),
),
)
.limit(1);
);
// Deterministiskt val: profilen med flest observationer (stabil över tid).
const p = profiles.sort((a, b) => b.observationCount - a.observationCount)[0];
const p = profiles[0];
return {
householdId,
recipeId: id,