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 = ` + ${rows.join("")} + ${text} +`; + 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 && ( + ))} + + +
+ {tab === "galleries" && } + {tab === "orders" && } + {tab === "products" && } + {tab === "sites" && } +
+ + ); +} + +function Galleries({ orgId }: { orgId: string }) { + const { api } = useAuth(); + const [galleries, setGalleries] = useState(null); + const [events, setEvents] = useState([]); + const [sites, setSites] = useState([]); + const [editing, setEditing] = useState(null); + const [note, setNote] = useState(null); + + const load = useCallback(() => { + api.listGalleries(orgId).then((r) => setGalleries(r.galleries), () => setGalleries([])); + }, [api, orgId]); + useEffect(() => { + load(); + api.listEvents(orgId).then((r) => setEvents(r.events), () => {}); + api.listSites(orgId).then((r) => setSites(r.sites), () => {}); + }, [api, orgId, load]); + + const publicUrl = (g: GallerySummary) => (sites[0] ? `${sites[0].domain.includes("localhost") || sites[0].domain.includes("127.0.0.1") ? "http" : "https"}://${sites[0].domain}/galeria/${g.slug}` : null); + + return ( +
+
+ {t.shop.galleries} + +
+

{t.shop.galleriesHelp}

+ {note &&

{note}

} + {editing && ( + { + setEditing(null); + load(); + }} + /> + )} +
+ {(galleries ?? []).map((g) => { + const url = publicUrl(g); + return ( +
+
{g.cover && }
+
+
+

{g.title}

+ {g.publishedAt ? t.shop.published : t.shop.draft} +
+

+ {t.shop.visibility[g.visibility]} · {g.photoCount} fotos{g.freeDownloads ? ` · ${t.shop.free}` : !g.forSale ? ` · ${t.shop.notForSale}` : ""} +

+
+ + + {url && g.publishedAt && ( + + {t.shop.open} ↗ + + )} +
+
+
+ ); + })} +
+ {galleries?.length === 0 &&

{t.shop.noGalleries}

} +
+ ); +} + +function GalleryForm({ orgId, events, gallery, onDone }: { orgId: string; events: EventSummary[]; gallery: GallerySummary | null; onDone: () => void }) { + const { api } = useAuth(); + const [form, setForm] = useState({ + title: gallery?.title ?? "", + description: gallery?.description ?? "", + visibility: gallery?.visibility ?? ("PUBLIC" as GalleryInput["visibility"]), + password: "", + eventId: gallery?.eventId ?? "", + forSale: gallery?.forSale ?? true, + freeDownloads: gallery?.freeDownloads ?? false, + /** New galleries from an event start with its picks (or every photo not rejected). */ + fill: "picks" as "picks" | "unrejected" | "none", + }); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const save = async () => { + setBusy(true); + setError(null); + try { + const body: GalleryInput = { + title: form.title, + description: form.description || null, + visibility: form.visibility, + ...(form.password && { password: form.password }), + eventId: form.eventId || null, + forSale: form.forSale, + freeDownloads: form.freeDownloads, + }; + const saved = gallery ? await api.updateGallery(gallery.id, body) : await api.createGallery(orgId, body); + if (!gallery && form.eventId && form.fill !== "none") { + const photos = await api.listPhotos(orgId, { event: form.eventId, limit: 500, flag: form.fill === "picks" ? "PICK" : "UNREJECTED" }); + if (photos.photos.length) await api.changeGalleryPhotos(saved.id, { add: photos.photos.map((p) => p.id) }); + } + onDone(); + } catch (err) { + setError(errorText(err)); + } finally { + setBusy(false); + } + }; + + const event = events.find((e) => e.id === form.eventId); + return ( +
+
+ + + + + {form.visibility === "PRIVATE" && ( + + )} + {!gallery && form.eventId && ( + + )} +
+
+ + +
+ {error &&

{error}

} +
+ {gallery ? ( + + ) : ( + + )} + + + + +
+
+ ); +} + +const ORDER_COLOR: Record = { PENDING: "text-faint", PAID: "text-[#7fb0ff]", FULFILLED: "text-ok", CANCELLED: "text-faint line-through", REFUNDED: "text-[#f0a35a]" }; + +function Orders({ orgId }: { orgId: string }) { + const { api } = useAuth(); + const [orders, setOrders] = useState(null); + const [open, setOpen] = useState(null); + const load = useCallback(() => { + api.listOrders(orgId).then((r) => setOrders(r.orders), () => setOrders([])); + }, [api, orgId]); + useEffect(load, [load]); + const paid = (orders ?? []).filter((o) => o.status === "PAID" || o.status === "FULFILLED"); + const replace = (o: OrderView) => setOrders((list) => list?.map((x) => (x.id === o.id ? o : x)) ?? null); + + return ( +
+
+ {t.shop.tabs.orders} + + {paid.length} · {eur(paid.reduce((s, o) => s + o.totalCents, 0))} + +
+ + + + + + + + + + + + {(orders ?? []).map((o) => ( + + setOpen(open === o.id ? null : o.id)}> + + + + + + + {open === o.id && ( + + + + )} + + ))} + +
N.º{t.shop.buyer}{t.shop.itemsCol}Total{t.shop.status}
{o.number} + {o.name} {o.email} + {o.items.length}{eur(o.totalCents)}{t.shop.orderStatus[o.status]}
+
    + {o.items.map((i) => ( +
  • + {i.photo && } + + {i.productName} + {i.quantity > 1 && ` × ${i.quantity}`} {i.photo?.name} + + {t.shop.itemStatus[i.status]} + {i.kind === "PRINT" && i.status !== "SHIPPED" && (o.status === "PAID" || o.status === "FULFILLED") && ( + + )} +
  • + ))} +
+

+ {o.reverseCharge ? `${t.shop.reverseCharge} ${o.vatNumber}` : `IVA ${eur(o.vatCents)}`} · {o.country} + {o.items.some((i) => i.status === "FAILED") && ( + + )} +

+
+ {orders?.length === 0 &&

{t.shop.noOrders}

} +
+ ); +} + +function Products({ orgId }: { orgId: string }) { + const { api } = useAuth(); + const [products, setProducts] = useState([]); + const [draft, setDraft] = useState({ kind: "DIGITAL" as ProductSummary["kind"], name: "", price: "", longEdge: "2048", printSize: "", leadDays: "3" }); + const [error, setError] = useState(null); + const load = useCallback(() => { + api.listProducts(orgId).then((r) => setProducts(r.products), () => {}); + }, [api, orgId]); + useEffect(load, [load]); + const cents = (s: string) => Math.round(Number(s.replace(",", ".")) * 100); + + return ( +
+
+ {t.shop.tabs.products} +
+

{t.shop.productsHelp}

+ + + {products.map((p) => ( + + + + + + + ))} + +
{p.kind === "DIGITAL" ? "JPEG" : t.shop.print} + {p.name} {p.kind === "DIGITAL" ? (p.longEdge ? `${p.longEdge} px` : t.shop.fullSize) : `${p.printSize ?? ""}${p.leadDays ? ` · ${p.leadDays} dias` : ""}`} + + { + const v = cents(e.target.value); + if (Number.isFinite(v) && v !== p.priceCents) void api.updateProduct(p.id, { priceCents: v }).then(load); + }} + />{" "} + € + + +
+
+ + setDraft({ ...draft, name: e.target.value })} /> + {draft.kind === "DIGITAL" ? ( + setDraft({ ...draft, longEdge: e.target.value })} /> + ) : ( + setDraft({ ...draft, printSize: e.target.value })} /> + )} + setDraft({ ...draft, price: e.target.value })} /> + +
+ {error &&

{error}

} +
+ ); +} + +function Sites({ orgId, isOwner }: { orgId: string; isOwner: boolean }) { + const { api } = useAuth(); + const [sites, setSites] = useState([]); + const [settings, setSettings] = useState(null); + const [draft, setDraft] = useState({ domain: "", skin: "photoreport" as SiteInfo["skin"], name: "" }); + const [pay, setPay] = useState({ legalName: "", vatNumber: "", vatRate: "23", stripeSecretKey: "", stripeWebhookSecret: "" }); + const [note, setNote] = useState(null); + const load = useCallback(() => { + api.listSites(orgId).then((r) => setSites(r.sites), () => {}); + api.getShopSettings(orgId).then((s) => { + setSettings(s); + setPay((p) => ({ ...p, legalName: s.legalName ?? "", vatNumber: s.vatNumber ?? "", vatRate: String(s.vatRate) })); + }, () => {}); + }, [api, orgId]); + useEffect(load, [load]); + + return ( + <> +
+
+ {t.shop.sites} +
+

{t.shop.sitesHelp}

+
    + {sites.map((s) => ( +
  • + + {s.name} {s.domain} + + + + + +
  • + ))} +
+
+ setDraft({ ...draft, domain: e.target.value })} aria-label={t.shop.domain} /> + setDraft({ ...draft, name: e.target.value })} /> + + +
+
+ +
+
+ {t.shop.payments} + + {settings?.stripeConfigured && settings.webhookConfigured ? t.shop.paymentsOn : t.shop.paymentsOff} + +
+
+ + + + + +
+ {t.shop.webhookUrl} +

