From 4385fe512507866cc1eb20b55bae3ff22d80606b Mon Sep 17 00:00:00 2001 From: "Sven (AAMOS AI)" Date: Thu, 6 Aug 2026 23:45:28 +0700 Subject: [PATCH] Fas 2 steg 3: Household Trust Score (admin + i18n status i appen) --- apps/api/src/routes/admin.ts | 55 ++++++++++- apps/api/src/routes/inventory.ts | 46 ++++++++- apps/api/test/admin-trust.test.ts | 83 +++++++++++++++++ apps/mobile/src/app/(tabs)/home.tsx | 9 +- apps/mobile/src/components/ui.tsx | 5 +- apps/mobile/src/locales/da/common.json | 5 +- apps/mobile/src/locales/de/common.json | 5 +- apps/mobile/src/locales/en/common.json | 5 +- apps/mobile/src/locales/es/common.json | 5 +- apps/mobile/src/locales/fi/common.json | 5 +- apps/mobile/src/locales/fr/common.json | 5 +- apps/mobile/src/locales/it/common.json | 5 +- apps/mobile/src/locales/nb/common.json | 5 +- apps/mobile/src/locales/nl/common.json | 5 +- apps/mobile/src/locales/pl/common.json | 5 +- apps/mobile/src/locales/pt/common.json | 5 +- apps/mobile/src/locales/sv/common.json | 5 +- apps/worker/src/index.ts | 2 +- apps/worker/src/processors/maintenance.ts | 3 +- packages/inventory-engine/src/trust.ts | 98 ++++++++++++++++++++ packages/inventory-engine/test/trust.test.ts | 58 +++++++++++- 21 files changed, 396 insertions(+), 23 deletions(-) create mode 100644 apps/api/test/admin-trust.test.ts diff --git a/apps/api/src/routes/admin.ts b/apps/api/src/routes/admin.ts index c78db88..c0a4910 100644 --- a/apps/api/src/routes/admin.ts +++ b/apps/api/src/routes/admin.ts @@ -1,11 +1,12 @@ import type { FastifyInstance } from "fastify"; -import { and, desc, eq, ilike, sql } from "drizzle-orm"; +import { and, desc, eq, ilike, isNull, sql } from "drizzle-orm"; import { schema } from "@app/database"; import { z } from "zod"; import { adminGrantInputSchema, totpCodeInputSchema } from "@app/validation"; import { errors, parse } from "../lib/errors.js"; import { audit } from "../lib/helpers.js"; import { generateTotpSecret, otpauthUrl, verifyTotp } from "../lib/totp.js"; +import { householdTrustScore } from "@app/inventory-engine"; import { BRAND } from "@app/shared-types"; /** Adminpanelens API (spec §57). Alla anrop kräver admin-roll och auditloggas. */ @@ -167,6 +168,58 @@ export async function adminRoutes(app: FastifyInstance) { return sub; }); + // --- Household trust score (Fas 2 §5.3) --- + app.get("/admin/v1/households/:id/trust", admin, async (req) => { + const params = z.object({ id: z.uuid() }).parse(req.params); + + const items = await app.db + .select() + .from(schema.inventoryItems) + .where( + and( + eq(schema.inventoryItems.householdId, params.id), + isNull(schema.inventoryItems.depletedAt), + ), + ); + + const thirtyDaysAgo = new Date(Date.now() - 30 * 86_400_000); + const txStats = await app.db + .select({ + total: sql`count(*)`, + adjustments: sql`count(*) FILTER (WHERE ${schema.inventoryTransactions.type} = 'adjust')`, + }) + .from(schema.inventoryTransactions) + .where( + and( + eq(schema.inventoryTransactions.householdId, params.id), + sql`${schema.inventoryTransactions.createdAt} >= ${thirtyDaysAgo}`, + ), + ); + + const result = householdTrustScore( + { + items: items.map((i) => ({ + confidence: i.confidence, + verifiedByUser: i.verifiedByUser, + lastVerifiedAt: i.lastVerifiedAt, + quantity: i.quantity, + updatedAt: i.updatedAt, + depletedAt: i.depletedAt, + })), + correctionCount30d: Number(txStats[0]?.adjustments ?? 0), + transactionCount30d: Number(txStats[0]?.total ?? 0), + }, + new Date(), + ); + + return { + householdId: params.id, + score: result.score, + status: result.status, + itemCount: items.length, + }; + }); + // --- Jobb & systemhälsa (spec §57–58) --- app.get("/admin/v1/jobs/overview", admin, async () => { const scanStats = await app.db diff --git a/apps/api/src/routes/inventory.ts b/apps/api/src/routes/inventory.ts index d3aac67..e3338ba 100644 --- a/apps/api/src/routes/inventory.ts +++ b/apps/api/src/routes/inventory.ts @@ -1,5 +1,5 @@ import type { FastifyInstance } from "fastify"; -import { and, desc, eq, gt, ilike, isNull, or } from "drizzle-orm"; +import { and, desc, eq, gt, ilike, isNull, or, sql } from "drizzle-orm"; import { schema } from "@app/database"; import { createInventoryItemInputSchema, @@ -8,9 +8,20 @@ import { inventoryTransactionInputSchema, updateInventoryItemInputSchema, } from "@app/validation"; -import { classifyExpiry, findDuplicateCandidates, normalizeDelta, computeTrust } from "@app/inventory-engine"; +import { + classifyExpiry, + findDuplicateCandidates, + normalizeDelta, + computeTrust, + householdTrustScore, +} from "@app/inventory-engine"; import { errors, parse } from "../lib/errors.js"; -import { emitEvent, getActiveDecayProfile, requireActiveHousehold, requireMembership } from "../lib/helpers.js"; +import { + emitEvent, + getActiveDecayProfile, + requireActiveHousehold, + requireMembership, +} from "../lib/helpers.js"; /** * Food Twin – lagret (spec §8). Transaktionsbaserat: varje förändring skrivs @@ -98,7 +109,34 @@ export async function inventoryRoutes(app: FastifyInstance) { const filtered = query.expiryStatus ? items.filter((i) => i.expiry.status === query.expiryStatus) : items; - return { items: filtered }; + + const thirtyDaysAgo = new Date(Date.now() - 30 * 86_400_000); + const txStats = await app.db + .select({ + total: sql`count(*)`, + adjustments: sql`count(*) FILTER (WHERE ${schema.inventoryTransactions.type} = 'adjust')`, + }) + .from(schema.inventoryTransactions) + .where( + and( + eq(schema.inventoryTransactions.householdId, householdId), + sql`${schema.inventoryTransactions.createdAt} >= ${thirtyDaysAgo}`, + ), + ); + + const householdTrust = householdTrustScore( + { + items: rows.map((r) => r.item), + correctionCount30d: Number(txStats[0]?.adjustments ?? 0), + transactionCount30d: Number(txStats[0]?.total ?? 0), + }, + new Date(), + ); + + return { + items: filtered, + trustStatus: householdTrust.status, + }; }); /** Varor som bör användas snart – driver "använd först" (spec §4.4, §40). */ diff --git a/apps/api/test/admin-trust.test.ts b/apps/api/test/admin-trust.test.ts new file mode 100644 index 0000000..520852a --- /dev/null +++ b/apps/api/test/admin-trust.test.ts @@ -0,0 +1,83 @@ +import "./setup-env.js"; +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"; + +describe("admin household trust score", () => { + const testDb = createDatabase(process.env.TEST_DATABASE_URL!); + const config = loadConfig(); + let app: Awaited>; + let adminToken: string; + let householdId: string; + const adminEmail = "admin-trust@example.invalid"; + + async function cleanup() { + const existing = await testDb.db + .select({ id: schema.users.id }) + .from(schema.users) + .where(inArray(schema.users.email, [adminEmail])); + for (const u of existing) { + await testDb.db.delete(schema.inventoryTransactions).where(eq(schema.inventoryTransactions.actorUserId, u.id)); + const owned = await testDb.db + .select({ id: schema.households.id }) + .from(schema.households) + .innerJoin(schema.householdMembers, eq(schema.householdMembers.householdId, schema.households.id)) + .where(eq(schema.householdMembers.userId, u.id)); + for (const h of owned) { + await testDb.db.delete(schema.inventoryItems).where(eq(schema.inventoryItems.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.householdMembers).where(eq(schema.householdMembers.userId, u.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)); + } + } + + beforeAll(async () => { + await cleanup(); + app = await buildServer(config); + await app.ready(); + + const res = await app.inject({ + method: "POST", + url: "/v1/auth/register", + payload: { email: adminEmail, password: "Password123!", displayName: "Admin Trust" }, + }); + const body = JSON.parse(res.body) as { accessToken: string }; + adminToken = body.accessToken; + const userId = (JSON.parse(atob(adminToken.split(".")[1]!)) as { sub: string }).sub; + + await testDb.db.update(schema.users).set({ role: "admin" }).where(eq(schema.users.id, userId)); + + const quick = await app.inject({ + method: "POST", + url: "/v1/onboarding/quick-start", + headers: { authorization: `Bearer ${adminToken}` }, + payload: { goals: ["cook_more"], precisionMode: "simple" }, + }); + householdId = (JSON.parse(quick.body) as { householdId: string }).householdId; + }); + + afterAll(async () => { + await cleanup(); + await closeDatabase(); + await app.close(); + }); + + it("returns numeric score and status for admin", async () => { + const res = await app.inject({ + method: "GET", + url: `/admin/v1/households/${householdId}/trust`, + headers: { authorization: `Bearer ${adminToken}` }, + }); + expect(res.statusCode).toBe(200); + const body = JSON.parse(res.body) as { householdId: string; score: number; status: string; itemCount: number }; + expect(body.householdId).toBe(householdId); + expect(typeof body.score).toBe("number"); + expect(["up_to_date", "needs_check", "uncertain"]).toContain(body.status); + expect(body.itemCount).toBe(0); + }); +}); diff --git a/apps/mobile/src/app/(tabs)/home.tsx b/apps/mobile/src/app/(tabs)/home.tsx index 1c86c5a..aa5c154 100644 --- a/apps/mobile/src/app/(tabs)/home.tsx +++ b/apps/mobile/src/app/(tabs)/home.tsx @@ -40,7 +40,7 @@ interface BudgetSummary { export default function HomeScreen() { const inventory = useQuery({ queryKey: ["inventory"], - queryFn: () => api<{ items: InventoryItem[] }>("/v1/inventory?limit=100"), + queryFn: () => api<{ items: InventoryItem[]; trustStatus?: "up_to_date" | "needs_check" | "uncertain" }>("/v1/inventory?limit=100"), }); const expiring = useQuery({ queryKey: ["inventory-expiring"], @@ -64,9 +64,16 @@ export default function HomeScreen() { grouped.set(item.locationName, list); } + const trustStatus = inventory.data?.trustStatus; + return ( {t("home.title")} + {trustStatus && ( + + {t(`home.trustStatus.${trustStatus}`)} + + )} router.push("/shopping")} /> diff --git a/apps/mobile/src/components/ui.tsx b/apps/mobile/src/components/ui.tsx index 308c46e..964e792 100644 --- a/apps/mobile/src/components/ui.tsx +++ b/apps/mobile/src/components/ui.tsx @@ -9,6 +9,7 @@ import { View, type StyleProp, type TextInputProps, + type TextStyle, type ViewStyle, } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; @@ -46,8 +47,8 @@ export function Heading({ children }: { children: ReactNode }) { export function Body({ children, muted = false }: { children: ReactNode; muted?: boolean }) { return {children}; } -export function Small({ children }: { children: ReactNode }) { - return {children}; +export function Small({ children, style }: { children: ReactNode; style?: StyleProp }) { + return {children}; } export function Card({ diff --git a/apps/mobile/src/locales/da/common.json b/apps/mobile/src/locales/da/common.json index aacc0b7..33d262a 100644 --- a/apps/mobile/src/locales/da/common.json +++ b/apps/mobile/src/locales/da/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Ud fra hvad I har derhjemme, hvad der snart skal bruges, og hvad I kan lide.", "wte.title": "Hvad skal vi spise?", "wte.whyTitle": "Hvorfor dette forslag?", - "onboarding.primaryGoal": "Primært" + "onboarding.primaryGoal": "Primært", + "home.trustStatus.up_to_date": "Opdateret", + "home.trustStatus.needs_check": "Nogle varer skal tjekkes", + "home.trustStatus.uncertain": "Lageret er usikkert – lav en hurtig tjek" } diff --git a/apps/mobile/src/locales/de/common.json b/apps/mobile/src/locales/de/common.json index 6aa00fb..8ae4284 100644 --- a/apps/mobile/src/locales/de/common.json +++ b/apps/mobile/src/locales/de/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Basierend auf dem, was ihr zuhause habt, was bald verbraucht werden sollte und was ihr mögt.", "wte.title": "Was essen wir?", "wte.whyTitle": "Warum dieser Vorschlag?", - "onboarding.primaryGoal": "Primär" + "onboarding.primaryGoal": "Primär", + "home.trustStatus.up_to_date": "Aktuell", + "home.trustStatus.needs_check": "Einige Artikel müssen geprüft werden", + "home.trustStatus.uncertain": "Bestand unsicher – schnelle Kontrolle empfohlen" } diff --git a/apps/mobile/src/locales/en/common.json b/apps/mobile/src/locales/en/common.json index 36b6f09..c8c85a9 100644 --- a/apps/mobile/src/locales/en/common.json +++ b/apps/mobile/src/locales/en/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Based on what you have at home, what should be used up, and what you like.", "wte.title": "What's for dinner?", "wte.whyTitle": "Why this suggestion?", - "onboarding.primaryGoal": "Primary" + "onboarding.primaryGoal": "Primary", + "home.trustStatus.up_to_date": "Up to date", + "home.trustStatus.needs_check": "Some items need checking", + "home.trustStatus.uncertain": "Inventory uncertain – do a quick check" } diff --git a/apps/mobile/src/locales/es/common.json b/apps/mobile/src/locales/es/common.json index 5ab4afa..51f8ea2 100644 --- a/apps/mobile/src/locales/es/common.json +++ b/apps/mobile/src/locales/es/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Según lo que tenéis en casa, lo que conviene usar pronto y lo que os gusta.", "wte.title": "¿Qué comemos?", "wte.whyTitle": "¿Por qué esta sugerencia?", - "onboarding.primaryGoal": "Principal" + "onboarding.primaryGoal": "Principal", + "home.trustStatus.up_to_date": "Actualizado", + "home.trustStatus.needs_check": "Algunos productos necesitan revisión", + "home.trustStatus.uncertain": "Inventario incierto – haz una revisión rápida" } diff --git a/apps/mobile/src/locales/fi/common.json b/apps/mobile/src/locales/fi/common.json index d0c3789..837d786 100644 --- a/apps/mobile/src/locales/fi/common.json +++ b/apps/mobile/src/locales/fi/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Sen mukaan mitä kotona on, mikä pitäisi käyttää pian ja mistä pidätte.", "wte.title": "Mitä syödään?", "wte.whyTitle": "Miksi tämä ehdotus?", - "onboarding.primaryGoal": "Ensisijainen" + "onboarding.primaryGoal": "Ensisijainen", + "home.trustStatus.up_to_date": "Ajan tasalla", + "home.trustStatus.needs_check": "Joitakin tuotteita on tarkistettava", + "home.trustStatus.uncertain": "Varasto epävarma – tee pikatarkistus" } diff --git a/apps/mobile/src/locales/fr/common.json b/apps/mobile/src/locales/fr/common.json index fc73fd9..021b9f2 100644 --- a/apps/mobile/src/locales/fr/common.json +++ b/apps/mobile/src/locales/fr/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Selon ce que vous avez chez vous, ce qu'il faut consommer vite et vos goûts.", "wte.title": "On mange quoi ?", "wte.whyTitle": "Pourquoi cette suggestion ?", - "onboarding.primaryGoal": "Principal" + "onboarding.primaryGoal": "Principal", + "home.trustStatus.up_to_date": "À jour", + "home.trustStatus.needs_check": "Certains articles doivent être vérifiés", + "home.trustStatus.uncertain": "Inventaire incertain – faites un rapide contrôle" } diff --git a/apps/mobile/src/locales/it/common.json b/apps/mobile/src/locales/it/common.json index 38d4a76..cb54a64 100644 --- a/apps/mobile/src/locales/it/common.json +++ b/apps/mobile/src/locales/it/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "In base a ciò che avete in casa, a cosa va consumato presto e ai vostri gusti.", "wte.title": "Cosa mangiamo?", "wte.whyTitle": "Perché questo suggerimento?", - "onboarding.primaryGoal": "Primario" + "onboarding.primaryGoal": "Primario", + "home.trustStatus.up_to_date": "Aggiornato", + "home.trustStatus.needs_check": "Alcuni articoli devono essere controllati", + "home.trustStatus.uncertain": "Inventario incerto – fai un controllo rapido" } diff --git a/apps/mobile/src/locales/nb/common.json b/apps/mobile/src/locales/nb/common.json index 866e1e2..5b73f03 100644 --- a/apps/mobile/src/locales/nb/common.json +++ b/apps/mobile/src/locales/nb/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Basert på hva dere har hjemme, hva som snart bør brukes, og hva dere liker.", "wte.title": "Hva skal vi spise?", "wte.whyTitle": "Hvorfor dette forslaget?", - "onboarding.primaryGoal": "Primært" + "onboarding.primaryGoal": "Primært", + "home.trustStatus.up_to_date": "Oppdatert", + "home.trustStatus.needs_check": "Noen varer må sjekkes", + "home.trustStatus.uncertain": "Lageret er usikkert – gjør en rask sjekk" } diff --git a/apps/mobile/src/locales/nl/common.json b/apps/mobile/src/locales/nl/common.json index eebd5c4..4a43346 100644 --- a/apps/mobile/src/locales/nl/common.json +++ b/apps/mobile/src/locales/nl/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Op basis van wat jullie in huis hebben, wat snel op moet en wat jullie lekker vinden.", "wte.title": "Wat eten we?", "wte.whyTitle": "Waarom deze suggestie?", - "onboarding.primaryGoal": "Primair" + "onboarding.primaryGoal": "Primair", + "home.trustStatus.up_to_date": "Bijgewerkt", + "home.trustStatus.needs_check": "Sommige items moeten worden gecontroleerd", + "home.trustStatus.uncertain": "Voorraad onzeker – doe een snelle controle" } diff --git a/apps/mobile/src/locales/pl/common.json b/apps/mobile/src/locales/pl/common.json index 4b4fd64..401ef5b 100644 --- a/apps/mobile/src/locales/pl/common.json +++ b/apps/mobile/src/locales/pl/common.json @@ -360,5 +360,8 @@ "wte.subtitle": "Na podstawie tego, co macie w domu, co trzeba wkrótce zużyć i co lubicie.", "wte.title": "Co jemy?", "wte.whyTitle": "Dlaczego ta propozycja?", - "onboarding.primaryGoal": "Główny" + "onboarding.primaryGoal": "Główny", + "home.trustStatus.up_to_date": "Aktualne", + "home.trustStatus.needs_check": "Niektóre produkty wymagają sprawdzenia", + "home.trustStatus.uncertain": "Stan niepewny – zrób szybką kontrolę" } diff --git a/apps/mobile/src/locales/pt/common.json b/apps/mobile/src/locales/pt/common.json index 0f5cacd..57f0475 100644 --- a/apps/mobile/src/locales/pt/common.json +++ b/apps/mobile/src/locales/pt/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Com base no que têm em casa, no que deve ser usado em breve e no que gostam.", "wte.title": "O que vamos comer?", "wte.whyTitle": "Porquê esta sugestão?", - "onboarding.primaryGoal": "Principal" + "onboarding.primaryGoal": "Principal", + "home.trustStatus.up_to_date": "Atualizado", + "home.trustStatus.needs_check": "Alguns itens precisam de verificação", + "home.trustStatus.uncertain": "Inventário incerto – faça uma verificação rápida" } diff --git a/apps/mobile/src/locales/sv/common.json b/apps/mobile/src/locales/sv/common.json index 5a35376..9f53f0c 100644 --- a/apps/mobile/src/locales/sv/common.json +++ b/apps/mobile/src/locales/sv/common.json @@ -346,5 +346,8 @@ "wte.subtitle": "Utifrån vad ni har hemma, vad som bör användas och vad ni gillar.", "wte.title": "Vad ska vi äta?", "wte.whyTitle": "Varför detta förslag?", - "onboarding.primaryGoal": "Primärt" + "onboarding.primaryGoal": "Primärt", + "home.trustStatus.up_to_date": "Uppdaterat", + "home.trustStatus.needs_check": "Några varor behöver kontrolleras", + "home.trustStatus.uncertain": "Lagret är osäkert – gör en snabbkoll" } diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 1327707..4708c4a 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -210,7 +210,7 @@ async function registerRepeatableJobs() { ); await queue.upsertJobScheduler( "scheduler-trust", - { every: 300_000 }, + { every: 6 * 60 * 60 * 1000 }, // var 6:e timme; decay lever på dygnsskala { name: "UPDATE_TRUST_STATES", data: { jobType: "UPDATE_TRUST_STATES" }, opts: baseOpts }, ); await queue.upsertJobScheduler( diff --git a/apps/worker/src/processors/maintenance.ts b/apps/worker/src/processors/maintenance.ts index 9dfb4b1..04d84c4 100644 --- a/apps/worker/src/processors/maintenance.ts +++ b/apps/worker/src/processors/maintenance.ts @@ -1,4 +1,4 @@ -import { and, eq, gt, inArray, isNull, lte, sql } from "drizzle-orm"; +import { and, asc, eq, gt, inArray, isNull, lte, sql } from "drizzle-orm"; import { schema } from "@app/database"; import { classifyExpiry, computeTrust } from "@app/inventory-engine"; import { deriveMemoryUpdates } from "@app/memory-client"; @@ -57,6 +57,7 @@ export async function processTrustDecay(ctx: WorkerContext): Promise { .select() .from(schema.inventoryItems) .where(and(isNull(schema.inventoryItems.depletedAt), gt(schema.inventoryItems.quantity, 0))) + .orderBy(asc(schema.inventoryItems.updatedAt)) .limit(500); let updated = 0; diff --git a/packages/inventory-engine/src/trust.ts b/packages/inventory-engine/src/trust.ts index 9f93343..082663d 100644 --- a/packages/inventory-engine/src/trust.ts +++ b/packages/inventory-engine/src/trust.ts @@ -19,6 +19,7 @@ export interface InventoryItemLike { lastVerifiedAt: Date | string | null; quantity: number; updatedAt: Date | string; + depletedAt?: Date | string | null; } export interface TrustResult { @@ -118,6 +119,103 @@ export function itemTrustState( return computeTrust(item, now, profile).state; } +export interface HouseholdTrustInput { + items: InventoryItemLike[]; + /** Antal justeringstransaktioner senaste 30 dagarna (korrigeringsfrekvens). */ + correctionCount30d: number; + /** Totalt antal transaktioner senaste 30 dagarna (används för korrigeringsfrekvens). */ + transactionCount30d: number; +} + +export interface HouseholdTrustResult { + score: number; // 0–100 + status: "up_to_date" | "needs_check" | "uncertain"; +} + +export const TRUST_STATUS_THRESHOLDS = { + upToDate: 80, + needsCheck: 50, +} as const; + +/** + * Deterministisk household trust score 0–100. + * + * Viktade komponenter (Fas 2 §5.3): + * - 25% verifierade poster (verifiedByUser) + * - 25% ålder på senaste kontroll (nyare = bättre) + * - 20% andel uppskattade mängder (lägre confidence ger mer osäkerhet) + * - 15% poster som borde vara slut (låg quantity utan depletedAt straffar) + * - 15% korrigeringsfrekvens (fler korrigeringar = lägre förtroende) + * + * Decay påverkar FORTROENDE, inte ätbarhet. + */ +export function householdTrustScore( + input: HouseholdTrustInput, + now: Date = new Date(), +): HouseholdTrustResult { + const items = input.items.filter((i) => i.quantity > 0 && !i.depletedAt); + if (items.length === 0) { + return { score: 100, status: "up_to_date" }; + } + + const nowMs = now.getTime(); + + // 1. Andel verifierade (0–100) + const verifiedRatio = items.filter((i) => i.verifiedByUser).length / items.length; + const verifiedScore = verifiedRatio * 100; + + // 2. Ålder på senaste kontroll (0–100, 100 = alla kontrollerade inom 7 dagar) + const ageScore = + items.reduce((sum, i) => { + const verifiedMs = i.lastVerifiedAt ? new Date(i.lastVerifiedAt).getTime() : null; + const referenceMs = verifiedMs ?? new Date(i.updatedAt).getTime(); + const days = Math.max(0, (nowMs - referenceMs) / 86_400_000); + return sum + Math.max(0, 100 - (days / 30) * 100); + }, 0) / items.length; + + // 3. Andel uppskattade mängder (0–100, 100 = alla har confidence 1) + const confidenceScore = + items.reduce((sum, i) => sum + Math.min(1, Math.max(0, i.confidence)), 0) / items.length * 100; + + // 4. Poster som borde vara slut (0–100, 100 = inga låga kvantiteter) + const depletionScore = + items.reduce((sum, i) => { + const qty = i.quantity; + if (qty <= 0) return sum + 0; + if (qty < 0.2) return sum + 40; + if (qty < 0.5) return sum + 70; + return sum + 100; + }, 0) / items.length; + + // 5. Korrigeringsfrekvens (0–100, 100 = inga korrigeringar) + const correctionRatio = + input.transactionCount30d > 0 + ? input.correctionCount30d / input.transactionCount30d + : 0; + const correctionScore = Math.max(0, 100 - correctionRatio * 200); + + const score = Math.round( + verifiedScore * 0.25 + + ageScore * 0.25 + + confidenceScore * 0.20 + + depletionScore * 0.15 + + correctionScore * 0.15, + ); + + const clamped = Math.max(0, Math.min(100, score)); + + let status: HouseholdTrustResult["status"]; + if (clamped >= TRUST_STATUS_THRESHOLDS.upToDate) { + status = "up_to_date"; + } else if (clamped >= TRUST_STATUS_THRESHOLDS.needsCheck) { + status = "needs_check"; + } else { + status = "uncertain"; + } + + return { score: clamped, status }; +} + /** Pick the most urgent trust state from a list (used for household summary). */ export function worstTrustState(states: TrustState[]): TrustState { const order: TrustState[] = ["stale", "decaying", "unverified", "trusted"]; diff --git a/packages/inventory-engine/test/trust.test.ts b/packages/inventory-engine/test/trust.test.ts index a979af9..ff6a658 100644 --- a/packages/inventory-engine/test/trust.test.ts +++ b/packages/inventory-engine/test/trust.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { applyDecay, computeTrust, worstTrustState } from "../src/trust.js"; +import { applyDecay, computeTrust, householdTrustScore, worstTrustState } from "../src/trust.js"; const PINNED = new Date("2026-08-06T12:00:00.000Z"); @@ -96,6 +96,62 @@ describe("computeTrust", () => { }); }); +describe("householdTrustScore", () => { + it("returns 100 / up_to_date for empty inventory", () => { + const result = householdTrustScore({ items: [], correctionCount30d: 0, transactionCount30d: 0 }, PINNED); + expect(result.score).toBe(100); + expect(result.status).toBe("up_to_date"); + }); + + it("scores high when all items are verified and recent", () => { + const result = householdTrustScore( + { + items: [ + { confidence: 1, verifiedByUser: true, lastVerifiedAt: PINNED, quantity: 2, updatedAt: PINNED }, + { confidence: 1, verifiedByUser: true, lastVerifiedAt: PINNED, quantity: 3, updatedAt: PINNED }, + ], + correctionCount30d: 0, + transactionCount30d: 0, + }, + PINNED, + ); + expect(result.score).toBeGreaterThanOrEqual(80); + expect(result.status).toBe("up_to_date"); + }); + + it("drops to uncertain when items are old and unverified", () => { + const old = new Date(PINNED.getTime() - 60 * 86_400_000); + const result = householdTrustScore( + { + items: [ + { confidence: 0.3, verifiedByUser: false, lastVerifiedAt: null, quantity: 0.1, updatedAt: old }, + ], + correctionCount30d: 5, + transactionCount30d: 10, + }, + PINNED, + ); + expect(result.status).toBe("uncertain"); + expect(result.score).toBeLessThan(50); + }); + + it("flags needs_check for partly verified household", () => { + const weekAgo = new Date(PINNED.getTime() - 7 * 86_400_000); + const result = householdTrustScore( + { + items: [ + { confidence: 0.8, verifiedByUser: true, lastVerifiedAt: weekAgo, quantity: 1, updatedAt: weekAgo }, + { confidence: 0.5, verifiedByUser: false, lastVerifiedAt: null, quantity: 1, updatedAt: weekAgo }, + ], + correctionCount30d: 1, + transactionCount30d: 5, + }, + PINNED, + ); + expect(result.status).toBe("needs_check"); + }); +}); + describe("worstTrustState", () => { it("returns stale if present", () => { expect(worstTrustState(["trusted", "stale", "decaying"])).toBe("stale");