Files
paula-alves cbd3f318d5
ci / rust (pull_request) Successful in 4m18s
ci / typescript (pull_request) Failing after 8m42s
fix(shop): accept an order when no payment method is connected
A buyer can still place the order. It stays unpaid until an admin records money collected out of band, and that admin is then responsible for delivering the work. No invoice goes out while invoicing is off.
2026-11-25 00:11:38 +00:00

588 lines
44 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 { InvoicingService } from "../src/invoicing/service.js";
import { Notifications } from "../src/notifications/service.js";
import { PressService } from "../src/shop/press.js";
import { EarningsService } from "../src/shop/earnings.js";
import { ShopService } from "../src/shop/service.js";
import { createCheckout, formEncode, signWebhook, StripeError, 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"]);
});
it("wraps a network-level Stripe failure into a StripeError instead of a bare, unlocatable fetch error (BIT-31961)", async () => {
const rejecting: typeof fetch = async () => {
throw new TypeError("fetch failed");
};
await expect(
createCheckout("sk_test", { reference: "o1", metadata: {}, currency: "eur", lines: [{ name: "x", unitCents: 100, quantity: 1 }], successUrl: "https://x/ok", cancelUrl: "https://x/cancel" }, rejecting),
).rejects.toThrow(StripeError);
});
});
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;
let transferStatus = 200;
/** 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" });
if (url === "https://api.stripe.com/v1/accounts") return Response.json({ id: "acct_photo_1" });
if (url.startsWith("https://api.stripe.com/v1/accounts/")) return Response.json({ id: "acct_photo_1", capabilities: { transfers: "active" } });
if (url === "https://api.stripe.com/v1/account_links") return Response.json({ url: "https://connect.stripe.com/setup/e/acct_photo_1/xyz" });
if (url === "https://api.stripe.com/v1/transfers") return transferStatus === 200 ? Response.json({ id: "tr_1" }) : Response.json({ error: { message: "Insufficient funds" } }, { status: transferStatus });
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, earnings: new EarningsService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fakeFetch, notifications: new Notifications(ctx.db) }), notifications: new Notifications(ctx.db), press: new PressService({ db: ctx.db, secret: ctx.config.JWT_SECRET }), 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;
transferStatus = 200;
});
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.
// (A different first character every time: replacing it with a fixed one is a no-op when it already is that one.)
const tampered = g.photos[0]!.preview.replace(/sig=(.)/, (_, c: string) => `sig=${c === "x" ? "y" : "x"}`);
expect((await ctx.app.inject({ method: "GET", url: tampered })).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("accepts an order when Stripe is off, and delivery waits until an admin records the payment", async () => {
const s = await setup();
expect((await s.api("PUT", `/v1/orgs/${s.orgId}/shop-settings`, { stripeSecretKey: "", stripeWebhookSecret: "" })).statusCode).toBe(200);
const g = await gallery(s, { title: "Sem Stripe" });
const created = await pub("POST", "/v1/public/orders", {
gallery: g.slug,
email: "[email protected]",
name: "Ana Costa",
country: "PT",
items: [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }],
});
expect(created.statusCode).toBe(201);
const body = created.json() as { order: { id: string; status: string; totalCents: number }; checkoutUrl: string | null };
expect(body.checkoutUrl).toBeNull();
expect(body.order).toMatchObject({ status: "PENDING" });
expect(body.order.totalCents).toBeGreaterThan(0);
expect(await shop.claimDownloads(5)).toEqual([]);
const paid = await s.api("POST", `/v1/orders/${body.order.id}/payment-received`);
expect(paid.statusCode).toBe(200);
expect(paid.json()).toMatchObject({ status: "PAID" });
const [itemId] = await shop.claimDownloads(5);
expect(itemId).toEqual(expect.any(String));
});
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" });
});
it("keeps a private gallery private when only its title changes", async () => {
const s = await setup();
const g = await gallery(s, { title: "Equipa", visibility: "PRIVATE", password: "abc-2026", forSale: false, freeDownloads: true });
const patched = (await s.api("PATCH", `/v1/galleries/${g.id}`, { title: "Equipa sénior" })).json() as Record<string, unknown>;
expect(patched).toMatchObject({ title: "Equipa sénior", visibility: "PRIVATE", forSale: false, freeDownloads: true, live: "OFF", proofing: false });
});
it("fills a live gallery from the event's picks, drops unpicked ones and respects photos taken out by hand", async () => {
const s = await setup();
const event = await ctx.db.event.create({ data: { organizationId: s.orgId, home: "SC Braga", away: "Sporting CP", startsAt: new Date(), ingestFrom: new Date(Date.now() - 3600_000), ingestUntil: new Date(Date.now() + 3600_000), iptcTemplate: {} } });
await ctx.db.photo.updateMany({ where: { id: { in: s.photos } }, data: { eventId: event.id } });
expect((await s.api("POST", `/v1/orgs/${s.orgId}/galleries`, { title: "Sem evento", live: "PICKS" })).json()).toMatchObject({ error: "live_needs_event" });
const g = (await s.api("POST", `/v1/orgs/${s.orgId}/galleries`, { title: "Braga ao vivo", eventId: event.id, live: "PICKS" })).json() as { id: string; slug: string; photoCount: number };
expect(g.photoCount).toBe(0);
// Live galleries go out empty, before the first pick.
expect((await s.api("POST", `/v1/galleries/${g.id}/publish`, { published: true })).statusCode).toBe(200);
await ctx.db.photo.updateMany({ where: { id: { in: [s.photos[0]!, s.photos[1]!] } }, data: { flag: "PICK" } });
await shop.live.sync(g.id);
let page = (await pub("GET", `/v1/public/galleries/${g.slug}`)).json() as { live: boolean; photos: { id: string; name: string }[] };
expect(page.live).toBe(true);
expect(page.photos.map((p) => p.id).sort()).toEqual([s.photos[0], s.photos[1]].sort());
expect(page.photos[0]!.name).toMatch(/^IMG_\d+\.jpg$/);
// Unpicked: it leaves. Taken out by hand: it never comes back, even when picked.
await ctx.db.photo.update({ where: { id: s.photos[1]! }, data: { flag: "NONE" } });
await s.api("POST", `/v1/galleries/${g.id}/photos`, { remove: [s.photos[0]] });
await ctx.db.photo.update({ where: { id: s.photos[2]! }, data: { flag: "PICK" } });
const ids = ((await s.api("GET", `/v1/galleries/${g.id}/photos`)).json() as { photoIds: string[] }).photoIds;
expect(ids).toEqual([s.photos[2]]);
// Added back by hand: it stays, whatever its flag.
await s.api("POST", `/v1/galleries/${g.id}/photos`, { add: [s.photos[0]] });
await ctx.db.photo.update({ where: { id: s.photos[0]! }, data: { flag: "NONE" } });
await shop.live.sync(g.id);
page = (await pub("GET", `/v1/public/galleries/${g.slug}`)).json() as typeof page;
expect(page.photos.map((p) => p.id).sort()).toEqual([s.photos[0], s.photos[2]].sort());
});
it("lets clients mark favourites and comment; comments show once approved and favourites become labels", async () => {
const s = await setup();
const g = await gallery(s, { title: "Casamento Ana e Rui", visibility: "PRIVATE", password: "noivos-2026", forSale: false });
const { token: galleryToken } = (await pub("POST", `/v1/public/galleries/${g.slug}/unlock`, { password: "noivos-2026" })).json() as { token: string };
const gh = { "x-gallery-token": galleryToken };
expect((await pub("POST", `/v1/public/galleries/${g.slug}/proofing/session`, {}, gh)).json()).toMatchObject({ error: "proofing_off" });
await s.api("PATCH", `/v1/galleries/${g.id}`, { proofing: true });
// Locked without the gallery token.
expect((await pub("POST", `/v1/public/galleries/${g.slug}/proofing/session`, {})).statusCode).toBe(401);
const session = (await pub("POST", `/v1/public/galleries/${g.slug}/proofing/session`, { name: "Ana" }, gh)).json() as { token: string; visitor: { name: string; favorites: string[] } };
expect(session.visitor).toEqual({ name: "Ana", email: null, favorites: [] });
const vh = { ...gh, "x-proofing-visitor": session.token };
const fav = (photoId: string, method: "PUT" | "DELETE" = "PUT", headers = vh) => ctx.app.inject({ method, url: `/v1/public/galleries/${g.slug}/proofing/favorites/${photoId}`, headers: { "x-site-domain": "photoreport.test", ...headers } });
expect((await fav(s.photos[0]!)).statusCode).toBe(204);
expect((await fav(s.photos[0]!)).statusCode).toBe(204); // twice is fine
expect((await fav(s.photos[1]!)).statusCode).toBe(204);
expect((await fav(s.photos[1]!, "DELETE")).statusCode).toBe(204);
expect((await fav(s.photos[2]!, "PUT", { ...gh, "x-proofing-visitor": session.token.replace(/.$/, (c) => (c === "x" ? "y" : "x")) })).statusCode).toBe(401);
expect((await fav("00000000-0000-4000-8000-000000000000")).statusCode).toBe(404);
// Resuming keeps the favourites.
const again = (await pub("POST", `/v1/public/galleries/${g.slug}/proofing/session`, { email: "[email protected]" }, vh)).json() as { visitor: { email: string; favorites: string[] } };
expect(again.visitor).toMatchObject({ email: "[email protected]", favorites: [s.photos[0]] });
// Comments: the author sees hers while pending, others only after approval.
const posted = await pub("POST", `/v1/public/galleries/${g.slug}/proofing/comments`, { photoId: s.photos[0], body: "Esta para o álbum, a cores" }, vh);
expect(posted.statusCode).toBe(201);
const other = (await pub("POST", `/v1/public/galleries/${g.slug}/proofing/session`, { name: "Rui" }, gh)).json() as { token: string };
const list = async (token: string) => ((await pub("GET", `/v1/public/galleries/${g.slug}/proofing/comments?photoId=${s.photos[0]}`, undefined, { ...gh, "x-proofing-visitor": token })).json() as { comments: { body: string; mine: boolean; status: string }[] }).comments;
expect(await list(session.token)).toMatchObject([{ mine: true, status: "PENDING" }]);
expect(await list(other.token)).toEqual([]);
const report = (await s.api("GET", `/v1/galleries/${g.id}/proofing`)).json() as { visitors: { name: string; favorites: string[] }[]; photos: { id: string; favorites: number; name: string }[]; comments: { id: string; author: string }[] };
expect(report.visitors.map((v) => v.name).sort()).toEqual(["Ana", "Rui"]);
expect(report.photos).toMatchObject([{ id: s.photos[0], favorites: 1 }]);
expect(report.comments).toMatchObject([{ author: "Ana" }]);
expect((await s.api("PATCH", `/v1/gallery-comments/${report.comments[0]!.id}`, { status: "APPROVED" })).statusCode).toBe(200);
expect(await list(other.token)).toMatchObject([{ body: "Esta para o álbum, a cores", mine: false, status: "APPROVED" }]);
const labelled = (await s.api("POST", `/v1/galleries/${g.id}/proofing/label`, { label: "PURPLE" })).json() as { labelled: number };
expect(labelled.labelled).toBe(1);
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: s.photos[0]! } })).colorLabel).toBe("PURPLE");
});
it("puts every ready download of an order in one ZIP", async () => {
const s = await setup();
const free = await gallery(s, { title: "Galeria do clube", forSale: false, freeDownloads: true });
const items = s.photos.map((photoId) => ({ photoId, productId: s.digital.id, quantity: 1 }));
const { order } = (await pub("POST", "/v1/public/orders", { gallery: free.slug, email: "[email protected]", name: "Sócio", country: "PT", items })).json() as { order: { id: string } };
const row = await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } });
let view = (await pub("GET", `/v1/public/orders/${order.id}?t=${row.accessToken}`)).json() as { zip: string | null };
expect(view.zip).toBeNull();
for (const id of await shop.claimDownloads(10)) await shop.fulfil(id);
view = (await pub("GET", `/v1/public/orders/${order.id}?t=${row.accessToken}`)).json() as typeof view;
expect(view.zip).toContain("/zip?t=");
const res = await ctx.app.inject({ method: "GET", url: view.zip! });
expect(res.statusCode).toBe(200);
expect(res.headers["content-type"]).toBe("application/zip");
const zipFile = path.join(dir, "order.zip");
await writeFile(zipFile, res.rawPayload);
const { execFileSync } = await import("node:child_process");
expect(execFileSync("unzip", ["-t", zipFile]).toString()).toContain("No errors detected");
expect(execFileSync("unzip", ["-Z1", zipFile]).toString().trim().split("\n")).toHaveLength(3);
const counts = await ctx.db.orderItem.findMany({ where: { orderId: order.id }, select: { downloads: true } });
expect(counts.every((c) => c.downloads === 1)).toBe(true);
expect((await ctx.app.inject({ method: "GET", url: view.zip!.replace(/t=.*/, "t=wrongwrongwrong") })).statusCode).toBe(404);
});
it("finds galleries by team, competition or player, keeps one sport, and lists the latest photos", async () => {
const s = await setup();
const t = new Date("2026-10-11T17:00:00Z");
const event = await ctx.db.event.create({ data: { organizationId: s.orgId, home: "ABC Braga", away: "CDE Gil Eanes", sport: "Andebol", competition: "Campeonato Betclic", startsAt: t, ingestFrom: t, ingestUntil: t, iptcTemplate: {} } });
const handball = await gallery(s, { title: "Jornada 8" });
await ctx.db.gallery.updateMany({ where: { slug: handball.slug }, data: { eventId: event.id } });
const other = await gallery(s, { title: "Treino aberto" });
await ctx.db.photo.update({ where: { id: s.photos[0]! }, data: { players: ["Diogo Branquinho"] } });
type List = { galleries: { slug: string; event: { sport: string | null } | null; live: boolean }[]; sports: string[] };
const list = async (query = "") => (await pub("GET", `/v1/public/galleries${query}`)).json() as List;
const all = await list();
expect(all.sports).toEqual(["andebol"]);
expect(all.galleries.find((g) => g.slug === handball.slug)).toMatchObject({ event: { sport: "Andebol" }, live: false });
expect((await list("?q=gil%20eanes")).galleries.map((g) => g.slug)).toEqual([handball.slug]);
expect((await list("?q=betclic")).galleries.map((g) => g.slug)).toEqual([handball.slug]);
// Players are named in the photos, which are in both galleries here.
expect((await list("?q=branquinho")).galleries.map((g) => g.slug).sort()).toEqual([handball.slug, other.slug].sort());
expect((await list("?q=50%25")).galleries).toEqual([]);
expect((await list("?sport=andebol")).galleries.map((g) => g.slug)).toEqual([handball.slug]);
const latest = (await pub("GET", "/v1/public/latest?limit=4")).json() as { photos: { thumb: string; gallery: { slug: string } }[] };
expect(latest.photos).toHaveLength(4);
expect(latest.photos[0]!.thumb).toContain("/v1/public/files/");
});
it("counts gallery visits for \"Mais vistas\" and captions each photo as it is delivered", async () => {
const s = await setup();
const t = new Date("2026-10-11T17:00:00Z");
const event = await ctx.db.event.create({
data: { organizationId: s.orgId, home: "ABC Braga", away: "FC Porto", sport: "andebol", startsAt: t, ingestFrom: t, ingestUntil: t, iptcTemplate: { caption: "{home} x {away}", creator: "Agência / PhotoReport.pt" } },
});
await ctx.db.photo.updateMany({ where: { id: { in: s.photos } }, data: { eventId: event.id } });
await ctx.db.photo.update({ where: { id: s.photos[1]! }, data: { iptcOverrides: { caption: "Golo de {players}" }, players: ["Rui Silva"] } });
const quiet = await gallery(s, { title: "Treino" });
const busy = await gallery(s, { title: "Final" });
expect((await pub("GET", "/v1/public/popular")).json()).toEqual({ galleries: [] });
for (let i = 0; i < 3; i++) expect((await pub("POST", `/v1/public/galleries/${busy.slug}/view`)).statusCode).toBe(204);
expect((await pub("POST", `/v1/public/galleries/${quiet.slug}/view`)).statusCode).toBe(204);
expect((await pub("POST", "/v1/public/galleries/nao-existe/view")).statusCode).toBe(404);
// Old visits fall out of the window.
const g = await ctx.db.gallery.findFirstOrThrow({ where: { slug: quiet.slug } });
await ctx.db.galleryView.create({ data: { galleryId: g.id, day: new Date("2020-01-01"), views: 100 } });
const popular = (await pub("GET", "/v1/public/popular")).json() as { galleries: { slug: string; views: number }[] };
expect(popular.galleries.map((x) => [x.slug, x.views])).toEqual([
[busy.slug, 3],
[quiet.slug, 1],
]);
const view = (await pub("GET", `/v1/public/galleries/${busy.slug}`)).json() as { photos: { id: string; caption: string | null; credit: string | null }[] };
const byId = new Map(view.photos.map((p) => [p.id, p]));
expect(byId.get(s.photos[0]!)).toMatchObject({ caption: "ABC Braga x FC Porto", credit: "Agência / PhotoReport.pt" });
expect(byId.get(s.photos[1]!)).toMatchObject({ caption: "Golo de Rui Silva" });
});
it("sells photo packages: N photos or the whole gallery at one price, applied to the cart by itself", async () => {
const s = await setup();
const g = await gallery(s, { title: "Final da Taça" });
const other = await gallery(s, { title: "Outra" });
const make = async (body: Record<string, unknown>) => s.api("POST", `/v1/orgs/${s.orgId}/bundles`, { productId: s.digital.id, ...body });
expect((await make({ name: "1 foto", photoCount: 1, priceCents: 100 })).statusCode).toBe(400);
expect((await make({ name: "Prints", productId: s.print.id, photoCount: 2, priceCents: 100 })).json()).toMatchObject({ error: "digital_product_not_found" });
const two = (await make({ name: "2 fotos", photoCount: 2, priceCents: 2000 })).json() as { id: string; galleryTitle: string | null };
expect(two.galleryTitle).toBeNull();
expect((await make({ name: "Galeria inteira", galleryId: g.id, photoCount: 0, priceCents: 2500 })).statusCode).toBe(201);
const view = (await pub("GET", `/v1/public/galleries/${g.slug}`)).json() as { bundles: { name: string; photoCount: number }[] };
expect(view.bundles.map((b) => b.name).sort()).toEqual(["2 fotos", "Galeria inteira"]);
expect(((await pub("GET", `/v1/public/galleries/${other.slug}`)).json() as { bundles: { name: string }[] }).bundles.map((b) => b.name)).toEqual(["2 fotos"]);
type Created = { order: { totalCents: number; items: { productName: string; totalCents: number }[] } };
const buy = async (slug: string, photos: string[]) =>
((await pub("POST", "/v1/public/orders", { gallery: slug, email: "[email protected]", name: "Adepto", country: "PT", items: photos.map((photoId) => ({ photoId, productId: s.digital.id, quantity: 1 })) })).json() as Created).order;
const pair = await buy(g.slug, s.photos.slice(0, 2));
expect(pair.totalCents).toBe(2000);
expect(pair.items.map((i) => i.productName)).toEqual(["Digital 2400 px · 2 fotos", "Digital 2400 px · 2 fotos"]);
expect(pair.items.map((i) => i.totalCents)).toEqual([1000, 1000]);
expect((await buy(g.slug, s.photos)).totalCents).toBe(2500);
// The whole-gallery package is that gallery's only.
expect((await buy(other.slug, s.photos)).totalCents).toBe(2000 + 1230);
expect((await s.api("PATCH", `/v1/bundles/${two.id}`, { active: false })).statusCode).toBe(200);
expect((await buy(other.slug, s.photos.slice(0, 2))).totalCents).toBe(2460);
expect(((await s.api("GET", `/v1/orgs/${s.orgId}/bundles`)).json() as { bundles: unknown[] }).bundles).toHaveLength(2);
});
it("limits downloads per bought file to the organization's setting at the time of the order", async () => {
const s = await setup();
await ctx.db.organization.update({ where: { id: s.orgId }, data: { maxDownloads: 2 } });
const free = await gallery(s, { title: "Clube", forSale: false, freeDownloads: true });
const { order } = (await pub("POST", "/v1/public/orders", { gallery: free.slug, email: "[email protected]", name: "Sócio", country: "PT", items: [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }] })).json() as { order: { id: string } };
// Changing the setting later does not change this order.
await ctx.db.organization.update({ where: { id: s.orgId }, data: { maxDownloads: 0 } });
for (const id of await shop.claimDownloads(10)) await shop.fulfil(id);
const row = await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } });
expect(row.maxDownloads).toBe(2);
type View = { items: { download: string | null; downloadsLeft: number | null }[] };
const view = async () => (await pub("GET", `/v1/public/orders/${order.id}?t=${row.accessToken}`)).json() as View;
const first = await view();
expect(first.items[0]).toMatchObject({ downloadsLeft: 2 });
expect((await ctx.app.inject({ method: "GET", url: first.items[0]!.download! })).statusCode).toBe(200);
expect((await ctx.app.inject({ method: "GET", url: first.items[0]!.download! })).statusCode).toBe(200);
expect((await ctx.app.inject({ method: "GET", url: first.items[0]!.download! })).statusCode).toBe(429);
expect((await view()).items[0]).toMatchObject({ download: null, downloadsLeft: 0 });
});
it("pays photographers their share and affiliates their commission, after the hold, by Stripe or by hand", async () => {
const s = await setup();
const g = await gallery(s, { title: "Taça" });
const owner = (await ctx.db.user.findUniqueOrThrow({ where: { email: "[email protected]" } })).id;
expect((await s.api("PUT", `/v1/orgs/${s.orgId}/earnings/settings`, { photographerSharePct: 50, earningsHoldDays: 14 })).statusCode).toBe(200);
const aff = await s.api("POST", `/v1/orgs/${s.orgId}/affiliates`, { name: "Clube Desportivo", code: "clube-cd", ratePct: 10 });
expect(aff.json()).toMatchObject({ code: "CLUBE-CD", stripe: "none", orders: 0 });
expect((await s.api("POST", `/v1/orgs/${s.orgId}/affiliates`, { name: "Outro", code: "CLUBE-CD" })).statusCode).toBe(409);
const affiliateId = (aff.json() as { id: string }).id;
const buy = async (ref?: string) => {
const r = (await pub("POST", "/v1/public/orders", { gallery: g.slug, email: "[email protected]", name: "João Silva", country: "PT", ...(ref && { ref }), items: [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }, { photoId: s.photos[1], productId: s.print.id, quantity: 2 }] })).json() as { order: { id: string } };
await shop.markPaid(r.order.id, "cs_test_1");
return r.order.id;
};
const paid = await buy("clube-cd");
await buy("NOPE"); // unknown codes are ignored
await buy();
// A second call never doubles anything.
await shop.markPaid(paid);
const rows = await ctx.db.earning.findMany({ where: { orderId: paid }, orderBy: { amountCents: "asc" } });
// Net of 12,30 € is 10,00 €: 50% is 5,00 € per line; the affiliate gets 10% of the order's 20,00 € net.
expect(rows.map((r) => [r.kind, r.amountCents])).toEqual([["AFFILIATE", 200], ["PHOTOGRAPHER", 500], ["PHOTOGRAPHER", 500]]);
expect(await ctx.db.earning.count()).toBe(7);
// Held for 14 days: nothing to pay yet.
const overview = (await s.api("GET", `/v1/orgs/${s.orgId}/earnings`)).json() as { balances: { kind: string; id: string; heldCents: number; payableCents: number }[] };
expect(overview.balances.find((b) => b.id === owner)).toMatchObject({ heldCents: 3000, payableCents: 0 });
expect(overview.balances.find((b) => b.id === affiliateId)).toMatchObject({ heldCents: 200 });
expect((await s.api("POST", `/v1/orgs/${s.orgId}/payouts`, { photographerId: owner, method: "manual", reference: "TRF 1" })).json()).toMatchObject({ error: "nothing_to_pay" });
// One order is refunded within the window: what it owed is cancelled.
const refunded = (await s.api("POST", `/v1/orders/${paid}/refunded`)).json();
expect(refunded).toEqual({ cancelled: 3, alreadyPaid: 0 });
await ctx.db.earning.updateMany({ data: { availableAt: new Date(Date.now() - 1000) } });
// Stripe: the photographer onboards (their own link), then gets a transfer of everything payable.
expect((await s.api("POST", `/v1/orgs/${s.orgId}/payouts`, { photographerId: owner, method: "stripe" })).json()).toMatchObject({ error: "stripe_account_not_ready" });
expect((await s.api("POST", `/v1/orgs/${s.orgId}/connect`, {})).json()).toEqual({ url: "https://connect.stripe.com/setup/e/acct_photo_1/xyz" });
expect((await s.api("POST", `/v1/orgs/${s.orgId}/connect/refresh`, {})).json()).toEqual({ ready: true });
transferStatus = 400;
expect((await s.api("POST", `/v1/orgs/${s.orgId}/payouts`, { photographerId: owner, method: "stripe" })).json()).toMatchObject({ error: "transfer_failed" });
transferStatus = 200;
const payout = (await s.api("POST", `/v1/orgs/${s.orgId}/payouts`, { photographerId: owner, method: "stripe" })).json();
expect(payout).toMatchObject({ amountCents: 2000, status: "PAID", reference: "tr_1", method: "stripe" });
const transfer = calls.filter((c) => c.url.endsWith("/v1/transfers")).at(-1)!;
expect(decodeURIComponent(transfer.body)).toContain("destination=acct_photo_1");
// The affiliate's other orders brought nothing; a bank transfer is recorded by hand.
expect((await s.api("POST", `/v1/orgs/${s.orgId}/payouts`, { affiliateId, method: "manual", reference: "TRF 2" })).json()).toMatchObject({ error: "nothing_to_pay" });
const mine = (await s.api("GET", `/v1/orgs/${s.orgId}/my-earnings`)).json();
expect(mine).toMatchObject({ sharePct: 50, payableCents: 0, paidCents: 2000, account: { stripe: "ready" } });
expect(mine.lines).toHaveLength(6);
expect(mine.payouts.map((p: { status: string }) => p.status)).toEqual(["PAID", "FAILED"]);
// The bell: three sales of their photos, the paid orders (as owner) and the payout.
const bell = (await s.api("GET", "/v1/me/notifications")).json() as { unreadCount: number; notifications: { id: string; type: string; payload: Record<string, unknown> }[] };
expect(bell.notifications.map((n) => n.type).sort()).toEqual(["order_paid", "order_paid", "order_paid", "payout_paid", "photo_sold", "photo_sold", "photo_sold"]);
expect(bell.notifications.find((n) => n.type === "photo_sold")!.payload).toMatchObject({ photos: 2, amountCents: 1000 });
expect(bell.notifications.find((n) => n.type === "payout_paid")!.payload).toEqual({ amountCents: 2000, method: "stripe" });
expect((await s.api("POST", `/v1/me/notifications/${bell.notifications[0]!.id}/read`)).json()).toEqual({ marked: 1 });
expect((await s.api("POST", "/v1/me/notifications/all/read")).json()).toEqual({ marked: 6 });
expect(((await s.api("GET", "/v1/me/notifications?unread=1")).json() as { unreadCount: number }).unreadCount).toBe(0);
expect((await s.api("PUT", `/v1/orgs/${s.orgId}/my-earnings/iban`, { payoutIban: "pt50 0002 0123 1234 5678 9015 4" })).json()).toMatchObject({ payoutIban: "PT50000201231234567890154" });
});
it("lets a press account sign in, order on account with its discount, and get one invoice for the month", async () => {
const s = await setup();
const g = await gallery(s, { title: "Clássico" });
const created = await s.api("POST", `/v1/orgs/${s.orgId}/press-accounts`, { name: "Diário do Norte", email: "[email protected]", vatNumber: "pt 503 221 118", discountPct: 20 });
expect(created.statusCode).toBe(201);
const { account, password } = created.json() as { account: { id: string; email: string; vatNumber: string }; password: string };
expect(account).toMatchObject({ email: "[email protected]", vatNumber: "PT503221118" });
expect(password).toMatch(/^[\w]{4}-[\w]{4}-[\w]{4}$/);
expect((await pub("POST", "/v1/public/press/login", { email: "[email protected]", password: "wrong-one" })).statusCode).toBe(401);
const login = (await pub("POST", "/v1/public/press/login", { email: "[email protected]", password })).json() as { token: string; account: { name: string } };
expect(login.account.name).toBe("Diário do Norte");
calls.length = 0;
const res = await pub("POST", "/v1/public/orders", { gallery: g.slug, email: "[email protected]", name: "Editor", country: "ES", vatNumber: "ESB12345678", pressToken: login.token, items: [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }] });
expect(res.statusCode).toBe(201);
const body = res.json() as { order: { id: string; status: string; totalCents: number; vatCents: number }; checkoutUrl: string | null };
// No Stripe: on account, 20% off 12,30 €, billed to the account (Portuguese NIF: VAT charged).
expect(body.checkoutUrl).toBeNull();
expect(calls.filter((c) => c.url.includes("stripe"))).toHaveLength(0);
expect(body.order).toMatchObject({ status: "PAID", totalCents: 984, vatCents: 184 });
const row = await ctx.db.order.findUniqueOrThrow({ where: { id: body.order.id } });
expect(row).toMatchObject({ provider: "press", pressAccountId: account.id, name: "Diário do Norte", country: "PT", vatNumber: "PT503221118", email: "[email protected]" });
const me = (await pub("GET", "/v1/public/press/me", undefined, { "x-press-token": login.token })).json() as { orders: { number: string; url: string }[] };
expect(me.orders).toHaveLength(1);
expect(me.orders[0]!.url).toContain(`/encomenda/${body.order.id}?t=`);
// A closed account can't order any more, even with a token it still holds.
await s.api("PATCH", `/v1/press-accounts/${account.id}`, { active: false });
expect((await pub("POST", "/v1/public/orders", { gallery: g.slug, email: "[email protected]", name: "Editor", country: "PT", pressToken: login.token, items: [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }] })).json()).toEqual({ error: "press_signed_out" });
// Month end: one invoice for the account, a line per item with the order number; none per order.
await ctx.db.organization.update({ where: { id: s.orgId }, data: { invoicingProvider: "invoicexpress" } });
await ctx.db.order.update({ where: { id: body.order.id }, data: { paidAt: new Date(Date.UTC(2026, 8, 20)) } });
const invoicing = new InvoicingService({ db: ctx.db, secrets: undefined, log: quiet });
expect(await invoicing.queueOrder(body.order.id)).toBe(false);
expect(await invoicing.queueMonthly(new Date(Date.UTC(2026, 9, 1, 3)))).toBe(1);
expect(await invoicing.queueMonthly(new Date(Date.UTC(2026, 9, 2)))).toBe(0);
const invoice = await ctx.db.invoice.findFirstOrThrow({ where: { pressAccountId: account.id } });
expect(invoice).toMatchObject({ period: "2026-09", kind: "invoices", totalCents: 984 });
const { doc, email } = await invoicing.monthlyDocument(invoice);
expect(email).toBe("[email protected]");
expect(doc).toMatchObject({ type: "invoices", reference: "Imprensa 2026-09", client: { name: "Diário do Norte", fiscalId: "503221118", country: "Portugal" } });
expect(doc.lines).toEqual([{ name: "Digital 2400 px", description: expect.stringContaining(row.number), unitPrice: 8, quantity: 1, vatRate: 23 }]);
expect(doc.dueDate.getTime() - doc.date.getTime()).toBe(30 * 24 * 3600_000);
const statements = (await s.api("GET", `/v1/press-accounts/${account.id}/statements`)).json() as { statements: { period: string; totalCents: number; invoice: { status: string } }[] };
expect(statements.statements).toEqual([{ period: "2026-09", orders: 1, totalCents: 984, invoice: { status: "PENDING", number: null, url: null } }]);
});
});