{settings ? api.absolute(settings.webhookUrl) : "…"}

+
+
+

{t.shop.paymentsHelp}

+ {note &&

{note}

} + {isOwner && ( +
+ +
+ )} +
+ + ); +} diff --git a/apps/site/next-env.d.ts b/apps/site/next-env.d.ts new file mode 100644 index 0000000..830fb59 --- /dev/null +++ b/apps/site/next-env.d.ts @@ -0,0 +1,6 @@ +/// +/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/apps/site/next.config.ts b/apps/site/next.config.ts new file mode 100644 index 0000000..5c50b01 --- /dev/null +++ b/apps/site/next.config.ts @@ -0,0 +1,17 @@ +import type { NextConfig } from "next"; + +const api = process.env.API_URL ?? "http://localhost:3000"; + +/** + * Public sites (photoreport.pt, shootyourmove.com...). One build serves every domain: the API decides the + * organization and skin from the domain. Browsers reach the API through `/v1` on the site's own origin. + */ +const config: NextConfig = { + reactStrictMode: true, + poweredByHeader: false, + async rewrites() { + return [{ source: "/v1/:path*", destination: `${api}/v1/:path*` }]; + }, +}; + +export default config; diff --git a/apps/site/package.json b/apps/site/package.json new file mode 100644 index 0000000..70a22cc --- /dev/null +++ b/apps/site/package.json @@ -0,0 +1,26 @@ +{ + "name": "@photoreport/site", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "next dev -p 3100", + "build": "next build", + "start": "next start -p 3100", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@fontsource/barlow": "^5.3.0", + "@fontsource/barlow-condensed": "^5.3.0", + "@fontsource/space-mono": "^5.3.0", + "@photoreport/contracts": "workspace:*", + "next": "15.5.26", + "react": "^19.3.0", + "react-dom": "^19.3.0" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0" + } +} diff --git a/apps/site/src/app/carrinho/Checkout.tsx b/apps/site/src/app/carrinho/Checkout.tsx new file mode 100644 index 0000000..540a2bb --- /dev/null +++ b/apps/site/src/app/carrinho/Checkout.tsx @@ -0,0 +1,156 @@ +"use client"; + +import type { OrderView } from "@photoreport/contracts"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { cartTotal, useCart, writeCart } from "../../lib/cart"; +import { eur } from "../../lib/format"; + +const COUNTRIES: [string, string][] = [ + ["PT", "Portugal"], + ["ES", "Espanha"], + ["FR", "França"], + ["DE", "Alemanha"], + ["IT", "Itália"], + ["NL", "Países Baixos"], + ["BE", "Bélgica"], + ["LU", "Luxemburgo"], + ["IE", "Irlanda"], + ["AT", "Áustria"], + ["CH", "Suíça"], + ["GB", "Reino Unido"], + ["BR", "Brasil"], + ["AO", "Angola"], + ["MZ", "Moçambique"], + ["CV", "Cabo Verde"], + ["US", "Estados Unidos"], +]; + +const ERRORS: Record = { + gallery_locked: "A galeria é privada: volta a abri-la com a palavra-passe.", + invalid_vat_number: "O número de contribuinte não é válido (usa o prefixo do país, ex.: PT123456789).", + payments_not_configured: "Os pagamentos ainda não estão disponíveis neste site.", + photo_not_in_gallery: "Uma das fotos já não está na galeria.", + product_not_found: "Um dos produtos já não está à venda.", + gallery_not_for_sale: "Esta galeria não tem fotos à venda.", +}; + +export function Checkout() { + const cart = useCart(); + const router = useRouter(); + const [form, setForm] = useState({ name: "", email: "", country: "PT", vatNumber: "" }); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const total = cartTotal(cart); + + if (!cart.lines.length) { + return ( +

+ O carrinho está vazio. Ver galerias +

