Files
kai 6cfdac2041
release / which version (push) Successful in 2s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m4s
release / tag and release (push) Successful in 2s
Prices and costs per dish, round total with budget light (26.11.16) (#17)
2026-11-07 06:18:41 +00:00

63 lines
2.7 KiB
TypeScript

import { randomUUID } from "node:crypto";
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { seedHousehold } from "./fixture";
vi.mock("server-only", () => ({}));
// lib/costs.ts gegen die Testdatenbank: Richtpreise aus dem Seed, eigener Preis
// schlägt Richtpreis, Grundvorrat zählt nicht einzeln, Einheit folgt der Eingabe.
const url = process.env.TEST_DATABASE_URL;
describe.skipIf(!url)("costs", () => {
const client = new pg.Client({ connectionString: url });
const h = randomUUID();
let costs: typeof import("@/lib/costs");
let db: typeof import("@/lib/db");
let dish = "";
let pasta = "";
let salt = "";
const as = <T>(fn: (c: pg.PoolClient) => Promise<T>) => db.withHousehold(h, fn);
beforeAll(async () => {
process.env.DATABASE_URL = url;
await client.connect();
const one = async (key: string) => (await client.query("select id from ingredients where key = $1", [key])).rows[0].id as string;
pasta = await one("spaghetti");
salt = await one("salt");
await seedHousehold(client, h, await one("potato")); // Bonpreis der Vorlage liegt auf Kartoffeln
costs = await import("@/lib/costs");
db = await import("@/lib/db");
await as(async (c) => {
dish = (await c.query("insert into dishes (household_id, title) values ($1, 'Nudeln') returning id", [h])).rows[0].id;
await c.query(
"insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit, position, is_staple) values ($1, $2, $3, 125, 'g', 1, false), ($1, $2, $4, 2, 'g', 2, true)",
[h, dish, pasta, salt],
);
});
});
afterAll(async () => {
await db.pool.end();
await client.end();
});
it("prices a dish from default prices with no confidence dots", async () => {
const r = await as(async (c) => (await costs.dishCosts(c, await costs.loadPrices(c, "EUR"), [dish])).get(dish));
expect(r?.perPortion).toBeGreaterThan(0);
expect(r).toMatchObject({ priced: 1, total: 1, confidence: 0 }); // Salz ist Grundvorrat
});
it("lets a manual price win over the default", async () => {
await as((c) => costs.setManualPrice(c, h, pasta, 2, 1, "kg")); // 2 € je kg → 0,25 € für 125 g
const r = await as(async (c) => (await costs.dishCosts(c, await costs.loadPrices(c, "EUR"), [dish])).get(dish));
expect(r?.perPortion).toBeCloseTo(0.25 * 1.05, 2);
const p = await as(async (c) => (await costs.loadPrices(c, "EUR")).get(pasta));
expect(p).toMatchObject({ source: "manual", unit: "g" });
});
it("refuses an amount that does not fit the unit", async () => {
await expect(as((c) => costs.setManualPrice(c, h, pasta, 2, 0, "g"))).rejects.toBeInstanceOf(costs.PriceRefused);
});
});