145 lines
7.6 KiB
TypeScript
145 lines
7.6 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { existsSync } from "node:fs";
|
|
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import pg from "pg";
|
|
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import { seedHousehold } from "./fixture";
|
|
|
|
vi.mock("server-only", () => ({}));
|
|
|
|
// Kassenbons gegen die Testdatenbank (lib/receipts.ts): Vorschläge aus Produkt,
|
|
// Suche und Gelerntem; Bestätigen schreibt Preise, lernt die Zeile, löscht das Foto.
|
|
const url = process.env.TEST_DATABASE_URL;
|
|
|
|
describe.skipIf(!url)("receipts", () => {
|
|
const client = new pg.Client({ connectionString: url });
|
|
const h = randomUUID();
|
|
let kai = "";
|
|
let store = "";
|
|
let spaghetti = "";
|
|
let receipts: typeof import("@/lib/receipts");
|
|
let db: typeof import("@/lib/db");
|
|
let dir = "";
|
|
const as = <T>(fn: (c: pg.PoolClient) => Promise<T>) => db.withHousehold(h, fn);
|
|
|
|
async function receiptWith(lines: [string, number | null][]): Promise<string> {
|
|
const id = randomUUID();
|
|
const photo = `${h}/${id}.jpg`;
|
|
await mkdir(path.join(dir, "bons", h), { recursive: true });
|
|
await writeFile(path.join(dir, "bons", photo), "x");
|
|
await as(async (c) => {
|
|
await c.query("insert into receipts (id, household_id, photo_path, status, store_id, created_by) values ($1, $2, $3, 'review', $4, $5)", [id, h, photo, store, kai]);
|
|
const s = await receipts.suggestLines(c, lines.map((l) => l[0]), "de", null);
|
|
for (const [i, [text, price]] of lines.entries()) {
|
|
await c.query(
|
|
`insert into receipt_lines (household_id, receipt_id, position, raw_text, total_price, ingredient_id, pack_qty, pack_unit, match_source)
|
|
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
|
[h, id, i + 1, text, price, s[i]!.ingredientId, s[i]!.pack?.qty ?? null, s[i]!.pack?.unit ?? null, s[i]!.source],
|
|
);
|
|
}
|
|
});
|
|
return id;
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
process.env.DATABASE_URL = url;
|
|
dir = await mkdtemp(path.join(os.tmpdir(), "lunch-bons-"));
|
|
process.env.APP_DATA_DIR = dir;
|
|
await client.connect();
|
|
spaghetti = (await client.query("select id from ingredients where key = 'spaghetti'")).rows[0].id;
|
|
const potato = (await client.query("select id from ingredients where key = 'potato'")).rows[0].id;
|
|
kai = (await seedHousehold(client, h, potato)).member;
|
|
receipts = await import("@/lib/receipts");
|
|
db = await import("@/lib/db");
|
|
await as(async (c) => {
|
|
store = (await c.query("select id from stores where is_default")).rows[0].id;
|
|
const dish = (await c.query("insert into dishes (household_id, title) values ($1, 'Pasta') returning id", [h])).rows[0].id;
|
|
await c.query(
|
|
"insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit, product) values ($1, $2, $3, 100, 'g', 'Barilla Spaghetti Nr. 5')",
|
|
[h, dish, spaghetti],
|
|
);
|
|
});
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await db.pool.end();
|
|
await client.end();
|
|
});
|
|
|
|
it("suggests from the dish's product, from search, and leaves household goods open", async () => {
|
|
const s = await as((c) => receipts.suggestLines(c, ["BARILLA SPAGH N5 500G", "ZWIEBELN", "KLOPAPIER 8ST"], "de", null));
|
|
expect(s[0]).toMatchObject({ ingredientId: spaghetti, source: "product", product: "Barilla Spaghetti Nr. 5", pack: { qty: 500, unit: "g" } });
|
|
expect(s[1]).toMatchObject({ source: "search" });
|
|
expect(s[2]).toMatchObject({ ingredientId: null, source: null });
|
|
});
|
|
|
|
it("confirming writes the price per gram, learns the line and deletes the photo", async () => {
|
|
const id = await receiptWith([["BARILLA SPAGH N5 500G", 1.79], ["KLOPAPIER 8ST", 3.49]]);
|
|
const r = await as((c) => receipts.getReceipt(c, id, "de"));
|
|
const photo = path.join(dir, "bons", h, `${id}.jpg`);
|
|
expect(existsSync(photo)).toBe(true);
|
|
await as((c) =>
|
|
receipts.confirmReceipt(c, h, id, {
|
|
storeId: store,
|
|
purchasedAt: "2026-11-07",
|
|
decisions: r!.lines.map((l: import("@/lib/receipts").ReviewLine) => ({ lineId: l.id, ingredientId: l.ingredientId, packQty: l.packQty, packUnit: l.packUnit as "g" | null })),
|
|
}),
|
|
);
|
|
const price = await as(async (c) => (await c.query("select price_per_unit::float as p, source, observed_at::date::text as d from price_points where receipt_id = $1", [id])).rows);
|
|
expect(price).toEqual([{ p: expect.closeTo(1.79 / 500, 6), source: "receipt", d: "2026-11-07" }]);
|
|
expect(existsSync(photo)).toBe(false);
|
|
expect(await as(async (c) => (await c.query("select status from receipts where id = $1", [id])).rows[0].status)).toBe("done");
|
|
// Dieselbe Zeile fragt die App nie wieder: gelernt.
|
|
const again = await as((c) => receipts.suggestLines(c, ["BARILLA SPAGH N5 500G"], "de", null));
|
|
expect(again[0]).toMatchObject({ ingredientId: spaghetti, source: "alias", pack: { qty: 500, unit: "g" } });
|
|
});
|
|
|
|
it("a line swiped away as not for cooking is remembered, and assigning it later overrides that (26.11.33)", async () => {
|
|
const id = await receiptWith([["TOASTBROT 500G", 1.19], ["KLOPAPIER 8ST", 3.49]]);
|
|
const r = await as((c) => receipts.getReceipt(c, id, "de"));
|
|
const [toast, paper] = r!.lines;
|
|
await as((c) =>
|
|
receipts.confirmReceipt(c, h, id, {
|
|
storeId: null,
|
|
purchasedAt: null,
|
|
decisions: [
|
|
{ lineId: toast!.id, ingredientId: null, packQty: null, packUnit: null, skip: true },
|
|
{ lineId: paper!.id, ingredientId: null, packQty: null, packUnit: null }, // nur nicht zugeordnet: wird nicht gelernt
|
|
],
|
|
}),
|
|
);
|
|
expect(await as(async (c) => (await c.query("select skipped from receipt_lines where id = $1", [toast!.id])).rows[0].skipped)).toBe(true);
|
|
const next = await as((c) => receipts.suggestLines(c, ["TOASTBROT 500G", "KLOPAPIER 8ST"], "de", null));
|
|
expect(next[0]).toEqual({ ingredientId: null, source: "skip", product: null, pack: null });
|
|
expect(next[1]).toMatchObject({ ingredientId: null, source: null });
|
|
// Toast Hawaii: doch zugeordnet — die gelernte Zuordnung gilt ab jetzt.
|
|
const id2 = await receiptWith([["TOASTBROT 500G", 1.19]]);
|
|
const r2 = await as((c) => receipts.getReceipt(c, id2, "de"));
|
|
await as((c) =>
|
|
receipts.confirmReceipt(c, h, id2, { storeId: null, purchasedAt: null, decisions: [{ lineId: r2!.lines[0]!.id, ingredientId: spaghetti, packQty: 500, packUnit: "g" }] }),
|
|
);
|
|
const after = await as((c) => receipts.suggestLines(c, ["TOASTBROT 500G"], "de", null));
|
|
expect(after[0]).toMatchObject({ ingredientId: spaghetti, source: "alias" });
|
|
});
|
|
|
|
it("two packs of 400 g give the price per gram of all 800 g", async () => {
|
|
const id = await receiptWith([["RINDERHACKFLEI. XXL -", 17.58]]);
|
|
await as((c) => c.query("update receipt_lines set qty = 2 where receipt_id = $1", [id]));
|
|
const r = await as((c) => receipts.getReceipt(c, id, "de"));
|
|
await as((c) =>
|
|
receipts.confirmReceipt(c, h, id, { storeId: null, purchasedAt: null, decisions: [{ lineId: r!.lines[0]!.id, ingredientId: spaghetti, packQty: 400, packUnit: "g" }] }),
|
|
);
|
|
const p = await as(async (c) => (await c.query("select price_per_unit::float as p from price_points where receipt_id = $1", [id])).rows[0].p);
|
|
expect(p * 100).toBeCloseTo(2.1975, 4); // 2,20 € je 100 g
|
|
});
|
|
|
|
it("refuses to confirm twice", async () => {
|
|
const id = await receiptWith([["ZWIEBELN", 0.99]]);
|
|
const confirm = () => as((c) => receipts.confirmReceipt(c, h, id, { storeId: null, purchasedAt: null, decisions: [] }));
|
|
await confirm();
|
|
await expect(confirm()).rejects.toBeInstanceOf(receipts.ReceiptRefused);
|
|
});
|
|
});
|