diff --git a/.gitignore b/.gitignore
index 1ef0ace..4f0ed28 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,3 +9,5 @@ coverage/
*.log
apps/api/src/generated/
apps/app/public/engine/
+.next/
+*.tsbuildinfo
diff --git a/apps/api/.env.example b/apps/api/.env.example
index 04fb5d1..8302ad0 100644
--- a/apps/api/.env.example
+++ b/apps/api/.env.example
@@ -32,3 +32,6 @@ FACES_PROCESSES=2
# Develop: replays edits and renders edited thumbnails and deliveries (workers/render).
RENDER_BIN=/srv/photoreport/target/release/photoreport-render
RENDER_PROCESSES=2
+# Shop: mail with the download link (optional) and the Stripe API (only changed for local tests).
+# SMTP_URL=smtps://user:password@mail.example.pt:465
+MAIL_FROM=PhotoReport
diff --git a/apps/api/package.json b/apps/api/package.json
index d1578e8..ad454b1 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -27,6 +27,7 @@
"exiftool-vendored": "^39.0.1",
"fastify": "^5.12.5",
"jose": "^6.2.12",
+ "nodemailer": "^7.0.13",
"pg": "^8.23.1",
"pino": "^10.4.0",
"sharp": "^0.35.5",
@@ -34,6 +35,7 @@
"zod": "^4.6.5"
},
"devDependencies": {
+ "@types/nodemailer": "^8.0.2",
"@types/pg": "^8.23.1",
"prisma": "^7.10.0",
"socket.io-client": "^4.8.4"
diff --git a/apps/api/prisma/migrations/20261011220000_shop/migration.sql b/apps/api/prisma/migrations/20261011220000_shop/migration.sql
new file mode 100644
index 0000000..0d5af3b
--- /dev/null
+++ b/apps/api/prisma/migrations/20261011220000_shop/migration.sql
@@ -0,0 +1,192 @@
+-- CreateEnum
+CREATE TYPE "GalleryVisibility" AS ENUM ('PUBLIC', 'UNLISTED', 'PRIVATE');
+
+-- CreateEnum
+CREATE TYPE "ProductKind" AS ENUM ('DIGITAL', 'PRINT');
+
+-- CreateEnum
+CREATE TYPE "OrderStatus" AS ENUM ('PENDING', 'PAID', 'FULFILLED', 'CANCELLED', 'REFUNDED');
+
+-- CreateEnum
+CREATE TYPE "FulfilmentStatus" AS ENUM ('PENDING', 'RUNNING', 'READY', 'SHIPPED', 'FAILED');
+
+-- AlterTable
+ALTER TABLE "organizations" ADD COLUMN "country" TEXT NOT NULL DEFAULT 'PT',
+ADD COLUMN "legal_name" TEXT,
+ADD COLUMN "stripe_secret_sealed" TEXT,
+ADD COLUMN "stripe_webhook_sealed" TEXT,
+ADD COLUMN "vat_number" TEXT,
+ADD COLUMN "vat_rate" DOUBLE PRECISION NOT NULL DEFAULT 23;
+
+-- CreateTable
+CREATE TABLE "sites" (
+ "id" UUID NOT NULL,
+ "organization_id" UUID NOT NULL,
+ "domain" TEXT NOT NULL,
+ "skin" TEXT NOT NULL DEFAULT 'photoreport',
+ "name" TEXT NOT NULL,
+ "settings" JSONB NOT NULL DEFAULT '{}',
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "sites_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "galleries" (
+ "id" UUID NOT NULL,
+ "organization_id" UUID NOT NULL,
+ "event_id" UUID,
+ "slug" TEXT NOT NULL,
+ "title" TEXT NOT NULL,
+ "description" TEXT,
+ "visibility" "GalleryVisibility" NOT NULL DEFAULT 'PUBLIC',
+ "password_hash" TEXT,
+ "cover_photo_id" UUID,
+ "published_at" TIMESTAMP(3),
+ "for_sale" BOOLEAN NOT NULL DEFAULT true,
+ "free_downloads" BOOLEAN NOT NULL DEFAULT false,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "galleries_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "gallery_photos" (
+ "gallery_id" UUID NOT NULL,
+ "photo_id" UUID NOT NULL,
+ "position" INTEGER NOT NULL,
+ "added_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "gallery_photos_pkey" PRIMARY KEY ("gallery_id","photo_id")
+);
+
+-- CreateTable
+CREATE TABLE "products" (
+ "id" UUID NOT NULL,
+ "organization_id" UUID NOT NULL,
+ "kind" "ProductKind" NOT NULL,
+ "name" TEXT NOT NULL,
+ "long_edge" INTEGER,
+ "print_size" TEXT,
+ "price_cents" INTEGER NOT NULL,
+ "lead_days" INTEGER,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "position" INTEGER NOT NULL DEFAULT 0,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "products_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "orders" (
+ "id" UUID NOT NULL,
+ "organization_id" UUID NOT NULL,
+ "site_id" UUID,
+ "number" TEXT NOT NULL,
+ "status" "OrderStatus" NOT NULL DEFAULT 'PENDING',
+ "email" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "vat_number" TEXT,
+ "country" TEXT NOT NULL,
+ "reverse_charge" BOOLEAN NOT NULL DEFAULT false,
+ "vies_name" TEXT,
+ "currency" TEXT NOT NULL DEFAULT 'EUR',
+ "net_cents" INTEGER NOT NULL,
+ "vat_cents" INTEGER NOT NULL,
+ "total_cents" INTEGER NOT NULL,
+ "access_token" TEXT NOT NULL,
+ "provider" TEXT NOT NULL DEFAULT 'stripe',
+ "provider_ref" TEXT,
+ "checkout_url" TEXT,
+ "paid_at" TIMESTAMP(3),
+ "fulfilled_at" TIMESTAMP(3),
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "orders_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "order_items" (
+ "id" UUID NOT NULL,
+ "order_id" UUID NOT NULL,
+ "photo_id" UUID,
+ "product_id" UUID,
+ "product_name" TEXT NOT NULL,
+ "kind" "ProductKind" NOT NULL,
+ "long_edge" INTEGER,
+ "quantity" INTEGER NOT NULL,
+ "unit_cents" INTEGER NOT NULL,
+ "vat_rate" DOUBLE PRECISION NOT NULL,
+ "total_cents" INTEGER NOT NULL,
+ "status" "FulfilmentStatus" NOT NULL DEFAULT 'PENDING',
+ "file_key" TEXT,
+ "downloads" INTEGER NOT NULL DEFAULT 0,
+ "error" TEXT,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "order_items_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "sites_domain_key" ON "sites"("domain");
+
+-- CreateIndex
+CREATE INDEX "galleries_organization_id_published_at_idx" ON "galleries"("organization_id", "published_at");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "galleries_organization_id_slug_key" ON "galleries"("organization_id", "slug");
+
+-- CreateIndex
+CREATE INDEX "gallery_photos_gallery_id_position_idx" ON "gallery_photos"("gallery_id", "position");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "orders_access_token_key" ON "orders"("access_token");
+
+-- CreateIndex
+CREATE INDEX "orders_organization_id_created_at_idx" ON "orders"("organization_id", "created_at");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "orders_organization_id_number_key" ON "orders"("organization_id", "number");
+
+-- CreateIndex
+CREATE INDEX "order_items_order_id_idx" ON "order_items"("order_id");
+
+-- CreateIndex
+CREATE INDEX "order_items_status_idx" ON "order_items"("status");
+
+-- AddForeignKey
+ALTER TABLE "sites" ADD CONSTRAINT "sites_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "galleries" ADD CONSTRAINT "galleries_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "galleries" ADD CONSTRAINT "galleries_event_id_fkey" FOREIGN KEY ("event_id") REFERENCES "events"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "gallery_photos" ADD CONSTRAINT "gallery_photos_gallery_id_fkey" FOREIGN KEY ("gallery_id") REFERENCES "galleries"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "gallery_photos" ADD CONSTRAINT "gallery_photos_photo_id_fkey" FOREIGN KEY ("photo_id") REFERENCES "photos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "products" ADD CONSTRAINT "products_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "orders" ADD CONSTRAINT "orders_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "orders" ADD CONSTRAINT "orders_site_id_fkey" FOREIGN KEY ("site_id") REFERENCES "sites"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "order_items" ADD CONSTRAINT "order_items_order_id_fkey" FOREIGN KEY ("order_id") REFERENCES "orders"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "order_items" ADD CONSTRAINT "order_items_photo_id_fkey" FOREIGN KEY ("photo_id") REFERENCES "photos"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "order_items" ADD CONSTRAINT "order_items_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma
index d8ad13e..84f5607 100644
--- a/apps/api/prisma/schema.prisma
+++ b/apps/api/prisma/schema.prisma
@@ -62,16 +62,29 @@ model Organization {
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
- memberships Membership[]
- events Event[]
- photos Photo[]
- codeLists CodeList[]
- ftpAccounts FtpAccount[]
- targets DeliveryTarget[]
- people Person[]
- faces Face[]
- faceGroups FaceGroup[]
- deliveries DeliveryItem[]
+ memberships Membership[]
+ events Event[]
+ photos Photo[]
+ codeLists CodeList[]
+ ftpAccounts FtpAccount[]
+ targets DeliveryTarget[]
+ people Person[]
+ faces Face[]
+ faceGroups FaceGroup[]
+ deliveries DeliveryItem[]
+ sites Site[]
+ galleries Gallery[]
+ products Product[]
+ orders Order[]
+ /// Shop: Stripe keys (AES-GCM sealed, like delivery passwords). Payments go to the organization's account.
+ stripeSecretSealed String? @map("stripe_secret_sealed")
+ stripeWebhookSealed String? @map("stripe_webhook_sealed")
+ /// Seller details printed on orders: legal name and VAT number (NIF).
+ legalName String? @map("legal_name")
+ vatNumber String? @map("vat_number")
+ /// The seller's country (ISO 3166-1 alpha-2) and VAT rate (percent) for sales without reverse charge.
+ country String @default("PT")
+ vatRate Float @default(23) @map("vat_rate")
@@map("organizations")
}
@@ -201,6 +214,7 @@ model Event {
photos Photo[]
deliveries DeliveryItem[]
faceGroups FaceGroup[]
+ galleries Gallery[]
@@index([organizationId, startsAt])
@@map("events")
@@ -290,6 +304,8 @@ model Photo {
deliveries DeliveryItem[]
faces Face[]
edits PhotoEdit[]
+ galleries GalleryPhoto[]
+ orderItems OrderItem[]
/// The same file sent twice (FTP retries, two cards) is stored once.
@@unique([organizationId, sha256])
@@ -498,3 +514,189 @@ model Face {
@@index([groupId])
@@map("faces")
}
+
+/// A public website of an organization (photoreport.pt, shootyourmove.com...). The domain picks the
+/// organization, the skin and the texts; every skin shows the same galleries and shop.
+model Site {
+ id String @id @default(uuid()) @db.Uuid
+ organizationId String @map("organization_id") @db.Uuid
+ domain String @unique
+ /// Skin: "photoreport" (editorial, light) or "shootyourmove" (dark, red).
+ skin String @default("photoreport")
+ name String
+ /// Free settings per skin: tagline, contact email, social links, accent colour.
+ settings Json @default("{}")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
+ orders Order[]
+
+ @@map("sites")
+}
+
+enum GalleryVisibility {
+ /// Listed on the site.
+ PUBLIC
+ /// Reachable by link only.
+ UNLISTED
+ /// Link plus password (clients, teams, families).
+ PRIVATE
+}
+
+model Gallery {
+ id String @id @default(uuid()) @db.Uuid
+ organizationId String @map("organization_id") @db.Uuid
+ eventId String? @map("event_id") @db.Uuid
+ slug String
+ title String
+ description String?
+ visibility GalleryVisibility @default(PUBLIC)
+ passwordHash String? @map("password_hash")
+ coverPhotoId String? @map("cover_photo_id") @db.Uuid
+ /// Unpublished galleries are only visible in the app.
+ publishedAt DateTime? @map("published_at")
+ /// Selling switched off: a news gallery, or a client gallery paid upfront (downloads free).
+ forSale Boolean @default(true) @map("for_sale")
+ freeDownloads Boolean @default(false) @map("free_downloads")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
+ event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
+ photos GalleryPhoto[]
+
+ @@unique([organizationId, slug])
+ @@index([organizationId, publishedAt])
+ @@map("galleries")
+}
+
+model GalleryPhoto {
+ galleryId String @map("gallery_id") @db.Uuid
+ photoId String @map("photo_id") @db.Uuid
+ position Int
+ addedAt DateTime @default(now()) @map("added_at")
+
+ gallery Gallery @relation(fields: [galleryId], references: [id], onDelete: Cascade)
+ photo Photo @relation(fields: [photoId], references: [id], onDelete: Cascade)
+
+ @@id([galleryId, photoId])
+ @@index([galleryId, position])
+ @@map("gallery_photos")
+}
+
+enum ProductKind {
+ /// A JPEG to download, at `longEdge` px (0: full size).
+ DIGITAL
+ /// A print, made and sent (or handed over) by the organization.
+ PRINT
+}
+
+model Product {
+ id String @id @default(uuid()) @db.Uuid
+ organizationId String @map("organization_id") @db.Uuid
+ kind ProductKind
+ name String
+ longEdge Int? @map("long_edge")
+ /// Print size label (15x20, 20x30...).
+ printSize String? @map("print_size")
+ /// Gross price (VAT included) in cents, as shown to consumers.
+ priceCents Int @map("price_cents")
+ /// Working days until a print ships.
+ leadDays Int? @map("lead_days")
+ active Boolean @default(true)
+ position Int @default(0)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
+ orderItems OrderItem[]
+
+ @@map("products")
+}
+
+enum OrderStatus {
+ /// Created, waiting for the payment (Multibanco references can take days).
+ PENDING
+ PAID
+ /// Downloads ready and prints shipped.
+ FULFILLED
+ CANCELLED
+ REFUNDED
+}
+
+model Order {
+ id String @id @default(uuid()) @db.Uuid
+ organizationId String @map("organization_id") @db.Uuid
+ siteId String? @map("site_id") @db.Uuid
+ /// Human order number per organization (PR-2026-000123).
+ number String
+ status OrderStatus @default(PENDING)
+ email String
+ name String
+ /// Buyer's VAT number (with country prefix) when buying as a company.
+ vatNumber String? @map("vat_number")
+ /// Buyer's country (ISO alpha-2).
+ country String
+ /// EU business buyer with a VIES-valid number in another member state: VAT reverse-charged.
+ reverseCharge Boolean @default(false) @map("reverse_charge")
+ viesName String? @map("vies_name")
+ currency String @default("EUR")
+ netCents Int @map("net_cents")
+ vatCents Int @map("vat_cents")
+ totalCents Int @map("total_cents")
+ /// Secret for the buyer's order page and downloads (sent by email; never listed).
+ accessToken String @unique @map("access_token")
+ provider String @default("stripe")
+ providerRef String? @map("provider_ref")
+ checkoutUrl String? @map("checkout_url")
+ paidAt DateTime? @map("paid_at")
+ fulfilledAt DateTime? @map("fulfilled_at")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
+ site Site? @relation(fields: [siteId], references: [id], onDelete: SetNull)
+ items OrderItem[]
+
+ @@unique([organizationId, number])
+ @@index([organizationId, createdAt])
+ @@map("orders")
+}
+
+enum FulfilmentStatus {
+ PENDING
+ RUNNING
+ READY
+ SHIPPED
+ FAILED
+}
+
+model OrderItem {
+ id String @id @default(uuid()) @db.Uuid
+ orderId String @map("order_id") @db.Uuid
+ photoId String? @map("photo_id") @db.Uuid
+ productId String? @map("product_id") @db.Uuid
+ /// Copied at purchase: later price or product changes never alter an order.
+ productName String @map("product_name")
+ kind ProductKind
+ longEdge Int? @map("long_edge")
+ quantity Int
+ unitCents Int @map("unit_cents")
+ vatRate Float @map("vat_rate")
+ totalCents Int @map("total_cents")
+ status FulfilmentStatus @default(PENDING)
+ /// Rendered download (DIGITAL), relative to storage.
+ fileKey String? @map("file_key")
+ downloads Int @default(0)
+ error String?
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
+ photo Photo? @relation(fields: [photoId], references: [id], onDelete: SetNull)
+ product Product? @relation(fields: [productId], references: [id], onDelete: SetNull)
+
+ @@index([orderId])
+ @@index([status])
+ @@map("order_items")
+}
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index b6744a4..db80c11 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -20,6 +20,9 @@ import { IngestService } from "./ingest/service.js";
import { registerDevelopRoutes } from "./develop/routes.js";
import { DevelopService } from "./develop/service.js";
import { registerFaceRoutes } from "./faces/routes.js";
+import { registerShopAdminRoutes } from "./shop/admin-routes.js";
+import { registerPublicShopRoutes } from "./shop/public-routes.js";
+import { ShopService } from "./shop/service.js";
import { FaceService } from "./faces/service.js";
import { registerOrgRoutes } from "./orgs/routes.js";
import { attachRealtime, type Broadcaster, silentBroadcaster } from "./realtime.js";
@@ -89,6 +92,10 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr
// Edits are stored and fanned out here; the worker replays and renders them.
const develop = new DevelopService({ db, storage, signer, broadcaster, log: app.log });
await registerDevelopRoutes(app, { db, sessions, develop });
+ // Shop: the public sites read galleries and place orders; the worker renders the bought files.
+ const shop = new ShopService({ db, storage, signer, secrets, log: app.log, secret: config.JWT_SECRET, stripeApiUrl: config.STRIPE_API_URL, ...(fetchImpl && { fetchImpl }) });
+ await registerShopAdminRoutes(app, { db, sessions, shop, secrets });
+ await registerPublicShopRoutes(app, { shop });
// Validation-only endpoint for the edit contract; the realtime path reuses the same schema.
app.post("/v1/edits/validate", async (req) => {
diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts
index 45f2ee1..ff959fd 100644
--- a/apps/api/src/config.ts
+++ b/apps/api/src/config.ts
@@ -46,6 +46,11 @@ const Env = z.object({
FACES_PROCESSES: z.coerce.number().int().positive().default(2),
/** Render worker binary (workers/render): edited thumbnails and deliveries of edited photos. */
RENDER_BIN: z.string().optional(),
+ /** Outgoing mail (order links). Unset: no emails; buyers still get the link on screen. */
+ SMTP_URL: z.string().optional(),
+ MAIL_FROM: z.string().default("PhotoReport "),
+ /** Stripe API base; only changed for local end-to-end runs against a stand-in. */
+ STRIPE_API_URL: z.string().url().default("https://api.stripe.com"),
RENDER_PROCESSES: z.coerce.number().int().positive().default(2),
COOKIE_SECURE: z
.enum(["true", "false"])
diff --git a/apps/api/src/lib/mailer.ts b/apps/api/src/lib/mailer.ts
new file mode 100644
index 0000000..aa5013f
--- /dev/null
+++ b/apps/api/src/lib/mailer.ts
@@ -0,0 +1,15 @@
+import nodemailer from "nodemailer";
+
+export interface Mailer {
+ send(msg: { to: string; subject: string; text: string }): Promise;
+}
+
+/** SMTP mail (order links). `SMTP_URL` like smtps://user:pass@mail.example.pt:465. */
+export function smtpMailer(url: string, from: string): Mailer {
+ const transport = nodemailer.createTransport(url);
+ return {
+ async send(msg) {
+ await transport.sendMail({ from, ...msg });
+ },
+ };
+}
diff --git a/apps/api/src/shop/admin-routes.ts b/apps/api/src/shop/admin-routes.ts
new file mode 100644
index 0000000..bc4b31b
--- /dev/null
+++ b/apps/api/src/shop/admin-routes.ts
@@ -0,0 +1,324 @@
+import { GalleryInput, GalleryPhotosChange, type OrderView, ProductInput, SiteInput } from "@photoreport/contracts";
+import type { FastifyInstance } from "fastify";
+import { z } from "zod";
+import { requireAuth, requireMembership } from "../auth/guard.js";
+import type { SessionService } from "../auth/sessions.js";
+import type { Db } from "../db.js";
+import type { SecretBox } from "../delivery/secrets.js";
+import type { Prisma } from "../generated/prisma/client.js";
+import { compact } from "../lib/compact.js";
+import { badRequest, conflict, notFound } from "../lib/errors.js";
+import type { ShopService } from "./service.js";
+
+const OrgParams = z.object({ orgId: z.uuid() });
+const IdParams = z.object({ id: z.uuid() });
+const OrderListQuery = z.object({ status: z.enum(["PENDING", "PAID", "FULFILLED", "CANCELLED", "REFUNDED"]).optional(), limit: z.coerce.number().int().min(1).max(500).default(100) });
+
+const ShopSettings = z.object({
+ legalName: z.string().trim().max(160).nullable().optional(),
+ vatNumber: z.string().trim().max(20).nullable().optional(),
+ country: z
+ .string()
+ .length(2)
+ .transform((c) => c.toUpperCase())
+ .optional(),
+ vatRate: z.number().min(0).max(30).optional(),
+ /** Write-only: sealed at rest, never returned. Empty string removes it. */
+ stripeSecretKey: z.string().max(200).optional(),
+ stripeWebhookSecret: z.string().max(200).optional(),
+});
+
+const slugify = (s: string) =>
+ s
+ .normalize("NFD")
+ .replace(/[̀-ͯ]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 100) || "galeria";
+
+/** The app's side of the shop: galleries, products, sites, orders and payment settings. */
+export async function registerShopAdminRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; shop: ShopService; secrets: SecretBox | undefined }) {
+ const { db, shop, secrets } = deps;
+ const authenticate = requireAuth(deps.sessions);
+
+ async function galleryInOrg(req: Parameters[1], id: string) {
+ const g = await db.gallery.findUnique({ where: { id }, include: { _count: { select: { photos: true } } } });
+ if (!g) throw notFound("gallery_not_found");
+ await requireMembership(db, req, g.organizationId, "EDITOR");
+ return g;
+ }
+
+ // ---- galleries ----------------------------------------------------------------------------------
+
+ app.get("/v1/orgs/:orgId/galleries", { preHandler: authenticate }, async (req) => {
+ const { orgId } = OrgParams.parse(req.params);
+ await requireMembership(db, req, orgId, "INGESTER");
+ const galleries = await db.gallery.findMany({ where: { organizationId: orgId }, include: { _count: { select: { photos: true } } }, orderBy: { createdAt: "desc" } });
+ return { galleries: await Promise.all(galleries.map((g) => shop.gallerySummary(g))) };
+ });
+
+ app.post("/v1/orgs/:orgId/galleries", { preHandler: authenticate }, async (req, reply) => {
+ const { orgId } = OrgParams.parse(req.params);
+ const input = GalleryInput.parse(req.body);
+ await requireMembership(db, req, orgId, "EDITOR");
+ if (input.visibility === "PRIVATE" && !input.password) throw badRequest("password_required");
+ if (input.eventId && !(await db.event.findFirst({ where: { id: input.eventId, organizationId: orgId } }))) throw notFound("event_not_found");
+ // A free slug from the title, unless one was given.
+ let slug = input.slug ?? slugify(input.title);
+ if (!input.slug) for (let i = 2; await db.gallery.findUnique({ where: { organizationId_slug: { organizationId: orgId, slug } } }); i++) slug = `${slugify(input.title)}-${i}`;
+ else if (await db.gallery.findUnique({ where: { organizationId_slug: { organizationId: orgId, slug } } })) throw conflict("slug_taken");
+ const g = await db.gallery.create({
+ data: {
+ organizationId: orgId,
+ slug,
+ title: input.title,
+ description: input.description ?? null,
+ visibility: input.visibility,
+ passwordHash: input.password ? await shop.hashGalleryPassword(input.password) : null,
+ eventId: input.eventId ?? null,
+ forSale: input.forSale,
+ freeDownloads: input.freeDownloads,
+ },
+ include: { _count: { select: { photos: true } } },
+ });
+ return reply.code(201).send(await shop.gallerySummary(g));
+ });
+
+ app.patch("/v1/galleries/:id", { preHandler: authenticate }, async (req) => {
+ const { id } = IdParams.parse(req.params);
+ const input = GalleryInput.partial().parse(req.body);
+ const g = await galleryInOrg(req, id);
+ if (input.slug && input.slug !== g.slug && (await db.gallery.findUnique({ where: { organizationId_slug: { organizationId: g.organizationId, slug: input.slug } } }))) throw conflict("slug_taken");
+ if ((input.visibility ?? g.visibility) === "PRIVATE" && !input.password && !g.passwordHash) throw badRequest("password_required");
+ const updated = await db.gallery.update({
+ where: { id },
+ data: {
+ ...(input.slug && { slug: input.slug }),
+ ...(input.title && { title: input.title }),
+ ...(input.description !== undefined && { description: input.description }),
+ ...(input.visibility && { visibility: input.visibility }),
+ ...(input.password && { passwordHash: await shop.hashGalleryPassword(input.password) }),
+ ...(input.eventId !== undefined && { eventId: input.eventId }),
+ ...(input.forSale !== undefined && { forSale: input.forSale }),
+ ...(input.freeDownloads !== undefined && { freeDownloads: input.freeDownloads }),
+ },
+ include: { _count: { select: { photos: true } } },
+ });
+ return shop.gallerySummary(updated);
+ });
+
+ app.delete("/v1/galleries/:id", { preHandler: authenticate }, async (req, reply) => {
+ const { id } = IdParams.parse(req.params);
+ await galleryInOrg(req, id);
+ await db.gallery.delete({ where: { id } });
+ return reply.code(204).send();
+ });
+
+ /** Adds photos (at the end, in capture order) and removes others; the cover must be in the gallery. */
+ app.post("/v1/galleries/:id/photos", { preHandler: authenticate }, async (req) => {
+ const { id } = IdParams.parse(req.params);
+ const change = GalleryPhotosChange.parse(req.body);
+ const g = await galleryInOrg(req, id);
+ await db.$transaction(async (tx) => {
+ if (change.remove.length) await tx.galleryPhoto.deleteMany({ where: { galleryId: id, photoId: { in: change.remove } } });
+ if (change.add.length) {
+ const photos = await tx.photo.findMany({
+ where: { id: { in: change.add }, organizationId: g.organizationId, status: "READY", galleries: { none: { galleryId: id } } },
+ orderBy: [{ capturedAt: { sort: "asc", nulls: "last" } }, { originalName: "asc" }],
+ select: { id: true },
+ });
+ const last = await tx.galleryPhoto.aggregate({ where: { galleryId: id }, _max: { position: true } });
+ let pos = (last._max.position ?? 0) + 1;
+ await tx.galleryPhoto.createMany({ data: photos.map((p) => ({ galleryId: id, photoId: p.id, position: pos++ })) });
+ }
+ if (change.cover !== undefined) {
+ if (change.cover && !(await tx.galleryPhoto.findUnique({ where: { galleryId_photoId: { galleryId: id, photoId: change.cover } } }))) throw badRequest("cover_not_in_gallery");
+ await tx.gallery.update({ where: { id }, data: { coverPhotoId: change.cover } });
+ }
+ if (g.coverPhotoId && change.remove.includes(g.coverPhotoId)) await tx.gallery.update({ where: { id }, data: { coverPhotoId: null } });
+ });
+ const updated = await db.gallery.findUniqueOrThrow({ where: { id }, include: { _count: { select: { photos: true } } } });
+ return shop.gallerySummary(updated);
+ });
+
+ app.get("/v1/galleries/:id/photos", { preHandler: authenticate }, async (req) => {
+ const { id } = IdParams.parse(req.params);
+ await galleryInOrg(req, id);
+ const rows = await db.galleryPhoto.findMany({ where: { galleryId: id }, orderBy: { position: "asc" }, select: { photoId: true } });
+ return { photoIds: rows.map((r) => r.photoId) };
+ });
+
+ app.post("/v1/galleries/:id/publish", { preHandler: authenticate }, async (req) => {
+ const { id } = IdParams.parse(req.params);
+ const { published } = z.object({ published: z.boolean() }).parse(req.body);
+ const g = await galleryInOrg(req, id);
+ if (published && g._count.photos === 0) throw badRequest("gallery_empty");
+ const updated = await db.gallery.update({ where: { id }, data: { publishedAt: published ? (g.publishedAt ?? new Date()) : null }, include: { _count: { select: { photos: true } } } });
+ return shop.gallerySummary(updated);
+ });
+
+ // ---- products -----------------------------------------------------------------------------------
+
+ app.get("/v1/orgs/:orgId/products", { preHandler: authenticate }, async (req) => {
+ const { orgId } = OrgParams.parse(req.params);
+ await requireMembership(db, req, orgId, "EDITOR");
+ const products = await db.product.findMany({ where: { organizationId: orgId }, orderBy: [{ kind: "asc" }, { position: "asc" }, { priceCents: "asc" }] });
+ return { products: products.map((p) => shop.productSummary(p)) };
+ });
+
+ app.post("/v1/orgs/:orgId/products", { preHandler: authenticate }, async (req, reply) => {
+ const { orgId } = OrgParams.parse(req.params);
+ const input = ProductInput.parse(req.body);
+ await requireMembership(db, req, orgId, "ADMIN");
+ const p = await db.product.create({
+ data: {
+ organizationId: orgId,
+ kind: input.kind,
+ name: input.name,
+ longEdge: input.kind === "DIGITAL" ? (input.longEdge ?? 0) : null,
+ printSize: input.kind === "PRINT" ? (input.printSize ?? null) : null,
+ priceCents: input.priceCents,
+ leadDays: input.leadDays ?? null,
+ active: input.active,
+ position: input.position,
+ },
+ });
+ return reply.code(201).send(shop.productSummary(p));
+ });
+
+ app.patch("/v1/products/:id", { preHandler: authenticate }, async (req) => {
+ const { id } = IdParams.parse(req.params);
+ const product = await db.product.findUnique({ where: { id } });
+ if (!product) throw notFound("product_not_found");
+ await requireMembership(db, req, product.organizationId, "ADMIN");
+ const input = z
+ .object({ name: z.string().trim().min(1).max(80), priceCents: z.number().int().min(0).max(1_000_000), active: z.boolean(), position: z.number().int().min(0), leadDays: z.number().int().min(0).max(60).nullable(), longEdge: z.number().int().min(0).max(20000).nullable(), printSize: z.string().max(20).nullable() })
+ .partial()
+ .parse(req.body);
+ return shop.productSummary(await db.product.update({ where: { id }, data: compact(input) }));
+ });
+
+ app.delete("/v1/products/:id", { preHandler: authenticate }, async (req, reply) => {
+ const { id } = IdParams.parse(req.params);
+ const product = await db.product.findUnique({ where: { id } });
+ if (!product) throw notFound("product_not_found");
+ await requireMembership(db, req, product.organizationId, "ADMIN");
+ // Products already sold stay (orders keep a copy of name and price); they are switched off instead.
+ if (await db.orderItem.count({ where: { productId: id } })) await db.product.update({ where: { id }, data: { active: false } });
+ else await db.product.delete({ where: { id } });
+ return reply.code(204).send();
+ });
+
+ // ---- sites --------------------------------------------------------------------------------------
+
+ app.get("/v1/orgs/:orgId/sites", { preHandler: authenticate }, async (req) => {
+ const { orgId } = OrgParams.parse(req.params);
+ await requireMembership(db, req, orgId, "EDITOR");
+ const sites = await db.site.findMany({ where: { organizationId: orgId }, orderBy: { domain: "asc" } });
+ return { sites: sites.map((s) => shop.siteInfo(s)) };
+ });
+
+ app.post("/v1/orgs/:orgId/sites", { preHandler: authenticate }, async (req, reply) => {
+ const { orgId } = OrgParams.parse(req.params);
+ const input = SiteInput.parse(req.body);
+ await requireMembership(db, req, orgId, "ADMIN");
+ if (await db.site.findUnique({ where: { domain: input.domain } })) throw conflict("domain_taken");
+ const site = await db.site.create({ data: { organizationId: orgId, domain: input.domain, skin: input.skin, name: input.name, settings: input.settings as Prisma.InputJsonValue } });
+ return reply.code(201).send(shop.siteInfo(site));
+ });
+
+ app.patch("/v1/sites/:id", { preHandler: authenticate }, async (req) => {
+ const { id } = IdParams.parse(req.params);
+ const input = SiteInput.partial().parse(req.body);
+ const site = await db.site.findUnique({ where: { id } });
+ if (!site) throw notFound("site_not_found");
+ await requireMembership(db, req, site.organizationId, "ADMIN");
+ if (input.domain && input.domain !== site.domain && (await db.site.findUnique({ where: { domain: input.domain } }))) throw conflict("domain_taken");
+ const updated = await db.site.update({
+ where: { id },
+ data: { ...(input.domain && { domain: input.domain }), ...(input.skin && { skin: input.skin }), ...(input.name && { name: input.name }), ...(input.settings && { settings: input.settings as Prisma.InputJsonValue }) },
+ });
+ return shop.siteInfo(updated);
+ });
+
+ app.delete("/v1/sites/:id", { preHandler: authenticate }, async (req, reply) => {
+ const { id } = IdParams.parse(req.params);
+ const site = await db.site.findUnique({ where: { id } });
+ if (!site) throw notFound("site_not_found");
+ await requireMembership(db, req, site.organizationId, "ADMIN");
+ await db.site.delete({ where: { id } });
+ return reply.code(204).send();
+ });
+
+ // ---- orders -------------------------------------------------------------------------------------
+
+ app.get("/v1/orgs/:orgId/orders", { preHandler: authenticate }, async (req) => {
+ const { orgId } = OrgParams.parse(req.params);
+ const q = OrderListQuery.parse(req.query);
+ await requireMembership(db, req, orgId, "EDITOR");
+ const orders = await db.order.findMany({ where: { organizationId: orgId, ...(q.status && { status: q.status }) }, orderBy: { createdAt: "desc" }, take: q.limit, select: { id: true } });
+ const views: OrderView[] = await Promise.all(orders.map((o) => shop.orderView(o.id, null)));
+ return { orders: views };
+ });
+
+ app.post("/v1/orders/:id/items/:itemId/shipped", { preHandler: authenticate }, async (req) => {
+ const { id, itemId } = z.object({ id: z.uuid(), itemId: z.uuid() }).parse(req.params);
+ const order = await db.order.findUnique({ where: { id }, include: { items: { where: { id: itemId } } } });
+ if (!order || !order.items[0]) throw notFound("order_not_found");
+ await requireMembership(db, req, order.organizationId, "EDITOR");
+ if (order.items[0].kind !== "PRINT") throw badRequest("not_a_print");
+ if (order.status !== "PAID" && order.status !== "FULFILLED") throw badRequest("order_not_paid");
+ await shop.markShipped(itemId);
+ return shop.orderView(id, null);
+ });
+
+ /** Re-renders failed downloads. */
+ app.post("/v1/orders/:id/retry", { preHandler: authenticate }, async (req) => {
+ const { id } = IdParams.parse(req.params);
+ const order = await db.order.findUnique({ where: { id } });
+ if (!order) throw notFound("order_not_found");
+ await requireMembership(db, req, order.organizationId, "EDITOR");
+ await db.orderItem.updateMany({ where: { orderId: id, status: "FAILED" }, data: { status: "PENDING", error: null } });
+ return shop.orderView(id, null);
+ });
+
+ // ---- shop settings (payments) -------------------------------------------------------------------
+
+ app.get("/v1/orgs/:orgId/shop-settings", { preHandler: authenticate }, async (req) => {
+ const { orgId } = OrgParams.parse(req.params);
+ await requireMembership(db, req, orgId, "ADMIN");
+ const org = await db.organization.findUniqueOrThrow({ where: { id: orgId } });
+ return {
+ legalName: org.legalName,
+ vatNumber: org.vatNumber,
+ country: org.country,
+ vatRate: org.vatRate,
+ stripeConfigured: !!org.stripeSecretSealed,
+ webhookConfigured: !!org.stripeWebhookSealed,
+ webhookUrl: `/v1/public/stripe/${org.id}/webhook`,
+ };
+ });
+
+ app.put("/v1/orgs/:orgId/shop-settings", { preHandler: authenticate }, async (req) => {
+ const { orgId } = OrgParams.parse(req.params);
+ const input = ShopSettings.parse(req.body);
+ await requireMembership(db, req, orgId, "OWNER");
+ const sealing = input.stripeSecretKey || input.stripeWebhookSecret;
+ if (sealing && !secrets) throw badRequest("secret_key_missing");
+ if (input.stripeSecretKey && !/^(sk|rk)_(live|test)_/.test(input.stripeSecretKey)) throw badRequest("invalid_stripe_key");
+ if (input.stripeWebhookSecret && !input.stripeWebhookSecret.startsWith("whsec_")) throw badRequest("invalid_webhook_secret");
+ await db.organization.update({
+ where: { id: orgId },
+ data: {
+ ...(input.legalName !== undefined && { legalName: input.legalName }),
+ ...(input.vatNumber !== undefined && { vatNumber: input.vatNumber }),
+ ...(input.country && { country: input.country }),
+ ...(input.vatRate !== undefined && { vatRate: input.vatRate }),
+ ...(input.stripeSecretKey !== undefined && { stripeSecretSealed: input.stripeSecretKey ? secrets!.seal(input.stripeSecretKey) : null }),
+ ...(input.stripeWebhookSecret !== undefined && { stripeWebhookSealed: input.stripeWebhookSecret ? secrets!.seal(input.stripeWebhookSecret) : null }),
+ },
+ });
+ return { ok: true };
+ });
+}
diff --git a/apps/api/src/shop/pricing.ts b/apps/api/src/shop/pricing.ts
new file mode 100644
index 0000000..2f4340b
--- /dev/null
+++ b/apps/api/src/shop/pricing.ts
@@ -0,0 +1,54 @@
+/** EU member states (ISO alpha-2; VIES uses EL for Greece). */
+export const EU = new Set(["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE"]);
+
+export interface PricedLine {
+ quantity: number;
+ /** Gross unit price as listed (VAT included). */
+ unitCents: number;
+ vatRate: number;
+ /** Line total charged. */
+ totalCents: number;
+ netCents: number;
+ vatCents: number;
+}
+
+export interface Totals {
+ lines: PricedLine[];
+ netCents: number;
+ vatCents: number;
+ totalCents: number;
+ reverseCharge: boolean;
+}
+
+/**
+ * Prices are shown VAT included (consumers buy most photos). A business in another EU member state with a
+ * VIES-valid VAT number pays the net price and accounts for the VAT itself (reverse charge); everyone else pays
+ * the listed price with the seller's VAT inside it. Rounded per line, in cents.
+ *
+ * Not tax advice: digital sales to consumers in other member states may fall under OSS (the buyer's country's
+ * rate); this applies the seller's rate, which is right below the OSS threshold.
+ */
+export function priceOrder(lines: { quantity: number; unitCents: number }[], opts: { vatRate: number; reverseCharge: boolean }): Totals {
+ const rate = opts.reverseCharge ? 0 : opts.vatRate;
+ const priced = lines.map((l) => {
+ const gross = l.unitCents * l.quantity;
+ const net = Math.round(gross / (1 + opts.vatRate / 100));
+ if (opts.reverseCharge) return { quantity: l.quantity, unitCents: l.unitCents, vatRate: 0, totalCents: net, netCents: net, vatCents: 0 };
+ return { quantity: l.quantity, unitCents: l.unitCents, vatRate: rate, totalCents: gross, netCents: net, vatCents: gross - net };
+ });
+ const sum = (k: "netCents" | "vatCents" | "totalCents") => priced.reduce((s, l) => s + l[k], 0);
+ return { lines: priced, netCents: sum("netCents"), vatCents: sum("vatCents"), totalCents: sum("totalCents"), reverseCharge: opts.reverseCharge };
+}
+
+/** "PT 123 456 789" -> { country: "PT", number: "123456789" }; Greece's VIES prefix is EL. */
+export function splitVat(raw: string): { country: string; number: string } | null {
+ const v = raw.replace(/[\s.-]/g, "").toUpperCase();
+ const m = /^([A-Z]{2})([0-9A-Z+*]{2,13})$/.exec(v);
+ if (!m) return null;
+ const country = m[1] === "EL" ? "GR" : m[1]!;
+ return EU.has(country) ? { country, number: m[2]! } : null;
+}
+
+export function formatOrderNumber(year: number, seq: number): string {
+ return `${year}-${String(seq).padStart(6, "0")}`;
+}
diff --git a/apps/api/src/shop/public-routes.ts b/apps/api/src/shop/public-routes.ts
new file mode 100644
index 0000000..99650e4
--- /dev/null
+++ b/apps/api/src/shop/public-routes.ts
@@ -0,0 +1,145 @@
+import { createReadStream } from "node:fs";
+import { CreateOrder } from "@photoreport/contracts";
+import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import type { Site } from "../generated/prisma/client.js";
+import { ShopError, type ShopService } from "./service.js";
+
+const SlugParams = z.object({ slug: z.string().min(1).max(120) });
+const OrderParams = z.object({ orderId: z.uuid() });
+const ItemParams = z.object({ orderId: z.uuid(), itemId: z.uuid() });
+const TokenQuery = z.object({ t: z.string().min(10).max(100) });
+const FileParams = z.object({ siteId: z.uuid(), photoId: z.uuid(), kind: z.enum(["thumb", "preview"]) });
+const FileQuery = z.object({ exp: z.coerce.number().int(), sig: z.string().min(10).max(100) });
+
+function fail(reply: FastifyReply, err: unknown) {
+ if (err instanceof ShopError) return reply.code(err.status).send({ error: err.code });
+ throw err;
+}
+
+/**
+ * Endpoints for the public sites (no login). The site comes from the `x-site-domain` header (the site's server
+ * renders pages) or the Host header (browsers going through the site's `/v1` proxy).
+ */
+export async function registerPublicShopRoutes(app: FastifyInstance, deps: { shop: ShopService }) {
+ const { shop } = deps;
+
+ async function siteOf(req: FastifyRequest): Promise {
+ const header = req.headers["x-site-domain"];
+ const host = (Array.isArray(header) ? header[0] : header) ?? req.headers["x-forwarded-host"]?.toString().split(",")[0] ?? req.headers.host;
+ const site = await shop.siteFor(host);
+ if (!site) throw new ShopError("site_not_found", 404);
+ return site;
+ }
+
+ const handle =
+ (fn: (req: FastifyRequest, reply: FastifyReply) => Promise) =>
+ async (req: FastifyRequest, reply: FastifyReply) => {
+ try {
+ return await fn(req, reply);
+ } catch (err) {
+ return fail(reply, err);
+ }
+ };
+
+ app.get(
+ "/v1/public/site",
+ handle(async (req) => shop.siteInfo(await siteOf(req))),
+ );
+
+ app.get(
+ "/v1/public/galleries",
+ handle(async (req) => ({ galleries: await shop.publicGalleries(await siteOf(req)) })),
+ );
+
+ app.get(
+ "/v1/public/galleries/:slug",
+ handle(async (req) => {
+ const { slug } = SlugParams.parse(req.params);
+ const token = req.headers["x-gallery-token"];
+ return shop.publicGallery(await siteOf(req), slug, Array.isArray(token) ? token[0] : token);
+ }),
+ );
+
+ app.post(
+ "/v1/public/galleries/:slug/unlock",
+ { config: { rateLimit: { max: 10, timeWindow: "1 minute" } } },
+ handle(async (req) => {
+ const { slug } = SlugParams.parse(req.params);
+ const { password } = z.object({ password: z.string().min(1).max(100) }).parse(req.body);
+ return { token: await shop.unlock(await siteOf(req), slug, password) };
+ }),
+ );
+
+ app.get(
+ "/v1/public/products",
+ handle(async (req) => ({ products: await shop.publicProducts(await siteOf(req)) })),
+ );
+
+ app.post(
+ "/v1/public/orders",
+ { config: { rateLimit: { max: 20, timeWindow: "1 minute" } } },
+ handle(async (req, reply) => {
+ const site = await siteOf(req);
+ const input = CreateOrder.parse(req.body);
+ const base = `https://${site.domain}`;
+ const out = await shop.createOrder(site, input, {
+ success: (id, token) => `${base}/encomenda/${id}?t=${token}`,
+ cancel: `${base}/galeria/${encodeURIComponent(input.gallery)}`,
+ });
+ return reply.code(201).send(out);
+ }),
+ );
+
+ app.get(
+ "/v1/public/orders/:orderId",
+ handle(async (req) => {
+ const { orderId } = OrderParams.parse(req.params);
+ const { t } = TokenQuery.parse(req.query);
+ return shop.orderView(orderId, t);
+ }),
+ );
+
+ app.get(
+ "/v1/public/orders/:orderId/items/:itemId/download",
+ handle(async (req, reply) => {
+ const { orderId, itemId } = ItemParams.parse(req.params);
+ const { t } = TokenQuery.parse(req.query);
+ const file = await shop.download(orderId, itemId, t);
+ return reply
+ .header("content-type", "image/jpeg")
+ .header("content-disposition", `attachment; filename="${file.fileName.replace(/[^\w.-]+/g, "_")}"`)
+ .header("cache-control", "private, no-store")
+ .send(createReadStream(file.path));
+ }),
+ );
+
+ app.get(
+ "/v1/public/files/:siteId/:photoId/:kind",
+ handle(async (req, reply) => {
+ const { siteId, photoId, kind } = FileParams.parse(req.params);
+ const { exp, sig } = FileQuery.parse(req.query);
+ if (!shop.verifyImage(siteId, photoId, kind, exp, sig)) throw new ShopError("file_not_found", 404);
+ const site = await shop.siteById(siteId);
+ if (!site) throw new ShopError("file_not_found", 404);
+ const path = await shop.publicImage(site, photoId, kind);
+ if (!path) throw new ShopError("file_not_found", 404);
+ return reply.header("content-type", "image/jpeg").header("cache-control", "public, max-age=86400, immutable").send(createReadStream(path));
+ }),
+ );
+
+ // Stripe needs the exact bytes it signed, so this route reads the body raw.
+ await app.register(async (scoped) => {
+ scoped.removeAllContentTypeParsers();
+ scoped.addContentTypeParser("*", { parseAs: "buffer" }, (_req, body, done) => done(null, body));
+ scoped.post(
+ "/v1/public/stripe/:orgId/webhook",
+ handle(async (req) => {
+ const { orgId } = z.object({ orgId: z.uuid() }).parse(req.params);
+ const sig = req.headers["stripe-signature"];
+ await shop.stripeWebhook(orgId, req.body as Buffer, Array.isArray(sig) ? sig[0] : sig);
+ return { received: true };
+ }),
+ );
+ });
+}
diff --git a/apps/api/src/shop/service.ts b/apps/api/src/shop/service.ts
new file mode 100644
index 0000000..c71f576
--- /dev/null
+++ b/apps/api/src/shop/service.ts
@@ -0,0 +1,541 @@
+import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
+import type { CreateOrder, GallerySummary, OrderView, ProductSummary, PublicGallery, PublicGallerySummary, PublicPhoto, SiteInfo, Skin } from "@photoreport/contracts";
+import { createdStamp } from "@photoreport/metadata";
+import { hashPassword, verifyPassword } from "../auth/passwords.js";
+import type { Db } from "../db.js";
+import { renderDelivery } from "../delivery/render.js";
+import type { SecretBox } from "../delivery/secrets.js";
+import type { DevelopService } from "../develop/service.js";
+import type { Event, Gallery, Order, OrderItem, Photo, Product, Site } from "../generated/prisma/client.js";
+import type { IngestLogger } from "../ingest/service.js";
+import { iptcForPhoto } from "../library/iptc.js";
+import type { LocalStorage, UrlSigner } from "../storage/storage.js";
+import { EU, formatOrderNumber, priceOrder, splitVat } from "./pricing.js";
+import { createCheckout, verifyWebhook } from "./stripe.js";
+import { checkVies } from "./vies.js";
+import { watermarked } from "./watermark.js";
+
+export type PublicImageKind = "thumb" | "preview";
+const PUBLIC_EDGE: Record = { thumb: 600, preview: 1600 };
+const GALLERY_TOKEN_TTL_SEC = 7 * 24 * 3600;
+const MAX_DOWNLOADS = 20;
+const STALE_RUNNING_MS = 10 * 60_000;
+
+export class ShopError extends Error {
+ constructor(
+ readonly code: string,
+ readonly status = 400,
+ ) {
+ super(code);
+ }
+}
+
+export interface ShopDeps {
+ db: Db;
+ storage: LocalStorage;
+ signer: UrlSigner;
+ secrets: SecretBox | undefined;
+ log: IngestLogger;
+ /** Key for gallery access tokens and public image URLs (derived from the server secret). */
+ secret: string;
+ fetchImpl?: typeof fetch;
+ /** Stripe's API (a local stand-in for end-to-end runs). */
+ stripeApiUrl?: string;
+ develop?: DevelopService | undefined;
+ mailer?: { send(msg: { to: string; subject: string; text: string }): Promise } | undefined;
+}
+
+const b64 = (b: Buffer) => b.toString("base64url");
+
+/**
+ * The shop: galleries on the public sites, products, orders paid through the organization's own Stripe account,
+ * and the downloads, rendered from the original with the photo's edits and IPTC.
+ */
+export class ShopService {
+ private readonly key: Buffer;
+
+ constructor(private readonly deps: ShopDeps) {
+ this.key = createHmac("sha256", deps.secret).update("photoreport:shop").digest();
+ }
+
+ private mac(text: string): string {
+ return b64(createHmac("sha256", this.key).update(text).digest()).slice(0, 32);
+ }
+
+ private same(a: string, b: string): boolean {
+ const x = Buffer.from(a);
+ const y = Buffer.from(b);
+ return x.length === y.length && timingSafeEqual(x, y);
+ }
+
+ // ---- sites ------------------------------------------------------------------------------------------
+
+ /** The site a request is for: exact domain, then without port, then without `www.`. */
+ async siteFor(host: string | undefined): Promise {
+ if (!host) return null;
+ const h = host.trim().toLowerCase();
+ const bare = h.replace(/:\d+$/, "");
+ const candidates = [...new Set([h, bare, bare.replace(/^www\./, "")])];
+ return this.deps.db.site.findFirst({ where: { domain: { in: candidates } }, orderBy: { domain: "desc" } });
+ }
+
+ siteById(id: string): Promise {
+ return this.deps.db.site.findUnique({ where: { id } });
+ }
+
+ siteInfo(site: Site): SiteInfo {
+ return { id: site.id, domain: site.domain, skin: site.skin as Skin, name: site.name, settings: (site.settings ?? {}) as SiteInfo["settings"] };
+ }
+
+ // ---- public images ----------------------------------------------------------------------------------
+
+ /** Signed, watermarked image URL for one site (the watermark carries the site's name). */
+ publicImageUrl(siteId: string, photo: { id: string; renderedSeq: number }, kind: PublicImageKind): string {
+ const exp = Math.ceil((Date.now() / 1000 + 6 * 3600) / 3600) * 3600;
+ const sig = this.mac(`img:${siteId}:${photo.id}:${kind}:${exp}`);
+ return `/v1/public/files/${siteId}/${photo.id}/${kind}?exp=${exp}&sig=${sig}${photo.renderedSeq ? `&v=${photo.renderedSeq}` : ""}`;
+ }
+
+ verifyImage(siteId: string, photoId: string, kind: string, exp: number, sig: string): boolean {
+ return Number.isFinite(exp) && exp >= Date.now() / 1000 && this.same(this.mac(`img:${siteId}:${photoId}:${kind}:${exp}`), sig);
+ }
+
+ /** The watermarked file (made on first request, then cached until the photo's edit changes). */
+ async publicImage(site: Site, photoId: string, kind: PublicImageKind): Promise {
+ const { db, storage } = this.deps;
+ const photo = await db.photo.findFirst({
+ where: { id: photoId, organizationId: site.organizationId, status: "READY", galleries: { some: { gallery: { publishedAt: { not: null } } } } },
+ });
+ if (!photo) return null;
+ const key = `${photo.organizationId}/public/${photo.sha256.slice(0, 2)}/${photo.sha256}.r${photo.renderedSeq}.${site.id.slice(0, 8)}.${kind}.jpg`;
+ if (await storage.exists(key)) return storage.resolve(key);
+ let source = storage.derivedKey(photo.organizationId, photo.sha256, "preview");
+ if (photo.renderedSeq > 0) {
+ const edited = storage.editedKey(photo.organizationId, photo.sha256, photo.renderedSeq, "preview");
+ if (await storage.exists(edited)) source = edited;
+ }
+ await storage.write(key, await watermarked(storage.resolve(source), site.name, PUBLIC_EDGE[kind]));
+ return storage.resolve(key);
+ }
+
+ // ---- galleries --------------------------------------------------------------------------------------
+
+ galleryToken(galleryId: string, now = Date.now()): string {
+ const exp = Math.floor(now / 1000) + GALLERY_TOKEN_TTL_SEC;
+ return `${galleryId}.${exp}.${this.mac(`gallery:${galleryId}:${exp}`)}`;
+ }
+
+ private tokenOpens(gallery: Gallery, token: string | undefined): boolean {
+ if (gallery.visibility !== "PRIVATE") return true;
+ if (!token) return false;
+ const [id, expRaw, sig] = token.split(".");
+ const exp = Number(expRaw);
+ return id === gallery.id && Number.isFinite(exp) && exp >= Date.now() / 1000 && !!sig && this.same(this.mac(`gallery:${id}:${exp}`), sig);
+ }
+
+ private async publishedGallery(site: Site, slug: string) {
+ const gallery = await this.deps.db.gallery.findFirst({
+ where: { organizationId: site.organizationId, slug, publishedAt: { not: null } },
+ include: { event: true, _count: { select: { photos: true } } },
+ });
+ if (!gallery) throw new ShopError("gallery_not_found", 404);
+ return gallery;
+ }
+
+ private eventInfo(e: Event | null) {
+ return e ? { home: e.home, away: e.away || null, competition: e.competition, venue: e.venue, startsAt: e.startsAt.toISOString() } : null;
+ }
+
+ private async coverOf(site: Site, gallery: Gallery): Promise {
+ const photo = gallery.coverPhotoId
+ ? await this.deps.db.photo.findUnique({ where: { id: gallery.coverPhotoId }, select: { id: true, renderedSeq: true } })
+ : (await this.deps.db.galleryPhoto.findFirst({ where: { galleryId: gallery.id }, orderBy: { position: "asc" }, include: { photo: { select: { id: true, renderedSeq: true } } } }))?.photo;
+ return photo ? this.publicImageUrl(site.id, photo, "thumb") : null;
+ }
+
+ async publicGalleries(site: Site): Promise {
+ const galleries = await this.deps.db.gallery.findMany({
+ where: { organizationId: site.organizationId, visibility: "PUBLIC", publishedAt: { not: null } },
+ include: { event: true, _count: { select: { photos: true } } },
+ orderBy: { publishedAt: "desc" },
+ take: 200,
+ });
+ return Promise.all(
+ galleries.map(async (g) => ({
+ slug: g.slug,
+ title: g.title,
+ description: g.description,
+ visibility: g.visibility,
+ photoCount: g._count.photos,
+ cover: await this.coverOf(site, g),
+ event: this.eventInfo(g.event),
+ publishedAt: g.publishedAt!.toISOString(),
+ })),
+ );
+ }
+
+ async publicGallery(site: Site, slug: string, token?: string): Promise {
+ const g = await this.publishedGallery(site, slug);
+ const open = this.tokenOpens(g, token);
+ const rows = open
+ ? await this.deps.db.galleryPhoto.findMany({ where: { galleryId: g.id, photo: { status: "READY" } }, orderBy: { position: "asc" }, include: { photo: true } })
+ : [];
+ const photos: PublicPhoto[] = rows.map(({ photo }) => ({
+ id: photo.id,
+ width: photo.width,
+ height: photo.height,
+ capturedAt: photo.capturedAt?.toISOString() ?? null,
+ players: photo.players,
+ thumb: this.publicImageUrl(site.id, photo, "thumb"),
+ preview: this.publicImageUrl(site.id, photo, "preview"),
+ }));
+ return {
+ slug: g.slug,
+ title: g.title,
+ description: g.description,
+ visibility: g.visibility,
+ photoCount: g._count.photos,
+ cover: open ? await this.coverOf(site, g) : null,
+ event: this.eventInfo(g.event),
+ publishedAt: g.publishedAt!.toISOString(),
+ forSale: g.forSale,
+ freeDownloads: g.freeDownloads,
+ locked: !open,
+ photos,
+ };
+ }
+
+ async unlock(site: Site, slug: string, password: string): Promise {
+ const g = await this.publishedGallery(site, slug);
+ if (g.visibility !== "PRIVATE") return this.galleryToken(g.id);
+ if (!g.passwordHash || !(await verifyPassword(g.passwordHash, password))) throw new ShopError("wrong_password", 401);
+ return this.galleryToken(g.id);
+ }
+
+ hashGalleryPassword(password: string): Promise {
+ return hashPassword(password);
+ }
+
+ async gallerySummary(g: Gallery & { _count: { photos: number } }): Promise {
+ const cover = g.coverPhotoId
+ ? await this.deps.db.photo.findUnique({ where: { id: g.coverPhotoId }, select: { id: true, renderedSeq: true } })
+ : (await this.deps.db.galleryPhoto.findFirst({ where: { galleryId: g.id }, orderBy: { position: "asc" }, include: { photo: { select: { id: true, renderedSeq: true } } } }))?.photo;
+ return {
+ id: g.id,
+ slug: g.slug,
+ title: g.title,
+ description: g.description,
+ visibility: g.visibility,
+ hasPassword: !!g.passwordHash,
+ eventId: g.eventId,
+ publishedAt: g.publishedAt?.toISOString() ?? null,
+ forSale: g.forSale,
+ freeDownloads: g.freeDownloads,
+ photoCount: g._count.photos,
+ cover: cover ? this.deps.signer.url(cover.id, "thumb", cover.renderedSeq) : null,
+ };
+ }
+
+ // ---- products ---------------------------------------------------------------------------------------
+
+ productSummary(p: Product): ProductSummary {
+ return { id: p.id, kind: p.kind, name: p.name, longEdge: p.longEdge, printSize: p.printSize, priceCents: p.priceCents, leadDays: p.leadDays, active: p.active, position: p.position };
+ }
+
+ async publicProducts(site: Site): Promise {
+ const products = await this.deps.db.product.findMany({ where: { organizationId: site.organizationId, active: true }, orderBy: [{ kind: "asc" }, { position: "asc" }, { priceCents: "asc" }] });
+ return products.map((p) => this.productSummary(p));
+ }
+
+ // ---- orders -----------------------------------------------------------------------------------------
+
+ async createOrder(site: Site, input: CreateOrder, urls: { success: (orderId: string, token: string) => string; cancel: string }): Promise<{ order: OrderView; checkoutUrl: string | null; token: string }> {
+ const { db, secrets } = this.deps;
+ const org = await db.organization.findUniqueOrThrow({ where: { id: site.organizationId } });
+ const gallery = await this.publishedGallery(site, input.gallery);
+ if (!this.tokenOpens(gallery, input.galleryToken)) throw new ShopError("gallery_locked", 401);
+ if (!gallery.forSale && !gallery.freeDownloads) throw new ShopError("gallery_not_for_sale");
+
+ const photoIds = [...new Set(input.items.map((i) => i.photoId))];
+ const inGallery = await db.galleryPhoto.findMany({ where: { galleryId: gallery.id, photoId: { in: photoIds } }, select: { photoId: true } });
+ if (inGallery.length !== photoIds.length) throw new ShopError("photo_not_in_gallery");
+ const products = new Map(
+ (await db.product.findMany({ where: { organizationId: org.id, active: true, id: { in: input.items.map((i) => i.productId) } } })).map((p) => [p.id, p]),
+ );
+ const lines = input.items.map((i) => {
+ const product = products.get(i.productId);
+ if (!product) throw new ShopError("product_not_found");
+ // A free-downloads gallery gives the digital files away; prints are still paid.
+ const free = gallery.freeDownloads && product.kind === "DIGITAL";
+ if (!gallery.forSale && !free) throw new ShopError("gallery_not_for_sale");
+ return { ...i, product, unitCents: free ? 0 : product.priceCents };
+ });
+
+ // B2B reverse charge: a VIES-valid number from another member state.
+ let reverseCharge = false;
+ let viesName: string | null = null;
+ const vat = input.vatNumber ? splitVat(input.vatNumber) : null;
+ if (input.vatNumber && !vat) throw new ShopError("invalid_vat_number");
+ if (vat && EU.has(input.country) && vat.country !== org.country) {
+ const check = await checkVies(input.vatNumber!, this.deps.fetchImpl);
+ reverseCharge = check?.valid === true;
+ viesName = check?.name ?? null;
+ }
+ const totals = priceOrder(lines, { vatRate: org.vatRate, reverseCharge });
+
+ const order = await db.$transaction(async (tx) => {
+ const year = new Date().getUTCFullYear();
+ await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`orders:${org.id}:${year}`}))`;
+ const count = await tx.order.count({ where: { organizationId: org.id, number: { startsWith: `${year}-` } } });
+ return tx.order.create({
+ data: {
+ organizationId: org.id,
+ siteId: site.id,
+ number: formatOrderNumber(year, count + 1),
+ email: input.email,
+ name: input.name,
+ vatNumber: vat ? `${vat.country === "GR" ? "EL" : vat.country}${vat.number}` : null,
+ country: input.country,
+ reverseCharge,
+ viesName,
+ netCents: totals.netCents,
+ vatCents: totals.vatCents,
+ totalCents: totals.totalCents,
+ accessToken: b64(randomBytes(24)),
+ items: {
+ create: lines.map((l, i) => ({
+ photoId: l.photoId,
+ productId: l.product.id,
+ productName: l.product.name,
+ kind: l.product.kind,
+ longEdge: l.product.longEdge,
+ quantity: l.quantity,
+ unitCents: l.unitCents,
+ vatRate: totals.lines[i]!.vatRate,
+ totalCents: totals.lines[i]!.totalCents,
+ })),
+ },
+ },
+ });
+ });
+
+ if (order.totalCents === 0) {
+ await this.markPaid(order.id, "free");
+ return { order: await this.orderView(order.id, order.accessToken), checkoutUrl: null, token: order.accessToken };
+ }
+ if (!org.stripeSecretSealed || !secrets) throw new ShopError("payments_not_configured", 503);
+ const checkout = await createCheckout(
+ secrets.open(org.stripeSecretSealed),
+ {
+ orderId: order.id,
+ orderNumber: order.number,
+ email: order.email,
+ currency: order.currency,
+ // Stripe charges what we computed: one line per item at its charged total.
+ lines: lines.map((l, i) => ({ name: l.quantity > 1 ? `${l.product.name} × ${l.quantity}` : l.product.name, unitCents: totals.lines[i]!.totalCents, quantity: 1 })),
+ successUrl: urls.success(order.id, order.accessToken),
+ cancelUrl: urls.cancel,
+ },
+ this.deps.fetchImpl,
+ this.deps.stripeApiUrl,
+ );
+ await db.order.update({ where: { id: order.id }, data: { providerRef: checkout.id, checkoutUrl: checkout.url } });
+ return { order: await this.orderView(order.id, order.accessToken), checkoutUrl: checkout.url, token: order.accessToken };
+ }
+
+ /** Paid (Stripe webhook, or nothing to pay): downloads get rendered by the worker. Idempotent. */
+ async markPaid(orderId: string, providerRef?: string): Promise {
+ const r = await this.deps.db.order.updateMany({
+ where: { id: orderId, status: "PENDING" },
+ data: { status: "PAID", paidAt: new Date(), ...(providerRef && { providerRef }) },
+ });
+ if (r.count) this.deps.log.info({ orderId }, "shop: order paid");
+ return r.count > 0;
+ }
+
+ /** A Stripe event for the organization's account (signature checked here). */
+ async stripeWebhook(organizationId: string, rawBody: Buffer, signature: string | undefined): Promise {
+ const { db, secrets } = this.deps;
+ const org = await db.organization.findUnique({ where: { id: organizationId } });
+ if (!org?.stripeWebhookSealed || !secrets) throw new ShopError("payments_not_configured", 404);
+ if (!verifyWebhook(rawBody, signature, secrets.open(org.stripeWebhookSealed))) throw new ShopError("bad_signature", 400);
+ const event = JSON.parse(rawBody.toString("utf8")) as { type: string; data: { object: { id: string; payment_status?: string; metadata?: { order_id?: string }; client_reference_id?: string } } };
+ const session = event.data.object;
+ const orderId = session.metadata?.order_id ?? session.client_reference_id;
+ if (!orderId) return;
+ const order = await db.order.findFirst({ where: { id: orderId, organizationId } });
+ if (!order) return;
+ switch (event.type) {
+ case "checkout.session.completed":
+ // Multibanco: completed when the reference is issued, paid later (async_payment_succeeded).
+ if (session.payment_status === "paid") await this.markPaid(order.id, session.id);
+ break;
+ case "checkout.session.async_payment_succeeded":
+ await this.markPaid(order.id, session.id);
+ break;
+ case "checkout.session.async_payment_failed":
+ case "checkout.session.expired":
+ await db.order.updateMany({ where: { id: order.id, status: "PENDING" }, data: { status: "CANCELLED" } });
+ break;
+ }
+ }
+
+ async orderView(orderId: string, token: string | null): Promise {
+ const order = await this.deps.db.order.findUnique({
+ where: { id: orderId },
+ include: { items: { include: { photo: { select: { id: true, originalName: true, renderedSeq: true } } }, orderBy: { id: "asc" } }, site: true },
+ });
+ if (!order || (token !== null && !this.same(order.accessToken, token))) throw new ShopError("order_not_found", 404);
+ return {
+ id: order.id,
+ number: order.number,
+ status: order.status,
+ email: order.email,
+ name: order.name,
+ country: order.country,
+ vatNumber: order.vatNumber,
+ reverseCharge: order.reverseCharge,
+ currency: order.currency,
+ netCents: order.netCents,
+ vatCents: order.vatCents,
+ totalCents: order.totalCents,
+ createdAt: order.createdAt.toISOString(),
+ paidAt: order.paidAt?.toISOString() ?? null,
+ checkoutUrl: order.status === "PENDING" ? order.checkoutUrl : null,
+ items: order.items.map((i) => ({
+ id: i.id,
+ productName: i.productName,
+ kind: i.kind,
+ quantity: i.quantity,
+ unitCents: i.unitCents,
+ totalCents: i.totalCents,
+ status: i.status,
+ photo: i.photo
+ ? { id: i.photo.id, name: i.photo.originalName, thumb: order.site ? this.publicImageUrl(order.site.id, i.photo, "thumb") : this.deps.signer.url(i.photo.id, "thumb", i.photo.renderedSeq) }
+ : null,
+ download: i.kind === "DIGITAL" && i.status === "READY" ? `/v1/public/orders/${order.id}/items/${i.id}/download?t=${order.accessToken}` : null,
+ })),
+ };
+ }
+
+ /** The rendered file of a paid digital item, counting downloads. */
+ async download(orderId: string, itemId: string, token: string): Promise<{ path: string; fileName: string }> {
+ const item = await this.deps.db.orderItem.findFirst({ where: { id: itemId, orderId }, include: { order: true, photo: true } });
+ if (!item || !this.same(item.order.accessToken, token)) throw new ShopError("order_not_found", 404);
+ if (item.status !== "READY" || !item.fileKey) throw new ShopError("not_ready", 409);
+ if (item.downloads >= MAX_DOWNLOADS) throw new ShopError("download_limit", 429);
+ await this.deps.db.orderItem.update({ where: { id: item.id }, data: { downloads: { increment: 1 } } });
+ const base = (item.photo?.originalName ?? "photo.jpg").replace(/\.[^.]+$/, "");
+ return { path: this.deps.storage.resolve(item.fileKey), fileName: `${item.order.number}-${base}.jpg` };
+ }
+
+ // ---- fulfilment (worker) ----------------------------------------------------------------------------
+
+ async claimDownloads(limit: number): Promise {
+ if (limit <= 0) return [];
+ const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
+ UPDATE order_items SET status = 'RUNNING', updated_at = now()
+ WHERE id IN (
+ SELECT oi.id FROM order_items oi JOIN orders o ON o.id = oi.order_id
+ WHERE oi.status = 'PENDING' AND oi.kind = 'DIGITAL' AND o.status = 'PAID'
+ ORDER BY o.paid_at LIMIT ${limit} FOR UPDATE OF oi SKIP LOCKED
+ )
+ RETURNING id`;
+ return rows.map((r) => r.id);
+ }
+
+ async requeueStale(now = new Date()): Promise {
+ const r = await this.deps.db.orderItem.updateMany({ where: { status: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } }, data: { status: "PENDING" } });
+ return r.count;
+ }
+
+ /** Renders one bought file: the edit, full IPTC, at the product's size. Never throws. */
+ async fulfil(itemId: string): Promise {
+ const { db, storage, log } = this.deps;
+ const item = await db.orderItem.findUnique({ where: { id: itemId }, include: { photo: true, order: true } });
+ if (!item) return;
+ try {
+ if (!item.photo) throw new Error("photo was deleted");
+ const photo: Photo = item.photo;
+ const iptc = await iptcForPhoto(db, photo.id);
+ const edited = await this.editFor(photo);
+ const longEdge = item.longEdge && item.longEdge > 0 ? item.longEdge : 65535;
+ const data = await renderDelivery(storage.resolve(photo.storageKey), iptc?.values ?? {}, { longEdge, quality: 95 }, photo.capturedAt ? createdStamp(photo.capturedAt) : undefined, edited);
+ const key = `${item.order.organizationId}/orders/${item.orderId}/${item.id}.jpg`;
+ await storage.write(key, data);
+ await db.orderItem.update({ where: { id: item.id }, data: { status: "READY", fileKey: key, error: null } });
+ await this.maybeFulfilled(item.order);
+ } catch (err) {
+ log.warn({ itemId, err: (err as Error).message }, "shop: download render failed");
+ await db.orderItem.update({ where: { id: item.id }, data: { status: "FAILED", error: (err as Error).message } }).catch(() => {});
+ }
+ }
+
+ private async editFor(photo: Photo) {
+ if (photo.developSeq === 0) return undefined;
+ const develop = this.deps.develop;
+ if (!develop?.engine) throw new Error("photo is edited but the render worker is not configured (RENDER_BIN)");
+ const { settings } = await develop.settings(photo.id);
+ return settings ? { engine: develop.engine, settings } : undefined;
+ }
+
+ /** All downloads ready (prints are shipped separately): tell the buyer once, and close the order when nothing is left. */
+ private async maybeFulfilled(order: Order): Promise {
+ const { db } = this.deps;
+ const items: OrderItem[] = await db.orderItem.findMany({ where: { orderId: order.id } });
+ const digitalDone = items.filter((i) => i.kind === "DIGITAL").every((i) => i.status === "READY");
+ if (!digitalDone) return;
+ const allDone = items.every((i) => (i.kind === "DIGITAL" ? i.status === "READY" : i.status === "SHIPPED"));
+ if (allDone) await db.order.updateMany({ where: { id: order.id, status: "PAID" }, data: { status: "FULFILLED", fulfilledAt: new Date() } });
+ if (this.deps.mailer) {
+ const site = order.siteId ? await db.site.findUnique({ where: { id: order.siteId } }) : null;
+ const link = site ? `https://${site.domain}/encomenda/${order.id}?t=${order.accessToken}` : null;
+ await this.deps.mailer
+ .send({
+ to: order.email,
+ subject: `${site?.name ?? "PhotoReport"}: encomenda ${order.number} pronta`,
+ text: `Olá ${order.name},\n\nAs fotos da encomenda ${order.number} estão prontas a descarregar${link ? `:\n${link}` : "."}\n\nObrigado.`,
+ })
+ .catch((err: Error) => this.deps.log.warn({ orderId: order.id, err: err.message }, "shop: email failed"));
+ }
+ }
+
+ async markShipped(itemId: string): Promise {
+ const item = await this.deps.db.orderItem.update({ where: { id: itemId }, data: { status: "SHIPPED" }, include: { order: true } });
+ await this.maybeFulfilled(item.order);
+ }
+}
+
+export class FulfilmentWorker {
+ private timer: NodeJS.Timeout | undefined;
+ private stopped = false;
+ private inFlight = 0;
+
+ constructor(
+ private readonly shop: ShopService,
+ private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger },
+ ) {}
+
+ start(): void {
+ void this.shop.requeueStale();
+ const tick = async () => {
+ try {
+ for (const id of await this.shop.claimDownloads(this.opts.concurrency - this.inFlight)) {
+ this.inFlight++;
+ void this.shop.fulfil(id).finally(() => {
+ this.inFlight--;
+ });
+ }
+ } catch (err) {
+ this.opts.log.warn({ err }, "shop: poll failed");
+ }
+ if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
+ };
+ this.timer = setTimeout(tick, 0);
+ }
+
+ stop(): void {
+ this.stopped = true;
+ if (this.timer) clearTimeout(this.timer);
+ }
+}
diff --git a/apps/api/src/shop/stripe.ts b/apps/api/src/shop/stripe.ts
new file mode 100644
index 0000000..91bf5a4
--- /dev/null
+++ b/apps/api/src/shop/stripe.ts
@@ -0,0 +1,87 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+
+/** Minimal Stripe client (Checkout Sessions and webhook signatures) over fetch: no SDK, easy to fake in tests. */
+export interface CheckoutLine {
+ name: string;
+ unitCents: number;
+ quantity: number;
+}
+
+export interface CheckoutRequest {
+ orderId: string;
+ orderNumber: string;
+ email: string;
+ currency: string;
+ lines: CheckoutLine[];
+ successUrl: string;
+ cancelUrl: string;
+}
+
+export class StripeError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+}
+
+/** Flattens nested params the way Stripe's form API expects (`line_items[0][price_data][currency]`). */
+export function formEncode(params: Record, prefix = ""): string[] {
+ const out: string[] = [];
+ for (const [k, v] of Object.entries(params)) {
+ const key = prefix ? `${prefix}[${k}]` : k;
+ if (v === undefined || v === null) continue;
+ if (Array.isArray(v)) v.forEach((item, i) => out.push(...(typeof item === "object" ? formEncode(item as Record, `${key}[${i}]`) : [`${encodeURIComponent(`${key}[${i}]`)}=${encodeURIComponent(String(item))}`])));
+ else if (typeof v === "object") out.push(...formEncode(v as Record, key));
+ else out.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`);
+ }
+ return out;
+}
+
+/**
+ * Creates a hosted Checkout page. Payment methods are the ones switched on in the organization's Stripe dashboard
+ * (cards, and for Portugal Multibanco and MB WAY where Stripe offers them), so none are listed here.
+ */
+export async function createCheckout(secretKey: string, req: CheckoutRequest, fetchImpl: typeof fetch = fetch, base = "https://api.stripe.com"): Promise<{ id: string; url: string }> {
+ const body = formEncode({
+ mode: "payment",
+ customer_email: req.email,
+ client_reference_id: req.orderId,
+ success_url: req.successUrl,
+ cancel_url: req.cancelUrl,
+ metadata: { order_id: req.orderId, order_number: req.orderNumber },
+ payment_intent_data: { metadata: { order_id: req.orderId, order_number: req.orderNumber } },
+ line_items: req.lines.map((l) => ({ quantity: l.quantity, price_data: { currency: req.currency.toLowerCase(), unit_amount: l.unitCents, product_data: { name: l.name } } })),
+ }).join("&");
+ const res = await fetchImpl(`${base}/v1/checkout/sessions`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${secretKey}`, "content-type": "application/x-www-form-urlencoded", "idempotency-key": `checkout-${req.orderId}` },
+ body,
+ });
+ const data = (await res.json()) as { id?: string; url?: string; error?: { message?: string } };
+ if (!res.ok || !data.id || !data.url) throw new StripeError(data.error?.message ?? `stripe ${res.status}`, res.status);
+ return { id: data.id, url: data.url };
+}
+
+/** Verifies a `Stripe-Signature` header (`t=...,v1=...`) over the raw body; rejects events older than `toleranceSec`. */
+export function verifyWebhook(rawBody: Buffer, header: string | undefined, secret: string, now = Date.now(), toleranceSec = 300): boolean {
+ if (!header) return false;
+ const parts = new Map();
+ for (const item of header.split(",")) {
+ const [k, v] = item.split("=", 2);
+ if (!k || !v) continue;
+ parts.set(k.trim(), [...(parts.get(k.trim()) ?? []), v.trim()]);
+ }
+ const t = Number(parts.get("t")?.[0]);
+ if (!Number.isFinite(t) || Math.abs(now / 1000 - t) > toleranceSec) return false;
+ const expected = createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest();
+ return (parts.get("v1") ?? []).some((sig) => {
+ const given = Buffer.from(sig, "hex");
+ return given.length === expected.length && timingSafeEqual(given, expected);
+ });
+}
+
+export function signWebhook(rawBody: string, secret: string, t = Math.floor(Date.now() / 1000)): string {
+ return `t=${t},v1=${createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex")}`;
+}
diff --git a/apps/api/src/shop/vies.ts b/apps/api/src/shop/vies.ts
new file mode 100644
index 0000000..f30ae53
--- /dev/null
+++ b/apps/api/src/shop/vies.ts
@@ -0,0 +1,29 @@
+import { splitVat } from "./pricing.js";
+
+export interface ViesResult {
+ valid: boolean;
+ name: string | null;
+}
+
+/**
+ * Checks an EU VAT number with the European Commission's VIES REST service. Returns null when VIES cannot answer
+ * (it is often down for a member state); callers then charge VAT, which is always safe.
+ */
+export async function checkVies(vatNumber: string, fetchImpl: typeof fetch = fetch): Promise {
+ const parts = splitVat(vatNumber);
+ if (!parts) return { valid: false, name: null };
+ const cc = parts.country === "GR" ? "EL" : parts.country;
+ try {
+ const res = await fetchImpl(`https://ec.europa.eu/taxation_customs/vies/rest-api/ms/${cc}/vat/${encodeURIComponent(parts.number)}`, {
+ headers: { accept: "application/json" },
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!res.ok) return null;
+ const body = (await res.json()) as { isValid?: boolean; name?: string; userError?: string };
+ if (body.userError && body.userError !== "VALID" && body.userError !== "INVALID") return null;
+ const name = body.name && body.name !== "---" ? body.name : null;
+ return { valid: body.isValid === true, name };
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/api/src/shop/watermark.ts b/apps/api/src/shop/watermark.ts
new file mode 100644
index 0000000..718fa78
--- /dev/null
+++ b/apps/api/src/shop/watermark.ts
@@ -0,0 +1,30 @@
+import sharp from "sharp";
+
+const escapeXml = (s: string) => s.replace(/[<>&"']/g, (c) => ({ "<": "<", ">": ">", "&": "&", '"': """, "'": "'" })[c]!);
+
+/**
+ * A preview for the public site: fitted to `longEdge`, with the brand tiled diagonally (light enough to judge the
+ * photo, strong enough that a screenshot is not worth using) and the brand once, solid, in a corner.
+ */
+export async function watermarked(source: string | Buffer, brand: string, longEdge: number): Promise {
+ const base = sharp(source).rotate().resize({ width: longEdge, height: longEdge, fit: "inside", withoutEnlargement: true });
+ const { data, info } = await base.toBuffer({ resolveWithObject: true });
+ const { width: w, height: h } = info;
+ const text = escapeXml(brand.toUpperCase());
+ const size = Math.max(14, Math.round(Math.min(w, h) / 14));
+ const stepX = Math.round(size * text.length * 0.75 + size * 2);
+ const stepY = Math.round(size * 3.2);
+ const rows: string[] = [];
+ for (let row = 0, y = -h; y < h * 2; row++, y += stepY) {
+ for (let x = -w; x < w * 2; x += stepX) rows.push(`${text}`);
+ }
+ const corner = Math.max(11, Math.round(size * 0.55));
+ const svg = ``;
+ return sharp(data)
+ .composite([{ input: Buffer.from(svg), top: 0, left: 0 }])
+ .jpeg({ quality: 82, mozjpeg: true })
+ .toBuffer();
+}
diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts
index d4d612a..dbb2560 100644
--- a/apps/api/src/worker.ts
+++ b/apps/api/src/worker.ts
@@ -7,6 +7,8 @@ import { DeliveryService, DeliveryWorker } from "./delivery/service.js";
import { RenderPool, RenderProcess } from "./develop/engine.js";
import { DevelopService, RenderWorker } from "./develop/service.js";
import { FacePool, FaceProcess } from "./faces/process.js";
+import { smtpMailer } from "./lib/mailer.js";
+import { FulfilmentWorker, ShopService } from "./shop/service.js";
import { FaceService, FaceWorker } from "./faces/service.js";
import { IngestScanner } from "./ingest/scanner.js";
import { IngestService } from "./ingest/service.js";
@@ -49,6 +51,11 @@ const deliveries = new DeliveryWorker(new DeliveryService({ db, storage, secrets
log,
});
+const mailer = config.SMTP_URL ? smtpMailer(config.SMTP_URL, config.MAIL_FROM) : undefined;
+if (!mailer) log.warn("SMTP_URL not set: buyers get no email when their photos are ready");
+const shop = new ShopService({ db, storage, signer, secrets, log, secret: config.JWT_SECRET, develop, mailer });
+const fulfilment = new FulfilmentWorker(shop, { concurrency: 2, intervalMs: 1000, log });
+
const faceEngine =
config.FACES_BIN && config.FACES_MODELS_DIR
? new FacePool(
@@ -64,6 +71,7 @@ scanner.start();
deliveries.start();
faces?.start();
renders?.start();
+fulfilment.start();
log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started");
const shutdown = async (signal: string) => {
@@ -72,6 +80,7 @@ const shutdown = async (signal: string) => {
deliveries.stop();
faces?.stop();
renders?.stop();
+ fulfilment.stop();
await faceEngine?.close();
await renderEngine?.close();
await closeRenderer();
diff --git a/apps/api/test/shop.test.ts b/apps/api/test/shop.test.ts
new file mode 100644
index 0000000..499a9d3
--- /dev/null
+++ b/apps/api/test/shop.test.ts
@@ -0,0 +1,211 @@
+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, "owner@pr.pt", { org: "photoreport", role: "OWNER" });
+ const token = (await login(ctx.app, "owner@pr.pt")).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 = {}) =>
+ ctx.app.inject({ method, url, headers: { "x-site-domain": "photoreport.test", ...headers }, ...(payload !== undefined && { payload: payload as object }) });
+
+ async function gallery(s: Awaited>, body: Record) {
+ 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: "pai@example.pt",
+ 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: "pai@example.pt" });
+ 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: "a@b.es", 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: "a@b.es", 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: "socio@clube.pt", 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: "socio@clube.pt", 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" });
+ });
+});
diff --git a/apps/app/src/App.tsx b/apps/app/src/App.tsx
index 48941c3..bda1954 100644
--- a/apps/app/src/App.tsx
+++ b/apps/app/src/App.tsx
@@ -4,6 +4,7 @@ import { AuthProvider, useAuth } from "./auth.js";
import { t } from "./i18n.js";
import { DevelopPage } from "./pages/DevelopPage.js";
import { DeliveryPage } from "./pages/DeliveryPage.js";
+import { ShopPage } from "./pages/ShopPage.js";
import { DevicePage } from "./pages/DevicePage.js";
import { LibraryPage } from "./pages/LibraryPage.js";
import { LoginPage } from "./pages/LoginPage.js";
@@ -26,6 +27,7 @@ function Gate() {
} />
} />
} />
+ } />
} />
} />
{t.notFound}
} />
diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts
index eddd496..63ed438 100644
--- a/apps/app/src/i18n.ts
+++ b/apps/app/src/i18n.ts
@@ -155,6 +155,76 @@ export const t = {
PHOTOGRAPHER: "Fotógrafo",
CLIENT: "Cliente",
},
+ shop: {
+ title: "Vendas",
+ tabs: { galleries: "Galerias", orders: "Encomendas", products: "Produtos", sites: "Sites e pagamentos" },
+ galleries: "Galerias",
+ galleriesHelp: "O que aparece nos sites (photoreport.pt, shootyourmove.com). Uma galeria pública fica na lista; não listada, só com o link; privada, com link e palavra-passe.",
+ newGallery: "Nova galeria",
+ noGalleries: "Ainda não há galerias. Cria uma a partir de um evento: entram logo as fotos escolhidas.",
+ published: "publicada",
+ draft: "rascunho",
+ publish: "Publicar",
+ unpublish: "Despublicar",
+ edit: "Editar",
+ open: "Abrir",
+ delete: "Apagar",
+ confirmDelete: "Apagar? Esta ação não se desfaz.",
+ free: "download grátis",
+ notForSale: "sem venda",
+ visibility: { PUBLIC: "Pública", UNLISTED: "Não listada", PRIVATE: "Privada" },
+ visibilityLabel: "Visibilidade",
+ event: "Evento",
+ galleryTitle: "Título",
+ description: "Descrição",
+ password: "Palavra-passe",
+ newPassword: "Nova palavra-passe (vazio mantém)",
+ fill: "Fotos iniciais",
+ fillPicks: "As escolhidas (⚑)",
+ fillUnrejected: "Todas menos rejeitadas",
+ fillNone: "Nenhuma (escolho depois)",
+ forSale: "À venda",
+ freeDownloads: "Downloads grátis (galeria de clube ou já paga)",
+ buyer: "Comprador",
+ itemsCol: "Artigos",
+ status: "Estado",
+ orderStatus: { PENDING: "por pagar", PAID: "paga", FULFILLED: "concluída", CANCELLED: "cancelada", REFUNDED: "reembolsada" },
+ itemStatus: { PENDING: "a preparar", RUNNING: "a preparar", READY: "pronto", SHIPPED: "enviado", FAILED: "falhou" },
+ markShipped: "Marcar enviada",
+ reverseCharge: "Autoliquidação",
+ noOrders: "Sem encomendas.",
+ productsHelp: "Preços com IVA incluído. JPEG: tamanho do lado maior (0 = original). Impressões: tamanho e prazo de envio.",
+ print: "Impressão",
+ fullSize: "original",
+ productName: "Nome (ex.: Digital alta resolução)",
+ add: "Adicionar",
+ enable: "Ativar",
+ disable: "Desativar",
+ sites: "Sites",
+ sitesHelp: "Cada domínio mostra as galerias desta organização com o seu aspeto. Aponta o DNS do domínio para o servidor dos sites.",
+ domain: "Domínio",
+ siteName: "Nome (ex.: ShootYourMove)",
+ payments: "Pagamentos (Stripe)",
+ paymentsOn: "ativos",
+ paymentsOff: "por configurar",
+ legalName: "Nome legal",
+ vatRate: "Taxa de IVA (%)",
+ stripeKey: "Chave secreta Stripe",
+ webhookSecret: "Segredo do webhook",
+ webhookUrl: "Endpoint para o webhook (eventos checkout.session.*)",
+ paymentsHelp: "Os métodos de pagamento (cartão, Multibanco, MB WAY) ligam-se no painel da Stripe. As chaves ficam cifradas e nunca voltam a ser mostradas.",
+ addToGallery: "Adicionar à galeria",
+ addedToGallery: (n: number, name: string) => `${n} ${n === 1 ? "foto adicionada" : "fotos adicionadas"} a ${name}`,
+ errors: {
+ password_required: "Uma galeria privada precisa de palavra-passe.",
+ slug_taken: "Já existe uma galeria com esse endereço.",
+ gallery_empty: "Junta fotos antes de publicar.",
+ domain_taken: "Esse domínio já está em uso.",
+ invalid_stripe_key: "A chave da Stripe começa por sk_live_ ou sk_test_.",
+ invalid_webhook_secret: "O segredo do webhook começa por whsec_.",
+ secret_key_missing: "Falta configurar a chave de cifra do servidor (DELIVERY_SECRET_KEY).",
+ } as Record,
+ },
dev: {
loading: "A abrir o motor de revelação…",
engineMissing: "O motor de revelação não está disponível neste servidor (falta compilar engine/wasm).",
diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx
index 57c5736..37d2951 100644
--- a/apps/app/src/pages/LibraryPage.tsx
+++ b/apps/app/src/pages/LibraryPage.tsx
@@ -1,4 +1,4 @@
-import type { LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
+import type { GallerySummary, LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
import { hasRole, type DeliveryTarget, type EventSummary } from "@photoreport/sdk";
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
import { useNavigate } from "react-router";
@@ -39,6 +39,8 @@ export function LibraryPage() {
const [facesTick, setFacesTick] = useState(0);
const [loupeFaces, setLoupeFaces] = useState([]);
const [error, setError] = useState(null);
+ const [galleries, setGalleries] = useState([]);
+ const [info, setInfo] = useState(null);
const loadEvents = useCallback(async () => {
if (!orgId) return;
@@ -211,6 +213,35 @@ export function LibraryPage() {
+ {canCull && selection.length > 0 && (
+
+ )}
+ {info && {info}}
{canCull && prefs.get("develop.clipboard") && selection.length > 0 && (