+ ); + } + + const setQty = (i: number, q: number) => + writeCart({ ...cart, lines: cart.lines.flatMap((l, j) => (j !== i ? [l] : q > 0 ? [{ ...l, quantity: Math.min(50, q) }] : [])) }); + + const submit = async (e: React.FormEvent) => { + e.preventDefault(); + setBusy(true); + setError(null); + const res = await fetch("/v1/public/orders", { + method: "POST", + headers: { "content-type": "application/json", "x-site-domain": window.location.host }, + body: JSON.stringify({ + gallery: cart.gallery, + ...(cart.galleryToken && { galleryToken: cart.galleryToken }), + items: cart.lines.map((l) => ({ photoId: l.photoId, productId: l.productId, quantity: l.quantity })), + email: form.email, + name: form.name, + country: form.country, + ...(form.vatNumber.trim() && { vatNumber: form.vatNumber.trim() }), + }), + }).catch(() => null); + if (!res?.ok) { + setBusy(false); + const code = res ? ((await res.json().catch(() => ({}))) as { error?: string }).error : undefined; + setError((code && ERRORS[code]) ?? "Não foi possível criar a encomenda. Tenta de novo."); + return; + } + const { order, checkoutUrl, token } = (await res.json()) as { order: OrderView; checkoutUrl: string | null; token: string }; + writeCart({ gallery: null, galleryTitle: null, galleryToken: null, lines: [] }); + // Free orders skip payment; paid ones go to the payment page (card, Multibanco, MB WAY). + if (checkoutUrl) window.location.href = checkoutUrl; + else router.push(`/encomenda/${order.id}?t=${encodeURIComponent(token)}`); + }; + + return ( +
+
+

{cart.galleryTitle}

+
+ {cart.lines.map((l, i) => ( +
+ +
+ {l.productName} +
{l.kind === "DIGITAL" ? "Download" : "Impressão"}
+ {l.kind === "PRINT" && ( + + )} +
+
+
{eur(l.priceCents * l.quantity)}
+ +
+
+ ))} +
+
+ IVA incluído + {eur(total)} +
+
+
+

Os teus dados

+ + + + + {error && ( +

+ {error} +

+ )} + +

Pagamento seguro por cartão, Multibanco ou MB WAY.

+
+
+ ); +} diff --git a/apps/site/src/app/carrinho/page.tsx b/apps/site/src/app/carrinho/page.tsx new file mode 100644 index 0000000..22214d3 --- /dev/null +++ b/apps/site/src/app/carrinho/page.tsx @@ -0,0 +1,15 @@ +import type { Metadata } from "next"; +import { Checkout } from "./Checkout"; + +export const metadata: Metadata = { title: "Carrinho", robots: { index: false } }; + +export default function CartPage() { + return ( +
+
+

Carrinho

+
+ +
+ ); +} diff --git a/apps/site/src/app/encomenda/[id]/Refresh.tsx b/apps/site/src/app/encomenda/[id]/Refresh.tsx new file mode 100644 index 0000000..b99154a --- /dev/null +++ b/apps/site/src/app/encomenda/[id]/Refresh.tsx @@ -0,0 +1,14 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect } from "react"; + +/** While the payment or the files are on their way, the page refreshes itself. */ +export function Refresh({ seconds }: { seconds: number }) { + const router = useRouter(); + useEffect(() => { + const id = setInterval(() => router.refresh(), seconds * 1000); + return () => clearInterval(id); + }, [router, seconds]); + return null; +} diff --git a/apps/site/src/app/encomenda/[id]/page.tsx b/apps/site/src/app/encomenda/[id]/page.tsx new file mode 100644 index 0000000..71fddf1 --- /dev/null +++ b/apps/site/src/app/encomenda/[id]/page.tsx @@ -0,0 +1,81 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getOrder, NotFound } from "../../../lib/api"; +import { eur, longDate } from "../../../lib/format"; +import { Refresh } from "./Refresh"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { title: "Encomenda", robots: { index: false } }; + +const STATUS: Record = { + PENDING: "À espera do pagamento", + PAID: "Paga", + FULFILLED: "Concluída", + CANCELLED: "Cancelada", + REFUNDED: "Reembolsada", +}; +const ITEM: Record = { PENDING: "a preparar", RUNNING: "a preparar", READY: "pronta", SHIPPED: "enviada", FAILED: "com problema: estamos a tratar" }; + +export default async function OrderPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ t?: string }> }) { + const { id } = await params; + const { t } = await searchParams; + if (!t) notFound(); + let order; + try { + order = await getOrder(id, t); + } catch (err) { + if (err instanceof NotFound) notFound(); + throw err; + } + const working = order.status === "PENDING" || order.items.some((i) => i.kind === "DIGITAL" && (i.status === "PENDING" || i.status === "RUNNING")); + return ( +
+
+ Encomenda {order.number} +

{STATUS[order.status]}

+ + {longDate(order.createdAt)} · {order.email} + +
+ {order.status === "PENDING" && ( +

+ Assim que o pagamento for confirmado (por Multibanco pode demorar algumas horas) as fotos aparecem aqui e enviamos-te um email. + {order.checkoutUrl && ( + <> + {" "} + + Voltar ao pagamento + + + )} +

+ )} +
+ {order.items.map((i) => ( +
+ {i.photo ? : } +
+ {i.productName} + {i.quantity > 1 && × {i.quantity}} +
{ITEM[i.status]}
+
+
+ {i.download ? ( + + Descarregar + + ) : ( + {eur(i.totalCents)} + )} +
+
+ ))} +
+
+ {order.reverseCharge ? Autoliquidação do IVA ({order.vatNumber}) : IVA incluído: {eur(order.vatCents)}} + {eur(order.totalCents)} +
+ {working && } +
+ ); +} diff --git a/apps/site/src/app/galeria/[slug]/GalleryView.tsx b/apps/site/src/app/galeria/[slug]/GalleryView.tsx new file mode 100644 index 0000000..4ea0667 --- /dev/null +++ b/apps/site/src/app/galeria/[slug]/GalleryView.tsx @@ -0,0 +1,131 @@ +"use client"; + +import type { ProductSummary, PublicGallery } from "@photoreport/contracts"; +import Link from "next/link"; +import { useCallback, useEffect, useState } from "react"; +import { addToCart, useCart } from "../../../lib/cart"; +import { eur } from "../../../lib/format"; + +/** The photos, a lightbox to look closer, and the products to buy each one as. */ +export function GalleryView({ gallery, products, token }: { gallery: PublicGallery; products: ProductSummary[]; token: string | null }) { + const [open, setOpen] = useState(null); + const [query, setQuery] = useState(""); + const [added, setAdded] = useState(null); + const cart = useCart(); + const inCart = new Set(cart.gallery === gallery.slug ? cart.lines.map((l) => l.photoId) : []); + const q = query.trim().toLowerCase(); + const photos = q ? gallery.photos.filter((p) => p.players.some((n) => n.toLowerCase().includes(q))) : gallery.photos; + const photo = open !== null ? photos[open] : undefined; + const free = (p: ProductSummary) => gallery.freeDownloads && p.kind === "DIGITAL"; + + const move = useCallback((d: number) => setOpen((i) => (i === null ? null : Math.max(0, Math.min(photos.length - 1, i + d)))), [photos.length]); + useEffect(() => { + if (open === null) return; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") setOpen(null); + if (e.key === "ArrowRight") move(1); + if (e.key === "ArrowLeft") move(-1); + }; + window.addEventListener("keydown", onKey); + document.body.style.overflow = "hidden"; + return () => { + window.removeEventListener("keydown", onKey); + document.body.style.overflow = ""; + }; + }, [open, move]); + + const hasNames = gallery.photos.some((p) => p.players.length); + return ( + <> +
+ {hasNames && ( + + )} + + {photos.length} de {gallery.photos.length} + + {cart.gallery === gallery.slug && cart.lines.length > 0 && ( + + Ver carrinho ({cart.lines.length}) + + )} +
+
+ {photos.map((p, i) => ( + + ))} +
+ + {photo && ( +
+
+ {photo.players.join(", + + {open! > 0 && ( + + )} + {open! < photos.length - 1 && ( + + )} +
+ +
+ )} + + ); +} diff --git a/apps/site/src/app/galeria/[slug]/Unlock.tsx b/apps/site/src/app/galeria/[slug]/Unlock.tsx new file mode 100644 index 0000000..6ba114d --- /dev/null +++ b/apps/site/src/app/galeria/[slug]/Unlock.tsx @@ -0,0 +1,50 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +/** Private galleries: the password is checked by the API; the token it returns is kept in a cookie for a week. */ +export function Unlock({ slug }: { slug: string }) { + const router = useRouter(); + const [password, setPassword] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + return ( +
{ + e.preventDefault(); + setBusy(true); + setError(null); + const res = await fetch(`/v1/public/galleries/${encodeURIComponent(slug)}/unlock`, { + method: "POST", + headers: { "content-type": "application/json", "x-site-domain": window.location.host }, + body: JSON.stringify({ password }), + }).catch(() => null); + setBusy(false); + if (!res?.ok) { + setError(res?.status === 401 ? "Palavra-passe errada." : res?.status === 429 ? "Demasiadas tentativas. Tenta daqui a um minuto." : "Não foi possível abrir a galeria."); + return; + } + const { token } = (await res.json()) as { token: string }; + document.cookie = `gt_${slug.replace(/[^a-z0-9-]/g, "")}=${token}; path=/; max-age=${7 * 24 * 3600}; samesite=lax${location.protocol === "https:" ? "; secure" : ""}`; + router.refresh(); + }} + > +

Esta galeria é privada. Usa a palavra-passe que recebeste.

+ + {error && ( +

+ {error} +

+ )} + +
+ ); +} diff --git a/apps/site/src/app/galeria/[slug]/page.tsx b/apps/site/src/app/galeria/[slug]/page.tsx new file mode 100644 index 0000000..eca62f3 --- /dev/null +++ b/apps/site/src/app/galeria/[slug]/page.tsx @@ -0,0 +1,50 @@ +import type { Metadata } from "next"; +import { cookies } from "next/headers"; +import { notFound } from "next/navigation"; +import { galleryCookie, getGallery, getProducts, NotFound } from "../../../lib/api"; +import { eventTitle, longDate } from "../../../lib/format"; +import { GalleryView } from "./GalleryView"; +import { Unlock } from "./Unlock"; + +export const dynamic = "force-dynamic"; + +type Params = { params: Promise<{ slug: string }> }; + +async function load(slug: string) { + try { + return await getGallery(slug); + } catch (err) { + if (err instanceof NotFound) notFound(); + throw err; + } +} + +export async function generateMetadata({ params }: Params): Promise { + const g = await load((await params).slug); + return { title: g.title, ...(g.visibility !== "PUBLIC" && { robots: { index: false } }), ...(g.cover && { openGraph: { images: [g.cover] } }) }; +} + +export default async function GalleryPage({ params }: Params) { + const { slug } = await params; + const [gallery, products] = await Promise.all([load(slug), getProducts()]); + const token = (await cookies()).get(galleryCookie(slug))?.value ?? null; + const e = gallery.event; + return ( +
+
+ {[e?.competition, e ? longDate(e.startsAt) : null].filter(Boolean).join(" · ")} +

{gallery.title || (e ? eventTitle(e) : "")}

+ + {gallery.photoCount} fotos{e?.venue ? ` · ${e.venue}` : ""} + {gallery.freeDownloads ? " · download gratuito" : ""} + + {gallery.description &&

{gallery.description}

} +
+ {gallery.locked ? ( + + ) : ( + gallery.forSale || (gallery.freeDownloads && p.kind === "DIGITAL"))} token={token} /> + )} +
+ ); +} diff --git a/apps/site/src/app/globals.css b/apps/site/src/app/globals.css new file mode 100644 index 0000000..30087ae --- /dev/null +++ b/apps/site/src/app/globals.css @@ -0,0 +1,485 @@ +/* Two skins over one structure. The skin is set on from the site's settings. */ +:root, +[data-skin="photoreport"] { + --bg: #f6f5f1; + --surface: #ffffff; + --ink: #111111; + --muted: #5f5f5f; + --faint: #8d8d8d; + --line: #dcdad2; + --accent: #1f6feb; + --accent-ink: #ffffff; + --bar: #111111; + --bar-ink: #f6f5f1; + --display: "Barlow Condensed", "Arial Narrow", sans-serif; + --text: "Barlow", system-ui, sans-serif; + --mono: "Space Mono", ui-monospace, monospace; + --radius: 0px; + color-scheme: light; +} + +[data-skin="shootyourmove"] { + --bg: #0b0b0c; + --surface: #141416; + --ink: #f2f2f2; + --muted: #a3a3a3; + --faint: #6f6f72; + --line: #26262a; + --accent: #ff0a0a; + --accent-ink: #ffffff; + --bar: #0b0b0c; + --bar-ink: #f2f2f2; + --radius: 2px; + color-scheme: dark; +} + +* { + box-sizing: border-box; +} +html, +body { + margin: 0; + background: var(--bg); + color: var(--ink); + font-family: var(--text); + font-size: 16px; + line-height: 1.5; + -webkit-font-smoothing: antialiased; +} +a { + color: inherit; + text-decoration: none; +} +img { + display: block; + max-width: 100%; +} +button, +input, +select { + font: inherit; +} +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.wrap { + width: 100%; + max-width: 1320px; + margin: 0 auto; + padding: 0 16px; +} +@media (min-width: 768px) { + .wrap { + padding: 0 32px; + } +} + +/* Header */ +.bar { + background: var(--bar); + color: var(--bar-ink); + border-bottom: 1px solid var(--line); + position: sticky; + top: 0; + z-index: 20; +} +.bar .wrap { + display: flex; + align-items: center; + gap: 24px; + height: 60px; +} +.brand { + display: flex; + align-items: center; + gap: 10px; + font-family: var(--display); + font-weight: 800; + font-size: 26px; + letter-spacing: 0.02em; + text-transform: uppercase; + line-height: 1; +} +.brand small { + font-family: var(--mono); + font-size: 11px; + font-weight: 400; + letter-spacing: 0; + opacity: 0.7; + text-transform: lowercase; +} +.nav { + margin-left: auto; + display: flex; + gap: 20px; + font-family: var(--display); + font-weight: 600; + font-size: 17px; + text-transform: uppercase; + letter-spacing: 0.04em; +} +.nav a:hover { + color: var(--accent); +} +.cart-count { + display: inline-block; + min-width: 20px; + margin-left: 6px; + padding: 0 6px; + background: var(--accent); + color: var(--accent-ink); + font-family: var(--mono); + font-size: 12px; + text-align: center; + border-radius: 10px; +} + +/* Type */ +.kicker { + font-family: var(--mono); + font-size: 12px; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--accent); +} +.title { + font-family: var(--display); + font-weight: 800; + text-transform: uppercase; + line-height: 0.95; + letter-spacing: 0.005em; + margin: 0; +} +.h1 { + font-size: clamp(40px, 7vw, 88px); +} +.h2 { + font-size: clamp(28px, 3.4vw, 40px); +} +.meta { + font-family: var(--mono); + font-size: 12px; + color: var(--muted); +} +.lead { + font-size: 18px; + color: var(--muted); + max-width: 60ch; +} + +/* Home */ +.hero { + padding: 56px 0 32px; + border-bottom: 1px solid var(--line); +} +.hero p { + margin: 16px 0 0; +} +.section-head { + display: flex; + align-items: baseline; + justify-content: space-between; + padding: 32px 0 16px; +} +.cards { + display: grid; + gap: 32px 24px; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + padding-bottom: 64px; +} +.card .frame { + aspect-ratio: 3 / 2; + background: var(--line); + overflow: hidden; + border-radius: var(--radius); +} +.card .frame img { + width: 100%; + height: 100%; + object-fit: cover; + transition: transform 0.4s ease; +} +.card:hover .frame img { + transform: scale(1.03); +} +.card .kicker { + margin-top: 12px; + display: block; +} +.card .title { + font-size: 28px; + margin-top: 4px; +} +.card:hover .title { + color: var(--accent); +} +.empty { + padding: 64px 0; + color: var(--muted); +} + +/* Gallery */ +.gallery-head { + padding: 40px 0 24px; + border-bottom: 1px solid var(--line); + display: grid; + gap: 8px; +} +.toolbar { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + padding: 16px 0; +} +.grid { + display: grid; + gap: 6px; + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); + padding-bottom: 64px; +} +@media (max-width: 600px) { + .grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 4px; + } +} +.tile { + position: relative; + aspect-ratio: 3 / 2; + background: var(--line); + overflow: hidden; + border: 0; + padding: 0; + cursor: zoom-in; + border-radius: var(--radius); +} +.tile img { + width: 100%; + height: 100%; + object-fit: cover; +} +.tile .in-cart { + position: absolute; + right: 6px; + top: 6px; + background: var(--accent); + color: var(--accent-ink); + font-family: var(--mono); + font-size: 11px; + padding: 2px 6px; +} +.tile .names { + position: absolute; + left: 0; + right: 0; + bottom: 0; + padding: 18px 8px 6px; + font-size: 12px; + color: #fff; + text-align: left; + background: linear-gradient(transparent, rgba(0, 0, 0, 0.7)); + opacity: 0; + transition: opacity 0.2s; +} +.tile:hover .names { + opacity: 1; +} + +/* Lightbox */ +.lightbox { + position: fixed; + inset: 0; + z-index: 50; + background: rgba(8, 8, 9, 0.96); + color: #f2f2f2; + display: grid; + grid-template-columns: 1fr; + grid-template-rows: 1fr auto; +} +@media (min-width: 900px) { + .lightbox { + grid-template-columns: 1fr 340px; + grid-template-rows: 1fr; + } +} +.lightbox .stage { + position: relative; + display: flex; + align-items: center; + justify-content: center; + padding: 16px; + min-height: 0; +} +.lightbox .stage img { + max-height: calc(100vh - 32px); + object-fit: contain; +} +.lightbox .side { + background: #121214; + padding: 24px; + overflow-y: auto; + border-left: 1px solid #222; +} +.lightbox .close, +.lightbox .arrow { + position: absolute; + background: rgba(0, 0, 0, 0.5); + color: #fff; + border: 0; + width: 44px; + height: 44px; + font-size: 22px; + cursor: pointer; +} +.lightbox .close { + top: 12px; + right: 12px; +} +.lightbox .arrow.prev { + left: 12px; + top: 50%; +} +.lightbox .arrow.next { + right: 12px; + top: 50%; +} + +/* Products and forms */ +.products { + display: grid; + gap: 8px; + margin: 16px 0; +} +.product { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + padding: 10px 12px; + border: 1px solid #2a2a2e; + background: transparent; + color: inherit; + cursor: pointer; + text-align: left; + border-radius: var(--radius); +} +.product:hover { + border-color: var(--accent); +} +.product .price { + font-family: var(--mono); + font-size: 14px; +} +.button { + display: inline-flex; + align-items: center; + justify-content: center; + height: 44px; + padding: 0 22px; + border: 0; + background: var(--accent); + color: var(--accent-ink); + font-family: var(--display); + font-weight: 700; + font-size: 18px; + text-transform: uppercase; + letter-spacing: 0.04em; + cursor: pointer; + border-radius: var(--radius); +} +.button:disabled { + opacity: 0.5; + cursor: default; +} +.button.ghost { + background: transparent; + color: var(--ink); + border: 1px solid var(--line); +} +.field { + display: grid; + gap: 4px; + font-size: 13px; + color: var(--muted); +} +.field input, +.field select { + height: 44px; + padding: 0 12px; + border: 1px solid var(--line); + background: var(--surface); + color: var(--ink); + border-radius: var(--radius); +} +.form { + display: grid; + gap: 14px; + max-width: 480px; +} +.error { + color: #d93025; + font-size: 14px; +} +.notice { + padding: 12px 16px; + border: 1px solid var(--line); + background: var(--surface); +} + +/* Cart and order */ +.lines { + display: grid; + gap: 0; + border-top: 1px solid var(--line); +} +.line { + display: grid; + grid-template-columns: 96px 1fr auto; + gap: 16px; + align-items: center; + padding: 12px 0; + border-bottom: 1px solid var(--line); +} +.line img { + width: 96px; + aspect-ratio: 3 / 2; + object-fit: cover; +} +.totals { + display: grid; + gap: 4px; + justify-items: end; + padding: 16px 0; + font-family: var(--mono); + font-size: 14px; +} +.totals strong { + font-size: 20px; +} +.columns { + display: grid; + gap: 48px; + padding: 32px 0 64px; +} +@media (min-width: 960px) { + .columns { + grid-template-columns: 1fr 420px; + } +} + +/* Footer */ +.footer { + border-top: 1px solid var(--line); + padding: 32px 0 48px; + color: var(--muted); + font-size: 14px; +} +.footer .wrap { + display: flex; + flex-wrap: wrap; + gap: 16px; + justify-content: space-between; +} diff --git a/apps/site/src/app/layout.tsx b/apps/site/src/app/layout.tsx new file mode 100644 index 0000000..7c1e0c2 --- /dev/null +++ b/apps/site/src/app/layout.tsx @@ -0,0 +1,67 @@ +import "@fontsource/barlow/400.css"; +import "@fontsource/barlow/500.css"; +import "@fontsource/barlow-condensed/600.css"; +import "@fontsource/barlow-condensed/700.css"; +import "@fontsource/barlow-condensed/800.css"; +import "@fontsource/space-mono/400.css"; +import "./globals.css"; +import type { Metadata } from "next"; +import Link from "next/link"; +import type { ReactNode } from "react"; +import { CartLink } from "../components/CartLink"; +import { Logo } from "../components/Logo"; +import { getSite, NotFound } from "../lib/api"; + +export async function generateMetadata(): Promise { + try { + const site = await getSite(); + return { title: { default: site.name, template: `%s · ${site.name}` }, description: site.settings.tagline ?? "Fotografia de desporto" }; + } catch { + return { title: "PhotoReport" }; + } +} + +export default async function RootLayout({ children }: { children: ReactNode }) { + let site; + try { + site = await getSite(); + } catch (err) { + if (!(err instanceof NotFound)) throw err; + return ( + + +
Este domínio não tem site configurado.
+ + + ); + } + return ( + + +
+
+ + + + +
+
+ {children} + + + + ); +} diff --git a/apps/site/src/app/page.tsx b/apps/site/src/app/page.tsx new file mode 100644 index 0000000..ff155fc --- /dev/null +++ b/apps/site/src/app/page.tsx @@ -0,0 +1,44 @@ +import Link from "next/link"; +import { getGalleries, getSite } from "../lib/api"; +import { eventTitle, longDate } from "../lib/format"; + +export const dynamic = "force-dynamic"; + +export default async function Home() { + const [site, galleries] = await Promise.all([getSite(), getGalleries()]); + return ( +
+
+
+ {site.skin === "shootyourmove" ? "Cada jogada, a tua fotografia" : "Agência de fotografia de desporto"} +

{site.settings.tagline ?? "As fotos do jogo"}

+

Encontra o teu jogo, escolhe as fotos e descarrega-as em alta resolução, ou recebe-as impressas.

+
+
+
+
+

Galerias

+ {galleries.length} publicadas +
+ {galleries.length === 0 ? ( +

Ainda não há galerias publicadas.

+ ) : ( +
+ {galleries.map((g) => ( + +
{g.cover ? : null}
+ + {[g.event?.competition, g.event ? longDate(g.event.startsAt) : longDate(g.publishedAt)].filter(Boolean).join(" · ")} + +

{g.title || (g.event ? eventTitle(g.event) : "")}

+ + {g.photoCount} fotos{g.event?.venue ? ` · ${g.event.venue}` : ""} + + + ))} +
+ )} +
+
+ ); +} diff --git a/apps/site/src/components/CartLink.tsx b/apps/site/src/components/CartLink.tsx new file mode 100644 index 0000000..a5524c3 --- /dev/null +++ b/apps/site/src/components/CartLink.tsx @@ -0,0 +1,14 @@ +"use client"; + +import Link from "next/link"; +import { useCart } from "../lib/cart"; + +export function CartLink() { + const cart = useCart(); + const count = cart.lines.reduce((s, l) => s + l.quantity, 0); + return ( + + Carrinho{count > 0 && {count}} + + ); +} diff --git a/apps/site/src/components/Logo.tsx b/apps/site/src/components/Logo.tsx new file mode 100644 index 0000000..e213e0f --- /dev/null +++ b/apps/site/src/components/Logo.tsx @@ -0,0 +1,30 @@ +import type { Skin } from "@photoreport/contracts"; + +/** The two brand marks: PhotoReport's wordmark, and ShootYourMove's viewfinder with the red dot. */ +export function Logo({ skin, name }: { skin: Skin; name: string }) { + if (skin === "shootyourmove") { + return ( + + + + ShootYourMove + + + ); + } + return ( + + + + {name.replace(/\.pt$/i, "")} + .pt + + + ); +} diff --git a/apps/site/src/lib/api.ts b/apps/site/src/lib/api.ts new file mode 100644 index 0000000..337e5d4 --- /dev/null +++ b/apps/site/src/lib/api.ts @@ -0,0 +1,33 @@ +import type { OrderView, ProductSummary, PublicGallery, PublicGallerySummary, SiteInfo } from "@photoreport/contracts"; +import { cookies, headers } from "next/headers"; + +const API = process.env.API_URL ?? "http://localhost:3000"; + +export class NotFound extends Error {} + +/** The domain this request is for (the API picks the organization and skin from it). */ +export async function siteDomain(): Promise { + const h = await headers(); + return (h.get("x-forwarded-host") ?? h.get("host") ?? "localhost").split(",")[0]!.trim(); +} + +async function get(path: string, extra: Record = {}): Promise { + const res = await fetch(`${API}${path}`, { headers: { "x-site-domain": await siteDomain(), ...extra }, cache: "no-store" }); + if (res.status === 404) throw new NotFound(path); + if (!res.ok) throw new Error(`${path}: ${res.status}`); + return (await res.json()) as T; +} + +export const getSite = () => get("/v1/public/site"); +export const getGalleries = () => get<{ galleries: PublicGallerySummary[] }>("/v1/public/galleries").then((r) => r.galleries); +export const getProducts = () => get<{ products: ProductSummary[] }>("/v1/public/products").then((r) => r.products); + +/** The gallery's unlock token lives in a cookie the unlock form sets. */ +export async function getGallery(slug: string): Promise { + const token = (await cookies()).get(galleryCookie(slug))?.value; + return get(`/v1/public/galleries/${encodeURIComponent(slug)}`, token ? { "x-gallery-token": token } : {}); +} + +export const getOrder = (id: string, token: string) => get(`/v1/public/orders/${id}?t=${encodeURIComponent(token)}`); + +export const galleryCookie = (slug: string) => `gt_${slug.replace(/[^a-z0-9-]/g, "")}`; diff --git a/apps/site/src/lib/cart.ts b/apps/site/src/lib/cart.ts new file mode 100644 index 0000000..6ffd644 --- /dev/null +++ b/apps/site/src/lib/cart.ts @@ -0,0 +1,85 @@ +"use client"; + +import { useSyncExternalStore } from "react"; + +/** The cart lives in this browser only (one gallery at a time, as orders are per gallery). */ +export interface CartLine { + photoId: string; + productId: string; + productName: string; + priceCents: number; + kind: "DIGITAL" | "PRINT"; + quantity: number; + thumb: string; +} + +export interface Cart { + gallery: string | null; + galleryTitle: string | null; + galleryToken: string | null; + lines: CartLine[]; +} + +const KEY = "pr.cart"; +const EMPTY: Cart = { gallery: null, galleryTitle: null, galleryToken: null, lines: [] }; +const listeners = new Set<() => void>(); +let cached: { raw: string | null; cart: Cart } = { raw: null, cart: EMPTY }; + +function read(): Cart { + let raw: string | null = null; + try { + raw = window.localStorage.getItem(KEY); + } catch { + raw = null; + } + if (raw === cached.raw) return cached.cart; + let cart = EMPTY; + try { + cart = raw ? ({ ...EMPTY, ...(JSON.parse(raw) as Cart) } as Cart) : EMPTY; + } catch { + cart = EMPTY; + } + cached = { raw, cart }; + return cart; +} + +export function writeCart(cart: Cart): void { + try { + window.localStorage.setItem(KEY, JSON.stringify(cart)); + } catch { + // storage unavailable: the cart lasts for this page only + cached = { raw: JSON.stringify(cart), cart }; + } + for (const fn of listeners) fn(); +} + +export function useCart(): Cart { + return useSyncExternalStore( + (fn) => { + listeners.add(fn); + const onStorage = (e: StorageEvent) => e.key === KEY && fn(); + window.addEventListener("storage", onStorage); + return () => { + listeners.delete(fn); + window.removeEventListener("storage", onStorage); + }; + }, + read, + () => EMPTY, + ); +} + +/** Adds a line; a photo from another gallery starts a new cart (orders are per gallery). */ +export function addToCart(gallery: { slug: string; title: string; token: string | null }, line: CartLine): void { + const cart = read(); + const base = cart.gallery === gallery.slug ? cart : { gallery: gallery.slug, galleryTitle: gallery.title, galleryToken: gallery.token, lines: [] }; + const same = base.lines.find((l) => l.photoId === line.photoId && l.productId === line.productId); + const lines = same + ? base.lines.map((l) => (l === same ? { ...l, quantity: Math.min(50, l.quantity + (line.kind === "PRINT" ? 1 : 0)) } : l)) + : [...base.lines, line]; + writeCart({ ...base, galleryToken: gallery.token ?? base.galleryToken, lines }); +} + +export function cartTotal(cart: Cart): number { + return cart.lines.reduce((s, l) => s + l.priceCents * l.quantity, 0); +} diff --git a/apps/site/src/lib/format.test.ts b/apps/site/src/lib/format.test.ts new file mode 100644 index 0000000..dca3ad3 --- /dev/null +++ b/apps/site/src/lib/format.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from "vitest"; +import { eur, eventTitle } from "./format"; + +describe("format", () => { + it("shows euros the Portuguese way and names matches", () => { + expect(eur(1230).replace(/\s/g, " ")).toBe("12,30 €"); + expect(eventTitle({ home: "SC Braga", away: "Sporting CP" })).toBe("SC Braga x Sporting CP"); + expect(eventTitle({ home: "Gala do Desporto", away: null })).toBe("Gala do Desporto"); + }); +}); diff --git a/apps/site/src/lib/format.ts b/apps/site/src/lib/format.ts new file mode 100644 index 0000000..09b77e6 --- /dev/null +++ b/apps/site/src/lib/format.ts @@ -0,0 +1,9 @@ +const money = new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }); +export const eur = (cents: number) => money.format(cents / 100); + +const day = new Intl.DateTimeFormat("pt-PT", { day: "numeric", month: "long", year: "numeric", timeZone: "Europe/Lisbon" }); +export const longDate = (iso: string) => day.format(new Date(iso)); + +export function eventTitle(e: { home: string; away: string | null }): string { + return e.away ? `${e.home} x ${e.away}` : e.home; +} diff --git a/apps/site/tsconfig.json b/apps/site/tsconfig.json new file mode 100644 index 0000000..3cc67a8 --- /dev/null +++ b/apps/site/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "preserve", + "strict": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": true, + "allowJs": false, + "noEmit": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + "incremental": true, + "plugins": [{ "name": "next" }], + "paths": { "@/*": ["./src/*"] } + }, + "include": ["next-env.d.ts", "src/**/*.ts", "src/**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2f3717e..f1beda3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -68,6 +68,26 @@ replaying the edit op log (phase 2). Files live on local disk behind `LocalStora derivatives per organization); the API and the worker share that folder (Proxmox bind mount). Garage replaces it when files must be served from more than one host. +## Galleries and shop + +- Sites: each domain (photoreport.pt, shootyourmove.com, ...) is a `sites` row: organization, skin + (`photoreport` editorial light, `shootyourmove` dark with red) and texts. `apps/site` (Next.js) is one build for + every domain; it asks the API with `x-site-domain` and proxies `/v1` so browsers stay on the site's origin. +- Galleries are made in the app (Vendas, or "Adicionar à galeria" on a library selection), usually from an + event with its picks. Public (listed), unlisted (link only) or private (link + password; the unlock returns a + token valid for a week, kept in a cookie). Photos on the sites are watermarked with the site's name (600 and + 1600 px), made on first view from the edited preview and cached until the edit changes; URLs are signed. +- Products per organization: JPEG downloads (long edge, 0 = original) and prints (size, lead days); prices are + gross. Orders keep a copy of names and prices. VAT: seller's rate inside the price; EU businesses with a + VIES-valid number from another member state get reverse charge (net price). OSS for EU consumers is not applied. +- Payments: the organization's own Stripe account (keys sealed with AES-GCM), hosted Checkout with the methods + switched on in its dashboard (cards; Multibanco and MB WAY where Stripe offers them). Webhooks + (`/v1/public/stripe/:orgId/webhook`, signature checked over the raw body) mark orders paid, including late + Multibanco payments. Free-download galleries skip payment for digital files. +- Fulfilment: the worker renders each bought JPEG from the original with the photo's edit and full IPTC at the + product's size (never enlarged), then emails the buyer the order link (SMTP). Downloads are counted (20 max). + Prints are marked shipped in the app; the order closes when everything is done. + ## Faces Only for organizations whose owner switched it on with a recorded legal basis (biometric data, GDPR art. 9). @@ -153,8 +173,10 @@ and weak connections (tus), and a real match run on the `next` containers (the p (a real match arrives captioned and delivered with no manual step). 2. Synced editor (done: WASM and native engine, op log, live sync, offline outbox, render worker, edited deliveries, crop with aspect presets and straighten, Basic and optional modules, copy/paste settings). -3. Galleries and sales: PhotoReport and ShootYourMove storefronts, private galleries, Stripe, VAT/VIES, - payouts, affiliates, press accounts, data import dry runs (end-to-end test purchase with invoice and payout). +3. Galleries and sales (done: both storefront skins, public/unlisted/private galleries, watermarks, cart, + Stripe Checkout and webhooks, VIES reverse charge, rendered downloads with IPTC, order emails, print + fulfilment, admin in the app. Open: invoicing software integration, photographer payouts, affiliates, + press accounts, data import from the old storefront). 4. Events and printing: QR guest flow, templates, print jobs, Print Agent (a real event printed). 5. Player identification: faces (done: detect, group, confirm, propagate, suggest across events), jersey numbers with squads, global search (parity with old projects validated). diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index 37ee969..5c8e97b 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -68,6 +68,12 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r every app deploy then rebuilds `apps/app/public/engine/` (`infra/engine/build-wasm.sh`). Serve `.wasm` as `application/wasm`. +10. Sites (pr-site): `API_URL` for `infra/pm2/site.config.cjs` (default http://127.0.0.1:3000), reverse proxy + every brand domain to port 3100. In the app (Vendas -> Sites e pagamentos) add each domain, then the + Stripe secret key and webhook secret; in Stripe add the shown endpoint for `checkout.session.completed`, + `checkout.session.async_payment_succeeded`, `checkout.session.async_payment_failed` and + `checkout.session.expired`. Set `SMTP_URL` on the worker for order emails. + ## Desktop and print agent Not deployed by webhook. A tag `desktop-v*` / `agent-v*` triggers Gitea Actions to build installers per OS and diff --git a/infra/deploy/deploy.sh b/infra/deploy/deploy.sh index 4e7e20c..b50d60e 100755 --- a/infra/deploy/deploy.sh +++ b/infra/deploy/deploy.sh @@ -73,13 +73,28 @@ deploy_app() { ls -1dt "$WEB_ROOT"/releases/* 2>/dev/null | tail -n +6 | xargs -r rm -rf } +deploy_site() { + local sha="$1" + node_install + rm -rf apps/site/.next + pnpm --filter "@photoreport/site..." build + APP_VERSION="$sha" pm2 startOrReload infra/pm2/site.config.cjs --update-env + local i + for ((i = 1; i <= HEALTH_TRIES; i++)); do + if curl -fsS --max-time 3 -o /dev/null "http://127.0.0.1:${SITE_PORT:-3100}/"; then return 0; fi + sleep 2 + done + return 1 +} + deploy_pending() { log "service $SERVICE has no deployable build yet; nothing to do"; } run_service() { case "$SERVICE" in api) deploy_api "$1" ;; app) deploy_app "$1" ;; - site | workers | ml) deploy_pending ;; + site) deploy_site "$1" ;; + workers | ml) deploy_pending ;; *) die "unknown service: $SERVICE" ;; esac } diff --git a/infra/pm2/site.config.cjs b/infra/pm2/site.config.cjs new file mode 100644 index 0000000..05edfe5 --- /dev/null +++ b/infra/pm2/site.config.cjs @@ -0,0 +1,14 @@ +// Public sites (apps/site, Next.js): one process serves every brand domain behind the reverse proxy. +module.exports = { + apps: [ + { + name: "photoreport-site", + cwd: __dirname + "/../../apps/site", + script: "node_modules/next/dist/bin/next", + args: "start -p 3100", + instances: 2, + exec_mode: "cluster", + env: { NODE_ENV: "production", PORT: "3100", API_URL: process.env.API_URL || "http://127.0.0.1:3000" }, + }, + ], +}; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 30ecbd8..a274bd4 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -1,3 +1,4 @@ export * from "./commands.js"; export * from "./controls.js"; export * from "./library.js"; +export * from "./shop.js"; diff --git a/packages/contracts/src/shop.ts b/packages/contracts/src/shop.ts new file mode 100644 index 0000000..d511d3f --- /dev/null +++ b/packages/contracts/src/shop.ts @@ -0,0 +1,196 @@ +import { z } from "zod"; + +/** Galleries, products and orders: the public sites (photoreport.pt, shootyourmove.com) and the shop. */ + +export const SKINS = ["photoreport", "shootyourmove"] as const; +export type Skin = (typeof SKINS)[number]; + +export interface SiteInfo { + id: string; + domain: string; + skin: Skin; + name: string; + settings: { tagline?: string; contactEmail?: string; instagram?: string; accent?: string }; +} + +export const SiteInput = z.object({ + domain: z + .string() + .trim() + .toLowerCase() + .regex(/^[a-z0-9.-]+(:\d+)?$/), + skin: z.enum(SKINS), + name: z.string().trim().min(1).max(80), + settings: z + .object({ + tagline: z.string().max(160).optional(), + contactEmail: z.email().optional(), + instagram: z.string().max(80).optional(), + accent: z + .string() + .regex(/^#[0-9a-fA-F]{6}$/) + .optional(), + }) + .default({}), +}); +export type SiteInput = z.infer; + +export type GalleryVisibility = "PUBLIC" | "UNLISTED" | "PRIVATE"; + +export interface GalleryEventInfo { + home: string; + away: string | null; + competition: string | null; + venue: string | null; + startsAt: string; +} + +/** A gallery as the app (editors) sees it. */ +export interface GallerySummary { + id: string; + slug: string; + title: string; + description: string | null; + visibility: GalleryVisibility; + hasPassword: boolean; + eventId: string | null; + publishedAt: string | null; + forSale: boolean; + freeDownloads: boolean; + photoCount: number; + cover: string | null; +} + +export const GalleryInput = z.object({ + slug: z + .string() + .trim() + .toLowerCase() + .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/) + .max(120) + .optional(), + title: z.string().trim().min(1).max(160), + description: z.string().trim().max(2000).nullable().optional(), + visibility: z.enum(["PUBLIC", "UNLISTED", "PRIVATE"]).default("PUBLIC"), + /** New password for PRIVATE galleries; omit to keep the current one. */ + password: z.string().min(4).max(100).optional(), + eventId: z.uuid().nullable().optional(), + forSale: z.boolean().default(true), + freeDownloads: z.boolean().default(false), +}); +export type GalleryInput = z.infer; + +export const GalleryPhotosChange = z.object({ + add: z.array(z.uuid()).max(2000).default([]), + remove: z.array(z.uuid()).max(2000).default([]), + cover: z.uuid().nullable().optional(), +}); +export type GalleryPhotosChange = z.infer; + +export interface PublicGallerySummary { + slug: string; + title: string; + description: string | null; + visibility: GalleryVisibility; + photoCount: number; + cover: string | null; + event: GalleryEventInfo | null; + publishedAt: string; +} + +export interface PublicPhoto { + id: string; + width: number | null; + height: number | null; + capturedAt: string | null; + players: string[]; + /** Watermarked, 600 px and 1600 px. */ + thumb: string; + preview: string; +} + +export interface PublicGallery extends PublicGallerySummary { + forSale: boolean; + freeDownloads: boolean; + /** PRIVATE without a valid token: no photos until unlocked. */ + locked: boolean; + photos: PublicPhoto[]; +} + +export type ProductKind = "DIGITAL" | "PRINT"; + +export interface ProductSummary { + id: string; + kind: ProductKind; + name: string; + longEdge: number | null; + printSize: string | null; + priceCents: number; + leadDays: number | null; + active: boolean; + position: number; +} + +export const ProductInput = z + .object({ + kind: z.enum(["DIGITAL", "PRINT"]), + name: z.string().trim().min(1).max(80), + longEdge: z.number().int().min(0).max(20000).nullable().optional(), + printSize: z.string().trim().max(20).nullable().optional(), + priceCents: z.number().int().min(0).max(1_000_000), + leadDays: z.number().int().min(0).max(60).nullable().optional(), + active: z.boolean().default(true), + position: z.number().int().min(0).default(0), + }) + .refine((p) => p.kind === "PRINT" || p.longEdge !== undefined, { message: "digital products need a long edge (0: full size)" }); +export type ProductInput = z.infer; + +export const CreateOrder = z.object({ + gallery: z.string().min(1).max(120), + galleryToken: z.string().max(400).optional(), + items: z + .array(z.object({ photoId: z.uuid(), productId: z.uuid(), quantity: z.number().int().min(1).max(50) })) + .min(1) + .max(200), + email: z.email(), + name: z.string().trim().min(2).max(120), + country: z + .string() + .length(2) + .transform((c) => c.toUpperCase()), + vatNumber: z.string().trim().max(20).optional(), +}); +export type CreateOrder = z.infer; + +export type OrderStatus = "PENDING" | "PAID" | "FULFILLED" | "CANCELLED" | "REFUNDED"; +export type FulfilmentStatus = "PENDING" | "RUNNING" | "READY" | "SHIPPED" | "FAILED"; + +export interface OrderView { + id: string; + number: string; + status: OrderStatus; + email: string; + name: string; + country: string; + vatNumber: string | null; + reverseCharge: boolean; + currency: string; + netCents: number; + vatCents: number; + totalCents: number; + createdAt: string; + paidAt: string | null; + checkoutUrl: string | null; + items: { + id: string; + productName: string; + kind: ProductKind; + quantity: number; + unitCents: number; + totalCents: number; + status: FulfilmentStatus; + photo: { id: string; name: string; thumb: string } | null; + /** Signed download URL once the file is ready. */ + download: string | null; + }[]; +} diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index fe348c6..d58cf17 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -1,5 +1,5 @@ -import type { ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, Module, PhotoPatch, PhotoSummary, PostEdits } from "@photoreport/contracts"; -import type { DeliveryTarget, DeliveryTargetInput, PersonSummary, PhotoFace, SquadPerson, DeviceGrant, FtpAccount, EventInput, EventSummary, IptcIssue, Me, Member, PhotoQuery, Role } from "./types.js"; +import type { ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, ProductInput, ProductSummary, SiteInfo, SiteInput } from "@photoreport/contracts"; +import type { DeliveryTarget, DeliveryTargetInput, PersonSummary, PhotoFace, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, EventInput, EventSummary, IptcIssue, Me, Member, PhotoQuery, Role } from "./types.js"; /** * Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it @@ -220,6 +220,88 @@ export class ApiClient { return this.request<{ content: string; entries: number; issues: { line: number; message: string }[] }>("PUT", `/v1/orgs/${orgId}/code-list`, { content }); } + // ---- shop ------------------------------------------------------------------------------------------- + + listGalleries(orgId: string) { + return this.request<{ galleries: GallerySummary[] }>("GET", `/v1/orgs/${orgId}/galleries`); + } + + createGallery(orgId: string, input: GalleryInput) { + return this.request("POST", `/v1/orgs/${orgId}/galleries`, input); + } + + updateGallery(id: string, input: Partial) { + return this.request("PATCH", `/v1/galleries/${id}`, input); + } + + deleteGallery(id: string) { + return this.request("DELETE", `/v1/galleries/${id}`); + } + + changeGalleryPhotos(id: string, change: Partial) { + return this.request("POST", `/v1/galleries/${id}/photos`, { add: [], remove: [], ...change }); + } + + galleryPhotoIds(id: string) { + return this.request<{ photoIds: string[] }>("GET", `/v1/galleries/${id}/photos`); + } + + publishGallery(id: string, published: boolean) { + return this.request("POST", `/v1/galleries/${id}/publish`, { published }); + } + + listProducts(orgId: string) { + return this.request<{ products: ProductSummary[] }>("GET", `/v1/orgs/${orgId}/products`); + } + + createProduct(orgId: string, input: ProductInput) { + return this.request("POST", `/v1/orgs/${orgId}/products`, input); + } + + updateProduct(id: string, patch: Partial>) { + return this.request("PATCH", `/v1/products/${id}`, patch); + } + + deleteProduct(id: string) { + return this.request("DELETE", `/v1/products/${id}`); + } + + listSites(orgId: string) { + return this.request<{ sites: SiteInfo[] }>("GET", `/v1/orgs/${orgId}/sites`); + } + + createSite(orgId: string, input: SiteInput) { + return this.request("POST", `/v1/orgs/${orgId}/sites`, input); + } + + updateSite(id: string, input: Partial) { + return this.request("PATCH", `/v1/sites/${id}`, input); + } + + deleteSite(id: string) { + return this.request("DELETE", `/v1/sites/${id}`); + } + + listOrders(orgId: string, status?: OrderView["status"]) { + return this.request<{ orders: OrderView[] }>("GET", `/v1/orgs/${orgId}/orders${status ? `?status=${status}` : ""}`); + } + + markShipped(orderId: string, itemId: string) { + return this.request("POST", `/v1/orders/${orderId}/items/${itemId}/shipped`); + } + + retryOrder(orderId: string) { + return this.request("POST", `/v1/orders/${orderId}/retry`); + } + + getShopSettings(orgId: string) { + return this.request("GET", `/v1/orgs/${orgId}/shop-settings`); + } + + updateShopSettings(orgId: string, input: Partial<{ legalName: string | null; vatNumber: string | null; country: string; vatRate: number; stripeSecretKey: string; stripeWebhookSecret: string }>) { + return this.request<{ ok: true }>("PUT", `/v1/orgs/${orgId}/shop-settings`, input); + } + // ---- develop ---------------------------------------------------------------------------------------- /** Snapshot plus the ops after it; with `since`, only the ops after that op-log position. */ diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index aafed40..1343214 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -155,3 +155,14 @@ export interface PhotoFace { person: PersonSummary | null; suggestion: PersonSummary | null; } + +export interface ShopSettings { + legalName: string | null; + vatNumber: string | null; + country: string; + vatRate: number; + stripeConfigured: boolean; + webhookConfigured: boolean; + /** Path on the API to give Stripe as the webhook endpoint. */ + webhookUrl: string; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6c538e4..cbec2d1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -62,6 +62,9 @@ importers: jose: specifier: ^6.2.12 version: 6.2.12 + nodemailer: + specifier: ^7.0.13 + version: 7.0.13 pg: specifier: ^8.23.1 version: 8.23.1 @@ -78,6 +81,9 @@ importers: specifier: ^4.6.5 version: 4.6.5 devDependencies: + '@types/nodemailer': + specifier: ^8.0.2 + version: 8.0.2 '@types/pg': specifier: ^8.23.1 version: 8.23.1 @@ -161,6 +167,37 @@ importers: specifier: ^2.12.2 version: 2.12.2 + apps/site: + dependencies: + '@fontsource/barlow': + specifier: ^5.3.0 + version: 5.3.0 + '@fontsource/barlow-condensed': + specifier: ^5.3.0 + version: 5.3.0 + '@fontsource/space-mono': + specifier: ^5.3.0 + version: 5.3.0 + '@photoreport/contracts': + specifier: workspace:* + version: link:../../packages/contracts + next: + specifier: 15.5.26 + version: 15.5.26(@types/node@22.20.5)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + react: + specifier: ^19.3.0 + version: 19.3.0 + react-dom: + specifier: ^19.3.0 + version: 19.3.0(react@19.3.0) + devDependencies: + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.3.0 + version: 19.3.0(@types/react@19.3.0) + infra/deploy-receiver: {} packages/contracts: @@ -717,6 +754,57 @@ packages: cpu: [x64] os: [linux] + '@next/env@15.5.26': + resolution: {integrity: sha512-NJBz9q10LU9h3KjHLEbdgWIV+ow/x+MYzKBRfqhm9/QmML3tPMhYmXF/UIV9SDVCNtOqFNc5oX7kZqeiigMCEA==} + + '@next/swc-darwin-arm64@15.5.26': + resolution: {integrity: sha512-So8eoJxIcXw/TexNUvvh3uY72J9nDo5BpJsAwUKx+FK57CrWXg6RqVufV7U9OT3BO+siMzJ2FuAwBhaHoPlLGg==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [darwin] + + '@next/swc-darwin-x64@15.5.26': + resolution: {integrity: sha512-jImzLUTClVWKhP91e5sgDumjxCLhaFSt7DuN5cnRYw99Dppxxhhq5jKRyDa2aTv3JE7dQmTSTsY3EFkSOp9Pog==} + engines: {node: '>= 10'} + cpu: [x64] + os: [darwin] + + '@next/swc-linux-arm64-gnu@15.5.26': + resolution: {integrity: sha512-CaWd+T/Lud2BmZbrsa1CzCnIOdU3YX9Nuk89virZaSB1O+C+8Yrrevgmnl68u4dvZIfOAzQ77S+Njrq7v1XwSA==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + + '@next/swc-linux-arm64-musl@15.5.26': + resolution: {integrity: sha512-97AyKI34yjpaudlkWHswAf7c1PjWQAC7lLyrw3R5K+bq834EOA+9IG68rIVy0VqrqGjtPSMjJmMmgeJ3wHR5og==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + + '@next/swc-linux-x64-gnu@15.5.26': + resolution: {integrity: sha512-eVtuOCew1sBPV7BEgxy7qxuVyqoU3tJIS/xDZwa1/NiQ4Q0LM2JMH7rny+/uVIN6hsQ3PTb0hTQWypA0L2QxtA==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + + '@next/swc-linux-x64-musl@15.5.26': + resolution: {integrity: sha512-EiUXADp+Z+OdQnSqbX10YgOSUrs0CXVODoTfySfsP2jdhngn9bq5RJd376FJzqMPe/XX25FMr1aXtYUVPA0qDw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + + '@next/swc-win32-arm64-msvc@15.5.26': + resolution: {integrity: sha512-HPl41fgkC4kdM5CCIoqNW6KlKEj1N+xS6bjNFFxDNKooUNUu09frgD948zo95TPw/C3XINZpkdkBGNU2RhjEnw==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [win32] + + '@next/swc-win32-x64-msvc@15.5.26': + resolution: {integrity: sha512-TgmJ5ginKr34RPsz01/swpYtFBxh51d66jM26aytpE6NIypU5KtBVI8C2hJjUNpWr7v6sWj8a6+og2MyntcnpA==} + engines: {node: '>= 10'} + cpu: [x64] + os: [win32] + '@node-rs/argon2-android-arm-eabi@2.2.2': resolution: {integrity: sha512-c11BOrPLBWNC1cDyzGB+Bil+flmxfZbB2hv8EhcobmAsFKMyqkHPNhUY4qhcjv1U+4+Vmw4G8H+l224iO2g/Dw==} engines: {node: '>= 10'} @@ -1076,6 +1164,9 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@swc/helpers@0.5.15': + resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==} + '@tailwindcss/node@4.3.3': resolution: {integrity: sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==} @@ -1340,6 +1431,9 @@ packages: '@types/node@22.20.5': resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} + '@types/nodemailer@8.0.2': + resolution: {integrity: sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==} + '@types/pg@8.23.1': resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==} @@ -1518,6 +1612,9 @@ packages: classnames@2.5.1: resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==} + client-only@0.0.1: + resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} + confbox@0.2.4: resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==} @@ -2014,10 +2111,35 @@ packages: resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==} engines: {node: '>= 0.6'} + next@15.5.26: + resolution: {integrity: sha512-EVCqhvq8Hs+nX9udH2VzE/iXAg9QodZBZnwVJTuAMl386GIYvlJtYhFytV9nSlDYxKw3kEyv8I2dCQs0+on0sQ==} + engines: {node: ^18.18.0 || ^19.8.0 || >= 20.0.0} + hasBin: true + peerDependencies: + '@opentelemetry/api': ^1.1.0 + '@playwright/test': ^1.51.1 + babel-plugin-react-compiler: '*' + react: ^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0 + react-dom: ^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0 + sass: ^1.3.0 + peerDependenciesMeta: + '@opentelemetry/api': + optional: true + '@playwright/test': + optional: true + babel-plugin-react-compiler: + optional: true + sass: + optional: true + node-releases@2.0.58: resolution: {integrity: sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg==} engines: {node: '>=18'} + nodemailer@7.0.13: + resolution: {integrity: sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==} + engines: {node: '>=6.0.0'} + object-assign@4.1.1: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} @@ -2100,6 +2222,10 @@ packages: pkg-types@2.3.3: resolution: {integrity: sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==} + postcss@8.4.31: + resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==} + engines: {node: ^10 || ^12 || >=14} + postcss@8.5.29: resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==} engines: {node: ^10 || ^12 || >=14} @@ -2332,6 +2458,19 @@ packages: strip-literal@3.1.0: resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} + styled-jsx@5.1.6: + resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==} + engines: {node: '>= 12.0.0'} + peerDependencies: + '@babel/core': '*' + babel-plugin-macros: '*' + react: '>= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0' + peerDependenciesMeta: + '@babel/core': + optional: true + babel-plugin-macros: + optional: true + tailwindcss@4.3.3: resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==} @@ -2999,6 +3138,32 @@ snapshots: '@napi-rs/lzma-linux-x64-gnu@1.5.1': optional: true + '@next/env@15.5.26': {} + + '@next/swc-darwin-arm64@15.5.26': + optional: true + + '@next/swc-darwin-x64@15.5.26': + optional: true + + '@next/swc-linux-arm64-gnu@15.5.26': + optional: true + + '@next/swc-linux-arm64-musl@15.5.26': + optional: true + + '@next/swc-linux-x64-gnu@15.5.26': + optional: true + + '@next/swc-linux-x64-musl@15.5.26': + optional: true + + '@next/swc-win32-arm64-msvc@15.5.26': + optional: true + + '@next/swc-win32-x64-msvc@15.5.26': + optional: true + '@node-rs/argon2-android-arm-eabi@2.2.2': optional: true @@ -3301,6 +3466,10 @@ snapshots: '@standard-schema/spec@1.1.0': {} + '@swc/helpers@0.5.15': + dependencies: + tslib: 2.8.1 + '@tailwindcss/node@4.3.3': dependencies: '@jridgewell/remapping': 2.3.5 @@ -3523,6 +3692,10 @@ snapshots: dependencies: undici-types: 6.21.0 + '@types/nodemailer@8.0.2': + dependencies: + '@types/node': 22.20.5 + '@types/pg@8.23.1': dependencies: '@types/node': 22.20.5 @@ -3762,6 +3935,8 @@ snapshots: classnames@2.5.1: {} + client-only@0.0.1: {} + confbox@0.2.4: {} confbox@0.3.1: {} @@ -4247,8 +4422,34 @@ snapshots: negotiator@0.6.3: {} + next@15.5.26(@types/node@22.20.5)(react-dom@19.3.0(react@19.3.0))(react@19.3.0): + dependencies: + '@next/env': 15.5.26 + '@swc/helpers': 0.5.15 + caniuse-lite: 1.0.30001815 + postcss: 8.4.31 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + styled-jsx: 5.1.6(react@19.3.0) + optionalDependencies: + '@next/swc-darwin-arm64': 15.5.26 + '@next/swc-darwin-x64': 15.5.26 + '@next/swc-linux-arm64-gnu': 15.5.26 + '@next/swc-linux-arm64-musl': 15.5.26 + '@next/swc-linux-x64-gnu': 15.5.26 + '@next/swc-linux-x64-musl': 15.5.26 + '@next/swc-win32-arm64-msvc': 15.5.26 + '@next/swc-win32-x64-msvc': 15.5.26 + sharp: 0.35.5(@types/node@22.20.5) + transitivePeerDependencies: + - '@babel/core' + - '@types/node' + - babel-plugin-macros + node-releases@2.0.58: {} + nodemailer@7.0.13: {} + object-assign@4.1.1: {} ohash@2.0.12: {} @@ -4332,6 +4533,12 @@ snapshots: exsolve: 1.1.3 pathe: 2.0.3 + postcss@8.4.31: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + postcss@8.5.29: dependencies: nanoid: 3.3.20 @@ -4592,6 +4799,11 @@ snapshots: dependencies: js-tokens: 9.0.1 + styled-jsx@5.1.6(react@19.3.0): + dependencies: + client-only: 0.0.1 + react: 19.3.0 + tailwindcss@4.3.3: {} tapable@2.3.3: {} @@ -4631,8 +4843,7 @@ snapshots: dependencies: punycode: 2.3.1 - tslib@2.8.1: - optional: true + tslib@2.8.1: {} tsx@4.23.15: dependencies: