Cotton code
182 lines · 10.9 KB · TypeScriptRaw
import { SELF } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import { addDays, localDate, type ActAnswer, type SyncAnswer, type WireRow } from "../src/protocol.ts";import { KITCHEN_TABLES, KITCHEN_TOOLS, NANCY_FLAVOUR } from "./kitchen.ts";const ADMIN = { authorization: "Bearer test-admin-token" };const TODAY = localDate(new Date(), "Asia/Kolkata");interface Answer<T> {  status: number;  body: T;}async function call<T = Record<string, unknown>>(slug: string, method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<Answer<T>> {  const res = await SELF.fetch(`https://example.test/b/${slug}${path}`, {    method,    headers: { "content-type": "application/json", ...headers },    body: body === undefined ? undefined : JSON.stringify(body),  });  return { status: res.status, body: (await res.json()) as T };}async function signIn(slug: string, phone: string, name?: string): Promise<{ credential: string; person: { id: string; role: string } }> {  const code = await call<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone, device_id: `device-${phone}` });  expect(code.status, JSON.stringify(code.body)).toBe(200);  const signed = await call<{ credential: string; person: { id: string; role: string } }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: `device-${phone}`, name });  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  return signed.body;}const auth = (credential: string): Record<string, string> => ({ authorization: `Bearer ${credential}` });async function act(slug: string, credential: string, act: string, args: Record<string, unknown>): Promise<Answer<ActAnswer & { code?: string; message?: string }>> {  return call(slug, "POST", "/v1/act", { act, args }, auth(credential));}async function sync(slug: string, credential: string | null): Promise<SyncAnswer> {  const answer = await call<SyncAnswer>(slug, "GET", "/v1/sync?since=0", undefined, credential ? auth(credential) : {});  expect(answer.status, JSON.stringify(answer.body)).toBe(200);  return answer.body;}const rowsOf = (rows: WireRow[], table: string): WireRow[] => rows.filter((r) => r.table === table && !r.deleted);/** RULE (owner, 24 Oct 2026): a business is JSON and seed data, never code — the kitchen packages install into an empty object and Nancy's rows follow. */describe("a business object running the kitchen packages", () => {  const slug = "kitchen";  const ids: Record<string, string> = {};  let owner = "";  let kavya = "";  beforeAll(async () => {    expect((await call(slug, "PUT", "/v1/admin/business", { name: "Nancy's Naga Kitchen", currency: "INR", timezone: "Asia/Kolkata", owner_phone: "+919100000001" }, ADMIN)).status).toBe(200);    expect((await call(slug, "PUT", "/v1/admin/definitions", { tools: KITCHEN_TOOLS, tables: KITCHEN_TABLES, flavour: NANCY_FLAVOUR }, ADMIN)).status).toBe(200);    const seeded = await call<{ ids: Record<string, string> }>(slug, "POST", "/v1/admin/import", {      rows: [        { ref: "pork", table: "kitchen_dish", data: { name: "Axone Pork with Rice", kind: "non_veg", price: 29900, currency: "INR", available: true } },        { ref: "rajma", table: "kitchen_dish", data: { name: "Rajma Rice", kind: "veg", price: 14900, currency: "INR", available: true } },        { ref: "today", table: "kitchen_menu_day", data: { name: "Today's pork", dish: "@pork", on: TODAY, quota: 2 } },        { ref: "tomorrow", table: "kitchen_menu_day", data: { name: "Tomorrow's rajma", dish: "@rajma", on: addDays(TODAY, 1), quota: 12 } },        { ref: "plan", table: "kitchen_plan", data: { name: "Weekday lunch · 5 meals", meals: 5, valid_days: 7, price: 119900, currency: "INR", available: true } },      ],    }, ADMIN);    expect(seeded.status, JSON.stringify(seeded.body)).toBe(200);    Object.assign(ids, seeded.body.ids);    owner = (await signIn(slug, "+919100000001", "Nancy")).credential;    kavya = (await signIn(slug, "+919100000002", "Kavya")).credential;  });  it("a customer's order is quoted from the dish, lined, and delivered unpaid; the quota counts down", async () => {    const order = await act(slug, kavya, "order", { slot: ids.today, quantity: 1 });    expect(order.status, JSON.stringify(order.body)).toBe(200);    expect(order.body.made!.table).toBe("kitchen_order");    const made = order.body.changed.find((r) => r.id === order.body.made!.id)!;    expect(made.data.quantity).toBe(1);    expect(made.data.currency).toBe("INR");    expect(made.data.for_day).toBe(TODAY);    const line = order.body.changed.find((r) => r.table === "kitchen_order_line")!;    expect(line.data.order).toBe(made.id);    expect(line.data.dish).toBe(ids.pork);    expect(line.data.price).toBe(29900);    expect(line.data.line_total).toBe(29900);    expect(line.data.name).toBe("Axone Pork with Rice");    expect(line.data.customer).toBe(made.data.customer);    const delivery = order.body.changed.find((r) => r.table === "kitchen_delivery")!;    expect(delivery.data.order).toBe(made.id);    expect(delivery.data.due_on).toBe(TODAY);    expect(delivery.data.delivered).toBe(false);    expect(delivery.data.paid).toBe(false);    ids.kavyaOrder = made.id;    ids.kavyaDelivery = delivery.id;    const tooMany = await act(slug, kavya, "order", { slot: ids.today, quantity: 2 });    expect(tooMany.status).toBe(409);    expect(tooMany.body.code).toBe("full");    const mine = await sync(slug, kavya);    expect(rowsOf(mine.rows, "kitchen_order").map((r) => r.id)).toEqual([made.id]);    expect(rowsOf(mine.rows, "kitchen_order_line").length).toBe(1);    expect(rowsOf(mine.rows, "kitchen_delivery").length).toBe(1);    const open = await sync(slug, null);    expect(rowsOf(open.rows, "kitchen_order").length).toBe(0);    expect(rowsOf(open.rows, "kitchen_menu_day").length).toBe(2);  });  it("the chef marks a delivery delivered, then paid, which writes the payment", async () => {    const delivered = await act(slug, owner, "record_act", { table: "kitchen_delivery", id: ids.kavyaDelivery, act: "delivered" });    expect(delivered.status, JSON.stringify(delivered.body)).toBe(200);    const row = delivered.body.changed.find((r) => r.table === "kitchen_delivery")!;    expect(row.data.delivered).toBe(true);    expect(row.data.delivered_at).toBe(TODAY);    const paid = await act(slug, owner, "record_act", { table: "kitchen_delivery", id: ids.kavyaDelivery, act: "paid" });    expect(paid.status, JSON.stringify(paid.body)).toBe(200);    const payment = paid.body.changed.find((r) => r.table === "kitchen_payment")!;    expect(payment.data.amount).toBe(29900);    expect(payment.data.order).toBe(ids.kavyaOrder);    expect(payment.data.taken_on).toBe(TODAY);    const again = await act(slug, owner, "record_act", { table: "kitchen_delivery", id: ids.kavyaDelivery, act: "paid" });    expect(again.status).toBe(409);  });  it("cancelling an order takes its line with it and gives the plate back", async () => {    const order = await act(slug, kavya, "order", { slot: ids.tomorrow, quantity: 2 });    expect(order.status, JSON.stringify(order.body)).toBe(200);    const cancelled = await act(slug, kavya, "cancel", { id: order.body.made!.id });    expect(cancelled.status, JSON.stringify(cancelled.body)).toBe(200);    const gone = cancelled.body.changed.filter((r) => r.deleted).map((r) => r.table).sort();    expect(gone).toEqual(["kitchen_order", "kitchen_order_line"]);    const after = await act(slug, kavya, "order", { slot: ids.tomorrow, quantity: 12 });    expect(after.status, JSON.stringify(after.body)).toBe(200);  });  it("a dish's Order takes the order on the menu day picked among that dish's, and refuses another dish's day", async () => {    const later = await call<{ ids: Record<string, string> }>(slug, "POST", "/v1/admin/import", {      rows: [{ ref: "later", table: "kitchen_menu_day", data: { name: "Later rajma", dish: ids.rajma, on: addDays(TODAY, 2), quota: 3 } }],    }, ADMIN);    expect(later.status, JSON.stringify(later.body)).toBe(200);    const day = later.body.ids.later!;    const customer = rowsOf((await sync(slug, owner)).rows, "kitchen_customer")[0]!;    const order = await act(slug, owner, "record_act", { table: "kitchen_dish", id: ids.rajma, act: "order", picked: [day, customer.id, 2] });    expect(order.status, JSON.stringify(order.body)).toBe(200);    const made = order.body.changed.find((r) => r.id === order.body.made!.id)!;    expect(made.table).toBe("kitchen_order");    expect(made.data.customer).toBe(customer.id);    expect(made.data.quantity).toBe(2);    expect(order.body.changed.find((r) => r.table === "kitchen_order_line")!.data.dish).toBe(ids.rajma);    const elsewhere = await act(slug, owner, "record_act", { table: "kitchen_dish", id: ids.pork, act: "order", picked: [day, customer.id, 1] });    expect(elsewhere.status, "a day of another dish is no choice for this one").toBe(400);    expect(elsewhere.body.code).toBe("bad_pick");  });  it("a meal on a plan is priced nothing, drawn from the plan's meals and delivered paid", async () => {    const customer = rowsOf((await sync(slug, kavya)).rows, "kitchen_customer")[0]!;    const seeded = await call<{ ids: Record<string, string> }>(slug, "POST", "/v1/admin/import", {      rows: [        { ref: "sub", table: "kitchen_subscription", data: { name: "Kavya · 5 meals", customer: customer.id, plan: ids.plan, meals: 1, started_on: TODAY, ends_on: addDays(TODAY, 6), status: "active" } },        { ref: "later", table: "kitchen_menu_day", data: { name: "Later rajma", dish: "@rajma", on: addDays(TODAY, 2), quota: 12 } },        { ref: "meal", verb: "reserve", slot: "@later", data: { customer: customer.id, name: "Kavya's lunch", quantity: 1, subscription: "@sub" } },        { ref: "delivery", verb: "find", table: "kitchen_delivery", where: { order: "@meal" } },      ].map((row) => (row.ref === "later" ? { ...row, data: { ...row.data, dish: ids.rajma } } : row)),    }, ADMIN);    expect(seeded.status, JSON.stringify(seeded.body)).toBe(200);    const all = await sync(slug, owner);    const meal = all.rows.find((r) => r.id === seeded.body.ids.meal)!;    expect(meal.data.subscription).toBe(seeded.body.ids.sub);    const line = rowsOf(all.rows, "kitchen_order_line").find((r) => r.data.order === meal.id)!;    expect(line.data.price).toBe(0);    expect(line.data.line_total).toBe(0);    const delivery = all.rows.find((r) => r.id === seeded.body.ids.delivery)!;    expect(delivery.data.paid).toBe(true);    expect(delivery.data.subscription).toBe(seeded.body.ids.sub);    const second = await call<{ code: string; message: string }>(slug, "POST", "/v1/admin/import", {      rows: [{ verb: "reserve", slot: seeded.body.ids.later, data: { customer: customer.id, name: "Kavya's second lunch", quantity: 1, subscription: seeded.body.ids.sub } }],    }, ADMIN);    expect(second.status).toBe(409);    expect(second.body.code).toBe("ledger_refused");  });});