Files
photoreport/apps/api/test/shop.test.ts
T
sparkandClaude Opus 5.5 8947a51d83
ci / typescript (push) Successful in 15m12s
ci / rust (push) Successful in 22m16s
feat(shop): galleries on the public sites, Stripe checkout and rendered downloads
Sites per domain with two skins (PhotoReport, ShootYourMove) in apps/site (Next.js); public, unlisted and private galleries with watermarked photos; products, cart, orders with VIES reverse charge; the organization's own Stripe Checkout and signed webhooks; bought files rendered from the original with edits and IPTC, emailed; Vendas module in the app.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-11 22:36:16 +01:00

212 lines
13 KiB
TypeScript

import { mkdir, mkdtemp, rm, writeFile } 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 { SecretBox } from "../src/delivery/secrets.js";
import { IngestService } from "../src/ingest/service.js";
import { MemoryBroadcaster } from "../src/realtime.js";
import { formatOrderNumber, priceOrder, splitVat } from "../src/shop/pricing.js";
import { ShopService } from "../src/shop/service.js";
import { formEncode, signWebhook, verifyWebhook } from "../src/shop/stripe.js";
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
const quiet = { info: () => {}, warn: () => {} };
const KEY = Buffer.alloc(32, 7).toString("base64");
const WHSEC = "whsec_test_123";
describe("pricing", () => {
it("keeps listed prices for consumers and charges business buyers abroad the net price", () => {
const consumer = priceOrder([{ quantity: 2, unitCents: 1230 }], { vatRate: 23, reverseCharge: false });
expect(consumer).toMatchObject({ totalCents: 2460, netCents: 2000, vatCents: 460 });
const b2b = priceOrder([{ quantity: 2, unitCents: 1230 }], { vatRate: 23, reverseCharge: true });
expect(b2b).toMatchObject({ totalCents: 2000, netCents: 2000, vatCents: 0, reverseCharge: true });
});
it("reads EU VAT numbers and numbers orders", () => {
expect(splitVat("pt 123 456 789")).toEqual({ country: "PT", number: "123456789" });
expect(splitVat("EL123456789")).toEqual({ country: "GR", number: "123456789" });
expect(splitVat("US123")).toBeNull();
expect(formatOrderNumber(2026, 42)).toBe("2026-000042");
});
it("signs and checks Stripe webhooks, and encodes nested form params", () => {
const body = '{"type":"x"}';
const header = signWebhook(body, WHSEC);
expect(verifyWebhook(Buffer.from(body), header, WHSEC)).toBe(true);
expect(verifyWebhook(Buffer.from(body + " "), header, WHSEC)).toBe(false);
expect(verifyWebhook(Buffer.from(body), signWebhook(body, WHSEC, Math.floor(Date.now() / 1000) - 3600), WHSEC)).toBe(false);
expect(formEncode({ a: { b: [{ c: 1 }] } })).toEqual(["a%5Bb%5D%5B0%5D%5Bc%5D=1"]);
});
});
describe("shop", () => {
let ctx: TestContext;
let dir: string;
let ingestRoot: string;
let ingest: IngestService;
let shop: ShopService;
const calls: { url: string; body: string }[] = [];
const mails: { to: string; subject: string; text: string }[] = [];
let viesValid = true;
/** Stripe and VIES, faked. */
const fakeFetch: typeof fetch = async (input, init) => {
const url = String(input);
calls.push({ url, body: String(init?.body ?? "") });
if (url.startsWith("https://api.stripe.com/v1/checkout/sessions")) return Response.json({ id: "cs_test_1", url: "https://checkout.stripe.com/c/pay/cs_test_1" });
if (url.includes("/vies/")) return Response.json({ isValid: viesValid, name: "Fotos Madrid SL" });
return new Response("nope", { status: 404 });
};
beforeAll(async () => {
dir = await mkdtemp(path.join(tmpdir(), "pr-shop-"));
ingestRoot = path.join(dir, "ingest");
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot, DELIVERY_SECRET_KEY: KEY }, new MemoryBroadcaster(), fakeFetch);
const storage = new LocalStorage(ctx.config.STORAGE_ROOT);
const signer = new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC);
ingest = new IngestService({ db: ctx.db, storage, signer, broadcaster: new MemoryBroadcaster(), ingestRoot, log: quiet });
shop = new ShopService({ db: ctx.db, storage, signer, secrets: new SecretBox(KEY), log: quiet, secret: ctx.config.JWT_SECRET, fetchImpl: fakeFetch, mailer: { send: async (m) => void mails.push(m) } });
});
afterAll(async () => {
await ctx.app.close();
await ctx.db.$disconnect();
await rm(dir, { recursive: true, force: true });
});
beforeEach(async () => {
await resetDb(ctx.db);
calls.length = 0;
mails.length = 0;
viesValid = true;
});
let n = 0;
async function setup() {
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "photoreport", role: "OWNER" });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
await ctx.db.ftpAccount.create({ data: { organizationId: org!.id, userId: user.id, login: "cam" } });
const photos: string[] = [];
for (let i = 0; i < 3; i++) {
const data = await sharp({ create: { width: 1200, height: 800, channels: 3, background: { r: (++n * 37) % 256, g: (n * 91) % 256, b: 60 } } }).jpeg().toBuffer();
const file = path.join(ingestRoot, "cam", `IMG_${n}.jpg`);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, data);
const out = await ingest.ingestFile(file);
if (out.status !== "ingested") throw new Error(JSON.stringify(out));
photos.push(out.photoId);
}
const api = (method: "GET" | "POST" | "PUT" | "PATCH", url: string, payload?: unknown) => ctx.app.inject({ method, url, headers: bearer(token), ...(payload !== undefined && { payload: payload as object }) });
expect((await api("POST", `/v1/orgs/${org!.id}/sites`, { domain: "photoreport.test", skin: "photoreport", name: "PhotoReport" })).statusCode).toBe(201);
expect((await api("PUT", `/v1/orgs/${org!.id}/shop-settings`, { stripeSecretKey: "sk_test_abc", stripeWebhookSecret: WHSEC, legalName: "BitReport Unip. Lda" })).statusCode).toBe(200);
const digital = (await api("POST", `/v1/orgs/${org!.id}/products`, { kind: "DIGITAL", name: "Digital 2400 px", longEdge: 2400, priceCents: 1230 })).json() as { id: string };
const print = (await api("POST", `/v1/orgs/${org!.id}/products`, { kind: "PRINT", name: "Impressão 15x20", printSize: "15x20", priceCents: 615, leadDays: 3 })).json() as { id: string };
return { orgId: org!.id, photos, api, digital, print };
}
const pub = (method: "GET" | "POST", url: string, payload?: unknown, headers: Record<string, string> = {}) =>
ctx.app.inject({ method, url, headers: { "x-site-domain": "photoreport.test", ...headers }, ...(payload !== undefined && { payload: payload as object }) });
async function gallery(s: Awaited<ReturnType<typeof setup>>, body: Record<string, unknown>) {
const g = (await s.api("POST", `/v1/orgs/${s.orgId}/galleries`, body)).json() as { id: string; slug: string };
expect((await s.api("POST", `/v1/galleries/${g.id}/publish`, { published: true })).json()).toMatchObject({ error: "gallery_empty" });
await s.api("POST", `/v1/galleries/${g.id}/photos`, { add: s.photos });
expect((await s.api("POST", `/v1/galleries/${g.id}/publish`, { published: true })).statusCode).toBe(200);
return g;
}
it("shows published galleries with watermarked photos, and private ones only after the password", async () => {
const s = await setup();
const open = await gallery(s, { title: "SC Braga x Sporting CP" });
expect(open.slug).toBe("sc-braga-x-sporting-cp");
const priv = await gallery(s, { title: "Equipa ABC", visibility: "PRIVATE", password: "abc-2026" });
const list = (await pub("GET", "/v1/public/galleries")).json() as { galleries: { slug: string; photoCount: number; cover: string }[] };
expect(list.galleries.map((g) => g.slug)).toEqual([open.slug]); // private ones are not listed
const g = (await pub("GET", `/v1/public/galleries/${open.slug}`)).json() as { photos: { preview: string }[]; locked: boolean };
expect(g.locked).toBe(false);
expect(g.photos).toHaveLength(3);
const img = await ctx.app.inject({ method: "GET", url: g.photos[0]!.preview });
expect(img.statusCode).toBe(200);
const meta = await sharp(img.rawPayload).metadata();
expect(Math.max(meta.width!, meta.height!)).toBeLessThanOrEqual(1600);
// A tampered URL is refused.
expect((await ctx.app.inject({ method: "GET", url: g.photos[0]!.preview.replace(/sig=./, "sig=x") })).statusCode).toBe(404);
const locked = (await pub("GET", `/v1/public/galleries/${priv.slug}`)).json() as { locked: boolean; photos: unknown[] };
expect(locked).toMatchObject({ locked: true, photos: [] });
expect((await pub("POST", `/v1/public/galleries/${priv.slug}/unlock`, { password: "nope" })).statusCode).toBe(401);
const { token } = (await pub("POST", `/v1/public/galleries/${priv.slug}/unlock`, { password: "abc-2026" })).json() as { token: string };
const unlocked = (await pub("GET", `/v1/public/galleries/${priv.slug}`, undefined, { "x-gallery-token": token })).json() as { locked: boolean; photos: unknown[] };
expect(unlocked.photos).toHaveLength(3);
});
it("sells through Stripe, renders the download once paid, and closes the order when prints ship", async () => {
const s = await setup();
const g = await gallery(s, { title: "Final da Taça" });
const created = await pub("POST", "/v1/public/orders", {
gallery: g.slug,
email: "[email protected]",
name: "João Silva",
country: "PT",
items: [
{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 },
{ photoId: s.photos[1], productId: s.print.id, quantity: 2 },
],
});
expect(created.statusCode).toBe(201);
const { order, checkoutUrl } = created.json() as { order: { id: string; number: string; totalCents: number; vatCents: number }; checkoutUrl: string };
expect(checkoutUrl).toContain("checkout.stripe.com");
expect(order).toMatchObject({ number: `${new Date().getUTCFullYear()}-000001`, totalCents: 1230 + 1230, vatCents: 230 + 230 });
const stripeCall = calls.find((c) => c.url.includes("checkout/sessions"))!;
expect(decodeURIComponent(stripeCall.body)).toContain("line_items[1][price_data][unit_amount]=1230");
// Not paid yet: no downloads.
expect(await shop.claimDownloads(5)).toEqual([]);
const row = await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } });
const event = JSON.stringify({ type: "checkout.session.completed", data: { object: { id: "cs_test_1", payment_status: "paid", metadata: { order_id: order.id } } } });
const bad = await ctx.app.inject({ method: "POST", url: `/v1/public/stripe/${s.orgId}/webhook`, headers: { "content-type": "application/json", "stripe-signature": signWebhook(event, "whsec_wrong") }, payload: event });
expect(bad.statusCode).toBe(400);
const ok = await ctx.app.inject({ method: "POST", url: `/v1/public/stripe/${s.orgId}/webhook`, headers: { "content-type": "application/json", "stripe-signature": signWebhook(event, WHSEC) }, payload: event });
expect(ok.statusCode).toBe(200);
const [itemId] = await shop.claimDownloads(5);
await shop.fulfil(itemId!);
const view = (await pub("GET", `/v1/public/orders/${order.id}?t=${row.accessToken}`)).json() as { status: string; items: { kind: string; download: string | null; id: string }[] };
expect(view.status).toBe("PAID");
const digital = view.items.find((i) => i.kind === "DIGITAL")!;
const file = await ctx.app.inject({ method: "GET", url: digital.download! });
expect(file.statusCode).toBe(200);
expect(file.headers["content-disposition"]).toContain("attachment");
expect(mails).toHaveLength(1);
expect(mails[0]).toMatchObject({ to: "[email protected]" });
expect(mails[0]!.text).toContain(`https://photoreport.test/encomenda/${order.id}?t=${row.accessToken}`);
expect((await sharp(file.rawPayload).metadata()).width).toBe(1200); // never enlarged to 2400
expect((await pub("GET", `/v1/public/orders/${order.id}?t=wrongwrongwrong`)).statusCode).toBe(404);
// The print ships: the order is complete.
const print = view.items.find((i) => i.kind === "PRINT")!;
await s.api("POST", `/v1/orders/${order.id}/items/${print.id}/shipped`);
expect((await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } })).status).toBe("FULFILLED");
});
it("reverse-charges VAT for EU businesses with a valid number, and gives free galleries away", async () => {
const s = await setup();
const g = await gallery(s, { title: "Clube" });
const items = [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }];
const b2b = (await pub("POST", "/v1/public/orders", { gallery: g.slug, email: "[email protected]", name: "Fotos Madrid", country: "ES", vatNumber: "ESB12345678", items })).json() as { order: { totalCents: number; reverseCharge: boolean } };
expect(b2b.order).toMatchObject({ totalCents: 1000, reverseCharge: true });
viesValid = false;
const invalid = (await pub("POST", "/v1/public/orders", { gallery: g.slug, email: "[email protected]", name: "Fotos Madrid", country: "ES", vatNumber: "ESB12345678", items })).json() as { order: { totalCents: number; reverseCharge: boolean } };
expect(invalid.order).toMatchObject({ totalCents: 1230, reverseCharge: false });
const free = await gallery(s, { title: "Galeria do clube", forSale: false, freeDownloads: true });
const freeOrder = (await pub("POST", "/v1/public/orders", { gallery: free.slug, email: "[email protected]", name: "Sócio", country: "PT", items })).json() as { order: { status: string; totalCents: number }; checkoutUrl: string | null };
expect(freeOrder).toMatchObject({ checkoutUrl: null, order: { status: "PAID", totalCents: 0 } });
// Prints are not free, and a gallery not for sale sells nothing else.
const printFree = await pub("POST", "/v1/public/orders", { gallery: free.slug, email: "[email protected]", name: "Sócio", country: "PT", items: [{ photoId: s.photos[0], productId: s.print.id, quantity: 1 }] });
expect(printFree.json()).toMatchObject({ error: "gallery_not_for_sale" });
});
});