feat(shop): galleries on the public sites, Stripe checkout and rendered downloads
ci / typescript (push) Successful in 15m12s
ci / rust (push) Successful in 22m16s

Sites per domain with two skins (PhotoReport, ShootYourMove) in apps/site (Next.js); public, unlisted and private galleries with watermarked photos; products, cart, orders with VIES reverse charge; the organization's own Stripe Checkout and signed webhooks; bought files rendered from the original with edits and IPTC, emailed; Vendas module in the app.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
This commit is contained in:
sparkandClaude Opus 5.5 committed 2026-10-11 22:36:16 +01:00
1 parent 64da90d2f2
commit 8947a51d83
51 files changed
+4446 -18

No files matched your search

+2
View File
@@ -9,3 +9,5 @@ coverage/
*.log *.log
apps/api/src/generated/ apps/api/src/generated/
apps/app/public/engine/ apps/app/public/engine/
.next/
*.tsbuildinfo
+3
View File
@@ -32,3 +32,6 @@ FACES_PROCESSES=2
# Develop: replays edits and renders edited thumbnails and deliveries (workers/render). # Develop: replays edits and renders edited thumbnails and deliveries (workers/render).
RENDER_BIN=/srv/photoreport/target/release/photoreport-render RENDER_BIN=/srv/photoreport/target/release/photoreport-render
RENDER_PROCESSES=2 RENDER_PROCESSES=2
# Shop: mail with the download link (optional) and the Stripe API (only changed for local tests).
# SMTP_URL=smtps://user:[email protected]:465
MAIL_FROM=PhotoReport <[email protected]>
+2
View File
@@ -27,6 +27,7 @@
"exiftool-vendored": "^39.0.1", "exiftool-vendored": "^39.0.1",
"fastify": "^5.12.5", "fastify": "^5.12.5",
"jose": "^6.2.12", "jose": "^6.2.12",
"nodemailer": "^7.0.13",
"pg": "^8.23.1", "pg": "^8.23.1",
"pino": "^10.4.0", "pino": "^10.4.0",
"sharp": "^0.35.5", "sharp": "^0.35.5",
@@ -34,6 +35,7 @@
"zod": "^4.6.5" "zod": "^4.6.5"
}, },
"devDependencies": { "devDependencies": {
"@types/nodemailer": "^8.0.2",
"@types/pg": "^8.23.1", "@types/pg": "^8.23.1",
"prisma": "^7.10.0", "prisma": "^7.10.0",
"socket.io-client": "^4.8.4" "socket.io-client": "^4.8.4"
@@ -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;
+212 -10
View File
@@ -62,16 +62,29 @@ model Organization {
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
memberships Membership[] memberships Membership[]
events Event[] events Event[]
photos Photo[] photos Photo[]
codeLists CodeList[] codeLists CodeList[]
ftpAccounts FtpAccount[] ftpAccounts FtpAccount[]
targets DeliveryTarget[] targets DeliveryTarget[]
people Person[] people Person[]
faces Face[] faces Face[]
faceGroups FaceGroup[] faceGroups FaceGroup[]
deliveries DeliveryItem[] 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") @@map("organizations")
} }
@@ -201,6 +214,7 @@ model Event {
photos Photo[] photos Photo[]
deliveries DeliveryItem[] deliveries DeliveryItem[]
faceGroups FaceGroup[] faceGroups FaceGroup[]
galleries Gallery[]
@@index([organizationId, startsAt]) @@index([organizationId, startsAt])
@@map("events") @@map("events")
@@ -290,6 +304,8 @@ model Photo {
deliveries DeliveryItem[] deliveries DeliveryItem[]
faces Face[] faces Face[]
edits PhotoEdit[] edits PhotoEdit[]
galleries GalleryPhoto[]
orderItems OrderItem[]
/// The same file sent twice (FTP retries, two cards) is stored once. /// The same file sent twice (FTP retries, two cards) is stored once.
@@unique([organizationId, sha256]) @@unique([organizationId, sha256])
@@ -498,3 +514,189 @@ model Face {
@@index([groupId]) @@index([groupId])
@@map("faces") @@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")
}
+7
View File
@@ -20,6 +20,9 @@ import { IngestService } from "./ingest/service.js";
import { registerDevelopRoutes } from "./develop/routes.js"; import { registerDevelopRoutes } from "./develop/routes.js";
import { DevelopService } from "./develop/service.js"; import { DevelopService } from "./develop/service.js";
import { registerFaceRoutes } from "./faces/routes.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 { FaceService } from "./faces/service.js";
import { registerOrgRoutes } from "./orgs/routes.js"; import { registerOrgRoutes } from "./orgs/routes.js";
import { attachRealtime, type Broadcaster, silentBroadcaster } from "./realtime.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. // Edits are stored and fanned out here; the worker replays and renders them.
const develop = new DevelopService({ db, storage, signer, broadcaster, log: app.log }); const develop = new DevelopService({ db, storage, signer, broadcaster, log: app.log });
await registerDevelopRoutes(app, { db, sessions, develop }); 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. // Validation-only endpoint for the edit contract; the realtime path reuses the same schema.
app.post("/v1/edits/validate", async (req) => { app.post("/v1/edits/validate", async (req) => {
+5
View File
@@ -46,6 +46,11 @@ const Env = z.object({
FACES_PROCESSES: z.coerce.number().int().positive().default(2), FACES_PROCESSES: z.coerce.number().int().positive().default(2),
/** Render worker binary (workers/render): edited thumbnails and deliveries of edited photos. */ /** Render worker binary (workers/render): edited thumbnails and deliveries of edited photos. */
RENDER_BIN: z.string().optional(), 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 <[email protected]>"),
/** 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), RENDER_PROCESSES: z.coerce.number().int().positive().default(2),
COOKIE_SECURE: z COOKIE_SECURE: z
.enum(["true", "false"]) .enum(["true", "false"])
+15
View File
@@ -0,0 +1,15 @@
import nodemailer from "nodemailer";
export interface Mailer {
send(msg: { to: string; subject: string; text: string }): Promise<void>;
}
/** SMTP mail (order links). `SMTP_URL` like smtps://user:[email protected]:465. */
export function smtpMailer(url: string, from: string): Mailer {
const transport = nodemailer.createTransport(url);
return {
async send(msg) {
await transport.sendMail({ from, ...msg });
},
};
}
+324
View File
@@ -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<typeof requireMembership>[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 };
});
}
+54
View File
@@ -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")}`;
}
+145
View File
@@ -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<Site> {
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 =
<T>(fn: (req: FastifyRequest, reply: FastifyReply) => Promise<T>) =>
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 };
}),
);
});
}
+541
View File
@@ -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<PublicImageKind, number> = { 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<void> } | 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<Site | null> {
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<Site | null> {
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<string | null> {
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<string | null> {
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<PublicGallerySummary[]> {
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<PublicGallery> {
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<string> {
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<string> {
return hashPassword(password);
}
async gallerySummary(g: Gallery & { _count: { photos: number } }): Promise<GallerySummary> {
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<ProductSummary[]> {
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<boolean> {
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<void> {
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<OrderView> {
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<string[]> {
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<number> {
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<void> {
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<void> {
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<void> {
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);
}
}
+87
View File
@@ -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<string, unknown>, 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<string, unknown>, `${key}[${i}]`) : [`${encodeURIComponent(`${key}[${i}]`)}=${encodeURIComponent(String(item))}`])));
else if (typeof v === "object") out.push(...formEncode(v as Record<string, unknown>, 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<string, string[]>();
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")}`;
}
+29
View File
@@ -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<ViesResult | null> {
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;
}
}
+30
View File
@@ -0,0 +1,30 @@
import sharp from "sharp";
const escapeXml = (s: string) => s.replace(/[<>&"']/g, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[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<Buffer> {
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 x="${x + (row % 2 ? stepX / 2 : 0)}" y="${y}">${text}</text>`);
}
const corner = Math.max(11, Math.round(size * 0.55));
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}">
<g transform="rotate(-30 ${w / 2} ${h / 2})" font-family="Barlow Condensed, Arial Narrow, Arial, sans-serif" font-weight="700" font-size="${size}" fill="#ffffff" fill-opacity="0.22" stroke="#000000" stroke-opacity="0.12" stroke-width="1" letter-spacing="2">${rows.join("")}</g>
<text x="${w - corner}" y="${h - corner}" text-anchor="end" font-family="Barlow Condensed, Arial Narrow, Arial, sans-serif" font-weight="700" font-size="${corner * 1.4}" fill="#ffffff" fill-opacity="0.85" stroke="#000000" stroke-opacity="0.35" stroke-width="1">${text}</text>
</svg>`;
return sharp(data)
.composite([{ input: Buffer.from(svg), top: 0, left: 0 }])
.jpeg({ quality: 82, mozjpeg: true })
.toBuffer();
}
+9
View File
@@ -7,6 +7,8 @@ import { DeliveryService, DeliveryWorker } from "./delivery/service.js";
import { RenderPool, RenderProcess } from "./develop/engine.js"; import { RenderPool, RenderProcess } from "./develop/engine.js";
import { DevelopService, RenderWorker } from "./develop/service.js"; import { DevelopService, RenderWorker } from "./develop/service.js";
import { FacePool, FaceProcess } from "./faces/process.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 { FaceService, FaceWorker } from "./faces/service.js";
import { IngestScanner } from "./ingest/scanner.js"; import { IngestScanner } from "./ingest/scanner.js";
import { IngestService } from "./ingest/service.js"; import { IngestService } from "./ingest/service.js";
@@ -49,6 +51,11 @@ const deliveries = new DeliveryWorker(new DeliveryService({ db, storage, secrets
log, 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 = const faceEngine =
config.FACES_BIN && config.FACES_MODELS_DIR config.FACES_BIN && config.FACES_MODELS_DIR
? new FacePool( ? new FacePool(
@@ -64,6 +71,7 @@ scanner.start();
deliveries.start(); deliveries.start();
faces?.start(); faces?.start();
renders?.start(); renders?.start();
fulfilment.start();
log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started"); log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started");
const shutdown = async (signal: string) => { const shutdown = async (signal: string) => {
@@ -72,6 +80,7 @@ const shutdown = async (signal: string) => {
deliveries.stop(); deliveries.stop();
faces?.stop(); faces?.stop();
renders?.stop(); renders?.stop();
fulfilment.stop();
await faceEngine?.close(); await faceEngine?.close();
await renderEngine?.close(); await renderEngine?.close();
await closeRenderer(); await closeRenderer();
+211
View File
@@ -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, "[email protected]", { org: "photoreport", role: "OWNER" });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
await ctx.db.ftpAccount.create({ data: { organizationId: org!.id, userId: user.id, login: "cam" } });
const photos: string[] = [];
for (let i = 0; i < 3; i++) {
const data = await sharp({ create: { width: 1200, height: 800, channels: 3, background: { r: (++n * 37) % 256, g: (n * 91) % 256, b: 60 } } }).jpeg().toBuffer();
const file = path.join(ingestRoot, "cam", `IMG_${n}.jpg`);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, data);
const out = await ingest.ingestFile(file);
if (out.status !== "ingested") throw new Error(JSON.stringify(out));
photos.push(out.photoId);
}
const api = (method: "GET" | "POST" | "PUT" | "PATCH", url: string, payload?: unknown) => ctx.app.inject({ method, url, headers: bearer(token), ...(payload !== undefined && { payload: payload as object }) });
expect((await api("POST", `/v1/orgs/${org!.id}/sites`, { domain: "photoreport.test", skin: "photoreport", name: "PhotoReport" })).statusCode).toBe(201);
expect((await api("PUT", `/v1/orgs/${org!.id}/shop-settings`, { stripeSecretKey: "sk_test_abc", stripeWebhookSecret: WHSEC, legalName: "BitReport Unip. Lda" })).statusCode).toBe(200);
const digital = (await api("POST", `/v1/orgs/${org!.id}/products`, { kind: "DIGITAL", name: "Digital 2400 px", longEdge: 2400, priceCents: 1230 })).json() as { id: string };
const print = (await api("POST", `/v1/orgs/${org!.id}/products`, { kind: "PRINT", name: "Impressão 15x20", printSize: "15x20", priceCents: 615, leadDays: 3 })).json() as { id: string };
return { orgId: org!.id, photos, api, digital, print };
}
const pub = (method: "GET" | "POST", url: string, payload?: unknown, headers: Record<string, string> = {}) =>
ctx.app.inject({ method, url, headers: { "x-site-domain": "photoreport.test", ...headers }, ...(payload !== undefined && { payload: payload as object }) });
async function gallery(s: Awaited<ReturnType<typeof setup>>, body: Record<string, unknown>) {
const g = (await s.api("POST", `/v1/orgs/${s.orgId}/galleries`, body)).json() as { id: string; slug: string };
expect((await s.api("POST", `/v1/galleries/${g.id}/publish`, { published: true })).json()).toMatchObject({ error: "gallery_empty" });
await s.api("POST", `/v1/galleries/${g.id}/photos`, { add: s.photos });
expect((await s.api("POST", `/v1/galleries/${g.id}/publish`, { published: true })).statusCode).toBe(200);
return g;
}
it("shows published galleries with watermarked photos, and private ones only after the password", async () => {
const s = await setup();
const open = await gallery(s, { title: "SC Braga x Sporting CP" });
expect(open.slug).toBe("sc-braga-x-sporting-cp");
const priv = await gallery(s, { title: "Equipa ABC", visibility: "PRIVATE", password: "abc-2026" });
const list = (await pub("GET", "/v1/public/galleries")).json() as { galleries: { slug: string; photoCount: number; cover: string }[] };
expect(list.galleries.map((g) => g.slug)).toEqual([open.slug]); // private ones are not listed
const g = (await pub("GET", `/v1/public/galleries/${open.slug}`)).json() as { photos: { preview: string }[]; locked: boolean };
expect(g.locked).toBe(false);
expect(g.photos).toHaveLength(3);
const img = await ctx.app.inject({ method: "GET", url: g.photos[0]!.preview });
expect(img.statusCode).toBe(200);
const meta = await sharp(img.rawPayload).metadata();
expect(Math.max(meta.width!, meta.height!)).toBeLessThanOrEqual(1600);
// A tampered URL is refused.
expect((await ctx.app.inject({ method: "GET", url: g.photos[0]!.preview.replace(/sig=./, "sig=x") })).statusCode).toBe(404);
const locked = (await pub("GET", `/v1/public/galleries/${priv.slug}`)).json() as { locked: boolean; photos: unknown[] };
expect(locked).toMatchObject({ locked: true, photos: [] });
expect((await pub("POST", `/v1/public/galleries/${priv.slug}/unlock`, { password: "nope" })).statusCode).toBe(401);
const { token } = (await pub("POST", `/v1/public/galleries/${priv.slug}/unlock`, { password: "abc-2026" })).json() as { token: string };
const unlocked = (await pub("GET", `/v1/public/galleries/${priv.slug}`, undefined, { "x-gallery-token": token })).json() as { locked: boolean; photos: unknown[] };
expect(unlocked.photos).toHaveLength(3);
});
it("sells through Stripe, renders the download once paid, and closes the order when prints ship", async () => {
const s = await setup();
const g = await gallery(s, { title: "Final da Taça" });
const created = await pub("POST", "/v1/public/orders", {
gallery: g.slug,
email: "[email protected]",
name: "João Silva",
country: "PT",
items: [
{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 },
{ photoId: s.photos[1], productId: s.print.id, quantity: 2 },
],
});
expect(created.statusCode).toBe(201);
const { order, checkoutUrl } = created.json() as { order: { id: string; number: string; totalCents: number; vatCents: number }; checkoutUrl: string };
expect(checkoutUrl).toContain("checkout.stripe.com");
expect(order).toMatchObject({ number: `${new Date().getUTCFullYear()}-000001`, totalCents: 1230 + 1230, vatCents: 230 + 230 });
const stripeCall = calls.find((c) => c.url.includes("checkout/sessions"))!;
expect(decodeURIComponent(stripeCall.body)).toContain("line_items[1][price_data][unit_amount]=1230");
// Not paid yet: no downloads.
expect(await shop.claimDownloads(5)).toEqual([]);
const row = await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } });
const event = JSON.stringify({ type: "checkout.session.completed", data: { object: { id: "cs_test_1", payment_status: "paid", metadata: { order_id: order.id } } } });
const bad = await ctx.app.inject({ method: "POST", url: `/v1/public/stripe/${s.orgId}/webhook`, headers: { "content-type": "application/json", "stripe-signature": signWebhook(event, "whsec_wrong") }, payload: event });
expect(bad.statusCode).toBe(400);
const ok = await ctx.app.inject({ method: "POST", url: `/v1/public/stripe/${s.orgId}/webhook`, headers: { "content-type": "application/json", "stripe-signature": signWebhook(event, WHSEC) }, payload: event });
expect(ok.statusCode).toBe(200);
const [itemId] = await shop.claimDownloads(5);
await shop.fulfil(itemId!);
const view = (await pub("GET", `/v1/public/orders/${order.id}?t=${row.accessToken}`)).json() as { status: string; items: { kind: string; download: string | null; id: string }[] };
expect(view.status).toBe("PAID");
const digital = view.items.find((i) => i.kind === "DIGITAL")!;
const file = await ctx.app.inject({ method: "GET", url: digital.download! });
expect(file.statusCode).toBe(200);
expect(file.headers["content-disposition"]).toContain("attachment");
expect(mails).toHaveLength(1);
expect(mails[0]).toMatchObject({ to: "[email protected]" });
expect(mails[0]!.text).toContain(`https://photoreport.test/encomenda/${order.id}?t=${row.accessToken}`);
expect((await sharp(file.rawPayload).metadata()).width).toBe(1200); // never enlarged to 2400
expect((await pub("GET", `/v1/public/orders/${order.id}?t=wrongwrongwrong`)).statusCode).toBe(404);
// The print ships: the order is complete.
const print = view.items.find((i) => i.kind === "PRINT")!;
await s.api("POST", `/v1/orders/${order.id}/items/${print.id}/shipped`);
expect((await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } })).status).toBe("FULFILLED");
});
it("reverse-charges VAT for EU businesses with a valid number, and gives free galleries away", async () => {
const s = await setup();
const g = await gallery(s, { title: "Clube" });
const items = [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }];
const b2b = (await pub("POST", "/v1/public/orders", { gallery: g.slug, email: "[email protected]", name: "Fotos Madrid", country: "ES", vatNumber: "ESB12345678", items })).json() as { order: { totalCents: number; reverseCharge: boolean } };
expect(b2b.order).toMatchObject({ totalCents: 1000, reverseCharge: true });
viesValid = false;
const invalid = (await pub("POST", "/v1/public/orders", { gallery: g.slug, email: "[email protected]", name: "Fotos Madrid", country: "ES", vatNumber: "ESB12345678", items })).json() as { order: { totalCents: number; reverseCharge: boolean } };
expect(invalid.order).toMatchObject({ totalCents: 1230, reverseCharge: false });
const free = await gallery(s, { title: "Galeria do clube", forSale: false, freeDownloads: true });
const freeOrder = (await pub("POST", "/v1/public/orders", { gallery: free.slug, email: "[email protected]", name: "Sócio", country: "PT", items })).json() as { order: { status: string; totalCents: number }; checkoutUrl: string | null };
expect(freeOrder).toMatchObject({ checkoutUrl: null, order: { status: "PAID", totalCents: 0 } });
// Prints are not free, and a gallery not for sale sells nothing else.
const printFree = await pub("POST", "/v1/public/orders", { gallery: free.slug, email: "[email protected]", name: "Sócio", country: "PT", items: [{ photoId: s.photos[0], productId: s.print.id, quantity: 1 }] });
expect(printFree.json()).toMatchObject({ error: "gallery_not_for_sale" });
});
});
+2
View File
@@ -4,6 +4,7 @@ import { AuthProvider, useAuth } from "./auth.js";
import { t } from "./i18n.js"; import { t } from "./i18n.js";
import { DevelopPage } from "./pages/DevelopPage.js"; import { DevelopPage } from "./pages/DevelopPage.js";
import { DeliveryPage } from "./pages/DeliveryPage.js"; import { DeliveryPage } from "./pages/DeliveryPage.js";
import { ShopPage } from "./pages/ShopPage.js";
import { DevicePage } from "./pages/DevicePage.js"; import { DevicePage } from "./pages/DevicePage.js";
import { LibraryPage } from "./pages/LibraryPage.js"; import { LibraryPage } from "./pages/LibraryPage.js";
import { LoginPage } from "./pages/LoginPage.js"; import { LoginPage } from "./pages/LoginPage.js";
@@ -26,6 +27,7 @@ function Gate() {
<Route path="develop/:photoId?" element={<DevelopPage />} /> <Route path="develop/:photoId?" element={<DevelopPage />} />
<Route path="metadata" element={<MetadataPage />} /> <Route path="metadata" element={<MetadataPage />} />
<Route path="delivery" element={<DeliveryPage />} /> <Route path="delivery" element={<DeliveryPage />} />
<Route path="shop" element={<ShopPage />} />
<Route path="members" element={<MembersPage />} /> <Route path="members" element={<MembersPage />} />
<Route path="preferences" element={<PreferencesPage />} /> <Route path="preferences" element={<PreferencesPage />} />
<Route path="*" element={<p className="p-6 text-sm text-muted">{t.notFound}</p>} /> <Route path="*" element={<p className="p-6 text-sm text-muted">{t.notFound}</p>} />
+70
View File
@@ -155,6 +155,76 @@ export const t = {
PHOTOGRAPHER: "Fotógrafo", PHOTOGRAPHER: "Fotógrafo",
CLIENT: "Cliente", 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<string, string>,
},
dev: { dev: {
loading: "A abrir o motor de revelação…", 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).", engineMissing: "O motor de revelação não está disponível neste servidor (falta compilar engine/wasm).",
+32 -1
View File
@@ -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 { hasRole, type DeliveryTarget, type EventSummary } from "@photoreport/sdk";
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
@@ -39,6 +39,8 @@ export function LibraryPage() {
const [facesTick, setFacesTick] = useState(0); const [facesTick, setFacesTick] = useState(0);
const [loupeFaces, setLoupeFaces] = useState<LoupeFace[]>([]); const [loupeFaces, setLoupeFaces] = useState<LoupeFace[]>([]);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [galleries, setGalleries] = useState<GallerySummary[]>([]);
const [info, setInfo] = useState<string | null>(null);
const loadEvents = useCallback(async () => { const loadEvents = useCallback(async () => {
if (!orgId) return; if (!orgId) return;
@@ -211,6 +213,35 @@ export function LibraryPage() {
<button onClick={() => fileInput.current?.click()} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"> <button onClick={() => fileInput.current?.click()} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.importPhotos} {t.importPhotos}
</button> </button>
{canCull && selection.length > 0 && (
<select
aria-label={t.shop.addToGallery}
className="h-6 border border-black bg-cell px-1.5 text-[12px] text-ink"
value=""
onFocus={() => {
if (!galleries.length) api.listGalleries(orgId).then((r) => setGalleries(r.galleries), () => {});
}}
onChange={(e) => {
const g = galleries.find((x) => x.id === e.target.value);
if (!g) return;
void api.changeGalleryPhotos(g.id, { add: selection.map((p) => p.id) }).then(
() => {
setInfo(t.shop.addedToGallery(selection.length, g.title));
setTimeout(() => setInfo(null), 4000);
},
() => setError(t.unexpectedError),
);
}}
>
<option value="">{t.shop.addToGallery}…</option>
{galleries.map((g) => (
<option key={g.id} value={g.id}>
{g.title}
</option>
))}
</select>
)}
{info && <span className="text-[11px] text-ok">{info}</span>}
{canCull && prefs.get("develop.clipboard") && selection.length > 0 && ( {canCull && prefs.get("develop.clipboard") && selection.length > 0 && (
<button <button
onClick={() => { onClick={() => {
+6
View File
@@ -74,6 +74,12 @@ export function Shell() {
<NavLink to="/delivery" className={moduleClass}> <NavLink to="/delivery" className={moduleClass}>
{t.delivery} {t.delivery}
</NavLink> </NavLink>
<span aria-hidden="true" className="text-[#3a3a3a]">
|
</span>
<NavLink to="/shop" className={moduleClass}>
{t.shop.title}
</NavLink>
</> </>
)} )}
</nav> </nav>
+558
View File
@@ -0,0 +1,558 @@
import type { GalleryInput, GallerySummary, OrderView, ProductSummary, SiteInfo } from "@photoreport/contracts";
import { ApiError, hasRole, type EventSummary, type ShopSettings } from "@photoreport/sdk";
import { Fragment, useCallback, useEffect, useState } from "react";
import { useAuth } from "../auth.js";
import { t } from "../i18n.js";
import { PageHeader } from "./Shell.js";
type Tab = "galleries" | "orders" | "products" | "sites";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const primary = "h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-50";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.shop.errors[err.code] ?? err.code) : t.unexpectedError);
/** Shop module: galleries for the public sites, orders, products and payments. */
export function ShopPage() {
const { organization, role } = useAuth();
const [tab, setTab] = useState<Tab>("galleries");
const isAdmin = role !== null && hasRole(role, "ADMIN");
if (!organization) return <p className="p-6 text-sm text-muted">{t.noAccess}</p>;
const tabs: Tab[] = isAdmin ? ["galleries", "orders", "products", "sites"] : ["galleries", "orders"];
return (
<>
<PageHeader title={t.shop.title}>
<nav className="flex gap-1" aria-label={t.shop.title}>
{tabs.map((x) => (
<button key={x} onClick={() => setTab(x)} aria-pressed={tab === x} className={`h-7 px-3 text-[12px] ${tab === x ? "bg-cell-on text-ink" : "text-faint hover:text-muted"}`}>
{t.shop.tabs[x]}
</button>
))}
</nav>
</PageHeader>
<div className="mx-auto max-w-6xl space-y-6 p-6 max-sm:p-3">
{tab === "galleries" && <Galleries orgId={organization.id} />}
{tab === "orders" && <Orders orgId={organization.id} />}
{tab === "products" && <Products orgId={organization.id} />}
{tab === "sites" && <Sites orgId={organization.id} isOwner={role === "OWNER"} />}
</div>
</>
);
}
function Galleries({ orgId }: { orgId: string }) {
const { api } = useAuth();
const [galleries, setGalleries] = useState<GallerySummary[] | null>(null);
const [events, setEvents] = useState<EventSummary[]>([]);
const [sites, setSites] = useState<SiteInfo[]>([]);
const [editing, setEditing] = useState<GallerySummary | "new" | null>(null);
const [note, setNote] = useState<string | null>(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 (
<section className="border border-line bg-panel">
<div className="panel-head">
<span>{t.shop.galleries}</span>
<button className="normal-case tracking-normal text-muted hover:text-ink" onClick={() => setEditing("new")}>
+ {t.shop.newGallery}
</button>
</div>
<p className="px-4 pt-3 text-[12px] text-faint">{t.shop.galleriesHelp}</p>
{note && <p className="px-4 pt-2 text-[12px] text-danger">{note}</p>}
{editing && (
<GalleryForm
orgId={orgId}
events={events}
gallery={editing === "new" ? null : editing}
onDone={() => {
setEditing(null);
load();
}}
/>
)}
<div className="grid gap-3 p-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))" }}>
{(galleries ?? []).map((g) => {
const url = publicUrl(g);
return (
<article key={g.id} className="border border-black bg-cell">
<div className="aspect-[3/2] bg-[#161617]">{g.cover && <img src={api.absolute(g.cover)} alt="" className="h-full w-full object-cover" />}</div>
<div className="space-y-1 p-3">
<div className="flex items-baseline justify-between gap-2">
<h3 className="truncate text-[14px] text-ink">{g.title}</h3>
<span className={`font-mono text-[10px] ${g.publishedAt ? "text-ok" : "text-faint"}`}>{g.publishedAt ? t.shop.published : t.shop.draft}</span>
</div>
<p className="font-mono text-[11px] text-faint">
{t.shop.visibility[g.visibility]} · {g.photoCount} fotos{g.freeDownloads ? ` · ${t.shop.free}` : !g.forSale ? ` · ${t.shop.notForSale}` : ""}
</p>
<div className="flex flex-wrap gap-1.5 pt-2">
<button
className={btn}
onClick={() =>
void api.publishGallery(g.id, !g.publishedAt).then(load, (err) => setNote(errorText(err)))
}
>
{g.publishedAt ? t.shop.unpublish : t.shop.publish}
</button>
<button className={btn} onClick={() => setEditing(g)}>
{t.shop.edit}
</button>
{url && g.publishedAt && (
<a className={`${btn} inline-flex items-center`} href={url} target="_blank" rel="noreferrer">
{t.shop.open} ↗
</a>
)}
</div>
</div>
</article>
);
})}
</div>
{galleries?.length === 0 && <p className="px-4 pb-6 text-[13px] text-faint">{t.shop.noGalleries}</p>}
</section>
);
}
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<string | null>(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 (
<div className="m-4 space-y-3 border border-accent/50 bg-[#1e1e1f] p-4">
<div className="grid gap-3 sm:grid-cols-2">
<label className="block text-[11px] text-faint">
{t.shop.event}
<select
className={input}
value={form.eventId}
onChange={(e) => {
const ev = events.find((x) => x.id === e.target.value);
setForm({ ...form, eventId: e.target.value, title: form.title || ev?.title || "" });
}}
>
<option value="">—</option>
{events.map((e) => (
<option key={e.id} value={e.id}>
{e.title}
</option>
))}
</select>
</label>
<label className="block text-[11px] text-faint">
{t.shop.galleryTitle}
<input className={input} value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder={event?.title} />
</label>
<label className="block text-[11px] text-faint sm:col-span-2">
{t.shop.description}
<input className={input} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
</label>
<label className="block text-[11px] text-faint">
{t.shop.visibilityLabel}
<select className={input} value={form.visibility} onChange={(e) => setForm({ ...form, visibility: e.target.value as GalleryInput["visibility"] })}>
{(["PUBLIC", "UNLISTED", "PRIVATE"] as const).map((v) => (
<option key={v} value={v}>
{t.shop.visibility[v]}
</option>
))}
</select>
</label>
{form.visibility === "PRIVATE" && (
<label className="block text-[11px] text-faint">
{gallery?.hasPassword ? t.shop.newPassword : t.shop.password}
<input className={input} value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} minLength={4} />
</label>
)}
{!gallery && form.eventId && (
<label className="block text-[11px] text-faint">
{t.shop.fill}
<select className={input} value={form.fill} onChange={(e) => setForm({ ...form, fill: e.target.value as typeof form.fill })}>
<option value="picks">{t.shop.fillPicks}</option>
<option value="unrejected">{t.shop.fillUnrejected}</option>
<option value="none">{t.shop.fillNone}</option>
</select>
</label>
)}
</div>
<div className="flex flex-wrap gap-4 text-[12px] text-muted">
<label className="flex items-center gap-2">
<input type="checkbox" checked={form.forSale} onChange={(e) => setForm({ ...form, forSale: e.target.checked })} />
{t.shop.forSale}
</label>
<label className="flex items-center gap-2">
<input type="checkbox" checked={form.freeDownloads} onChange={(e) => setForm({ ...form, freeDownloads: e.target.checked })} />
{t.shop.freeDownloads}
</label>
</div>
{error && <p className="text-[12px] text-danger">{error}</p>}
<div className="flex justify-between gap-2">
{gallery ? (
<button
className="text-[12px] text-danger underline"
onClick={() => {
if (window.confirm(t.shop.confirmDelete)) void api.deleteGallery(gallery.id).then(onDone, (err) => setError(errorText(err)));
}}
>
{t.shop.delete}
</button>
) : (
<span />
)}
<span className="flex gap-2">
<button className={btn} onClick={onDone}>
{t.cancel}
</button>
<button className={primary} disabled={busy || !form.title.trim()} onClick={() => void save()}>
{t.save}
</button>
</span>
</div>
</div>
);
}
const ORDER_COLOR: Record<OrderView["status"], string> = { 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<OrderView[] | null>(null);
const [open, setOpen] = useState<string | null>(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 (
<section className="border border-line bg-panel">
<div className="panel-head">
<span>{t.shop.tabs.orders}</span>
<span className="font-mono normal-case tracking-normal text-faint">
{paid.length} · {eur(paid.reduce((s, o) => s + o.totalCents, 0))}
</span>
</div>
<table className="w-full border-collapse text-[12px]">
<thead>
<tr className="text-left text-[11px] uppercase tracking-wider text-faint">
<th className="border-b border-line px-3 py-2 font-semibold">N.º</th>
<th className="border-b border-line px-3 py-2 font-semibold">{t.shop.buyer}</th>
<th className="border-b border-line px-3 py-2 font-semibold">{t.shop.itemsCol}</th>
<th className="border-b border-line px-3 py-2 text-right font-semibold">Total</th>
<th className="border-b border-line px-3 py-2 font-semibold">{t.shop.status}</th>
</tr>
</thead>
<tbody>
{(orders ?? []).map((o) => (
<Fragment key={o.id}>
<tr className="cursor-pointer hover:bg-raised" onClick={() => setOpen(open === o.id ? null : o.id)}>
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px]">{o.number}</td>
<td className="border-b border-line px-3 py-1.5">
{o.name} <span className="text-faint">{o.email}</span>
</td>
<td className="border-b border-line px-3 py-1.5 text-faint">{o.items.length}</td>
<td className="border-b border-line px-3 py-1.5 text-right font-mono">{eur(o.totalCents)}</td>
<td className={`border-b border-line px-3 py-1.5 font-mono text-[11px] ${ORDER_COLOR[o.status]}`}>{t.shop.orderStatus[o.status]}</td>
</tr>
{open === o.id && (
<tr key={`${o.id}-items`}>
<td colSpan={5} className="border-b border-line bg-[#1e1e1f] px-3 py-2">
<ul className="space-y-1.5">
{o.items.map((i) => (
<li key={i.id} className="flex items-center gap-3">
{i.photo && <img src={api.absolute(i.photo.thumb)} alt="" className="h-10 w-14 object-cover" />}
<span className="flex-1">
{i.productName}
{i.quantity > 1 && ` × ${i.quantity}`} <span className="text-faint">{i.photo?.name}</span>
</span>
<span className="font-mono text-[11px] text-faint">{t.shop.itemStatus[i.status]}</span>
{i.kind === "PRINT" && i.status !== "SHIPPED" && (o.status === "PAID" || o.status === "FULFILLED") && (
<button className={btn} onClick={() => void api.markShipped(o.id, i.id).then(replace)}>
{t.shop.markShipped}
</button>
)}
</li>
))}
</ul>
<p className="mt-2 font-mono text-[11px] text-faint">
{o.reverseCharge ? `${t.shop.reverseCharge} ${o.vatNumber}` : `IVA ${eur(o.vatCents)}`} · {o.country}
{o.items.some((i) => i.status === "FAILED") && (
<button className="ml-3 underline" onClick={() => void api.retryOrder(o.id).then(replace)}>
{t.retry}
</button>
)}
</p>
</td>
</tr>
)}
</Fragment>
))}
</tbody>
</table>
{orders?.length === 0 && <p className="p-6 text-center text-[13px] text-faint">{t.shop.noOrders}</p>}
</section>
);
}
function Products({ orgId }: { orgId: string }) {
const { api } = useAuth();
const [products, setProducts] = useState<ProductSummary[]>([]);
const [draft, setDraft] = useState({ kind: "DIGITAL" as ProductSummary["kind"], name: "", price: "", longEdge: "2048", printSize: "", leadDays: "3" });
const [error, setError] = useState<string | null>(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 (
<section className="border border-line bg-panel">
<div className="panel-head">
<span>{t.shop.tabs.products}</span>
</div>
<p className="px-4 pt-3 text-[12px] text-faint">{t.shop.productsHelp}</p>
<table className="mt-2 w-full border-collapse text-[12px]">
<tbody>
{products.map((p) => (
<tr key={p.id} className={p.active ? "" : "opacity-50"}>
<td className="border-b border-line px-3 py-1.5 font-mono text-[10px] text-faint">{p.kind === "DIGITAL" ? "JPEG" : t.shop.print}</td>
<td className="border-b border-line px-3 py-1.5">
{p.name} <span className="text-faint">{p.kind === "DIGITAL" ? (p.longEdge ? `${p.longEdge} px` : t.shop.fullSize) : `${p.printSize ?? ""}${p.leadDays ? ` · ${p.leadDays} dias` : ""}`}</span>
</td>
<td className="border-b border-line px-3 py-1.5 text-right">
<input
aria-label={`Preço ${p.name}`}
className="h-7 w-20 border border-black bg-[#161617] px-2 text-right font-mono text-[12px]"
defaultValue={(p.priceCents / 100).toFixed(2)}
onBlur={(e) => {
const v = cents(e.target.value);
if (Number.isFinite(v) && v !== p.priceCents) void api.updateProduct(p.id, { priceCents: v }).then(load);
}}
/>{" "}
€
</td>
<td className="border-b border-line px-3 py-1.5 text-right">
<button className={btn} onClick={() => void api.updateProduct(p.id, { active: !p.active }).then(load)}>
{p.active ? t.shop.disable : t.shop.enable}
</button>
</td>
</tr>
))}
</tbody>
</table>
<div className="grid gap-2 p-4 sm:grid-cols-[110px_1fr_110px_110px_auto]">
<select className={input} value={draft.kind} onChange={(e) => setDraft({ ...draft, kind: e.target.value as ProductSummary["kind"] })} aria-label="Tipo">
<option value="DIGITAL">JPEG</option>
<option value="PRINT">{t.shop.print}</option>
</select>
<input className={input} placeholder={t.shop.productName} value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
{draft.kind === "DIGITAL" ? (
<input className={input} placeholder="px (0 = original)" value={draft.longEdge} onChange={(e) => setDraft({ ...draft, longEdge: e.target.value })} />
) : (
<input className={input} placeholder="15x20" value={draft.printSize} onChange={(e) => setDraft({ ...draft, printSize: e.target.value })} />
)}
<input className={input} placeholder="€" value={draft.price} onChange={(e) => setDraft({ ...draft, price: e.target.value })} />
<button
className={primary}
disabled={!draft.name || !draft.price}
onClick={() =>
void api
.createProduct(orgId, {
kind: draft.kind,
name: draft.name,
priceCents: cents(draft.price),
...(draft.kind === "DIGITAL" ? { longEdge: Number(draft.longEdge) || 0 } : { printSize: draft.printSize || null, leadDays: Number(draft.leadDays) || null }),
active: true,
position: products.length + 1,
})
.then(() => {
setDraft({ ...draft, name: "", price: "" });
setError(null);
load();
}, (err) => setError(errorText(err)))
}
>
{t.shop.add}
</button>
</div>
{error && <p className="px-4 pb-3 text-[12px] text-danger">{error}</p>}
</section>
);
}
function Sites({ orgId, isOwner }: { orgId: string; isOwner: boolean }) {
const { api } = useAuth();
const [sites, setSites] = useState<SiteInfo[]>([]);
const [settings, setSettings] = useState<ShopSettings | null>(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<string | null>(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 (
<>
<section className="border border-line bg-panel">
<div className="panel-head">
<span>{t.shop.sites}</span>
</div>
<p className="px-4 pt-3 text-[12px] text-faint">{t.shop.sitesHelp}</p>
<ul className="divide-y divide-line px-4 py-2 text-[13px]">
{sites.map((s) => (
<li key={s.id} className="flex items-center justify-between gap-3 py-2">
<span>
{s.name} <span className="font-mono text-[11px] text-faint">{s.domain}</span>
</span>
<span className="flex items-center gap-2">
<select className="h-7 border border-black bg-[#161617] px-2 text-[12px]" value={s.skin} onChange={(e) => void api.updateSite(s.id, { skin: e.target.value as SiteInfo["skin"] }).then(load)} aria-label={`Aspeto de ${s.name}`}>
<option value="photoreport">PhotoReport</option>
<option value="shootyourmove">ShootYourMove</option>
</select>
<button className="text-[12px] text-faint underline hover:text-danger" onClick={() => window.confirm(t.shop.confirmDelete) && void api.deleteSite(s.id).then(load)}>
{t.shop.delete}
</button>
</span>
</li>
))}
</ul>
<div className="grid gap-2 px-4 pb-4 sm:grid-cols-[1fr_1fr_160px_auto]">
<input className={input} placeholder="photoreport.pt" value={draft.domain} onChange={(e) => setDraft({ ...draft, domain: e.target.value })} aria-label={t.shop.domain} />
<input className={input} placeholder={t.shop.siteName} value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
<select className={input} value={draft.skin} onChange={(e) => setDraft({ ...draft, skin: e.target.value as SiteInfo["skin"] })} aria-label="Aspeto">
<option value="photoreport">PhotoReport</option>
<option value="shootyourmove">ShootYourMove</option>
</select>
<button
className={primary}
disabled={!draft.domain || !draft.name}
onClick={() =>
void api.createSite(orgId, { ...draft, settings: {} }).then(() => {
setDraft({ domain: "", skin: "photoreport", name: "" });
setNote(null);
load();
}, (err) => setNote(errorText(err)))
}
>
{t.shop.add}
</button>
</div>
</section>
<section className="border border-line bg-panel">
<div className="panel-head">
<span>{t.shop.payments}</span>
<span className={`normal-case tracking-normal ${settings?.stripeConfigured && settings.webhookConfigured ? "text-ok" : "text-faint"}`}>
{settings?.stripeConfigured && settings.webhookConfigured ? t.shop.paymentsOn : t.shop.paymentsOff}
</span>
</div>
<div className="grid gap-3 p-4 sm:grid-cols-3">
<label className="block text-[11px] text-faint">
{t.shop.legalName}
<input className={input} value={pay.legalName} disabled={!isOwner} onChange={(e) => setPay({ ...pay, legalName: e.target.value })} />
</label>
<label className="block text-[11px] text-faint">
NIF
<input className={input} value={pay.vatNumber} disabled={!isOwner} onChange={(e) => setPay({ ...pay, vatNumber: e.target.value })} />
</label>
<label className="block text-[11px] text-faint">
{t.shop.vatRate}
<input className={input} value={pay.vatRate} disabled={!isOwner} onChange={(e) => setPay({ ...pay, vatRate: e.target.value })} />
</label>
<label className="block text-[11px] text-faint">
{t.shop.stripeKey} {settings?.stripeConfigured && <span className="text-ok">✓</span>}
<input className={input} type="password" placeholder="sk_live_…" value={pay.stripeSecretKey} disabled={!isOwner} onChange={(e) => setPay({ ...pay, stripeSecretKey: e.target.value })} autoComplete="off" />
</label>
<label className="block text-[11px] text-faint">
{t.shop.webhookSecret} {settings?.webhookConfigured && <span className="text-ok">✓</span>}
<input className={input} type="password" placeholder="whsec_…" value={pay.stripeWebhookSecret} disabled={!isOwner} onChange={(e) => setPay({ ...pay, stripeWebhookSecret: e.target.value })} autoComplete="off" />
</label>
<div className="text-[11px] text-faint">
{t.shop.webhookUrl}
<p className="mt-1 break-all bg-[#161617] p-2 font-mono text-[10.5px] text-ink">{settings ? api.absolute(settings.webhookUrl) : "…"}</p>
</div>
</div>
<p className="px-4 text-[11px] text-faint">{t.shop.paymentsHelp}</p>
{note && <p className="px-4 pt-2 text-[12px] text-danger">{note}</p>}
{isOwner && (
<div className="flex justify-end p-4">
<button
className={primary}
onClick={() =>
void api
.updateShopSettings(orgId, {
legalName: pay.legalName || null,
vatNumber: pay.vatNumber || null,
vatRate: Number(pay.vatRate.replace(",", ".")),
...(pay.stripeSecretKey && { stripeSecretKey: pay.stripeSecretKey }),
...(pay.stripeWebhookSecret && { stripeWebhookSecret: pay.stripeWebhookSecret }),
})
.then(() => {
setPay((p) => ({ ...p, stripeSecretKey: "", stripeWebhookSecret: "" }));
setNote(null);
load();
}, (err) => setNote(errorText(err)))
}
>
{t.save}
</button>
</div>
)}
</section>
</>
);
}
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+17
View File
@@ -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;
+26
View File
@@ -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"
}
}
+156
View File
@@ -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<string, string> = {
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<string | null>(null);
const [busy, setBusy] = useState(false);
const total = cartTotal(cart);
if (!cart.lines.length) {
return (
<p className="empty">
O carrinho está vazio. <Link href="/" style={{ color: "var(--accent)" }}>Ver galerias</Link>
</p>
);
}
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 (
<div className="columns">
<section>
<p className="kicker">{cart.galleryTitle}</p>
<div className="lines">
{cart.lines.map((l, i) => (
<div className="line" key={`${l.photoId}-${l.productId}`}>
<img src={l.thumb} alt="" />
<div>
<strong>{l.productName}</strong>
<div className="meta">{l.kind === "DIGITAL" ? "Download" : "Impressão"}</div>
{l.kind === "PRINT" && (
<label className="meta">
Quantidade{" "}
<input type="number" min={1} max={50} value={l.quantity} onChange={(e) => setQty(i, Number(e.target.value))} style={{ width: 56 }} />
</label>
)}
</div>
<div style={{ textAlign: "right" }}>
<div className="meta">{eur(l.priceCents * l.quantity)}</div>
<button className="meta" style={{ background: "none", border: 0, cursor: "pointer", textDecoration: "underline" }} onClick={() => setQty(i, 0)}>
remover
</button>
</div>
</div>
))}
</div>
<div className="totals">
<span>IVA incluído</span>
<strong>{eur(total)}</strong>
</div>
</section>
<form className="form" onSubmit={submit}>
<h2 className="title h2">Os teus dados</h2>
<label className="field">
Nome
<input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required minLength={2} autoComplete="name" />
</label>
<label className="field">
Email (enviamos para aqui o link das fotos)
<input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required autoComplete="email" />
</label>
<label className="field">
País
<select value={form.country} onChange={(e) => setForm({ ...form, country: e.target.value })}>
{COUNTRIES.map(([code, name]) => (
<option key={code} value={code}>
{name}
</option>
))}
</select>
</label>
<label className="field">
NIF / VAT (opcional, para fatura em nome de empresa)
<input value={form.vatNumber} onChange={(e) => setForm({ ...form, vatNumber: e.target.value })} placeholder="PT123456789" />
</label>
{error && (
<p className="error" role="alert">
{error}
</p>
)}
<button className="button" disabled={busy}>
{total === 0 ? "Obter fotos" : `Pagar ${eur(total)}`}
</button>
<p className="meta">Pagamento seguro por cartão, Multibanco ou MB WAY.</p>
</form>
</div>
);
}
+15
View File
@@ -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 (
<main className="wrap">
<header className="gallery-head">
<h1 className="title h1">Carrinho</h1>
</header>
<Checkout />
</main>
);
}
@@ -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;
}
+81
View File
@@ -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<string, string> = {
PENDING: "À espera do pagamento",
PAID: "Paga",
FULFILLED: "Concluída",
CANCELLED: "Cancelada",
REFUNDED: "Reembolsada",
};
const ITEM: Record<string, string> = { 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 (
<main className="wrap">
<header className="gallery-head">
<span className="kicker">Encomenda {order.number}</span>
<h1 className="title h1">{STATUS[order.status]}</h1>
<span className="meta">
{longDate(order.createdAt)} · {order.email}
</span>
</header>
{order.status === "PENDING" && (
<p className="notice" style={{ marginTop: 24 }}>
Assim que o pagamento for confirmado (por Multibanco pode demorar algumas horas) as fotos aparecem aqui e enviamos-te um email.
{order.checkoutUrl && (
<>
{" "}
<a href={order.checkoutUrl} style={{ color: "var(--accent)" }}>
Voltar ao pagamento
</a>
</>
)}
</p>
)}
<div className="lines" style={{ marginTop: 24 }}>
{order.items.map((i) => (
<div className="line" key={i.id}>
{i.photo ? <img src={i.photo.thumb} alt="" /> : <span />}
<div>
<strong>{i.productName}</strong>
{i.quantity > 1 && <span className="meta"> × {i.quantity}</span>}
<div className="meta">{ITEM[i.status]}</div>
</div>
<div style={{ textAlign: "right" }}>
{i.download ? (
<a className="button" href={i.download}>
Descarregar
</a>
) : (
<span className="meta">{eur(i.totalCents)}</span>
)}
</div>
</div>
))}
</div>
<div className="totals">
{order.reverseCharge ? <span>Autoliquidação do IVA ({order.vatNumber})</span> : <span>IVA incluído: {eur(order.vatCents)}</span>}
<strong>{eur(order.totalCents)}</strong>
</div>
{working && <Refresh seconds={5} />}
</main>
);
}
@@ -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<number | null>(null);
const [query, setQuery] = useState("");
const [added, setAdded] = useState<string | null>(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 (
<>
<div className="toolbar">
{hasNames && (
<label className="field" style={{ minWidth: 260 }}>
<span className="meta">Procurar jogador</span>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Nome" />
</label>
)}
<span className="meta" style={{ marginLeft: "auto" }}>
{photos.length} de {gallery.photos.length}
</span>
{cart.gallery === gallery.slug && cart.lines.length > 0 && (
<Link className="button" href="/carrinho">
Ver carrinho ({cart.lines.length})
</Link>
)}
</div>
<div className="grid">
{photos.map((p, i) => (
<button key={p.id} className="tile" onClick={() => setOpen(i)} aria-label={`Ver foto ${i + 1}${p.players.length ? `: ${p.players.join(", ")}` : ""}`}>
<img src={p.thumb} alt="" loading="lazy" />
{inCart.has(p.id) && <span className="in-cart">no carrinho</span>}
{p.players.length > 0 && <span className="names">{p.players.join(", ")}</span>}
</button>
))}
</div>
{photo && (
<div className="lightbox" role="dialog" aria-modal="true" aria-label="Foto">
<div className="stage">
<img src={photo.preview} alt={photo.players.join(", ")} />
<button className="close" onClick={() => setOpen(null)} aria-label="Fechar">
×
</button>
{open! > 0 && (
<button className="arrow prev" onClick={() => move(-1)} aria-label="Anterior">
‹
</button>
)}
{open! < photos.length - 1 && (
<button className="arrow next" onClick={() => move(1)} aria-label="Seguinte">
›
</button>
)}
</div>
<aside className="side">
<span className="kicker">
Foto {open! + 1} de {photos.length}
</span>
{photo.players.length > 0 && <h2 className="title" style={{ fontSize: 30, marginTop: 6 }}>{photo.players.join(", ")}</h2>}
{products.length === 0 ? (
<p className="meta" style={{ marginTop: 16 }}>
Esta galeria não tem fotos à venda.
</p>
) : (
<div className="products">
{products.map((p) => (
<button
key={p.id}
className="product"
onClick={() => {
addToCart(
{ slug: gallery.slug, title: gallery.title, token },
{ photoId: photo.id, productId: p.id, productName: p.name, priceCents: free(p) ? 0 : p.priceCents, kind: p.kind, quantity: 1, thumb: photo.thumb },
);
setAdded(`${p.name} adicionada ao carrinho`);
setTimeout(() => setAdded(null), 2500);
}}
>
<span>
{p.name}
<br />
<span className="meta">{p.kind === "DIGITAL" ? (p.longEdge ? `JPEG ${p.longEdge} px` : "JPEG tamanho original") : `Impressão${p.leadDays ? ` · envio em ${p.leadDays} dias úteis` : ""}`}</span>
</span>
<span className="price">{free(p) ? "grátis" : eur(p.priceCents)}</span>
</button>
))}
</div>
)}
<p className="meta" role="status" aria-live="polite">
{added}
</p>
{cart.gallery === gallery.slug && cart.lines.length > 0 && (
<Link className="button" href="/carrinho" style={{ width: "100%", marginTop: 8 }}>
Ver carrinho
</Link>
)}
</aside>
</div>
)}
</>
);
}
@@ -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<string | null>(null);
const [busy, setBusy] = useState(false);
return (
<form
className="form"
style={{ padding: "32px 0 64px" }}
onSubmit={async (e) => {
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();
}}
>
<p className="lead">Esta galeria é privada. Usa a palavra-passe que recebeste.</p>
<label className="field">
Palavra-passe
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" required />
</label>
{error && (
<p className="error" role="alert">
{error}
</p>
)}
<button className="button" disabled={busy || !password}>
Abrir galeria
</button>
</form>
);
}
+50
View File
@@ -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<Metadata> {
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 (
<main className="wrap">
<header className="gallery-head">
<span className="kicker">{[e?.competition, e ? longDate(e.startsAt) : null].filter(Boolean).join(" · ")}</span>
<h1 className="title h1">{gallery.title || (e ? eventTitle(e) : "")}</h1>
<span className="meta">
{gallery.photoCount} fotos{e?.venue ? ` · ${e.venue}` : ""}
{gallery.freeDownloads ? " · download gratuito" : ""}
</span>
{gallery.description && <p className="lead">{gallery.description}</p>}
</header>
{gallery.locked ? (
<Unlock slug={slug} />
) : (
<GalleryView gallery={gallery} products={products.filter((p) => gallery.forSale || (gallery.freeDownloads && p.kind === "DIGITAL"))} token={token} />
)}
</main>
);
}
+485
View File
@@ -0,0 +1,485 @@
/* Two skins over one structure. The skin is set on <html data-skin> 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;
}
+67
View File
@@ -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<Metadata> {
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 (
<html lang="pt">
<body>
<main className="wrap empty">Este domínio não tem site configurado.</main>
</body>
</html>
);
}
return (
<html lang="pt" data-skin={site.skin} style={site.settings.accent ? ({ "--accent": site.settings.accent } as React.CSSProperties) : undefined}>
<body>
<header className="bar">
<div className="wrap">
<Link href="/">
<Logo skin={site.skin} name={site.name} />
</Link>
<nav className="nav" aria-label="Principal">
<Link href="/">Galerias</Link>
<CartLink />
</nav>
</div>
</header>
{children}
<footer className="footer">
<div className="wrap">
<span>
© {new Date().getFullYear()} {site.name}
</span>
<span style={{ display: "flex", gap: 16 }}>
{site.settings.contactEmail && <a href={`mailto:${site.settings.contactEmail}`}>{site.settings.contactEmail}</a>}
{site.settings.instagram && <a href={`https://instagram.com/${site.settings.instagram.replace(/^@/, "")}`}>Instagram</a>}
</span>
</div>
</footer>
</body>
</html>
);
}
+44
View File
@@ -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 (
<main>
<section className="hero">
<div className="wrap">
<span className="kicker">{site.skin === "shootyourmove" ? "Cada jogada, a tua fotografia" : "Agência de fotografia de desporto"}</span>
<h1 className="title h1">{site.settings.tagline ?? "As fotos do jogo"}</h1>
<p className="lead">Encontra o teu jogo, escolhe as fotos e descarrega-as em alta resolução, ou recebe-as impressas.</p>
</div>
</section>
<div className="wrap">
<div className="section-head">
<h2 className="title h2">Galerias</h2>
<span className="meta">{galleries.length} publicadas</span>
</div>
{galleries.length === 0 ? (
<p className="empty">Ainda não há galerias publicadas.</p>
) : (
<div className="cards">
{galleries.map((g) => (
<Link key={g.slug} href={`/galeria/${g.slug}`} className="card">
<div className="frame">{g.cover ? <img src={g.cover} alt="" loading="lazy" /> : null}</div>
<span className="kicker">
{[g.event?.competition, g.event ? longDate(g.event.startsAt) : longDate(g.publishedAt)].filter(Boolean).join(" · ")}
</span>
<h3 className="title">{g.title || (g.event ? eventTitle(g.event) : "")}</h3>
<span className="meta">
{g.photoCount} fotos{g.event?.venue ? ` · ${g.event.venue}` : ""}
</span>
</Link>
))}
</div>
)}
</div>
</main>
);
}
+14
View File
@@ -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 (
<Link href="/carrinho" aria-label={`Carrinho, ${count} artigos`}>
Carrinho{count > 0 && <span className="cart-count">{count}</span>}
</Link>
);
}
+30
View File
@@ -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 (
<span className="brand" aria-label={name}>
<svg width="30" height="30" viewBox="0 0 30 30" aria-hidden="true">
<path d="M2 10V2h8M20 2h8v8M28 20v8h-8M10 28H2v-8" fill="none" stroke="currentColor" strokeWidth="2.5" />
<circle cx="15" cy="15" r="4.5" fill="#ff0a0a" />
</svg>
<span>
Shoot<span style={{ color: "var(--accent)" }}>Your</span>Move
</span>
</span>
);
}
return (
<span className="brand" aria-label={name}>
<svg width="26" height="26" viewBox="0 0 26 26" aria-hidden="true">
<rect x="1.5" y="1.5" width="23" height="23" fill="none" stroke="currentColor" strokeWidth="2.5" />
<rect x="8" y="8" width="10" height="10" fill="#1f6feb" />
</svg>
<span>
{name.replace(/\.pt$/i, "")}
<small>.pt</small>
</span>
</span>
);
}
+33
View File
@@ -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<string> {
const h = await headers();
return (h.get("x-forwarded-host") ?? h.get("host") ?? "localhost").split(",")[0]!.trim();
}
async function get<T>(path: string, extra: Record<string, string> = {}): Promise<T> {
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<SiteInfo>("/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<PublicGallery> {
const token = (await cookies()).get(galleryCookie(slug))?.value;
return get<PublicGallery>(`/v1/public/galleries/${encodeURIComponent(slug)}`, token ? { "x-gallery-token": token } : {});
}
export const getOrder = (id: string, token: string) => get<OrderView>(`/v1/public/orders/${id}?t=${encodeURIComponent(token)}`);
export const galleryCookie = (slug: string) => `gt_${slug.replace(/[^a-z0-9-]/g, "")}`;
+85
View File
@@ -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);
}
+10
View File
@@ -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");
});
});
+9
View File
@@ -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;
}
+22
View File
@@ -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"]
}
+24 -2
View File
@@ -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 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. 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 ## Faces
Only for organizations whose owner switched it on with a recorded legal basis (biometric data, GDPR art. 9). 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). (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 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). 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, 3. Galleries and sales (done: both storefront skins, public/unlisted/private galleries, watermarks, cart,
payouts, affiliates, press accounts, data import dry runs (end-to-end test purchase with invoice and payout). 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). 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 5. Player identification: faces (done: detect, group, confirm, propagate, suggest across events), jersey
numbers with squads, global search (parity with old projects validated). numbers with squads, global search (parity with old projects validated).
+6
View File
@@ -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 every app deploy then rebuilds `apps/app/public/engine/` (`infra/engine/build-wasm.sh`). Serve `.wasm` as
`application/wasm`. `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 ## Desktop and print agent
Not deployed by webhook. A tag `desktop-v*` / `agent-v*` triggers Gitea Actions to build installers per OS and Not deployed by webhook. A tag `desktop-v*` / `agent-v*` triggers Gitea Actions to build installers per OS and
+16 -1
View File
@@ -73,13 +73,28 @@ deploy_app() {
ls -1dt "$WEB_ROOT"/releases/* 2>/dev/null | tail -n +6 | xargs -r rm -rf 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"; } deploy_pending() { log "service $SERVICE has no deployable build yet; nothing to do"; }
run_service() { run_service() {
case "$SERVICE" in case "$SERVICE" in
api) deploy_api "$1" ;; api) deploy_api "$1" ;;
app) deploy_app "$1" ;; app) deploy_app "$1" ;;
site | workers | ml) deploy_pending ;; site) deploy_site "$1" ;;
workers | ml) deploy_pending ;;
*) die "unknown service: $SERVICE" ;; *) die "unknown service: $SERVICE" ;;
esac esac
} }
+14
View File
@@ -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" },
},
],
};
+1
View File
@@ -1,3 +1,4 @@
export * from "./commands.js"; export * from "./commands.js";
export * from "./controls.js"; export * from "./controls.js";
export * from "./library.js"; export * from "./library.js";
export * from "./shop.js";
+196
View File
@@ -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<typeof SiteInput>;
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<typeof GalleryInput>;
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<typeof GalleryPhotosChange>;
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<typeof ProductInput>;
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<typeof CreateOrder>;
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;
}[];
}
+84 -2
View File
@@ -1,5 +1,5 @@
import type { ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, Module, PhotoPatch, PhotoSummary, PostEdits } from "@photoreport/contracts"; 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, SquadPerson, DeviceGrant, FtpAccount, EventInput, EventSummary, IptcIssue, Me, Member, PhotoQuery, Role } from "./types.js"; 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 * 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 }); 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<GallerySummary>("POST", `/v1/orgs/${orgId}/galleries`, input);
}
updateGallery(id: string, input: Partial<GalleryInput>) {
return this.request<GallerySummary>("PATCH", `/v1/galleries/${id}`, input);
}
deleteGallery(id: string) {
return this.request<void>("DELETE", `/v1/galleries/${id}`);
}
changeGalleryPhotos(id: string, change: Partial<GalleryPhotosChange>) {
return this.request<GallerySummary>("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<GallerySummary>("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<ProductSummary>("POST", `/v1/orgs/${orgId}/products`, input);
}
updateProduct(id: string, patch: Partial<Pick<ProductSummary, "name" | "priceCents" | "active" | "position" | "leadDays" | "longEdge" | "printSize">>) {
return this.request<ProductSummary>("PATCH", `/v1/products/${id}`, patch);
}
deleteProduct(id: string) {
return this.request<void>("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<SiteInfo>("POST", `/v1/orgs/${orgId}/sites`, input);
}
updateSite(id: string, input: Partial<SiteInput>) {
return this.request<SiteInfo>("PATCH", `/v1/sites/${id}`, input);
}
deleteSite(id: string) {
return this.request<void>("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<OrderView>("POST", `/v1/orders/${orderId}/items/${itemId}/shipped`);
}
retryOrder(orderId: string) {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/retry`);
}
getShopSettings(orgId: string) {
return this.request<ShopSettings>("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 ---------------------------------------------------------------------------------------- // ---- develop ----------------------------------------------------------------------------------------
/** Snapshot plus the ops after it; with `since`, only the ops after that op-log position. */ /** Snapshot plus the ops after it; with `since`, only the ops after that op-log position. */
+11
View File
@@ -155,3 +155,14 @@ export interface PhotoFace {
person: PersonSummary | null; person: PersonSummary | null;
suggestion: 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;
}
+213 -2
View File
@@ -62,6 +62,9 @@ importers:
jose: jose:
specifier: ^6.2.12 specifier: ^6.2.12
version: 6.2.12 version: 6.2.12
nodemailer:
specifier: ^7.0.13
version: 7.0.13
pg: pg:
specifier: ^8.23.1 specifier: ^8.23.1
version: 8.23.1 version: 8.23.1
@@ -78,6 +81,9 @@ importers:
specifier: ^4.6.5 specifier: ^4.6.5
version: 4.6.5 version: 4.6.5
devDependencies: devDependencies:
'@types/nodemailer':
specifier: ^8.0.2
version: 8.0.2
'@types/pg': '@types/pg':
specifier: ^8.23.1 specifier: ^8.23.1
version: 8.23.1 version: 8.23.1
@@ -161,6 +167,37 @@ importers:
specifier: ^2.12.2 specifier: ^2.12.2
version: 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/[email protected])([email protected]([email protected]))([email protected])
react:
specifier: ^19.3.0
version: 19.3.0
react-dom:
specifier: ^19.3.0
version: 19.3.0([email protected])
devDependencies:
'@types/react':
specifier: ^19.3.0
version: 19.3.0
'@types/react-dom':
specifier: ^19.3.0
version: 19.3.0(@types/[email protected])
infra/deploy-receiver: {} infra/deploy-receiver: {}
packages/contracts: packages/contracts:
@@ -717,6 +754,57 @@ packages:
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
'@next/[email protected]':
resolution: {integrity: sha512-NJBz9q10LU9h3KjHLEbdgWIV+ow/x+MYzKBRfqhm9/QmML3tPMhYmXF/UIV9SDVCNtOqFNc5oX7kZqeiigMCEA==}
'@next/[email protected]':
resolution: {integrity: sha512-So8eoJxIcXw/TexNUvvh3uY72J9nDo5BpJsAwUKx+FK57CrWXg6RqVufV7U9OT3BO+siMzJ2FuAwBhaHoPlLGg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@next/[email protected]':
resolution: {integrity: sha512-jImzLUTClVWKhP91e5sgDumjxCLhaFSt7DuN5cnRYw99Dppxxhhq5jKRyDa2aTv3JE7dQmTSTsY3EFkSOp9Pog==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@next/[email protected]':
resolution: {integrity: sha512-CaWd+T/Lud2BmZbrsa1CzCnIOdU3YX9Nuk89virZaSB1O+C+8Yrrevgmnl68u4dvZIfOAzQ77S+Njrq7v1XwSA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
'@next/[email protected]':
resolution: {integrity: sha512-97AyKI34yjpaudlkWHswAf7c1PjWQAC7lLyrw3R5K+bq834EOA+9IG68rIVy0VqrqGjtPSMjJmMmgeJ3wHR5og==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
'@next/[email protected]':
resolution: {integrity: sha512-eVtuOCew1sBPV7BEgxy7qxuVyqoU3tJIS/xDZwa1/NiQ4Q0LM2JMH7rny+/uVIN6hsQ3PTb0hTQWypA0L2QxtA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
'@next/[email protected]':
resolution: {integrity: sha512-EiUXADp+Z+OdQnSqbX10YgOSUrs0CXVODoTfySfsP2jdhngn9bq5RJd376FJzqMPe/XX25FMr1aXtYUVPA0qDw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
'@next/[email protected]':
resolution: {integrity: sha512-HPl41fgkC4kdM5CCIoqNW6KlKEj1N+xS6bjNFFxDNKooUNUu09frgD948zo95TPw/C3XINZpkdkBGNU2RhjEnw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@next/[email protected]':
resolution: {integrity: sha512-TgmJ5ginKr34RPsz01/swpYtFBxh51d66jM26aytpE6NIypU5KtBVI8C2hJjUNpWr7v6sWj8a6+og2MyntcnpA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@node-rs/[email protected]': '@node-rs/[email protected]':
resolution: {integrity: sha512-c11BOrPLBWNC1cDyzGB+Bil+flmxfZbB2hv8EhcobmAsFKMyqkHPNhUY4qhcjv1U+4+Vmw4G8H+l224iO2g/Dw==} resolution: {integrity: sha512-c11BOrPLBWNC1cDyzGB+Bil+flmxfZbB2hv8EhcobmAsFKMyqkHPNhUY4qhcjv1U+4+Vmw4G8H+l224iO2g/Dw==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
@@ -1076,6 +1164,9 @@ packages:
'@standard-schema/[email protected]': '@standard-schema/[email protected]':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
'@swc/[email protected]':
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}
'@tailwindcss/[email protected]': '@tailwindcss/[email protected]':
resolution: {integrity: sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==} resolution: {integrity: sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==}
@@ -1340,6 +1431,9 @@ packages:
'@types/[email protected]': '@types/[email protected]':
resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==}
'@types/[email protected]':
resolution: {integrity: sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==}
'@types/[email protected]': '@types/[email protected]':
resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==} resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==}
@@ -1518,6 +1612,9 @@ packages:
[email protected]: [email protected]:
resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==} resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}
[email protected]:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
[email protected]: [email protected]:
resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==} resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==}
@@ -2014,10 +2111,35 @@ packages:
resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==} resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==}
engines: {node: '>= 0.6'} engines: {node: '>= 0.6'}
[email protected]:
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
[email protected]: [email protected]:
resolution: {integrity: sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg==} resolution: {integrity: sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg==}
engines: {node: '>=18'} engines: {node: '>=18'}
[email protected]:
resolution: {integrity: sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==}
engines: {node: '>=6.0.0'}
[email protected]: [email protected]:
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
@@ -2100,6 +2222,10 @@ packages:
[email protected]: [email protected]:
resolution: {integrity: sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==} resolution: {integrity: sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==}
[email protected]:
resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==}
engines: {node: ^10 || ^12 || >=14}
[email protected]: [email protected]:
resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==} resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==}
engines: {node: ^10 || ^12 || >=14} engines: {node: ^10 || ^12 || >=14}
@@ -2332,6 +2458,19 @@ packages:
[email protected]: [email protected]:
resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==}
[email protected]:
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
[email protected]: [email protected]:
resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==} resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==}
@@ -2999,6 +3138,32 @@ snapshots:
'@napi-rs/[email protected]': '@napi-rs/[email protected]':
optional: true optional: true
'@next/[email protected]': {}
'@next/[email protected]':
optional: true
'@next/[email protected]':
optional: true
'@next/[email protected]':
optional: true
'@next/[email protected]':
optional: true
'@next/[email protected]':
optional: true
'@next/[email protected]':
optional: true
'@next/[email protected]':
optional: true
'@next/[email protected]':
optional: true
'@node-rs/[email protected]': '@node-rs/[email protected]':
optional: true optional: true
@@ -3301,6 +3466,10 @@ snapshots:
'@standard-schema/[email protected]': {} '@standard-schema/[email protected]': {}
'@swc/[email protected]':
dependencies:
tslib: 2.8.1
'@tailwindcss/[email protected]': '@tailwindcss/[email protected]':
dependencies: dependencies:
'@jridgewell/remapping': 2.3.5 '@jridgewell/remapping': 2.3.5
@@ -3523,6 +3692,10 @@ snapshots:
dependencies: dependencies:
undici-types: 6.21.0 undici-types: 6.21.0
'@types/[email protected]':
dependencies:
'@types/node': 22.20.5
'@types/[email protected]': '@types/[email protected]':
dependencies: dependencies:
'@types/node': 22.20.5 '@types/node': 22.20.5
@@ -3762,6 +3935,8 @@ snapshots:
[email protected]: {} [email protected]: {}
[email protected]: {}
[email protected]: {} [email protected]: {}
[email protected]: {} [email protected]: {}
@@ -4247,8 +4422,34 @@ snapshots:
[email protected]: {} [email protected]: {}
[email protected](@types/[email protected])([email protected]([email protected]))([email protected]):
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([email protected])
styled-jsx: 5.1.6([email protected])
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/[email protected])
transitivePeerDependencies:
- '@babel/core'
- '@types/node'
- babel-plugin-macros
[email protected]: {} [email protected]: {}
[email protected]: {}
[email protected]: {} [email protected]: {}
[email protected]: {} [email protected]: {}
@@ -4332,6 +4533,12 @@ snapshots:
exsolve: 1.1.3 exsolve: 1.1.3
pathe: 2.0.3 pathe: 2.0.3
[email protected]:
dependencies:
nanoid: 3.3.20
picocolors: 1.1.1
source-map-js: 1.2.2
[email protected]: [email protected]:
dependencies: dependencies:
nanoid: 3.3.20 nanoid: 3.3.20
@@ -4592,6 +4799,11 @@ snapshots:
dependencies: dependencies:
js-tokens: 9.0.1 js-tokens: 9.0.1
[email protected]([email protected]):
dependencies:
client-only: 0.0.1
react: 19.3.0
[email protected]: {} [email protected]: {}
[email protected]: {} [email protected]: {}
@@ -4631,8 +4843,7 @@ snapshots:
dependencies: dependencies:
punycode: 2.3.1 punycode: 2.3.1
[email protected]: [email protected]: {}
optional: true
[email protected]: [email protected]:
dependencies: dependencies: