Fas 2 steg 3: Household Trust Score (admin + i18n status i appen)
This commit is contained in:
@@ -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<number>`count(*)`,
|
||||
adjustments: sql<number>`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
|
||||
|
||||
@@ -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<number>`count(*)`,
|
||||
adjustments: sql<number>`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). */
|
||||
|
||||
@@ -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<ReturnType<typeof buildServer>>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user