Bugfix: what-to-eat utan hushall ger forslag; onboarding mal kan valjas multi
This commit is contained in:
@@ -62,17 +62,27 @@ export async function onboardingRoutes(app: FastifyInstance) {
|
||||
app.post("/v1/onboarding/quick-start", auth, async (req) => {
|
||||
const input = parse(quickStartInputSchema, req.body);
|
||||
|
||||
// Normalize goals: multi-select UI sends `goals`; legacy clients send `primaryGoal`.
|
||||
const goals = input.goals?.length
|
||||
? input.goals
|
||||
: input.primaryGoal
|
||||
? [input.primaryGoal]
|
||||
: [];
|
||||
const primaryGoal = goals[0];
|
||||
|
||||
// Upsert minimal preferences
|
||||
await app.db
|
||||
.insert(schema.userPreferences)
|
||||
.values({
|
||||
userId: req.userId,
|
||||
...(input.primaryGoal ? { primaryGoal: input.primaryGoal } : {}),
|
||||
goals,
|
||||
...(primaryGoal ? { primaryGoal } : {}),
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: schema.userPreferences.userId,
|
||||
set: {
|
||||
...(input.primaryGoal ? { primaryGoal: input.primaryGoal } : {}),
|
||||
goals,
|
||||
...(primaryGoal ? { primaryGoal } : {}),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
@@ -91,7 +101,7 @@ export async function onboardingRoutes(app: FastifyInstance) {
|
||||
await audit(app.db, {
|
||||
actorUserId: req.userId,
|
||||
action: "onboarding.quick_start",
|
||||
metadata: { primaryGoal: input.primaryGoal, precisionMode: input.precisionMode },
|
||||
metadata: { goals, primaryGoal, precisionMode: input.precisionMode },
|
||||
ip: req.ip,
|
||||
correlationId: req.correlationId,
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
} from "@app/recommendation-engine";
|
||||
import { DEFAULT_TARGETS, computeDailyTargets, summarizeDay } from "@app/nutrition-engine";
|
||||
import { parse } from "../lib/errors.js";
|
||||
import { requireActiveHousehold, todayIso } from "../lib/helpers.js";
|
||||
import { getActiveHouseholdId, todayIso } from "../lib/helpers.js";
|
||||
|
||||
/**
|
||||
* "Vad ska vi äta?" (spec §18) – appens viktigaste endpoint.
|
||||
@@ -37,34 +37,38 @@ export async function recommendationRoutes(app: FastifyInstance) {
|
||||
|
||||
app.get("/v1/recommendations/what-to-eat", auth, async (req) => {
|
||||
const q = parse(whatToEatQuerySchema, req.query);
|
||||
const householdId = await requireActiveHousehold(app.db, req.userId);
|
||||
// Graceful for users without a household yet (e.g. after step A onboarding):
|
||||
// treat it as an empty pantry / single-person context instead of failing.
|
||||
const householdId = await getActiveHouseholdId(app.db, req.userId);
|
||||
const today = new Date();
|
||||
|
||||
// --- 1. Kontext: lager ---
|
||||
const stockRows = await app.db
|
||||
.select({
|
||||
item: schema.inventoryItems,
|
||||
locationType: schema.storageLocations.type,
|
||||
shelfLife: schema.canonicalIngredients.shelfLifeGuidance,
|
||||
density: schema.canonicalIngredients.densityGPerMl,
|
||||
gramsPerPiece: schema.canonicalIngredients.gramsPerPiece,
|
||||
})
|
||||
.from(schema.inventoryItems)
|
||||
.innerJoin(
|
||||
schema.storageLocations,
|
||||
eq(schema.inventoryItems.storageLocationId, schema.storageLocations.id),
|
||||
)
|
||||
.leftJoin(
|
||||
schema.canonicalIngredients,
|
||||
eq(schema.inventoryItems.canonicalIngredientId, schema.canonicalIngredients.id),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.inventoryItems.householdId, householdId),
|
||||
isNull(schema.inventoryItems.depletedAt),
|
||||
gt(schema.inventoryItems.quantity, 0),
|
||||
),
|
||||
);
|
||||
const stockRows = householdId
|
||||
? await app.db
|
||||
.select({
|
||||
item: schema.inventoryItems,
|
||||
locationType: schema.storageLocations.type,
|
||||
shelfLife: schema.canonicalIngredients.shelfLifeGuidance,
|
||||
density: schema.canonicalIngredients.densityGPerMl,
|
||||
gramsPerPiece: schema.canonicalIngredients.gramsPerPiece,
|
||||
})
|
||||
.from(schema.inventoryItems)
|
||||
.innerJoin(
|
||||
schema.storageLocations,
|
||||
eq(schema.inventoryItems.storageLocationId, schema.storageLocations.id),
|
||||
)
|
||||
.leftJoin(
|
||||
schema.canonicalIngredients,
|
||||
eq(schema.inventoryItems.canonicalIngredientId, schema.canonicalIngredients.id),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.inventoryItems.householdId, householdId),
|
||||
isNull(schema.inventoryItems.depletedAt),
|
||||
gt(schema.inventoryItems.quantity, 0),
|
||||
),
|
||||
)
|
||||
: [];
|
||||
|
||||
const pantry: PantryItem[] = stockRows.map((r) => ({
|
||||
id: r.item.id,
|
||||
@@ -90,11 +94,13 @@ export async function recommendationRoutes(app: FastifyInstance) {
|
||||
);
|
||||
|
||||
// --- 2. Hushållets samlade begränsningar (spec §7: strängaste gäller) ---
|
||||
const members = await app.db
|
||||
.select({ userId: schema.householdMembers.userId })
|
||||
.from(schema.householdMembers)
|
||||
.where(eq(schema.householdMembers.householdId, householdId));
|
||||
const memberIds = members.map((m) => m.userId);
|
||||
const members = householdId
|
||||
? await app.db
|
||||
.select({ userId: schema.householdMembers.userId })
|
||||
.from(schema.householdMembers)
|
||||
.where(eq(schema.householdMembers.householdId, householdId))
|
||||
: [];
|
||||
const memberIds = members.length ? members.map((m) => m.userId) : [req.userId];
|
||||
const allPrefs = await app.db
|
||||
.select()
|
||||
.from(schema.userPreferences)
|
||||
@@ -189,14 +195,16 @@ export async function recommendationRoutes(app: FastifyInstance) {
|
||||
.map((e) => e.slug);
|
||||
|
||||
// --- 6. Senast lagat (variation) + hushållsbetyg ---
|
||||
const cooks = await app.db
|
||||
.select({
|
||||
recipeId: schema.recipeCooks.recipeId,
|
||||
last: sql<string>`max(${schema.recipeCooks.cookedAt})`,
|
||||
})
|
||||
.from(schema.recipeCooks)
|
||||
.where(eq(schema.recipeCooks.householdId, householdId))
|
||||
.groupBy(schema.recipeCooks.recipeId);
|
||||
const cooks = householdId
|
||||
? await app.db
|
||||
.select({
|
||||
recipeId: schema.recipeCooks.recipeId,
|
||||
last: sql<string>`max(${schema.recipeCooks.cookedAt})`,
|
||||
})
|
||||
.from(schema.recipeCooks)
|
||||
.where(eq(schema.recipeCooks.householdId, householdId))
|
||||
.groupBy(schema.recipeCooks.recipeId)
|
||||
: [];
|
||||
const lastCooked = new Map(cooks.map((c) => [c.recipeId, c.last]));
|
||||
const householdRatings = await app.db
|
||||
.select({
|
||||
@@ -213,7 +221,7 @@ export async function recommendationRoutes(app: FastifyInstance) {
|
||||
|
||||
const ctx: RecommendationContext = {
|
||||
mealType: q.mealType,
|
||||
persons: q.persons ?? members.length,
|
||||
persons: q.persons ?? (members.length ? members.length : 1),
|
||||
maxMinutes: q.maxMinutes ?? myPrefs?.maxCookingMinutesWeekday ?? undefined,
|
||||
maxCostMinorPerPortion: q.maxCostMinorPerPortion,
|
||||
remainingProteinG: Math.max(0, daySummary.remaining.proteinG),
|
||||
@@ -312,7 +320,7 @@ export async function recommendationRoutes(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
// --- 10. Matlådor först när rimligt (spec §24) ---
|
||||
const mealBoxes = q.includeLeftovers
|
||||
const mealBoxes = q.includeLeftovers && householdId
|
||||
? await app.db
|
||||
.select()
|
||||
.from(schema.mealBoxes)
|
||||
|
||||
@@ -12,6 +12,16 @@ describe("progressive onboarding validering (FAS 1b)", () => {
|
||||
expect(result.precisionMode).toBe("exact");
|
||||
});
|
||||
|
||||
it("quick-start accepterar flera mål", () => {
|
||||
const result = parse(quickStartInputSchema, {
|
||||
goals: ["lose_weight", "cook_more"],
|
||||
precisionMode: "simple",
|
||||
});
|
||||
expect(result.goals).toEqual(["lose_weight", "cook_more"]);
|
||||
expect(result.primaryGoal).toBeUndefined();
|
||||
expect(result.precisionMode).toBe("simple");
|
||||
});
|
||||
|
||||
it("quick-start är valfri – endast precision får default", () => {
|
||||
const result = parse(quickStartInputSchema, {});
|
||||
expect(result.primaryGoal).toBeUndefined();
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, expect, it, beforeAll, afterAll } from "vitest";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { buildServer } from "../src/server.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import { createDatabase, closeDatabase, schema } from "@app/database";
|
||||
|
||||
/**
|
||||
* Regression test: what-to-eat must work for a brand-new user who has not
|
||||
* created a household yet (empty pantry, single-person context).
|
||||
*/
|
||||
describe("what-to-eat without household", () => {
|
||||
const testDb = createDatabase(process.env.TEST_DATABASE_URL);
|
||||
const config = loadConfig({
|
||||
...process.env,
|
||||
DATABASE_URL: process.env.TEST_DATABASE_URL!,
|
||||
});
|
||||
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"];
|
||||
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.userPreferences).where(eq(schema.userPreferences.userId, u.id));
|
||||
await testDb.db.delete(schema.users).where(eq(schema.users.id, u.id));
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
app = await buildServer(config);
|
||||
await app.ready();
|
||||
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/auth/register",
|
||||
payload: { email: userEmail, password: "Password123!", displayName: "Repro" },
|
||||
});
|
||||
const body = JSON.parse(res.body) as { accessToken: string };
|
||||
accessToken = body.accessToken;
|
||||
|
||||
await testDb.db
|
||||
.insert(schema.userPreferences)
|
||||
.values({ userId: (JSON.parse(atob(accessToken.split(".")[1]!)) as { sub: string }).sub, primaryGoal: "cook_more" })
|
||||
.onConflictDoNothing();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await closeDatabase();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("returns recommendations for a new user without a household and a craving set", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/v1/recommendations/what-to-eat?limit=5&craving=asiatiskt",
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body) as {
|
||||
recommendations: unknown[];
|
||||
mealBoxSuggestions: unknown[];
|
||||
context: { persons: number; craving: { cuisine: string } | null };
|
||||
};
|
||||
expect(body.recommendations).toBeDefined();
|
||||
expect(body.mealBoxSuggestions).toBeDefined();
|
||||
expect(body.context.persons).toBe(1);
|
||||
expect(body.context.craving).not.toBeNull();
|
||||
expect(body.context.craving?.cuisine).toBe("thai");
|
||||
});
|
||||
|
||||
it("quick-start stores goals array and sets primaryGoal to the first goal", async () => {
|
||||
const registerRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/auth/register",
|
||||
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;
|
||||
|
||||
const quickRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/onboarding/quick-start",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { goals: ["cook_more", "less_waste"], precisionMode: "simple" },
|
||||
});
|
||||
expect(quickRes.statusCode).toBe(200);
|
||||
|
||||
const [prefs] = await testDb.db
|
||||
.select()
|
||||
.from(schema.userPreferences)
|
||||
.where(eq(schema.userPreferences.userId, userId))
|
||||
.limit(1);
|
||||
|
||||
expect(prefs?.goals).toEqual(["cook_more", "less_waste"]);
|
||||
expect(prefs?.primaryGoal).toBe("cook_more");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user