fix(recipe-generation): BRAND.name-interpolation för creatorDisplayName + rubriker/filnamn
feat(recommendation-engine,api): S4 Smak/Hälsa/Lager-vyer för 'Vad ska vi äta?' - Ersätter hårdkodat 'Cibello' i scale-batch, scale-smoke-test och export-verified. - DB-backfill: 224 recept hade 'Cibello AI' i creator_display_name (värdena motsvarar nuvarande BRAND.name, ingen rad ändrades men kontrollen är gjord). - Lägger till view-query-param (default|taste|health|pantry) med fördefinierade ScoringWeights och samtyckesgrind. - Unit-tester för vyer; integrationstester för vy-param, validering och fallback utan personalization-samtycke. - brand-guard grön; pnpm typecheck 19/19; pnpm test --force x2 grönt (34 tasks, 275 tester).
This commit is contained in:
@@ -17,6 +17,7 @@ import {
|
||||
rankAll,
|
||||
seasonForDate,
|
||||
summarizeContext,
|
||||
viewWeights,
|
||||
type CookingAssumption,
|
||||
type RecommendationCandidate,
|
||||
type RecommendationContext,
|
||||
@@ -381,11 +382,17 @@ export async function recommendationRoutes(app: FastifyInstance) {
|
||||
? Math.floor((today.getTime() - Date.parse(lastDate)) / 86_400_000)
|
||||
: null,
|
||||
householdRating: householdRatingMap.get(recipe.id) ?? null,
|
||||
ingredientIds: recipeIngredients.map((i) => i.canonicalIngredientId).filter((id): id is string => id != null),
|
||||
ingredientIds: recipeIngredients
|
||||
.map((i) => i.canonicalIngredientId)
|
||||
.filter((id): id is string => id != null),
|
||||
});
|
||||
}
|
||||
|
||||
const weights = personalizationEnabled ? undefined : NON_PERSONALIZED_WEIGHTS;
|
||||
const weights = personalizationEnabled
|
||||
? q.view === "default"
|
||||
? undefined
|
||||
: viewWeights(q.view)
|
||||
: NON_PERSONALIZED_WEIGHTS;
|
||||
let recommendations = rankAll(scoredCandidates, ctx, weights, q.limit);
|
||||
|
||||
// --- 9. AAMOS-omrankning bakom feature flag (aldrig obligatorisk) ---
|
||||
@@ -416,19 +423,20 @@ export async function recommendationRoutes(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
// --- 10. Matlådor först när rimligt (spec §24) ---
|
||||
const mealBoxes = q.includeLeftovers && householdId
|
||||
? await app.db
|
||||
.select()
|
||||
.from(schema.mealBoxes)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.mealBoxes.householdId, householdId),
|
||||
eq(schema.mealBoxes.status, "available"),
|
||||
),
|
||||
)
|
||||
.orderBy(schema.mealBoxes.recommendedUseBy)
|
||||
.limit(5)
|
||||
: [];
|
||||
const mealBoxes =
|
||||
q.includeLeftovers && householdId
|
||||
? await app.db
|
||||
.select()
|
||||
.from(schema.mealBoxes)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.mealBoxes.householdId, householdId),
|
||||
eq(schema.mealBoxes.status, "available"),
|
||||
),
|
||||
)
|
||||
.orderBy(schema.mealBoxes.recommendedUseBy)
|
||||
.limit(5)
|
||||
: [];
|
||||
const mealBoxSuggestions = mealBoxes.map((box) => ({
|
||||
mealBoxId: box.id,
|
||||
titleSv: box.titleSv,
|
||||
@@ -449,6 +457,7 @@ export async function recommendationRoutes(app: FastifyInstance) {
|
||||
remainingKcal: ctx.remainingKcal,
|
||||
remainingProteinG: ctx.remainingProteinG,
|
||||
craving: craving ?? null,
|
||||
view: personalizationEnabled ? q.view : "default",
|
||||
},
|
||||
mealBoxSuggestions,
|
||||
recommendations,
|
||||
|
||||
@@ -5,6 +5,9 @@ import { buildServer } from "../src/server.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import { createDatabase, closeDatabase, schema } from "@app/database";
|
||||
|
||||
const userEmail = "what-to-eat-repro@example.invalid";
|
||||
const viewTestEmail = "view-test@example.invalid";
|
||||
|
||||
/**
|
||||
* Regression test: what-to-eat must work for a brand-new user who has not
|
||||
* created a household yet (empty pantry, single-person context).
|
||||
@@ -14,16 +17,23 @@ describe("what-to-eat without household", () => {
|
||||
const config = loadConfig();
|
||||
let app: Awaited<ReturnType<typeof buildServer>>;
|
||||
let accessToken: string;
|
||||
const userEmail = "what-to-eat-repro@example.invalid";
|
||||
|
||||
async function cleanup() {
|
||||
const emails = [userEmail, "goals-multi@example.invalid", "auto-household@example.invalid"];
|
||||
const emails = [
|
||||
userEmail,
|
||||
"goals-multi@example.invalid",
|
||||
"auto-household@example.invalid",
|
||||
"personalization-gate@example.invalid",
|
||||
viewTestEmail,
|
||||
];
|
||||
const existing = await testDb.db
|
||||
.select({ id: schema.users.id })
|
||||
.from(schema.users)
|
||||
.where(inArray(schema.users.email, emails));
|
||||
for (const u of existing) {
|
||||
await testDb.db.delete(schema.householdMembers).where(eq(schema.householdMembers.userId, u.id));
|
||||
await testDb.db
|
||||
.delete(schema.householdMembers)
|
||||
.where(eq(schema.householdMembers.userId, u.id));
|
||||
const ownedHouseholds = await testDb.db
|
||||
.select({ id: schema.households.id })
|
||||
.from(schema.households)
|
||||
@@ -31,9 +41,13 @@ describe("what-to-eat without household", () => {
|
||||
schema.householdMembers,
|
||||
eq(schema.householdMembers.householdId, schema.households.id),
|
||||
)
|
||||
.where(and(eq(schema.householdMembers.userId, u.id), eq(schema.householdMembers.role, "owner")));
|
||||
.where(
|
||||
and(eq(schema.householdMembers.userId, u.id), eq(schema.householdMembers.role, "owner")),
|
||||
);
|
||||
for (const h of ownedHouseholds) {
|
||||
await testDb.db.delete(schema.storageLocations).where(eq(schema.storageLocations.householdId, h.id));
|
||||
await testDb.db
|
||||
.delete(schema.storageLocations)
|
||||
.where(eq(schema.storageLocations.householdId, h.id));
|
||||
await testDb.db.delete(schema.households).where(eq(schema.households.id, h.id));
|
||||
}
|
||||
await testDb.db.delete(schema.userPreferences).where(eq(schema.userPreferences.userId, u.id));
|
||||
@@ -56,7 +70,10 @@ describe("what-to-eat without household", () => {
|
||||
|
||||
await testDb.db
|
||||
.insert(schema.userPreferences)
|
||||
.values({ userId: (JSON.parse(atob(accessToken.split(".")[1]!)) as { sub: string }).sub, primaryGoal: "cook_more" })
|
||||
.values({
|
||||
userId: (JSON.parse(atob(accessToken.split(".")[1]!)) as { sub: string }).sub,
|
||||
primaryGoal: "cook_more",
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
});
|
||||
|
||||
@@ -90,7 +107,11 @@ describe("what-to-eat without household", () => {
|
||||
const registerRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/auth/register",
|
||||
payload: { email: "goals-multi@example.invalid", password: "Password123!", displayName: "Goals" },
|
||||
payload: {
|
||||
email: "goals-multi@example.invalid",
|
||||
password: "Password123!",
|
||||
displayName: "Goals",
|
||||
},
|
||||
});
|
||||
const { accessToken: token } = JSON.parse(registerRes.body) as { accessToken: string };
|
||||
const userId = (JSON.parse(atob(token.split(".")[1]!)) as { sub: string }).sub;
|
||||
@@ -117,7 +138,11 @@ describe("what-to-eat without household", () => {
|
||||
const registerRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/auth/register",
|
||||
payload: { email: "personalization-gate@example.invalid", password: "Password123!", displayName: "Gate" },
|
||||
payload: {
|
||||
email: "personalization-gate@example.invalid",
|
||||
password: "Password123!",
|
||||
displayName: "Gate",
|
||||
},
|
||||
});
|
||||
const { accessToken: token } = JSON.parse(registerRes.body) as { accessToken: string };
|
||||
const userId = (JSON.parse(atob(token.split(".")[1]!)) as { sub: string }).sub;
|
||||
@@ -183,7 +208,11 @@ describe("what-to-eat without household", () => {
|
||||
const registerRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/auth/register",
|
||||
payload: { email: "auto-household@example.invalid", password: "Password123!", displayName: "Auto" },
|
||||
payload: {
|
||||
email: "auto-household@example.invalid",
|
||||
password: "Password123!",
|
||||
displayName: "Auto",
|
||||
},
|
||||
});
|
||||
const { accessToken: token } = JSON.parse(registerRes.body) as { accessToken: string };
|
||||
const userId = (JSON.parse(atob(token.split(".")[1]!)) as { sub: string }).sub;
|
||||
@@ -213,3 +242,110 @@ describe("what-to-eat without household", () => {
|
||||
expect(locations.map((l) => l.type).sort()).toEqual(["freezer", "fridge", "pantry"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("S4 recommendation views", () => {
|
||||
const testDb = createDatabase(process.env.TEST_DATABASE_URL!);
|
||||
const config = loadConfig();
|
||||
let app: Awaited<ReturnType<typeof buildServer>>;
|
||||
let accessToken: string;
|
||||
let userId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildServer(config);
|
||||
await app.ready();
|
||||
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/auth/register",
|
||||
payload: { email: viewTestEmail, password: "Password123!", displayName: "View" },
|
||||
});
|
||||
const body = JSON.parse(res.body) as { accessToken: string };
|
||||
accessToken = body.accessToken;
|
||||
userId = (JSON.parse(atob(accessToken.split(".")[1]!)) as { sub: string }).sub;
|
||||
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/onboarding/quick-start",
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
payload: { goals: ["cook_more"], persons: 2, precisionMode: "simple" },
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await testDb.pool.end();
|
||||
});
|
||||
|
||||
it("rejects unsupported view values", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/v1/recommendations/what-to-eat?view=spicy&limit=1",
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("returns requested view when personalization consent is granted", async () => {
|
||||
await testDb.db
|
||||
.insert(schema.userConsents)
|
||||
.values({ userId, kind: "personalization", status: "granted" })
|
||||
.onConflictDoUpdate({
|
||||
target: [schema.userConsents.userId, schema.userConsents.kind],
|
||||
set: { status: "granted" },
|
||||
});
|
||||
|
||||
for (const view of ["taste", "health", "pantry"] as const) {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/v1/recommendations/what-to-eat?view=${view}&limit=1`,
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body) as {
|
||||
context: { view: string };
|
||||
recommendations: unknown[];
|
||||
};
|
||||
expect(body.context.view).toBe(view);
|
||||
expect(body.recommendations.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores view and falls back to default without personalization consent", async () => {
|
||||
// Revoke consent.
|
||||
await testDb.db
|
||||
.insert(schema.userConsents)
|
||||
.values({ userId, kind: "personalization", status: "revoked" })
|
||||
.onConflictDoUpdate({
|
||||
target: [schema.userConsents.userId, schema.userConsents.kind],
|
||||
set: { status: "revoked" },
|
||||
});
|
||||
|
||||
const defaultRes = await app.inject({
|
||||
method: "GET",
|
||||
url: "/v1/recommendations/what-to-eat?limit=1",
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
const viewRes = await app.inject({
|
||||
method: "GET",
|
||||
url: "/v1/recommendations/what-to-eat?view=taste&limit=1",
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
|
||||
expect(defaultRes.statusCode).toBe(200);
|
||||
expect(viewRes.statusCode).toBe(200);
|
||||
|
||||
const defaultBody = JSON.parse(defaultRes.body) as {
|
||||
context: { view: string };
|
||||
recommendations: Array<{ recipeId: string }>;
|
||||
};
|
||||
const viewBody = JSON.parse(viewRes.body) as {
|
||||
context: { view: string };
|
||||
recommendations: Array<{ recipeId: string }>;
|
||||
};
|
||||
|
||||
expect(viewBody.context.view).toBe("default");
|
||||
expect(viewBody.recommendations.map((r) => r.recipeId)).toEqual(
|
||||
defaultBody.recommendations.map((r) => r.recipeId),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user