Events can charge per print: the guest pays on Stripe's page first and the webhook (shared with the shop) sends the job to the queue or to approval; abandoned payments cancel the job. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
147 lines
10 KiB
TypeScript
147 lines
10 KiB
TypeScript
import { mkdtemp, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import sharp from "sharp";
|
|
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
|
import { layoutPrint } from "../src/print/layout.js";
|
|
import { MemoryBroadcaster } from "../src/realtime.js";
|
|
import { signWebhook } from "../src/shop/stripe.js";
|
|
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
|
|
|
const GUEST = "guest-0123456789abcdef";
|
|
|
|
function multipart(fields: Record<string, string>, file: Buffer) {
|
|
const boundary = "----pr-print";
|
|
const parts = Object.entries(fields).map(([k, v]) => Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`));
|
|
const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="selfie.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`);
|
|
return { payload: Buffer.concat([...parts, head, file, Buffer.from(`\r\n--${boundary}--\r\n`)]), headers: { "content-type": `multipart/form-data; boundary=${boundary}` } };
|
|
}
|
|
|
|
describe("print layout", () => {
|
|
it("fills the paper in the photo's orientation, with the event's band", async () => {
|
|
const landscape = await sharp({ create: { width: 3000, height: 2000, channels: 3, background: "#336699" } }).jpeg().toBuffer();
|
|
const out = await layoutPrint(landscape, "15x20", { bandText: "Casamento Ana & Rui", bandColor: "#ffffff", textColor: "#111111", borderMm: 3 });
|
|
const meta = await sharp(out).metadata();
|
|
expect([meta.width, meta.height, meta.density]).toEqual([2400, 1800, 300]);
|
|
const portrait = await sharp({ create: { width: 1000, height: 1600, channels: 3, background: "#993333" } }).jpeg().toBuffer();
|
|
expect(await sharp(await layoutPrint(portrait, "10x15", { bandText: "", bandColor: "#ffffff", textColor: "#111111", borderMm: 0 })).metadata()).toMatchObject({ width: 1200, height: 1800 });
|
|
});
|
|
});
|
|
|
|
describe("printing", () => {
|
|
let ctx: TestContext;
|
|
let dir: string;
|
|
const broadcaster = new MemoryBroadcaster();
|
|
const stripeCalls: string[] = [];
|
|
|
|
beforeAll(async () => {
|
|
dir = await mkdtemp(path.join(tmpdir(), "pr-print-"));
|
|
const fakeStripe: typeof fetch = async (input, init) => {
|
|
stripeCalls.push(String(init?.body ?? ""));
|
|
return String(input).includes("/v1/checkout/sessions") ? Response.json({ id: "cs_print_1", url: "https://checkout.stripe.com/c/pay/cs_print_1" }) : new Response("no", { status: 404 });
|
|
};
|
|
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: path.join(dir, "ingest"), DELIVERY_SECRET_KEY: Buffer.alloc(32, 9).toString("base64") }, broadcaster, fakeStripe);
|
|
});
|
|
afterAll(async () => {
|
|
await ctx.app.close();
|
|
await ctx.db.$disconnect();
|
|
await rm(dir, { recursive: true, force: true });
|
|
});
|
|
beforeEach(async () => {
|
|
await resetDb(ctx.db);
|
|
broadcaster.sent.length = 0;
|
|
});
|
|
|
|
async function setup(event: Record<string, unknown> = {}) {
|
|
const { org } = await seedUser(ctx.db, "[email protected]", { org: "events", role: "OWNER" });
|
|
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
|
const api = (method: "GET" | "POST" | "PATCH" | "PUT", url: string, payload?: unknown) => ctx.app.inject({ method, url, headers: bearer(token), ...(payload !== undefined && { payload: payload as object }) });
|
|
const created = await api("POST", `/v1/orgs/${org!.id}/print-events`, { name: "Casamento Ana & Rui", template: { bandText: "Ana & Rui · 11.10.2026" }, ...event });
|
|
expect(created.statusCode).toBe(201);
|
|
return { orgId: org!.id, api, event: created.json() as { id: string; slug: string } };
|
|
}
|
|
|
|
const photo = (color = "#446688") => sharp({ create: { width: 1600, height: 1200, channels: 3, background: color } }).jpeg().toBuffer();
|
|
const upload = async (slug: string, guest = GUEST, name = "Tia Rosa") => {
|
|
const body = multipart({ guest, name }, await photo());
|
|
return ctx.app.inject({ method: "POST", url: `/v1/public/print/${slug}/upload`, ...body });
|
|
};
|
|
|
|
it("takes guests' photos from the QR page into the queue, with a limit per guest", async () => {
|
|
const { event } = await setup({ guestLimit: 2 });
|
|
expect(event.slug).toBe("casamento-ana-rui");
|
|
const page = (await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}` })).json();
|
|
expect(page).toMatchObject({ name: "Casamento Ana & Rui", size: "15x20", active: true });
|
|
|
|
expect((await upload(event.slug)).statusCode).toBe(201);
|
|
expect((await upload(event.slug)).json()).toMatchObject({ status: "QUEUED" });
|
|
expect((await upload(event.slug)).json()).toMatchObject({ error: "guest_limit" });
|
|
expect((await upload(event.slug, "another-guest-012345")).statusCode).toBe(201);
|
|
|
|
const mine = (await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/jobs?guest=${GUEST}` })).json() as { jobs: { ahead: number; preview: string }[] };
|
|
expect(mine.jobs.map((j) => j.ahead).sort()).toEqual([0, 1]);
|
|
const preview = await ctx.app.inject({ method: "GET", url: mine.jobs[0]!.preview });
|
|
expect(preview.statusCode).toBe(200);
|
|
expect(broadcaster.sent.filter((s) => s.message.type === "print.updated")).toHaveLength(3);
|
|
});
|
|
|
|
it("holds jobs for approval when the event asks for it", async () => {
|
|
const { event, api } = await setup({ requireApproval: true });
|
|
const { id } = (await upload(event.slug)).json() as { id: string };
|
|
expect((await api("GET", `/v1/print-events/${event.id}/jobs`)).json().jobs[0]).toMatchObject({ status: "APPROVAL", guestName: "Tia Rosa" });
|
|
expect((await api("POST", `/v1/print-jobs/${id}/approve`, {})).json()).toMatchObject({ status: "QUEUED" });
|
|
});
|
|
|
|
it("pairs a station, learns its printers, and prints only on paper that is loaded", async () => {
|
|
const { orgId, api, event } = await setup();
|
|
const { code } = (await api("POST", `/v1/orgs/${orgId}/print-stations`, { name: "Portátil do evento" })).json() as { code: string };
|
|
expect((await ctx.app.inject({ method: "POST", url: "/v1/print/agent/pair", payload: { code: "WRONGCODE" } })).statusCode).toBe(401);
|
|
const paired = (await ctx.app.inject({ method: "POST", url: "/v1/print/agent/pair", payload: { code: code.toLowerCase(), platform: "darwin", agentVersion: "0.1.0" } })).json() as { token: string };
|
|
expect(paired.token).toMatch(/^pst_/);
|
|
// The code works once.
|
|
expect((await ctx.app.inject({ method: "POST", url: "/v1/print/agent/pair", payload: { code } })).statusCode).toBe(401);
|
|
const agent = (method: "GET" | "POST", url: string, payload?: unknown) => ctx.app.inject({ method, url, headers: { authorization: `Bearer ${paired.token}` }, ...(payload !== undefined && { payload: payload as object }) });
|
|
|
|
expect((await agent("POST", "/v1/print/agent/heartbeat", { printers: [{ systemName: "Mitsubishi_CP_D90DW", state: "idle" }] })).statusCode).toBe(200);
|
|
const { printers, stations } = (await api("GET", `/v1/orgs/${orgId}/printers`)).json() as { printers: { id: string; sizes: string[]; online: boolean }[]; stations: { online: boolean; paired: boolean }[] };
|
|
expect(printers[0]).toMatchObject({ sizes: ["15x20"], online: true });
|
|
expect(stations[0]).toMatchObject({ paired: true, online: true });
|
|
|
|
// A 10x15 event: nothing to claim until the operator says that paper is loaded.
|
|
await api("PATCH", `/v1/print-events/${event.id}`, { size: "10x15" });
|
|
await upload(event.slug);
|
|
expect((await agent("POST", "/v1/print/agent/claim")).json()).toEqual({ job: null });
|
|
await api("PATCH", `/v1/printers/${printers[0]!.id}`, { sizes: ["15x20", "10x15"] });
|
|
const { job } = (await agent("POST", "/v1/print/agent/claim")).json() as { job: { id: string; printer: string; size: string; file: string } };
|
|
expect(job).toMatchObject({ printer: "Mitsubishi_CP_D90DW", size: "10x15" });
|
|
const file = await agent("GET", job.file);
|
|
expect((await sharp(file.rawPayload).metadata()).width).toBe(1800); // landscape 10x15
|
|
expect((await agent("POST", `/v1/print/agent/jobs/${job.id}/result`, { ok: true })).statusCode).toBe(200);
|
|
expect((await api("GET", `/v1/print-events/${event.id}/jobs`)).json().jobs[0]).toMatchObject({ status: "DONE" });
|
|
|
|
// A printer error: retried, then failed after three attempts; reprint puts it back.
|
|
await upload(event.slug, "third-guest-0123456");
|
|
for (let i = 0; i < 3; i++) {
|
|
const claimed = (await agent("POST", "/v1/print/agent/claim")).json() as { job: { id: string } };
|
|
await agent("POST", `/v1/print/agent/jobs/${claimed.job.id}/result`, { ok: false, error: "paper jam" });
|
|
}
|
|
const failed = (await api("GET", `/v1/print-events/${event.id}/jobs`)).json().jobs[0];
|
|
expect(failed).toMatchObject({ status: "FAILED", error: "paper jam" });
|
|
expect((await api("POST", `/v1/print-jobs/${failed.id}/reprint`, {})).json()).toMatchObject({ status: "QUEUED" });
|
|
expect((await ctx.app.inject({ method: "POST", url: "/v1/print/agent/claim", headers: { authorization: "Bearer pst_nope" } })).statusCode).toBe(401);
|
|
});
|
|
|
|
it("sells prints: the guest pays first, the webhook sends the job to the queue", async () => {
|
|
const { orgId, api, event } = await setup({ priceCents: 300 });
|
|
await api("PUT", `/v1/orgs/${orgId}/shop-settings`, { stripeSecretKey: "sk_test_print", stripeWebhookSecret: "whsec_print" });
|
|
const created = (await ctx.app.inject({ method: "POST", url: `/v1/public/print/${event.slug}/upload`, headers: { ...multipart({ guest: GUEST }, await photo()).headers, "x-site-domain": "events.photoreport.pt" }, payload: multipart({ guest: GUEST }, await photo()).payload })).json() as { id: string; status: string; checkoutUrl: string };
|
|
expect(created).toMatchObject({ status: "PAYMENT", checkoutUrl: "https://checkout.stripe.com/c/pay/cs_print_1" });
|
|
expect(decodeURIComponent(stripeCalls[0]!)).toContain(`success_url=https://events.photoreport.pt/e/${event.slug}?paid=${created.id}`);
|
|
expect(decodeURIComponent(stripeCalls[0]!)).toContain("unit_amount]=300");
|
|
const body = JSON.stringify({ type: "checkout.session.completed", data: { object: { id: "cs_print_1", payment_status: "paid", metadata: { print_job_id: created.id } } } });
|
|
const hook = await ctx.app.inject({ method: "POST", url: `/v1/public/stripe/${orgId}/webhook`, headers: { "content-type": "application/json", "stripe-signature": signWebhook(body, "whsec_print") }, payload: body });
|
|
expect(hook.statusCode).toBe(200);
|
|
expect((await api("GET", `/v1/print-events/${event.id}/jobs`)).json().jobs[0]).toMatchObject({ status: "QUEUED" });
|
|
});
|
|
});
|