Hermetiska integrationstester + auto-hushall i onboarding (size, i18n, locations)
This commit is contained in:
@@ -47,6 +47,41 @@ export async function requireMembership(
|
||||
return { role: member.role, portionFactor: member.portionFactor };
|
||||
}
|
||||
|
||||
/** Skapa hushåll med standard-förvaringsplatser (spec §7–8). Återanvänds av
|
||||
* både POST /v1/households och onboarding auto-create. */
|
||||
export async function createHouseholdWithDefaults(
|
||||
db: Database,
|
||||
{
|
||||
userId,
|
||||
name,
|
||||
size,
|
||||
}: {
|
||||
userId: string;
|
||||
name: string;
|
||||
size?: number;
|
||||
},
|
||||
): Promise<{ id: string; name: string }> {
|
||||
const [household] = await db
|
||||
.insert(schema.households)
|
||||
.values({
|
||||
name,
|
||||
inviteCode: generateInviteCode(),
|
||||
size: size ?? null,
|
||||
})
|
||||
.returning();
|
||||
await db.insert(schema.householdMembers).values({
|
||||
householdId: household!.id,
|
||||
userId,
|
||||
role: "owner",
|
||||
});
|
||||
await db.insert(schema.storageLocations).values([
|
||||
{ householdId: household!.id, type: "fridge", name: "Kylen", sortOrder: 0 },
|
||||
{ householdId: household!.id, type: "freezer", name: "Frysen", sortOrder: 1 },
|
||||
{ householdId: household!.id, type: "pantry", name: "Skafferiet", sortOrder: 2 },
|
||||
]);
|
||||
return { id: household!.id, name: household!.name };
|
||||
}
|
||||
|
||||
/** Hämta användarens aktiva hushåll (första medlemskapet) eller null. */
|
||||
export async function getActiveHouseholdId(db: Database, userId: string): Promise<string | null> {
|
||||
const [member] = await db
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const cache: Record<string, Record<string, string>> = {};
|
||||
|
||||
/**
|
||||
* Minimal server-side i18n lookup into the mobile app's common.json files.
|
||||
* Falls back to the requested key if the translation is missing.
|
||||
*/
|
||||
export function t(key: string, languageTag: string): string {
|
||||
const lang = (languageTag.split("-")[0] ?? languageTag).toLowerCase();
|
||||
let dict = cache[lang];
|
||||
if (!dict) {
|
||||
try {
|
||||
const file = path.resolve(
|
||||
__dirname,
|
||||
"../../../../apps/mobile/src/locales",
|
||||
lang,
|
||||
"common.json",
|
||||
);
|
||||
dict = JSON.parse(readFileSync(file, "utf8")) as Record<string, string>;
|
||||
} catch {
|
||||
dict = {};
|
||||
}
|
||||
cache[lang] = dict;
|
||||
}
|
||||
return dict[key] ?? key;
|
||||
}
|
||||
@@ -13,7 +13,13 @@ import {
|
||||
} from "@app/validation";
|
||||
import { loadEntitlements } from "../lib/entitlements.js";
|
||||
import { errors, parse } from "../lib/errors.js";
|
||||
import { audit, emitEvent, generateInviteCode, requireMembership } from "../lib/helpers.js";
|
||||
import {
|
||||
audit,
|
||||
createHouseholdWithDefaults,
|
||||
emitEvent,
|
||||
generateInviteCode,
|
||||
requireMembership,
|
||||
} from "../lib/helpers.js";
|
||||
|
||||
/** Hushåll (spec §7): delat lager/plan/lista, individuella mål och roller. */
|
||||
export async function householdRoutes(app: FastifyInstance) {
|
||||
@@ -34,23 +40,20 @@ export async function householdRoutes(app: FastifyInstance) {
|
||||
|
||||
app.post("/v1/households", auth, async (req, reply) => {
|
||||
const input = parse(createHouseholdInputSchema, req.body);
|
||||
const [household] = await app.db
|
||||
.insert(schema.households)
|
||||
.values({
|
||||
name: input.name,
|
||||
inviteCode: generateInviteCode(),
|
||||
weeklyBudgetMinor: input.weeklyBudgetMinor ?? null,
|
||||
...(input.currencyCode ? { currencyCode: input.currencyCode } : {}),
|
||||
})
|
||||
.returning();
|
||||
await app.db
|
||||
.insert(schema.householdMembers)
|
||||
.values({ householdId: household!.id, userId: req.userId, role: "owner" });
|
||||
await app.db.insert(schema.storageLocations).values([
|
||||
{ householdId: household!.id, type: "fridge", name: "Kylen", sortOrder: 0 },
|
||||
{ householdId: household!.id, type: "freezer", name: "Frysen", sortOrder: 1 },
|
||||
{ householdId: household!.id, type: "pantry", name: "Skafferiet", sortOrder: 2 },
|
||||
]);
|
||||
const household = await createHouseholdWithDefaults(app.db, {
|
||||
userId: req.userId,
|
||||
name: input.name,
|
||||
});
|
||||
if (input.weeklyBudgetMinor != null || input.currencyCode) {
|
||||
await app.db
|
||||
.update(schema.households)
|
||||
.set({
|
||||
weeklyBudgetMinor: input.weeklyBudgetMinor ?? null,
|
||||
...(input.currencyCode ? { currencyCode: input.currencyCode } : {}),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(schema.households.id, household.id));
|
||||
}
|
||||
return reply.status(201).send(household);
|
||||
});
|
||||
|
||||
|
||||
@@ -4,7 +4,13 @@ import { z } from "zod";
|
||||
import { schema } from "@app/database";
|
||||
import { quickStartInputSchema, onboardingInputSchema } from "@app/validation";
|
||||
import { errors, parse } from "../lib/errors.js";
|
||||
import { audit, generateInviteCode, getActiveHouseholdId } from "../lib/helpers.js";
|
||||
import {
|
||||
audit,
|
||||
createHouseholdWithDefaults,
|
||||
getActiveHouseholdId,
|
||||
} from "../lib/helpers.js";
|
||||
|
||||
import { t } from "../lib/i18n.js";
|
||||
import { KNOWN_FLAGS } from "@app/feature-flags";
|
||||
|
||||
/**
|
||||
@@ -87,6 +93,24 @@ export async function onboardingRoutes(app: FastifyInstance) {
|
||||
},
|
||||
});
|
||||
|
||||
// Auto-create a household so the user can scan, shop, plan and budget
|
||||
// immediately instead of hitting the "no household" wall in 21 endpoints.
|
||||
let householdId = await getActiveHouseholdId(app.db, req.userId);
|
||||
if (!householdId) {
|
||||
const [user] = await app.db
|
||||
.select({ locale: schema.users.locale })
|
||||
.from(schema.users)
|
||||
.where(eq(schema.users.id, req.userId))
|
||||
.limit(1);
|
||||
const householdName = t("onboarding.householdDefaultName", user?.locale ?? "sv-SE");
|
||||
const household = await createHouseholdWithDefaults(app.db, {
|
||||
userId: req.userId,
|
||||
name: householdName,
|
||||
size: input.persons,
|
||||
});
|
||||
householdId = household.id;
|
||||
}
|
||||
|
||||
// Advance to step B
|
||||
const [user] = await app.db
|
||||
.update(schema.users)
|
||||
@@ -101,7 +125,7 @@ export async function onboardingRoutes(app: FastifyInstance) {
|
||||
await audit(app.db, {
|
||||
actorUserId: req.userId,
|
||||
action: "onboarding.quick_start",
|
||||
metadata: { goals, primaryGoal, precisionMode: input.precisionMode },
|
||||
metadata: { goals, primaryGoal, precisionMode: input.precisionMode, householdId },
|
||||
ip: req.ip,
|
||||
correlationId: req.correlationId,
|
||||
});
|
||||
@@ -110,6 +134,7 @@ export async function onboardingRoutes(app: FastifyInstance) {
|
||||
ok: true,
|
||||
step: user!.onboardingStep,
|
||||
onboardingCompleted: user!.onboardingCompleted,
|
||||
householdId,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -128,22 +153,20 @@ export async function onboardingRoutes(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
let householdId: string | null = await getActiveHouseholdId(app.db, req.userId);
|
||||
if (input.householdChoice.kind === "create" && !householdId) {
|
||||
const [household] = await app.db
|
||||
.insert(schema.households)
|
||||
.values({ name: input.householdChoice.name, inviteCode: generateInviteCode() })
|
||||
.returning();
|
||||
await app.db.insert(schema.householdMembers).values({
|
||||
householdId: household!.id,
|
||||
userId: req.userId,
|
||||
role: "owner",
|
||||
});
|
||||
await app.db.insert(schema.storageLocations).values([
|
||||
{ householdId: household!.id, type: "fridge", name: "Kylen", sortOrder: 0 },
|
||||
{ householdId: household!.id, type: "freezer", name: "Frysen", sortOrder: 1 },
|
||||
{ householdId: household!.id, type: "pantry", name: "Skafferiet", sortOrder: 2 },
|
||||
]);
|
||||
householdId = household!.id;
|
||||
if (input.householdChoice.kind === "create") {
|
||||
if (householdId) {
|
||||
// Auto-created household already exists; update name if user provided a custom one.
|
||||
await app.db
|
||||
.update(schema.households)
|
||||
.set({ name: input.householdChoice.name, updatedAt: new Date() })
|
||||
.where(eq(schema.households.id, householdId));
|
||||
} else {
|
||||
const household = await createHouseholdWithDefaults(app.db, {
|
||||
userId: req.userId,
|
||||
name: input.householdChoice.name,
|
||||
});
|
||||
householdId = household.id;
|
||||
}
|
||||
} else if (input.householdChoice.kind === "join") {
|
||||
const [household] = await app.db
|
||||
.select()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import "./setup-env.js";
|
||||
import { describe, expect, it, beforeAll, afterAll } from "vitest";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { buildServer } from "../src/server.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import { createDatabase, closeDatabase, schema } from "@app/database";
|
||||
@@ -9,22 +10,32 @@ import { createDatabase, closeDatabase, schema } from "@app/database";
|
||||
* 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!,
|
||||
});
|
||||
const testDb = createDatabase(process.env.TEST_DATABASE_URL!);
|
||||
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"];
|
||||
const emails = [userEmail, "goals-multi@example.invalid", "auto-household@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.householdMembers).where(eq(schema.householdMembers.userId, u.id));
|
||||
const ownedHouseholds = await testDb.db
|
||||
.select({ id: schema.households.id })
|
||||
.from(schema.households)
|
||||
.innerJoin(
|
||||
schema.householdMembers,
|
||||
eq(schema.householdMembers.householdId, schema.households.id),
|
||||
)
|
||||
.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.households).where(eq(schema.households.id, h.id));
|
||||
}
|
||||
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));
|
||||
}
|
||||
@@ -101,4 +112,38 @@ describe("what-to-eat without household", () => {
|
||||
expect(prefs?.goals).toEqual(["cook_more", "less_waste"]);
|
||||
expect(prefs?.primaryGoal).toBe("cook_more");
|
||||
});
|
||||
|
||||
it("quick-start auto-creates a household with default storage locations", async () => {
|
||||
const registerRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/auth/register",
|
||||
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;
|
||||
|
||||
const quickRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/onboarding/quick-start",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { goals: ["cook_more"], persons: 2, precisionMode: "simple" },
|
||||
});
|
||||
expect(quickRes.statusCode).toBe(200);
|
||||
const { householdId } = JSON.parse(quickRes.body) as { householdId: string };
|
||||
expect(householdId).toBeTruthy();
|
||||
|
||||
const [household] = await testDb.db
|
||||
.select()
|
||||
.from(schema.households)
|
||||
.where(eq(schema.households.id, householdId))
|
||||
.limit(1);
|
||||
expect(household).toBeTruthy();
|
||||
expect(household!.size).toBe(2);
|
||||
|
||||
const locations = await testDb.db
|
||||
.select()
|
||||
.from(schema.storageLocations)
|
||||
.where(eq(schema.storageLocations.householdId, householdId));
|
||||
expect(locations.map((l) => l.type).sort()).toEqual(["freezer", "fridge", "pantry"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Hermetic test environment for API integration tests.
|
||||
* Must run BEFORE any application module is imported so that `loadConfig`
|
||||
* sees deterministic values instead of whatever happens to be in `.env`.
|
||||
*/
|
||||
process.env.NODE_ENV = "test";
|
||||
process.env.AAMOS_MODE = "mock";
|
||||
process.env.EMAIL_MODE = "log";
|
||||
process.env.S3_MODE = "mock";
|
||||
process.env.LOG_LEVEL = "error";
|
||||
|
||||
// Local test database fallback – tests still need a Postgres instance, but
|
||||
// the connection string is not a secret and the value is predictable.
|
||||
process.env.TEST_DATABASE_URL ||= "postgres://app_user:app_dev_password@localhost:5432/cibello_test";
|
||||
process.env.DATABASE_URL = process.env.TEST_DATABASE_URL;
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: "node",
|
||||
globals: false,
|
||||
setupFiles: [path.resolve(__dirname, "test/setup-env.ts")],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user