From 454247364fed87b60b6177f757dce39b955d4826 Mon Sep 17 00:00:00 2001 From: spark Date: Thu, 12 Nov 2026 00:14:14 +0000 Subject: [PATCH] feat(galleries): deliver a session as its own page on the site (#260) A client gallery is its own module. It is built from an event and its photographs and opens at /cliente/ on the events site. --- apps/api/.env.example | 6 + .../20261111224000_app_modules/migration.sql | 4 + .../migration.sql | 120 ++++ apps/api/prisma/schema.prisma | 145 ++++- apps/api/src/app.ts | 41 +- apps/api/src/config.ts | 22 +- apps/api/src/me/routes.ts | 35 +- apps/api/src/modules/access.test.ts | 19 + apps/api/src/modules/access.ts | 119 ++++ apps/api/src/orgs/routes.ts | 73 ++- apps/api/src/site-galleries/routes.ts | 131 ++++ apps/api/src/site-galleries/service.ts | 452 ++++++++++++++ apps/api/test/modules.test.ts | 85 +++ apps/app/src/App.tsx | 38 +- apps/app/src/auth.tsx | 5 + apps/app/src/i18n.ts | 111 ++++ apps/app/src/modules.test.ts | 13 + apps/app/src/modules.ts | 26 + apps/app/src/offline/siteGalleries.ts | 51 ++ apps/app/src/pages/MembersPage.tsx | 110 +++- apps/app/src/pages/Shell.tsx | 93 ++- apps/app/src/pages/SiteGalleriesPage.tsx | 580 ++++++++++++++++++ apps/app/src/pages/modules.test.tsx | 112 ++++ apps/site/package.json | 1 + apps/site/public/cliente/aisle.jpg | Bin 0 -> 212095 bytes apps/site/public/cliente/bride.jpg | Bin 0 -> 691432 bytes apps/site/public/cliente/ceremony.jpg | Bin 0 -> 254636 bytes apps/site/public/cliente/couple.jpg | Bin 0 -> 443402 bytes apps/site/public/cliente/cover.jpg | Bin 0 -> 239177 bytes apps/site/public/cliente/dance.jpg | Bin 0 -> 186048 bytes apps/site/public/cliente/dress.jpg | Bin 0 -> 109318 bytes apps/site/public/cliente/kiss.jpg | Bin 0 -> 172105 bytes apps/site/public/cliente/ready.jpg | Bin 0 -> 264360 bytes apps/site/public/cliente/rings.jpg | Bin 0 -> 157912 bytes apps/site/public/cliente/walk.jpg | Bin 0 -> 157518 bytes apps/site/src/app/cliente/ClientGallery.tsx | 362 +++++++++++ apps/site/src/app/cliente/[slug]/Unlock.tsx | 45 ++ apps/site/src/app/cliente/[slug]/page.tsx | 53 ++ apps/site/src/app/cliente/client-gallery.css | 519 ++++++++++++++++ apps/site/src/app/cliente/exemplo/page.tsx | 12 + apps/site/src/app/cliente/gallery.ts | 79 +++ apps/site/src/app/cliente/layout.tsx | 10 + apps/site/src/app/layout.tsx | 13 +- apps/site/src/lib/client-gallery-cookie.ts | 1 + apps/site/src/lib/client-gallery.ts | 18 + apps/site/src/middleware.ts | 2 +- docs/ARCHITECTURE.md | 12 + packages/contracts/src/desk.ts | 3 +- packages/contracts/src/index.ts | 2 + packages/contracts/src/modules.test.ts | 42 ++ packages/contracts/src/modules.ts | 74 +++ packages/contracts/src/site-gallery.test.ts | 34 + packages/contracts/src/site-gallery.ts | 274 +++++++++ packages/sdk/src/client.ts | 63 +- packages/sdk/src/types.ts | 20 +- pnpm-lock.yaml | 8 + 56 files changed, 3933 insertions(+), 105 deletions(-) create mode 100644 apps/api/prisma/migrations/20261111224000_app_modules/migration.sql create mode 100644 apps/api/prisma/migrations/20261111235000_site_galleries/migration.sql create mode 100644 apps/api/src/modules/access.test.ts create mode 100644 apps/api/src/modules/access.ts create mode 100644 apps/api/src/site-galleries/routes.ts create mode 100644 apps/api/src/site-galleries/service.ts create mode 100644 apps/api/test/modules.test.ts create mode 100644 apps/app/src/modules.test.ts create mode 100644 apps/app/src/modules.ts create mode 100644 apps/app/src/offline/siteGalleries.ts create mode 100644 apps/app/src/pages/SiteGalleriesPage.tsx create mode 100644 apps/app/src/pages/modules.test.tsx create mode 100644 apps/site/public/cliente/aisle.jpg create mode 100644 apps/site/public/cliente/bride.jpg create mode 100644 apps/site/public/cliente/ceremony.jpg create mode 100644 apps/site/public/cliente/couple.jpg create mode 100644 apps/site/public/cliente/cover.jpg create mode 100644 apps/site/public/cliente/dance.jpg create mode 100644 apps/site/public/cliente/dress.jpg create mode 100644 apps/site/public/cliente/kiss.jpg create mode 100644 apps/site/public/cliente/ready.jpg create mode 100644 apps/site/public/cliente/rings.jpg create mode 100644 apps/site/public/cliente/walk.jpg create mode 100644 apps/site/src/app/cliente/ClientGallery.tsx create mode 100644 apps/site/src/app/cliente/[slug]/Unlock.tsx create mode 100644 apps/site/src/app/cliente/[slug]/page.tsx create mode 100644 apps/site/src/app/cliente/client-gallery.css create mode 100644 apps/site/src/app/cliente/exemplo/page.tsx create mode 100644 apps/site/src/app/cliente/gallery.ts create mode 100644 apps/site/src/app/cliente/layout.tsx create mode 100644 apps/site/src/lib/client-gallery-cookie.ts create mode 100644 apps/site/src/lib/client-gallery.ts create mode 100644 packages/contracts/src/modules.test.ts create mode 100644 packages/contracts/src/modules.ts create mode 100644 packages/contracts/src/site-gallery.test.ts create mode 100644 packages/contracts/src/site-gallery.ts diff --git a/apps/api/.env.example b/apps/api/.env.example index 27698f9..085037c 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -17,6 +17,9 @@ REFRESH_TOKEN_TTL_DAYS=30 CORS_ORIGINS=https://app.next.photoreport.pt,tauri://localhost,http://tauri.localhost APP_PUBLIC_URL=https://app.next.photoreport.pt ALLOW_SIGNUP=false +# Workspace modules this server may offer (library,develop,metadata,delivery,siteGallery,shop,print,archive,faces,numbers). +# Unset: an organization can switch any of them on. A list here is the ceiling. +# PHOTOREPORT_APP_MODULES= # Library and ingest STORAGE_ROOT=/srv/photoreport-data/storage @@ -55,6 +58,9 @@ MAIL_FROM=PhotoReport # DESKTOP_RELEASES_TOKEN= # Public address of this API (installer links for the desktop updater). # API_PUBLIC_URL=https://api.next.photoreport.pt +# Public events site. A client gallery opens at /cliente/. +# Unset: api. becomes events.; any other API address uses http://localhost:3100. +# SITE_PUBLIC_URL=http://localhost:3100 # Errors to errors.bitreport.pt (BitReport's error hub; Paperclip picks them up and fixes them). The ingest key of # the "photoreport" project there; without it nothing is sent. API, worker and the browsers (through the API's diff --git a/apps/api/prisma/migrations/20261111224000_app_modules/migration.sql b/apps/api/prisma/migrations/20261111224000_app_modules/migration.sql new file mode 100644 index 0000000..db4aef9 --- /dev/null +++ b/apps/api/prisma/migrations/20261111224000_app_modules/migration.sql @@ -0,0 +1,4 @@ +-- Workspace modules. Null means "not chosen yet": the organization keeps the areas it already had, +-- and each person follows their role. Site galleries stay off until an admin turns that module on. +ALTER TABLE "organizations" ADD COLUMN "app_modules" JSONB; +ALTER TABLE "memberships" ADD COLUMN "app_modules" JSONB; diff --git a/apps/api/prisma/migrations/20261111235000_site_galleries/migration.sql b/apps/api/prisma/migrations/20261111235000_site_galleries/migration.sql new file mode 100644 index 0000000..844185f --- /dev/null +++ b/apps/api/prisma/migrations/20261111235000_site_galleries/migration.sql @@ -0,0 +1,120 @@ +-- A client gallery is its own delivery: a page on the site, not the sports shop and not a file send. +CREATE TABLE "site_galleries" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "event_id" UUID, + "created_by_id" UUID, + "title" TEXT NOT NULL, + "date_label" TEXT NOT NULL DEFAULT '', + "slug" TEXT NOT NULL, + "language" TEXT NOT NULL DEFAULT 'pt', + "password_hash" TEXT, + "favorites" BOOLEAN NOT NULL DEFAULT true, + "reviews" BOOLEAN NOT NULL DEFAULT false, + "design" JSONB NOT NULL, + "downloads" JSONB NOT NULL, + "cover_photo_id" UUID, + "published_at" TIMESTAMP(3), + "offline_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "site_galleries_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "site_galleries_slug_key" ON "site_galleries"("slug"); +CREATE INDEX "site_galleries_organization_id_idx" ON "site_galleries"("organization_id"); + +CREATE TABLE "site_gallery_sets" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "gallery_id" UUID NOT NULL, + "name" TEXT NOT NULL, + "position" INTEGER NOT NULL, + + CONSTRAINT "site_gallery_sets_pkey" PRIMARY KEY ("id") +); + +CREATE INDEX "site_gallery_sets_gallery_id_position_idx" ON "site_gallery_sets"("gallery_id", "position"); + +CREATE TABLE "site_gallery_photos" ( + "set_id" UUID NOT NULL, + "photo_id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "position" INTEGER NOT NULL, + + CONSTRAINT "site_gallery_photos_pkey" PRIMARY KEY ("set_id", "photo_id") +); + +CREATE INDEX "site_gallery_photos_photo_id_idx" ON "site_gallery_photos"("photo_id"); + +CREATE TABLE "site_gallery_shares" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "gallery_id" UUID NOT NULL, + "email" TEXT NOT NULL, + "subject" TEXT NOT NULL, + "message" TEXT NOT NULL DEFAULT '', + "sent_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "site_gallery_shares_pkey" PRIMARY KEY ("id") +); + +CREATE INDEX "site_gallery_shares_gallery_id_created_at_idx" ON "site_gallery_shares"("gallery_id", "created_at"); + +CREATE TABLE "site_gallery_reviews" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "gallery_id" UUID NOT NULL, + "name" TEXT NOT NULL, + "message" TEXT NOT NULL, + "recommends" BOOLEAN NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "site_gallery_reviews_pkey" PRIMARY KEY ("id") +); + +CREATE INDEX "site_gallery_reviews_gallery_id_created_at_idx" ON "site_gallery_reviews"("gallery_id", "created_at"); + +CREATE TABLE "site_gallery_views" ( + "gallery_id" UUID NOT NULL, + "day" DATE NOT NULL, + "views" INTEGER NOT NULL DEFAULT 0, + + CONSTRAINT "site_gallery_views_pkey" PRIMARY KEY ("gallery_id", "day") +); + +CREATE TABLE "site_gallery_brands" ( + "organization_id" UUID NOT NULL, + "studio" TEXT NOT NULL, + "contact_email" TEXT, + "instagram" TEXT, + "website" TEXT, + "terms_url" TEXT, + "privacy_url" TEXT, + + CONSTRAINT "site_gallery_brands_pkey" PRIMARY KEY ("organization_id") +); + +ALTER TABLE "site_galleries" ADD CONSTRAINT "site_galleries_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "site_galleries" ADD CONSTRAINT "site_galleries_event_id_fkey" FOREIGN KEY ("event_id") REFERENCES "events"("id") ON DELETE SET NULL ON UPDATE CASCADE; +ALTER TABLE "site_galleries" ADD CONSTRAINT "site_galleries_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE; +ALTER TABLE "site_galleries" ADD CONSTRAINT "site_galleries_cover_photo_id_fkey" FOREIGN KEY ("cover_photo_id") REFERENCES "photos"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +ALTER TABLE "site_gallery_sets" ADD CONSTRAINT "site_gallery_sets_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "site_gallery_sets" ADD CONSTRAINT "site_gallery_sets_gallery_id_fkey" FOREIGN KEY ("gallery_id") REFERENCES "site_galleries"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "site_gallery_photos" ADD CONSTRAINT "site_gallery_photos_set_id_fkey" FOREIGN KEY ("set_id") REFERENCES "site_gallery_sets"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "site_gallery_photos" ADD CONSTRAINT "site_gallery_photos_photo_id_fkey" FOREIGN KEY ("photo_id") REFERENCES "photos"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "site_gallery_photos" ADD CONSTRAINT "site_gallery_photos_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "site_gallery_shares" ADD CONSTRAINT "site_gallery_shares_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "site_gallery_shares" ADD CONSTRAINT "site_gallery_shares_gallery_id_fkey" FOREIGN KEY ("gallery_id") REFERENCES "site_galleries"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "site_gallery_reviews" ADD CONSTRAINT "site_gallery_reviews_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "site_gallery_reviews" ADD CONSTRAINT "site_gallery_reviews_gallery_id_fkey" FOREIGN KEY ("gallery_id") REFERENCES "site_galleries"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "site_gallery_views" ADD CONSTRAINT "site_gallery_views_gallery_id_fkey" FOREIGN KEY ("gallery_id") REFERENCES "site_galleries"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "site_gallery_brands" ADD CONSTRAINT "site_gallery_brands_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 7ae76a8..3c1a164 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -45,6 +45,7 @@ model User { deviceGrants DeviceAuthorization[] assignments EventAssignment[] uploads Photo[] + siteGalleries SiteGallery[] ftpAccounts FtpAccount[] edits PhotoEdit[] earnings Earning[] @@ -64,6 +65,8 @@ model Organization { biometricsLegalBasis String? @map("biometrics_legal_basis") /// Interior brackets. Off: the area is hidden and its routes refuse work. Sports ingest is unchanged. realEstateEnabled Boolean @default(false) @map("real_estate_enabled") + /// Workspace modules this organization has. Null: the areas that already existed (site galleries stay off). + appModules Json? @map("app_modules") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") @@ -123,6 +126,12 @@ model Organization { printers Printer[] printJobs PrintJob[] jerseySamples JerseySample[] + siteGalleries SiteGallery[] + siteGallerySets SiteGallerySet[] + siteGalleryPhotos SiteGalleryPhoto[] + siteGalleryShares SiteGalleryShare[] + siteGalleryReviews SiteGalleryReview[] + siteGalleryBrand SiteGalleryBrand? @@map("organizations") } @@ -132,6 +141,8 @@ model Membership { userId String @map("user_id") @db.Uuid organizationId String @map("organization_id") @db.Uuid role Role + /// Workspace modules for this person. Null: follow the role, inside what the organization has. Owners ignore this. + appModules Json? @map("app_modules") /// Photographer's share of sales of their photos, in percent (null: the organization's default). sharePct Float? @map("share_pct") /// Stripe Connect account (under the organization's Stripe) that receives payouts by transfer. @@ -277,8 +288,9 @@ model Event { photos Photo[] deliveries DeliveryItem[] faceGroups FaceGroup[] - galleries Gallery[] - cloudFolders CloudFolder[] + galleries Gallery[] + siteGalleries SiteGallery[] + cloudFolders CloudFolder[] /// FTP logins sending everything to this event, whatever the camera's clock says ("Receber FTP aqui"). ftpTargets FtpAccount[] teamSides ArchiveTeamSide[] @@ -431,6 +443,8 @@ model Photo { cloudFiles CloudFile[] edits PhotoEdit[] galleries GalleryPhoto[] + siteGalleryPhotos SiteGalleryPhoto[] + siteGalleryCovers SiteGallery[] @relation("siteGalleryCover") galleryExclusions GalleryExclusion[] favorites GalleryFavorite[] comments GalleryComment[] @@ -926,6 +940,133 @@ model GalleryComment { @@map("gallery_comments") } +/// A session delivered as its own page. Not a shop gallery and not a file delivery. +model SiteGallery { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + eventId String? @map("event_id") @db.Uuid + createdById String? @map("created_by_id") @db.Uuid + title String + dateLabel String @default("") @map("date_label") + /// Public address, unique across organizations: /cliente/. + slug String @unique + language String @default("pt") + passwordHash String? @map("password_hash") + favorites Boolean @default(true) + reviews Boolean @default(false) + /// SiteGalleryDesign. + design Json + /// StoredDownloads (the PIN is a hash). + downloads Json + coverPhotoId String? @map("cover_photo_id") @db.Uuid + publishedAt DateTime? @map("published_at") + offlineAt DateTime? @map("offline_at") + 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) + createdBy User? @relation(fields: [createdById], references: [id], onDelete: SetNull) + coverPhoto Photo? @relation("siteGalleryCover", fields: [coverPhotoId], references: [id], onDelete: SetNull) + sets SiteGallerySet[] + shares SiteGalleryShare[] + reviewRows SiteGalleryReview[] + views SiteGalleryView[] + + @@index([organizationId]) + @@map("site_galleries") +} + +model SiteGallerySet { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + galleryId String @map("gallery_id") @db.Uuid + name String + position Int + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + gallery SiteGallery @relation(fields: [galleryId], references: [id], onDelete: Cascade) + photos SiteGalleryPhoto[] + + @@index([galleryId, position]) + @@map("site_gallery_sets") +} + +model SiteGalleryPhoto { + setId String @map("set_id") @db.Uuid + photoId String @map("photo_id") @db.Uuid + organizationId String @map("organization_id") @db.Uuid + position Int + + set SiteGallerySet @relation(fields: [setId], references: [id], onDelete: Cascade) + photo Photo @relation(fields: [photoId], references: [id], onDelete: Cascade) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + + @@id([setId, photoId]) + @@index([photoId]) + @@map("site_gallery_photos") +} + +model SiteGalleryShare { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + galleryId String @map("gallery_id") @db.Uuid + email String + subject String + message String @default("") + /// Null when the message was kept but no mail server sent it. + sentAt DateTime? @map("sent_at") + createdAt DateTime @default(now()) @map("created_at") + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + gallery SiteGallery @relation(fields: [galleryId], references: [id], onDelete: Cascade) + + @@index([galleryId, createdAt]) + @@map("site_gallery_shares") +} + +model SiteGalleryReview { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + galleryId String @map("gallery_id") @db.Uuid + name String + message String + recommends Boolean + createdAt DateTime @default(now()) @map("created_at") + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + gallery SiteGallery @relation(fields: [galleryId], references: [id], onDelete: Cascade) + + @@index([galleryId, createdAt]) + @@map("site_gallery_reviews") +} + +model SiteGalleryView { + galleryId String @map("gallery_id") @db.Uuid + day DateTime @db.Date + views Int @default(0) + + gallery SiteGallery @relation(fields: [galleryId], references: [id], onDelete: Cascade) + + @@id([galleryId, day]) + @@map("site_gallery_views") +} + +/// The name and the contact a client gallery shows. One per organization. +model SiteGalleryBrand { + organizationId String @id @map("organization_id") @db.Uuid + studio String + contactEmail String? @map("contact_email") + instagram String? + website String? + termsUrl String? @map("terms_url") + privacyUrl String? @map("privacy_url") + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + + @@map("site_gallery_brands") +} + enum ProductKind { /// A JPEG to download, at `longEdge` px (0: full size). DIGITAL diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index b843cfd..d5955cb 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -7,6 +7,7 @@ import Fastify, { type FastifyInstance } from "fastify"; import { registerArchiveRoutes } from "./archive/routes.js"; import { ArchiveService } from "./archive/service.js"; import { registerArchiveViewerRoutes, ViewerTokens } from "./archive/viewer.js"; +import { requireAuth } from "./auth/guard.js"; import { registerAuthRoutes } from "./auth/routes.js"; import { SessionService } from "./auth/sessions.js"; import type { Config } from "./config.js"; @@ -39,6 +40,8 @@ import { modelsDir } from "./lib/models.js"; import { JerseyModel, JerseyPool } from "./jersey/model.js"; import type { JerseyReader } from "./faces/lookup.js"; import { registerJerseyRoutes } from "./jersey/routes.js"; +import { smtpMailer } from "./lib/mailer.js"; +import { clientGalleryOrigin, registerSiteGalleryRoutes } from "./site-galleries/routes.js"; import { JerseyService } from "./jersey/service.js"; import { registerSearchRoutes } from "./library/search.js"; import { registerPrintRoutes } from "./print/routes.js"; @@ -57,6 +60,7 @@ import { ProofingService } from "./shop/proofing.js"; import { registerPublicShopRoutes } from "./shop/public-routes.js"; import { ShopService } from "./shop/service.js"; import { FaceService } from "./faces/service.js"; +import { moduleFromRecord, moduleFromUrl, requireAppModule } from "./modules/access.js"; import { registerOrgRoutes } from "./orgs/routes.js"; import { registerSportsRoutes } from "./sports/routes.js"; import { SportsService } from "./sports/service.js"; @@ -135,10 +139,19 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give return { status: "ok", version: config.APP_VERSION }; }); + const authenticate = requireAuth(sessions); + // A module route answers only when this person has that module. Shared library and develop routes stay open. + app.addHook("preHandler", async (req, reply) => { + const gated = moduleFromUrl(req.url) ?? (await moduleFromRecord(db, req.url)); + if (!gated) return; + await authenticate(req, reply); + await requireAppModule(db, req, gated.orgId, gated.module, config.appModules); + }); + await registerAuthRoutes(app, { db, config, sessions }); - await registerMeRoutes(app, { db, sessions, broadcaster }); + await registerMeRoutes(app, { db, sessions, broadcaster, serverModules: config.appModules }); await registerCalendarRoutes(app, { sessions, calendar: new CalendarService({ db, secrets, ...(fetchImpl && { fetchImpl }) }) }); - await registerOrgRoutes(app, { db, sessions }); + await registerOrgRoutes(app, { db, sessions, serverModules: config.appModules }); await registerEventRoutes(app, { db, sessions, sports, broadcaster }); await registerSportsRoutes(app, { db, sessions, sports }); // Photos whose IPTC changes go again to where they went. @@ -222,7 +235,21 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give // Corrections to the autopilot's edits teach it (autopilot/learning.ts). const corrections = new CorrectionRecorder(db, 5_000, (err) => app.log.warn({ err }, "autopilot: correction not recorded")); app.addHook("onClose", async () => corrections.flush()); - const develop = new DevelopService({ db, storage, signer, broadcaster, log: app.log, onHumanEdit: (id) => corrections.schedule(id) }); + const develop = new DevelopService({ + db, + storage, + signer, + broadcaster, + log: app.log, + onHumanEdit: (id) => { + corrections.schedule(id); + // A crop or tone changed after the file already went out: send the new one. Un-pick is a library flag and retracts. + void db.photo + .findUnique({ where: { id }, select: { organizationId: true } }) + .then((photo) => (photo ? delivery.resendPhotos(photo.organizationId, [id]) : 0)) + .catch((err) => app.log.warn({ err }, "delivery: resend after edit failed")); + }, + }); await registerDevelopRoutes(app, { db, sessions, develop }); await registerAutopilotRoutes(app, { db, sessions }); await registerRealEstateRoutes(app, { db, sessions }); @@ -244,6 +271,14 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give const releases = config.DESKTOP_RELEASES_API && config.DESKTOP_RELEASES_TOKEN ? new DesktopReleases({ api: config.DESKTOP_RELEASES_API, token: config.DESKTOP_RELEASES_TOKEN }, fetchImpl ?? fetch) : undefined; await registerDesktopRoutes(app, { releases, publicApiUrl: config.API_PUBLIC_URL }); await registerJerseyRoutes(app, { db, sessions, jersey: new JerseyService({ db, storage, secret: config.JWT_SECRET }) }); + const mailer = config.SMTP_URL ? smtpMailer(config.SMTP_URL, config.MAIL_FROM) : undefined; + await registerSiteGalleryRoutes(app, { + db, + storage, + secret: config.JWT_SECRET, + publicOrigin: clientGalleryOrigin(config.API_PUBLIC_URL, config.SITE_PUBLIC_URL), + ...(mailer ? { mailer } : {}), + }); // Validation-only endpoint for the edit contract; the realtime path reuses the same schema. app.post("/v1/edits/validate", async (req) => { diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index 360b2d3..2ab81cf 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -1,3 +1,4 @@ +import { APP_MODULES, isAppModule, type AppModule } from "@photoreport/contracts"; import { z } from "zod"; const Env = z.object({ @@ -100,13 +101,31 @@ const Env = z.object({ DESKTOP_RELEASES_TOKEN: z.string().min(10).optional(), /** This API's public address (installer links handed to the desktop updater). */ API_PUBLIC_URL: z.string().url().default("http://localhost:3000"), + /** + * Public events site, where a client gallery is opened (`/cliente/`). + * Unset: `api.` becomes `events.`; any other API address uses http://localhost:3100. + */ + SITE_PUBLIC_URL: z.string().url().optional(), + /** + * Workspace modules this process may offer, comma-separated (library, develop, siteGallery, …). + * Unset: every module can be switched on for an organization. A list here is the ceiling. + */ + PHOTOREPORT_APP_MODULES: z.string().optional(), COOKIE_SECURE: z .enum(["true", "false"]) .optional() .transform((v) => (v === undefined ? undefined : v === "true")), }); -export type Config = z.infer & { corsOrigins: string[]; cookieSecure: boolean }; +export type Config = z.infer & { corsOrigins: string[]; cookieSecure: boolean; appModules: AppModule[] | null }; + +function serverModules(raw: string | undefined): AppModule[] | null { + if (raw == null || raw.trim() === "") return null; + const ids = raw.split(",").map((part) => part.trim()).filter(Boolean); + const unknown = ids.filter((id) => !isAppModule(id)); + if (unknown.length > 0) throw new Error(`Invalid configuration: PHOTOREPORT_APP_MODULES: unknown module ${unknown.join(", ")}`); + return APP_MODULES.filter((id) => ids.includes(id)); +} export function loadConfig(source: NodeJS.ProcessEnv = process.env): Config { const parsed = Env.safeParse(source); @@ -119,5 +138,6 @@ export function loadConfig(source: NodeJS.ProcessEnv = process.env): Config { ...env, corsOrigins: env.CORS_ORIGINS.split(",").map((o) => o.trim()).filter(Boolean), cookieSecure: env.COOKIE_SECURE ?? env.NODE_ENV === "production", + appModules: serverModules(env.PHOTOREPORT_APP_MODULES), }; } diff --git a/apps/api/src/me/routes.ts b/apps/api/src/me/routes.ts index 2ba3cb7..3e97253 100644 --- a/apps/api/src/me/routes.ts +++ b/apps/api/src/me/routes.ts @@ -1,4 +1,4 @@ -import { DeskCommand, MODULES } from "@photoreport/contracts"; +import { APP_MODULES, DeskCommand, memberModuleList, MODULES, orgModuleList, readModuleList, type AppModule, type MembershipRole } from "@photoreport/contracts"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { currentUserId, requireAuth } from "../auth/guard.js"; @@ -14,8 +14,9 @@ const PreferencesBody = z.object({ .transform((mods) => [...new Set(mods)]), }); -export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; broadcaster?: Broadcaster }) { +export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; broadcaster?: Broadcaster; serverModules?: readonly AppModule[] | null }) { const { db } = deps; + const serverModules = deps.serverModules ?? null; const broadcaster = deps.broadcaster ?? silentBroadcaster; const authenticate = requireAuth(deps.sessions); @@ -30,16 +31,26 @@ export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; ses if (!user) throw notFound("user_not_found"); return { user: { id: user.id, email: user.email, name: user.name, locale: user.locale }, - memberships: user.memberships.map((m) => ({ - role: m.role, - organization: { - id: m.organization.id, - slug: m.organization.slug, - name: m.organization.name, - mode: m.organization.mode, - realEstateEnabled: m.organization.realEstateEnabled, - }, - })), + memberships: user.memberships.map((m) => { + const storedOrg = readModuleList(m.organization.appModules); + const storedMember = readModuleList(m.appModules); + const orgModules = orgModuleList(storedOrg, serverModules); + return { + role: m.role, + appModules: storedMember, + modules: memberModuleList(m.role as MembershipRole, storedMember, orgModules), + organization: { + id: m.organization.id, + slug: m.organization.slug, + name: m.organization.name, + mode: m.organization.mode, + realEstateEnabled: m.organization.realEstateEnabled, + appModules: storedOrg, + modules: orgModules, + moduleCatalog: serverModules == null ? [...APP_MODULES] : [...serverModules], + }, + }; + }), preferences: { editorModules: user.preferences?.editorModules ?? ["crop", "basic"] }, }; }); diff --git a/apps/api/src/modules/access.test.ts b/apps/api/src/modules/access.test.ts new file mode 100644 index 0000000..3273c45 --- /dev/null +++ b/apps/api/src/modules/access.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { moduleFromUrl } from "./access.js"; + +describe("moduleFromUrl", () => { + const org = "11111111-1111-4111-8111-111111111111"; + + it("maps an organization route to its module", () => { + expect(moduleFromUrl(`/v1/orgs/${org}/galleries`)).toEqual({ orgId: org, module: "shop" }); + expect(moduleFromUrl(`/v1/orgs/${org}/site-galleries?x=1`)).toEqual({ orgId: org, module: "siteGallery" }); + expect(moduleFromUrl(`/v1/orgs/${org}/delivery-targets`)).toEqual({ orgId: org, module: "delivery" }); + }); + + it("leaves the library and a local delivery alone", () => { + expect(moduleFromUrl(`/v1/orgs/${org}/events`)).toBeNull(); + expect(moduleFromUrl(`/v1/orgs/${org}/deliveries/local/claim`)).toBeNull(); + expect(moduleFromUrl(`/v1/orgs/${org}/deliveries/${org}/local-file`)).toBeNull(); + expect(moduleFromUrl("/v1/public/galleries")).toBeNull(); + }); +}); diff --git a/apps/api/src/modules/access.ts b/apps/api/src/modules/access.ts new file mode 100644 index 0000000..eb559d0 --- /dev/null +++ b/apps/api/src/modules/access.ts @@ -0,0 +1,119 @@ +import { + memberModuleList, + orgModuleList, + readModuleList, + type AppModule, + type MembershipRole, +} from "@photoreport/contracts"; +import type { FastifyRequest } from "fastify"; +import { currentUserId } from "../auth/guard.js"; +import type { Db } from "../db.js"; +import { forbidden } from "../lib/errors.js"; + +/** Second path segment under /v1/orgs/:orgId/ that belongs to one module. */ +const BY_SEGMENT: Record = { + "delivery-targets": "delivery", + deliveries: "delivery", + galleries: "shop", + products: "shop", + bundles: "shop", + sites: "shop", + orders: "shop", + "shop-settings": "shop", + earnings: "shop", + affiliates: "shop", + connect: "shop", + "my-earnings": "shop", + "press-accounts": "shop", + invoices: "shop", + invoicing: "shop", + payouts: "shop", + "print-events": "print", + printers: "print", + "print-stations": "print", + "cloud-sources": "archive", + "face-review": "faces", + persons: "faces", + faces: "faces", + jersey: "numbers", + "site-galleries": "siteGallery", +}; + +const ORG_ROUTE = /^\/v1\/orgs\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/([^/?]+)/i; + +/** + * The desktop finishes a local delivery from any module. Those calls stay open + * so a person without the Entregar screen can still complete a file already queued. + */ +const LOCAL_DELIVERY = /\/deliveries\/local\/|\/local-file(?:\/|$)|\/local-result(?:\/|$)/; + +/** Which module an organization-scoped URL belongs to. Null: shared, public, or not a module route. */ +export function moduleFromUrl(url: string): { orgId: string; module: AppModule } | null { + const path = url.split("?")[0] ?? url; + if (LOCAL_DELIVERY.test(path)) return null; + const match = ORG_ROUTE.exec(path); + if (!match?.[1] || !match[2]) return null; + const module = BY_SEGMENT[match[2]]; + if (!module) return null; + return { orgId: match[1], module }; +} + +type IdRoute = { module: AppModule; prefix: string; find: (db: Db, id: string) => Promise<{ organizationId: string } | null> }; + +const ID_ROUTES: IdRoute[] = [ + { module: "shop", prefix: "/v1/galleries/", find: (db, id) => db.gallery.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "shop", prefix: "/v1/products/", find: (db, id) => db.product.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "shop", prefix: "/v1/bundles/", find: (db, id) => db.bundle.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "shop", prefix: "/v1/sites/", find: (db, id) => db.site.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "shop", prefix: "/v1/orders/", find: (db, id) => db.order.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "shop", prefix: "/v1/press-accounts/", find: (db, id) => db.pressAccount.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "shop", prefix: "/v1/invoices/", find: (db, id) => db.invoice.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "shop", prefix: "/v1/affiliates/", find: (db, id) => db.affiliate.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "shop", prefix: "/v1/payouts/", find: (db, id) => db.payout.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "print", prefix: "/v1/print-events/", find: (db, id) => db.printEvent.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "print", prefix: "/v1/printers/", find: (db, id) => db.printer.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "print", prefix: "/v1/print-stations/", find: (db, id) => db.printStation.findUnique({ where: { id }, select: { organizationId: true } }) }, + { module: "archive", prefix: "/v1/cloud-sources/", find: (db, id) => db.cloudSource.findUnique({ where: { id }, select: { organizationId: true } }) }, +]; + +const ID_IN_PATH = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i; + +/** + * Module for a URL that names a row instead of an organization. + * Missing row: null, so the route can answer 404. + */ +export async function moduleFromRecord(db: Db, url: string): Promise<{ orgId: string; module: AppModule } | null> { + const path = url.split("?")[0] ?? url; + if (path.startsWith("/v1/public/")) return null; + for (const route of ID_ROUTES) { + if (!path.startsWith(route.prefix)) continue; + const id = ID_IN_PATH.exec(path.slice(route.prefix.length))?.[1]; + if (!id) return null; + const row = await route.find(db, id); + if (!row) return null; + return { orgId: row.organizationId, module: route.module }; + } + return null; +} + +/** Refuses the call when this person does not have the module in this organization. */ +export async function requireAppModule( + db: Db, + req: FastifyRequest, + organizationId: string, + module: AppModule, + serverModules: readonly AppModule[] | null, +) { + const membership = await db.membership.findUnique({ + where: { userId_organizationId: { userId: currentUserId(req), organizationId } }, + include: { organization: { select: { appModules: true } } }, + }); + if (!membership) throw forbidden("insufficient_role"); + const allowed = memberModuleList( + membership.role as MembershipRole, + readModuleList(membership.appModules), + orgModuleList(readModuleList(membership.organization.appModules), serverModules), + ); + if (!allowed.includes(module)) throw forbidden("module_disabled"); + return membership; +} diff --git a/apps/api/src/orgs/routes.ts b/apps/api/src/orgs/routes.ts index 0f5e492..bb5101f 100644 --- a/apps/api/src/orgs/routes.ts +++ b/apps/api/src/orgs/routes.ts @@ -1,10 +1,11 @@ +import { AppModuleId, memberModuleList, orgModuleList, readModuleList, type AppModule, type MembershipRole } from "@photoreport/contracts"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { ROLE_RANK, currentUserId, requireAuth, requireMembership } from "../auth/guard.js"; import { MIN_PASSWORD_LENGTH, hashPassword } from "../auth/passwords.js"; import type { SessionService } from "../auth/sessions.js"; import type { Db } from "../db.js"; -import { Role } from "../generated/prisma/client.js"; +import { Prisma, Role } from "../generated/prisma/client.js"; import { badRequest, conflict, forbidden, notFound } from "../lib/errors.js"; const OrgParams = z.object({ orgId: z.uuid() }); @@ -18,9 +19,19 @@ const AddMemberBody = z.object({ password: z.string().min(MIN_PASSWORD_LENGTH).max(512).optional(), }); const UpdateMemberBody = z.object({ role: RoleSchema }); +const OrgModulesBody = z.object({ + appModules: z.array(AppModuleId).transform((ids) => [...new Set(ids)]), +}); +const MemberModulesBody = z.object({ + appModules: z + .array(AppModuleId) + .nullable() + .transform((ids) => (ids === null ? null : [...new Set(ids)])), +}); -export async function registerOrgRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService }) { +export async function registerOrgRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; serverModules?: readonly AppModule[] | null }) { const { db } = deps; + const serverModules = deps.serverModules ?? null; const authenticate = requireAuth(deps.sessions); /** Nobody can grant a role above their own. */ @@ -54,13 +65,20 @@ export async function registerOrgRoutes(app: FastifyInstance, deps: { db: Db; se include: { user: true }, orderBy: { createdAt: "asc" }, }); - return members.map((m) => ({ - userId: m.userId, - email: m.user.email, - name: m.user.name, - role: m.role, - disabled: m.user.disabledAt !== null, - })); + const organization = await db.organization.findUnique({ where: { id: orgId }, select: { appModules: true } }); + const orgModules = orgModuleList(readModuleList(organization?.appModules), serverModules); + return members.map((m) => { + const stored = readModuleList(m.appModules); + return { + userId: m.userId, + email: m.user.email, + name: m.user.name, + role: m.role, + disabled: m.user.disabledAt !== null, + appModules: stored, + modules: memberModuleList(m.role as MembershipRole, stored, orgModules), + }; + }); }); app.post("/v1/orgs/:orgId/members", { preHandler: authenticate }, async (req, reply) => { @@ -102,6 +120,43 @@ export async function registerOrgRoutes(app: FastifyInstance, deps: { db: Db; se return { userId, role }; }); + /** Which modules this organization offers. The personal lists are cut down to this. */ + app.put("/v1/orgs/:orgId/modules", { preHandler: authenticate }, async (req) => { + const { orgId } = OrgParams.parse(req.params); + await requireMembership(db, req, orgId, "ADMIN"); + const body = OrgModulesBody.parse(req.body); + const cap = serverModules == null ? null : new Set(serverModules); + if (cap && body.appModules.some((id) => !cap.has(id))) throw forbidden("module_unavailable"); + const organization = await db.organization.update({ where: { id: orgId }, data: { appModules: body.appModules }, select: { appModules: true } }); + const stored = readModuleList(organization.appModules); + return { appModules: stored, modules: orgModuleList(stored, serverModules) }; + }); + + /** Personal modules. Null follows the role. The owner always has the organization's modules. */ + app.put("/v1/orgs/:orgId/members/:userId/modules", { preHandler: authenticate }, async (req) => { + const { orgId, userId } = MemberParams.parse(req.params); + await requireMembership(db, req, orgId, "ADMIN"); + const body = MemberModulesBody.parse(req.body); + const target = await db.membership.findUnique({ + where: { userId_organizationId: { userId, organizationId: orgId } }, + include: { organization: { select: { appModules: true } } }, + }); + if (!target) throw notFound("member_not_found"); + if (target.role === "OWNER") throw badRequest("owner_has_org_modules"); + const offered = orgModuleList(readModuleList(target.organization.appModules), serverModules); + if (body.appModules?.some((id) => !offered.includes(id))) throw forbidden("module_unavailable"); + const saved = await db.membership.update({ + where: { id: target.id }, + data: { appModules: body.appModules === null ? Prisma.DbNull : body.appModules }, + }); + const stored = readModuleList(saved.appModules); + return { + userId, + appModules: stored, + modules: memberModuleList(saved.role as MembershipRole, stored, offered), + }; + }); + app.delete("/v1/orgs/:orgId/members/:userId", { preHandler: authenticate }, async (req, reply) => { const { orgId, userId } = MemberParams.parse(req.params); const me = await requireMembership(db, req, orgId, "ADMIN"); diff --git a/apps/api/src/site-galleries/routes.ts b/apps/api/src/site-galleries/routes.ts new file mode 100644 index 0000000..d6483e1 --- /dev/null +++ b/apps/api/src/site-galleries/routes.ts @@ -0,0 +1,131 @@ +import { + CreateSiteGallery, + SiteGalleryBrandInput, + SiteGalleryReviewInput, + SiteGallerySetsInput, + SiteGalleryShareInput, + UpdateSiteGallery, +} from "@photoreport/contracts"; +import { createReadStream } from "node:fs"; +import type { FastifyInstance } from "fastify"; +import { z } from "zod"; +import { requireMembership } from "../auth/guard.js"; +import type { Db } from "../db.js"; +import type { Mailer } from "../lib/mailer.js"; +import type { LocalStorage } from "../storage/storage.js"; +import { SiteGalleries } from "./service.js"; + +const OrgParams = z.object({ orgId: z.uuid() }); +const GalleryParams = OrgParams.extend({ galleryId: z.uuid() }); +const PublicParams = z.object({ slug: z.string().min(1).max(80) }); +const FileParams = z.object({ galleryId: z.uuid(), photoId: z.uuid() }); +const FileQuery = z.object({ + exp: z.coerce.number(), + sig: z.string().min(1), + download: z.enum(["0", "1"]).optional(), + pin: z.string().max(12).optional(), +}); + +function tokenOf(header: string | string[] | undefined): string | undefined { + const value = Array.isArray(header) ? header[0] : header; + return value && value.length > 0 ? value : undefined; +} + +export function clientGalleryOrigin(apiPublicUrl: string, sitePublicUrl?: string): string { + if (sitePublicUrl) return sitePublicUrl.replace(/\/+$/, ""); + const url = new URL(apiPublicUrl); + if (url.hostname.startsWith("api.")) return `${url.protocol}//events.${url.hostname.slice("api.".length)}`; + return "http://localhost:3100"; +} + +export async function registerSiteGalleryRoutes( + app: FastifyInstance, + deps: { db: Db; storage: LocalStorage; secret: string; publicOrigin: string; mailer?: Mailer }, +): Promise { + const galleries = new SiteGalleries(deps.db, deps.storage, deps.secret, deps.publicOrigin, deps.mailer); + + app.get("/v1/orgs/:orgId/site-galleries/brand", async (req) => { + const { orgId } = OrgParams.parse(req.params); + await requireMembership(deps.db, req, orgId, "PHOTOGRAPHER"); + return galleries.brand(orgId); + }); + + app.put("/v1/orgs/:orgId/site-galleries/brand", async (req) => { + const { orgId } = OrgParams.parse(req.params); + await requireMembership(deps.db, req, orgId, "ADMIN"); + return galleries.saveBrand(orgId, SiteGalleryBrandInput.parse(req.body)); + }); + + app.get("/v1/orgs/:orgId/site-galleries", async (req) => { + const { orgId } = OrgParams.parse(req.params); + const membership = await requireMembership(deps.db, req, orgId, "PHOTOGRAPHER"); + return { galleries: await galleries.list(orgId, membership), linkBase: galleries.link("").replace(/\/$/, "") }; + }); + + app.post("/v1/orgs/:orgId/site-galleries", async (req, reply) => { + const { orgId } = OrgParams.parse(req.params); + const membership = await requireMembership(deps.db, req, orgId, "PHOTOGRAPHER"); + const gallery = await galleries.create(orgId, membership, CreateSiteGallery.parse(req.body)); + return reply.code(201).send(gallery); + }); + + app.get("/v1/orgs/:orgId/site-galleries/:galleryId", async (req) => { + const { orgId, galleryId } = GalleryParams.parse(req.params); + const membership = await requireMembership(deps.db, req, orgId, "PHOTOGRAPHER"); + return galleries.detail(orgId, galleryId, membership); + }); + + app.patch("/v1/orgs/:orgId/site-galleries/:galleryId", async (req) => { + const { orgId, galleryId } = GalleryParams.parse(req.params); + const membership = await requireMembership(deps.db, req, orgId, "PHOTOGRAPHER"); + return galleries.update(orgId, galleryId, membership, UpdateSiteGallery.parse(req.body)); + }); + + app.delete("/v1/orgs/:orgId/site-galleries/:galleryId", async (req, reply) => { + const { orgId, galleryId } = GalleryParams.parse(req.params); + const membership = await requireMembership(deps.db, req, orgId, "PHOTOGRAPHER"); + await galleries.remove(orgId, galleryId, membership); + return reply.code(204).send(); + }); + + app.put("/v1/orgs/:orgId/site-galleries/:galleryId/sets", async (req) => { + const { orgId, galleryId } = GalleryParams.parse(req.params); + const membership = await requireMembership(deps.db, req, orgId, "PHOTOGRAPHER"); + const body = SiteGallerySetsInput.parse(req.body); + return galleries.replaceSets(orgId, galleryId, membership, body.sets); + }); + + app.post("/v1/orgs/:orgId/site-galleries/:galleryId/shares", async (req, reply) => { + const { orgId, galleryId } = GalleryParams.parse(req.params); + const membership = await requireMembership(deps.db, req, orgId, "PHOTOGRAPHER"); + const gallery = await galleries.share(orgId, galleryId, membership, SiteGalleryShareInput.parse(req.body)); + return reply.code(201).send(gallery); + }); + + app.get("/v1/public/client-galleries/:slug", async (req) => { + const { slug } = PublicParams.parse(req.params); + const query = z.object({ count: z.enum(["0", "1"]).optional() }).parse(req.query); + return galleries.open(slug, tokenOf(req.headers["x-client-gallery-token"]), new Date(), query.count !== "0"); + }); + + app.post("/v1/public/client-galleries/:slug/unlock", async (req) => { + const { slug } = PublicParams.parse(req.params); + const { password } = z.object({ password: z.string().min(1).max(80) }).parse(req.body); + return galleries.unlock(slug, password); + }); + + app.post("/v1/public/client-galleries/:slug/reviews", async (req, reply) => { + const { slug } = PublicParams.parse(req.params); + await galleries.review(slug, tokenOf(req.headers["x-client-gallery-token"]), SiteGalleryReviewInput.parse(req.body)); + return reply.code(201).send({ ok: true }); + }); + + app.get("/v1/public/client-files/:galleryId/:photoId", async (req, reply) => { + const { galleryId, photoId } = FileParams.parse(req.params); + const query = FileQuery.parse(req.query); + const file = await galleries.file(galleryId, photoId, query.exp, query.sig, query.download === "1", query.pin); + const response = reply.header("content-type", "image/jpeg").header("cache-control", query.download === "1" ? "private, no-store" : "public, max-age=3600"); + if (file.downloadName) response.header("content-disposition", `attachment; filename="${file.downloadName}"`); + return response.send(createReadStream(file.path)); + }); +} diff --git a/apps/api/src/site-galleries/service.ts b/apps/api/src/site-galleries/service.ts new file mode 100644 index 0000000..708b5f3 --- /dev/null +++ b/apps/api/src/site-galleries/service.ts @@ -0,0 +1,452 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; +import { + photographerOwnsPhoto, + readDesign, + readStoredDownloads, + slugifyTitle, + type CreateSiteGallery, + type PublicClientGallery, + type SiteGalleryBrand, + type SiteGalleryBrandInput, + type SiteGalleryDetail, + type SiteGalleryDownloadsInput, + type SiteGalleryReviewInput, + type SiteGallerySetInput, + type SiteGalleryShareInput, + type SiteGallerySummary, + type StoredDownloads, + type UpdateSiteGallery, +} from "@photoreport/contracts"; +import { hashPassword, verifyPassword } from "../auth/passwords.js"; +import { ROLE_RANK } from "../auth/guard.js"; +import type { Db } from "../db.js"; +import type { Role } from "../generated/prisma/client.js"; +import { Prisma } from "../generated/prisma/client.js"; +import { badRequest, conflict, forbidden, notFound, unauthorized } from "../lib/errors.js"; +import type { Mailer } from "../lib/mailer.js"; +import type { LocalStorage } from "../storage/storage.js"; +import { watermarked } from "../shop/watermark.js"; + +const WEEK = 7 * 24 * 3600; +const FILE_TTL = 6 * 3600; + +type Actor = { userId: string; role: Role }; + +function mac(secret: string, value: string): string { + return createHmac("sha256", secret).update(value).digest("base64url"); +} + +function same(a: string, b: string): boolean { + const left = Buffer.from(a); + const right = Buffer.from(b); + return left.length === right.length && timingSafeEqual(left, right); +} + +function dayOf(now: Date): Date { + return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())); +} + +function canEditAny(role: Role): boolean { + return ROLE_RANK[role] >= ROLE_RANK.EDITOR; +} + +function asJson(value: StoredDownloads): Prisma.InputJsonValue { + return { ...value }; +} + +export class SiteGalleries { + constructor( + private readonly db: Db, + private readonly storage: LocalStorage, + private readonly secret: string, + private readonly publicOrigin: string, + private readonly mailer?: Mailer, + ) {} + + private async own(orgId: string, galleryId: string, actor: Actor) { + const gallery = await this.db.siteGallery.findFirst({ where: { id: galleryId, organizationId: orgId } }); + if (!gallery) throw notFound("gallery_not_found"); + if (!canEditAny(actor.role) && gallery.createdById !== actor.userId) throw forbidden("not_your_gallery"); + return gallery; + } + + private async eventAllowed(orgId: string, eventId: string | null, actor: Actor) { + if (!eventId || canEditAny(actor.role)) return; + const event = await this.db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }); + if (!event) throw badRequest("event_not_found"); + const assigned = await this.db.eventAssignment.findUnique({ where: { eventId_userId: { eventId, userId: actor.userId } } }); + if (!assigned) throw forbidden("not_your_event"); + } + + async list(orgId: string, actor: Actor): Promise { + const rows = await this.db.siteGallery.findMany({ + where: { organizationId: orgId, ...(canEditAny(actor.role) ? {} : { createdById: actor.userId }) }, + orderBy: { updatedAt: "desc" }, + include: { sets: { include: { _count: { select: { photos: true } } } } }, + }); + return rows.map((row) => ({ + id: row.id, + title: row.title, + slug: row.slug, + dateLabel: row.dateLabel, + language: row.language === "en" ? "en" : "pt", + published: row.publishedAt !== null && (row.offlineAt === null || row.offlineAt.getTime() > Date.now()), + offlineAt: row.offlineAt?.toISOString() ?? null, + photoCount: row.sets.reduce((sum, set) => sum + set._count.photos, 0), + pending: false, + })); + } + + async detail(orgId: string, galleryId: string, actor: Actor): Promise { + const row = await this.db.siteGallery.findFirst({ + where: { id: galleryId, organizationId: orgId }, + include: { + sets: { orderBy: { position: "asc" }, include: { photos: { orderBy: { position: "asc" }, select: { photoId: true } } } }, + shares: { orderBy: { createdAt: "desc" }, take: 50 }, + _count: { select: { reviewRows: true } }, + views: { select: { views: true } }, + }, + }); + if (!row) throw notFound("gallery_not_found"); + if (!canEditAny(actor.role) && row.createdById !== actor.userId) throw forbidden("not_your_gallery"); + const downloads = readStoredDownloads(row.downloads); + return { + id: row.id, + title: row.title, + slug: row.slug, + dateLabel: row.dateLabel, + language: row.language === "en" ? "en" : "pt", + published: row.publishedAt !== null && (row.offlineAt === null || row.offlineAt.getTime() > Date.now()), + offlineAt: row.offlineAt?.toISOString() ?? null, + photoCount: row.sets.reduce((sum, set) => sum + set.photos.length, 0), + pending: false, + eventId: row.eventId, + hasPassword: row.passwordHash !== null, + favorites: row.favorites, + reviews: row.reviews, + design: readDesign(row.design), + downloads: { gallery: downloads.gallery, single: downloads.single, size: downloads.size, limit: downloads.limit, hasPin: downloads.pinHash !== null, used: downloads.used }, + coverPhotoId: row.coverPhotoId, + views: row.views.reduce((sum, day) => sum + day.views, 0), + sets: row.sets.map((set) => ({ id: set.id, name: set.name, photoIds: set.photos.map((photo) => photo.photoId) })), + shares: row.shares.map((share) => ({ id: share.id, email: share.email, subject: share.subject, sentAt: share.sentAt?.toISOString() ?? null })), + reviewCount: row._count.reviewRows, + }; + } + + async create(orgId: string, actor: Actor, input: CreateSiteGallery): Promise { + await this.eventAllowed(orgId, input.eventId, actor); + const slug = input.slug ?? (await this.freeSlug(slugifyTitle(input.title))); + if (input.slug) { + const taken = await this.db.siteGallery.findUnique({ where: { slug: input.slug }, select: { id: true } }); + if (taken) throw conflict("slug_taken"); + } + const downloads = await this.storeDownloads(input.downloads, null); + const row = await this.db.siteGallery.create({ + data: { + organizationId: orgId, + createdById: actor.userId, + eventId: input.eventId, + title: input.title, + dateLabel: input.dateLabel, + slug, + language: input.language, + favorites: input.favorites, + reviews: input.reviews, + design: input.design, + downloads: asJson(downloads), + passwordHash: input.password ? await hashPassword(input.password) : null, + }, + }); + await this.db.siteGallerySet.create({ + data: { + organizationId: orgId, + galleryId: row.id, + name: input.language === "en" ? "Photographs" : "Fotografias", + position: 0, + }, + }); + return this.detail(orgId, row.id, actor); + } + + async update(orgId: string, galleryId: string, actor: Actor, input: UpdateSiteGallery): Promise { + const current = await this.own(orgId, galleryId, actor); + if (input.eventId !== undefined) await this.eventAllowed(orgId, input.eventId, actor); + if (input.slug && input.slug !== current.slug) { + const taken = await this.db.siteGallery.findUnique({ where: { slug: input.slug }, select: { id: true } }); + if (taken) throw conflict("slug_taken"); + } + const data: Prisma.SiteGalleryUpdateInput = {}; + if (input.title !== undefined) data.title = input.title; + if (input.dateLabel !== undefined) data.dateLabel = input.dateLabel; + if (input.slug !== undefined) data.slug = input.slug; + if (input.language !== undefined) data.language = input.language; + if (input.eventId !== undefined) data.event = input.eventId ? { connect: { id: input.eventId } } : { disconnect: true }; + if (input.favorites !== undefined) data.favorites = input.favorites; + if (input.reviews !== undefined) data.reviews = input.reviews; + if (input.design !== undefined) data.design = input.design; + if (input.published === true) data.publishedAt = current.publishedAt ?? new Date(); + if (input.published === false) data.publishedAt = null; + if (input.offlineAt !== undefined) data.offlineAt = input.offlineAt; + if (input.coverPhotoId !== undefined) data.coverPhoto = input.coverPhotoId ? { connect: { id: input.coverPhotoId } } : { disconnect: true }; + if (input.password !== undefined) data.passwordHash = input.password ? await hashPassword(input.password) : null; + if (input.downloads) data.downloads = asJson(await this.storeDownloads(input.downloads, readStoredDownloads(current.downloads))); + await this.db.siteGallery.update({ where: { id: current.id }, data }); + return this.detail(orgId, current.id, actor); + } + + async remove(orgId: string, galleryId: string, actor: Actor): Promise { + const current = await this.own(orgId, galleryId, actor); + await this.db.siteGallery.delete({ where: { id: current.id } }); + } + + async replaceSets(orgId: string, galleryId: string, actor: Actor, sets: SiteGallerySetInput[]): Promise { + const current = await this.own(orgId, galleryId, actor); + const ids = [...new Set(sets.flatMap((set) => set.photoIds))]; + const photos = ids.length + ? await this.db.photo.findMany({ where: { id: { in: ids }, organizationId: orgId, status: "READY" }, select: { id: true, uploaderId: true } }) + : []; + if (photos.length !== ids.length) throw badRequest("photo_not_ready"); + if (!canEditAny(actor.role) && photos.some((photo) => !photographerOwnsPhoto(photo, actor.userId))) throw forbidden("not_your_photo"); + const known = new Set(ids); + await this.db.$transaction(async (tx) => { + await tx.siteGallerySet.deleteMany({ where: { galleryId: current.id } }); + for (const [index, set] of sets.entries()) { + await tx.siteGallerySet.create({ + data: { + organizationId: orgId, + galleryId: current.id, + name: set.name, + position: index, + photos: { + create: set.photoIds.map((photoId, position) => ({ organizationId: orgId, photoId, position })), + }, + }, + }); + } + if (current.coverPhotoId && !known.has(current.coverPhotoId)) { + await tx.siteGallery.update({ where: { id: current.id }, data: { coverPhotoId: null } }); + } + }); + return this.detail(orgId, current.id, actor); + } + + async share(orgId: string, galleryId: string, actor: Actor, input: SiteGalleryShareInput): Promise { + const current = await this.own(orgId, galleryId, actor); + const link = `${this.publicOrigin}/cliente/${current.slug}`; + const text = [input.message, link].filter((line) => line.length > 0).join("\n\n"); + let sentAt: Date | null = null; + if (this.mailer) { + try { + await this.mailer.send({ to: input.email, subject: input.subject, text }); + sentAt = new Date(); + } catch { + sentAt = null; + } + } + await this.db.siteGalleryShare.create({ + data: { organizationId: orgId, galleryId: current.id, email: input.email, subject: input.subject, message: input.message, sentAt }, + }); + return this.detail(orgId, current.id, actor); + } + + async brand(orgId: string): Promise { + const row = await this.db.siteGalleryBrand.findUnique({ where: { organizationId: orgId } }); + const org = await this.db.organization.findUnique({ where: { id: orgId }, select: { name: true } }); + if (!org) throw notFound("organization_not_found"); + return { + studio: row?.studio ?? org.name, + contactEmail: row?.contactEmail ?? null, + instagram: row?.instagram ?? null, + website: row?.website ?? null, + termsUrl: row?.termsUrl ?? null, + privacyUrl: row?.privacyUrl ?? null, + }; + } + + async saveBrand(orgId: string, input: SiteGalleryBrandInput): Promise { + await this.db.siteGalleryBrand.upsert({ + where: { organizationId: orgId }, + create: { organizationId: orgId, ...input }, + update: input, + }); + return this.brand(orgId); + } + + link(slug: string): string { + return `${this.publicOrigin}/cliente/${slug}`; + } + + async open(slug: string, token: string | undefined, now = new Date(), count = true): Promise { + const gallery = await this.published(slug, now); + if (gallery.passwordHash && !this.tokenOpens(gallery.id, token)) throw unauthorized("password_required"); + if (count) await this.db.siteGalleryView.upsert({ + where: { galleryId_day: { galleryId: gallery.id, day: dayOf(now) } }, + create: { galleryId: gallery.id, day: dayOf(now), views: 1 }, + update: { views: { increment: 1 } }, + }); + return this.present(gallery); + } + + async unlock(slug: string, password: string, now = new Date()): Promise<{ token: string }> { + const gallery = await this.published(slug, now); + if (!gallery.passwordHash) return { token: this.tokenFor(gallery.id, now) }; + if (!(await verifyPassword(gallery.passwordHash, password))) throw unauthorized("wrong_password"); + return { token: this.tokenFor(gallery.id, now) }; + } + + async review(slug: string, token: string | undefined, input: SiteGalleryReviewInput, now = new Date()): Promise { + const gallery = await this.published(slug, now); + if (!gallery.reviews) throw forbidden("reviews_off"); + if (gallery.passwordHash && !this.tokenOpens(gallery.id, token)) throw unauthorized("password_required"); + await this.db.siteGalleryReview.create({ + data: { organizationId: gallery.organizationId, galleryId: gallery.id, name: input.name, message: input.message, recommends: input.recommends }, + }); + } + + async file(galleryId: string, photoId: string, exp: number, sig: string, download: boolean, pin: string | undefined, now = new Date()): Promise<{ path: string; downloadName: string | null }> { + if (!this.fileSigOk(galleryId, photoId, exp, sig, now)) throw notFound("file_not_found"); + const gallery = await this.db.siteGallery.findUnique({ where: { id: galleryId } }); + if (!gallery || !this.isOpen(gallery, now)) throw notFound("file_not_found"); + const placed = await this.db.siteGalleryPhoto.findFirst({ + where: { photoId, organizationId: gallery.organizationId, set: { galleryId } }, + include: { photo: true }, + }); + if (!placed) throw notFound("file_not_found"); + const downloads = readStoredDownloads(gallery.downloads); + const photo = placed.photo; + if (download) { + if (!downloads.single && !downloads.gallery) throw forbidden("downloads_off"); + if (downloads.pinHash) { + if (!pin || !(await verifyPassword(downloads.pinHash, pin))) throw unauthorized("wrong_pin"); + } + if (downloads.limit && downloads.limit > 0 && downloads.used >= downloads.limit) throw forbidden("download_limit"); + } + const brand = await this.brand(gallery.organizationId); + if (download && downloads.limit && downloads.limit > 0) { + const next = { ...downloads, used: downloads.used + 1 }; + await this.db.siteGallery.update({ where: { id: gallery.id }, data: { downloads: asJson(next) } }); + } + if (download && downloads.size === "original" && photo.originalStored && photo.storageKey.toLowerCase().endsWith(".jpg")) { + return { path: this.storage.resolve(photo.storageKey), downloadName: `${gallery.slug}-${photo.id}.jpg` }; + } + const path = await this.previewFile(photo, brand.studio, gallery.id); + const name = download ? `${gallery.slug}-${photo.id}.jpg` : null; + return { path, downloadName: name }; + } + + private async previewFile(photo: { organizationId: string; sha256: string; renderedSeq: number }, studio: string, galleryId: string): Promise { + const key = `${photo.organizationId}/public/client/${photo.sha256.slice(0, 2)}/${photo.sha256}.r${photo.renderedSeq}.${galleryId.slice(0, 8)}.jpg`; + if (await this.storage.exists(key)) return this.storage.resolve(key); + let source = this.storage.derivedKey(photo.organizationId, photo.sha256, "preview"); + if (photo.renderedSeq > 0) { + const edited = this.storage.editedKey(photo.organizationId, photo.sha256, photo.renderedSeq, "preview"); + if (await this.storage.exists(edited)) source = edited; + } + await this.storage.write(key, await watermarked(this.storage.resolve(source), studio, 2048)); + return this.storage.resolve(key); + } + + imagePath(galleryId: string, photoId: string, now = Date.now()): string { + const exp = Math.ceil((Math.floor(now / 1000) + FILE_TTL) / 3600) * 3600; + const sig = mac(this.secret, `cgfile:${galleryId}:${photoId}:${exp}`); + return `/v1/public/client-files/${galleryId}/${photoId}?exp=${exp}&sig=${sig}`; + } + + private fileSigOk(galleryId: string, photoId: string, exp: number, sig: string, now: Date): boolean { + if (!Number.isFinite(exp) || exp < Math.floor(now.getTime() / 1000)) return false; + return same(mac(this.secret, `cgfile:${galleryId}:${photoId}:${exp}`), sig); + } + + private tokenFor(galleryId: string, now: Date): string { + const exp = Math.floor(now.getTime() / 1000) + WEEK; + return `${galleryId}.${exp}.${mac(this.secret, `cg:${galleryId}:${exp}`)}`; + } + + private tokenOpens(galleryId: string, token: string | undefined): boolean { + if (!token) return false; + const [id, expRaw, sig] = token.split("."); + const exp = Number(expRaw); + return id === galleryId && Number.isFinite(exp) && exp >= Date.now() / 1000 && !!sig && same(mac(this.secret, `cg:${id}:${exp}`), sig); + } + + private isOpen(gallery: { publishedAt: Date | null; offlineAt: Date | null }, now: Date): boolean { + return gallery.publishedAt !== null && (gallery.offlineAt === null || gallery.offlineAt.getTime() > now.getTime()); + } + + private async published(slug: string, now: Date) { + const gallery = await this.db.siteGallery.findUnique({ + where: { slug }, + include: { + sets: { orderBy: { position: "asc" }, include: { photos: { orderBy: { position: "asc" }, include: { photo: true } } } }, + }, + }); + if (!gallery || !this.isOpen(gallery, now)) throw notFound("gallery_not_found"); + return gallery; + } + + private async present(gallery: Awaited>): Promise { + const design = readDesign(gallery.design); + const downloads = readStoredDownloads(gallery.downloads); + const brand = await this.brand(gallery.organizationId); + const byId = new Map(); + for (const set of gallery.sets) { + for (const placed of set.photos) { + const photo = placed.photo; + const existing = byId.get(photo.id); + if (existing) { + existing.sets.push(set.id); + continue; + } + byId.set(photo.id, { + id: photo.id, + src: this.imagePath(gallery.id, photo.id), + alt: photo.originalName, + width: photo.width ?? 1600, + height: photo.height ?? 1067, + sets: [set.id], + }); + } + } + const photos = [...byId.values()]; + const cover = (gallery.coverPhotoId && photos.find((photo) => photo.id === gallery.coverPhotoId)?.src) || photos[0]?.src || ""; + return { + slug: gallery.slug, + studio: brand.studio, + title: gallery.title, + date: gallery.dateLabel, + language: gallery.language === "en" ? "en" : "pt", + cover, + template: design.cover, + palette: design.palette, + font: design.font, + grid: design.grid, + size: design.size, + spacing: design.spacing, + focalX: design.focalX, + focalY: design.focalY, + favorites: gallery.favorites, + reviews: gallery.reviews, + downloads: { single: downloads.single, gallery: downloads.gallery, hasPin: downloads.pinHash !== null }, + sets: gallery.sets.map((set) => ({ id: set.id, name: set.name })), + photos, + }; + } + + private async freeSlug(base: string): Promise { + let slug = base; + for (let n = 2; n < 40; n += 1) { + const taken = await this.db.siteGallery.findUnique({ where: { slug }, select: { id: true } }); + if (!taken) return slug; + slug = `${base}-${n}`.slice(0, 80); + } + throw conflict("slug_taken"); + } + + private async storeDownloads(input: SiteGalleryDownloadsInput, current: StoredDownloads | null): Promise { + let pinHash = current?.pinHash ?? null; + if (input.pin === null) pinHash = null; + else if (typeof input.pin === "string") pinHash = await hashPassword(input.pin); + return { gallery: input.gallery, single: input.single, size: input.size, limit: input.limit, pinHash, used: current?.used ?? 0 }; + } +} diff --git a/apps/api/test/modules.test.ts b/apps/api/test/modules.test.ts new file mode 100644 index 0000000..9af3b18 --- /dev/null +++ b/apps/api/test/modules.test.ts @@ -0,0 +1,85 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { LEGACY_ORG_MODULES } from "@photoreport/contracts"; +import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; + +let ctx: TestContext; +beforeAll(async () => { + ctx = await createTestApp(); +}); +afterAll(async () => { + await ctx.app.close(); + await ctx.db.$disconnect(); +}); +beforeEach(() => resetDb(ctx.db)); + +describe("workspace modules", () => { + it("follows the role until an admin grants site galleries", async () => { + const { org, user: owner } = await seedUser(ctx.db, "owner@photoreport.pt", { org: "photoreport", role: "OWNER" }); + const { user: photographer } = await seedUser(ctx.db, "foto@photoreport.pt", { org: "photoreport", role: "PHOTOGRAPHER" }); + const ownerSession = await login(ctx.app, "owner@photoreport.pt"); + const photoSession = await login(ctx.app, "foto@photoreport.pt"); + const orgId = org?.id; + if (!orgId) throw new Error("missing org"); + + const me = await ctx.app.inject({ method: "GET", url: "/v1/me", headers: bearer(photoSession.body.accessToken) }); + expect(me.json().memberships[0].modules).toEqual(["library", "develop"]); + expect(me.json().memberships[0].organization.modules).toEqual([...LEGACY_ORG_MODULES]); + + const blocked = await ctx.app.inject({ + method: "GET", + url: `/v1/orgs/${orgId}/galleries`, + headers: bearer(photoSession.body.accessToken), + }); + expect(blocked.statusCode).toBe(403); + expect(blocked.json().error).toBe("module_disabled"); + + const offered = [...LEGACY_ORG_MODULES, "siteGallery"]; + const turnedOn = await ctx.app.inject({ + method: "PUT", + url: `/v1/orgs/${orgId}/modules`, + headers: bearer(ownerSession.body.accessToken), + payload: { appModules: offered }, + }); + expect(turnedOn.statusCode).toBe(200); + expect(turnedOn.json().modules).toContain("siteGallery"); + + const ownerLocked = await ctx.app.inject({ + method: "PUT", + url: `/v1/orgs/${orgId}/members/${owner.id}/modules`, + headers: bearer(ownerSession.body.accessToken), + payload: { appModules: ["library"] }, + }); + expect(ownerLocked.json().error).toBe("owner_has_org_modules"); + + const granted = await ctx.app.inject({ + method: "PUT", + url: `/v1/orgs/${orgId}/members/${photographer.id}/modules`, + headers: bearer(ownerSession.body.accessToken), + payload: { appModules: ["library", "develop", "siteGallery"] }, + }); + expect(granted.statusCode).toBe(200); + expect(granted.json().modules).toEqual(["library", "develop", "siteGallery"]); + + const again = await ctx.app.inject({ method: "GET", url: "/v1/me", headers: bearer(photoSession.body.accessToken) }); + expect(again.json().memberships[0].modules).toEqual(["library", "develop", "siteGallery"]); + }); + + it("refuses a module the server does not offer", async () => { + const limited = await createTestApp({ PHOTOREPORT_APP_MODULES: "library,develop" }); + try { + const { org } = await seedUser(limited.db, "owner@photoreport.pt", { org: "photoreport", role: "OWNER" }); + const session = await login(limited.app, "owner@photoreport.pt"); + const res = await limited.app.inject({ + method: "PUT", + url: `/v1/orgs/${org?.id}/modules`, + headers: bearer(session.body.accessToken), + payload: { appModules: ["library", "develop", "shop"] }, + }); + expect(res.statusCode).toBe(403); + expect(res.json().error).toBe("module_unavailable"); + } finally { + await limited.app.close(); + await limited.db.$disconnect(); + } + }); +}); diff --git a/apps/app/src/App.tsx b/apps/app/src/App.tsx index 022ab97..d57a423 100644 --- a/apps/app/src/App.tsx +++ b/apps/app/src/App.tsx @@ -1,7 +1,10 @@ +import type { AppModule } from "@photoreport/contracts"; import type { ApiClient } from "@photoreport/sdk"; +import type { ReactNode } from "react"; import { BrowserRouter, Navigate, Route, Routes, useLocation } from "react-router"; import { AuthProvider, useAuth } from "./auth.js"; import { t } from "./i18n.js"; +import { MODULE_PATH } from "./modules.js"; import { ArchivePage } from "./pages/ArchivePage.js"; import { DevelopPage } from "./pages/DevelopPage.js"; import { DeliveryPage } from "./pages/DeliveryPage.js"; @@ -10,6 +13,7 @@ import { HelpPage } from "./pages/HelpPage.js"; import { NumbersPage } from "./pages/NumbersPage.js"; import { PrintPage } from "./pages/PrintPage.js"; import { ShopPage } from "./pages/ShopPage.js"; +import { SiteGalleriesPage } from "./pages/SiteGalleriesPage.js"; import { DevicePage } from "./pages/DevicePage.js"; import { LibraryPage } from "./pages/LibraryPage.js"; import { LoginPage } from "./pages/LoginPage.js"; @@ -18,6 +22,21 @@ import { MetadataPage } from "./pages/MetadataPage.js"; import { PreferencesPage } from "./pages/PreferencesPage.js"; import { Shell } from "./pages/Shell.js"; +function ModuleGate({ module, children }: { module: AppModule; children: ReactNode }) { + const { modules } = useAuth(); + if (!modules.includes(module)) return

{t.noAccess}

; + return children; +} + +/** Library when this person has it; otherwise the first module they do have. */ +function Home() { + const { modules } = useAuth(); + if (modules.includes("library")) return ; + const next = (Object.keys(MODULE_PATH) as AppModule[]).find((id) => id !== "library" && modules.includes(id)); + if (next) return ; + return

{t.noAccess}

; +} + function Gate() { const { status } = useAuth(); const location = useLocation(); @@ -28,15 +47,16 @@ function Gate() { } /> }> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> } /> } /> } /> diff --git a/apps/app/src/auth.tsx b/apps/app/src/auth.tsx index 9660427..89c4f46 100644 --- a/apps/app/src/auth.tsx +++ b/apps/app/src/auth.tsx @@ -1,7 +1,9 @@ +import type { AppModule } from "@photoreport/contracts"; import type { ApiClient, Me, Organization, Role } from "@photoreport/sdk"; import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { createApi } from "./api.js"; import { isNetworkError } from "./offline/queue.js"; +import { workspaceModules } from "./modules.js"; import { isDesktop, prefs } from "./platform.js"; type Status = "loading" | "signedOut" | "signedIn"; @@ -12,6 +14,8 @@ interface AuthState { me: Me | null; organization: Organization | null; role: Role | null; + /** Modules this person can open in the current organization. */ + modules: AppModule[]; selectOrganization: (id: string) => void; signIn: (email: string, password: string) => Promise; completeDeviceSignIn: () => Promise; @@ -83,6 +87,7 @@ export function AuthProvider({ children, api: injected }: { children: ReactNode; me, organization: membership?.organization ?? null, role: membership?.role ?? null, + modules: workspaceModules(membership), selectOrganization: (id) => { setOrgId(id); prefs.set("org", id); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index d3a480b..1d8096e 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -33,6 +33,7 @@ export const t = { archiveNav: "Arquivo", facesNav: "Caras", numbersNav: "Camisolas", + siteGalleryNav: "Galerias", delivery: "Entregar", soon: "Em breve", events: "Eventos", @@ -1444,10 +1445,120 @@ export const t = { hdr: "HDR", advanced: "Avançado", }, + appModuleNames: { + library: "Biblioteca", + develop: "Revelar", + metadata: "Metadados", + delivery: "Entregar", + siteGallery: "Galerias", + shop: "Vendas", + print: "Impressão", + archive: "Arquivo", + faces: "Caras", + numbers: "Camisolas", + }, + orgModulesTitle: "Módulos da organização", + orgModulesHelp: "O que esta organização tem. Quem não tiver um módulo não o vê na web nem na app de secretária.", + memberModulesTitle: "Módulos de cada pessoa", + memberModulesHelp: "Sem uma lista própria, a pessoa segue o papel. Fotógrafo e cliente ficam com Biblioteca e Revelar. A partir de ingester ficam com os módulos da organização, e Galerias marca-se à parte. O proprietário tem os módulos da organização.", + followsRole: "Segue o papel", + useRoleModules: "Seguir o papel", + siteGalleries: { + title: "Galerias", + lead: "Entrega de uma sessão para uma galeria num site, com link para quem a recebe. A loja de jogos fica em Vendas. O envio de ficheiros fica em Entregar.", + emptyTitle: "Ainda não há galerias de cliente", + empty: "Cria uma com o nome da sessão. As fotos saem da biblioteca, com a capa, os conjuntos e as pessoas com quem a partilhas.", + example: "Há uma galeria de exemplo no site, em /cliente/exemplo.", + openExample: "Abrir o exemplo", + newTitle: "Nova galeria", + date: "Data", + event: "Sessão", + noEvent: "Sem sessão", + create: "Criar galeria", + waiting: "À espera de ligação", + published: "No ar", + draft: "Rascunho", + back: "Todas as galerias", + general: "Geral", + sets: "Conjuntos", + design: "Desenho", + share: "Partilhar", + slug: "Endereço", + language: "Língua", + password: "Palavra-passe", + passwordHint: "Em branco mantém a actual. Escreve uma nova para a mudar.", + clearPassword: "Tirar a palavra-passe", + favorites: "Favoritas", + reviews: "Notas de quem vê", + publish: "Publicar", + unpublish: "Tirar do ar", + offline: "Fecha em", + save: "Guardar", + saved: "Guardado", + link: "Ligação", + copy: "Copiar", + copied: "Ligação copiada", + setName: "Nome do conjunto", + addSet: "Acrescentar conjunto", + saveSets: "Guardar conjuntos", + pickEvent: "Esta sessão ainda não tem fotografias prontas.", + noPhotos: "Ainda não há fotografias prontas na biblioteca.", + useCover: "Usar como capa", + isCover: "Capa", + cover: "Capa", + palette: "Paleta", + font: "Letra", + grid: "Grelha", + size: "Tamanho", + spacing: "Espaço", + focal: "Ponto da capa", + email: "Para", + subject: "Assunto", + message: "Mensagem", + send: "Enviar", + sentMail: "Enviada", + keptMail: "Guardada, sem correio. A ligação está pronta a copiar.", + views: "Visitas", + reviewCount: "Notas", + downloadsUsed: "Descargas", + studio: "Nome no site", + contact: "Email de contacto", + instagram: "Instagram", + website: "Site", + terms: "Termos", + privacy: "Privacidade", + saveBrand: "Guardar marca", + remove: "Apagar galeria", + pin: "PIN das descargas", + pinHint: "Em branco mantém o PIN. Escreve um novo, ou marca para o tirar.", + clearPin: "Tirar o PIN", + downloadGallery: "Descarregar a galeria", + downloadSingle: "Descarregar uma foto", + downloadSize: "Tamanho", + web: "Web", + original: "Original", + limit: "Limite de descargas", + noLimit: "Sem limite", + covers: { framed: "Moldura", classic: "Clássica", timeless: "Ampla", simplicity: "Simples", modern: "Moderna" }, + palettes: { paper: "Papel", ink: "Tinta", sand: "Areia", night: "Noite", forest: "Floresta" }, + fonts: { serif: "Serifada", sans: "Reta" }, + grids: { masonry: "Mosaico", rows: "Filas", square: "Quadrados" }, + sizes: { s: "Pequeno", m: "Médio", l: "Grande" }, + spacings: { tight: "Junta", regular: "Normal", wide: "Larga" }, + errors: { + slug_taken: "Esse endereço já existe.", + not_your_photo: "Só podes pôr fotografias tuas.", + not_your_event: "Essa sessão não te foi atribuída.", + photo_not_ready: "Uma das fotografias ainda não está pronta.", + generic: "Não foi possível guardar.", + }, + }, memberErrors: { user_not_found: "Não existe conta com esse email. Indica nome e palavra-passe inicial para a criar.", already_member: "Essa pessoa já é membro.", cannot_grant_higher_role: "Não podes dar um papel acima do teu.", last_owner: "A organização tem de ter pelo menos um proprietário.", + module_unavailable: "Esse módulo não está disponível nesta organização.", + owner_has_org_modules: "O proprietário tem os módulos da organização.", } as Record, } as const; diff --git a/apps/app/src/modules.test.ts b/apps/app/src/modules.test.ts new file mode 100644 index 0000000..1144c86 --- /dev/null +++ b/apps/app/src/modules.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import { workspaceModules } from "./modules.js"; + +describe("workspaceModules", () => { + it("uses the list the server already resolved", () => { + expect(workspaceModules({ role: "PHOTOGRAPHER", modules: ["library"] })).toEqual(["library"]); + }); + + it("falls back to the role when the saved session has no modules yet", () => { + expect(workspaceModules({ role: "PHOTOGRAPHER" })).toEqual(["library", "develop"]); + expect(workspaceModules({ role: "EDITOR" })).not.toContain("siteGallery"); + }); +}); diff --git a/apps/app/src/modules.ts b/apps/app/src/modules.ts new file mode 100644 index 0000000..9c0087a --- /dev/null +++ b/apps/app/src/modules.ts @@ -0,0 +1,26 @@ +import { APP_MODULES, memberModuleList, type AppModule, type MembershipRole } from "@photoreport/contracts"; +import type { Role } from "@photoreport/sdk"; + +/** Where each workspace module lives. Library is the front page. */ +export const MODULE_PATH: Record = { + library: "/", + develop: "/develop", + metadata: "/metadata", + delivery: "/delivery", + siteGallery: "/site-galleries", + shop: "/shop", + print: "/print", + archive: "/archive", + faces: "/faces", + numbers: "/numbers", +}; + +/** + * Modules for the open organization. + * A session saved before modules existed has no list: use the role, without site galleries. + */ +export function workspaceModules(membership: { role: Role; modules?: readonly AppModule[] | null } | null): AppModule[] { + if (!membership) return []; + if (Array.isArray(membership.modules)) return [...membership.modules]; + return memberModuleList(membership.role as MembershipRole, null, APP_MODULES.filter((id) => id !== "siteGallery")); +} diff --git a/apps/app/src/offline/siteGalleries.ts b/apps/app/src/offline/siteGalleries.ts new file mode 100644 index 0000000..88e682e --- /dev/null +++ b/apps/app/src/offline/siteGalleries.ts @@ -0,0 +1,51 @@ +import type { ApiClient } from "@photoreport/sdk"; +import { isNetworkError } from "./queue.js"; + +/** A gallery typed here while the server could not be reached. It is created when the link is back. */ +export interface PendingSiteGallery { + localId: string; + title: string; + dateLabel: string; + eventId: string | null; +} + +const key = (orgId: string) => `pr.site-gallery.${orgId}`; + +export function pendingSiteGalleries(orgId: string): PendingSiteGallery[] { + try { + const raw = localStorage.getItem(key(orgId)); + if (!raw) return []; + const parsed = JSON.parse(raw) as unknown; + if (!Array.isArray(parsed)) return []; + return parsed.filter((row): row is PendingSiteGallery => { + if (!row || typeof row !== "object") return false; + const item = row as PendingSiteGallery; + return typeof item.localId === "string" && typeof item.title === "string"; + }); + } catch { + return []; + } +} + +export function rememberSiteGallery(orgId: string, row: PendingSiteGallery): void { + const rows = pendingSiteGalleries(orgId).filter((item) => item.localId !== row.localId); + rows.unshift(row); + localStorage.setItem(key(orgId), JSON.stringify(rows)); +} + +export function forgetSiteGallery(orgId: string, localId: string): void { + localStorage.setItem(key(orgId), JSON.stringify(pendingSiteGalleries(orgId).filter((item) => item.localId !== localId))); +} + +/** Sends galleries that were kept offline. Stops at the first one the network still refuses. */ +export async function flushSiteGalleries(api: ApiClient, orgId: string): Promise { + for (const row of pendingSiteGalleries(orgId)) { + try { + await api.createSiteGallery(orgId, { title: row.title, dateLabel: row.dateLabel, eventId: row.eventId }); + forgetSiteGallery(orgId, row.localId); + } catch (err) { + if (isNetworkError(err)) return; + forgetSiteGallery(orgId, row.localId); + } + } +} diff --git a/apps/app/src/pages/MembersPage.tsx b/apps/app/src/pages/MembersPage.tsx index bbf6de7..f95648b 100644 --- a/apps/app/src/pages/MembersPage.tsx +++ b/apps/app/src/pages/MembersPage.tsx @@ -1,3 +1,4 @@ +import { APP_MODULES, type AppModule } from "@photoreport/contracts"; import { ApiError, hasRole, type Member, type Role } from "@photoreport/sdk"; import { useCallback, useEffect, useState, type FormEvent } from "react"; import { useAuth } from "../auth.js"; @@ -18,8 +19,39 @@ const ROLES: Role[] = [ const memberError = (err: unknown) => (err instanceof ApiError && t.memberErrors[err.code]) || t.unexpectedError; +function ModuleChecks({ + ids, + selected, + disabled, + onToggle, +}: { + ids: readonly AppModule[]; + selected: readonly AppModule[]; + disabled?: boolean; + onToggle: (id: AppModule, on: boolean) => void; +}) { + return ( +
    + {ids.map((id) => ( +
  • + +
  • + ))} +
+ ); +} + export function MembersPage() { - const { api, organization, role } = useAuth(); + const { api, organization, role, reload } = useAuth(); const [members, setMembers] = useState([]); const [error, setError] = useState(null); const [form, setForm] = useState({ @@ -39,9 +71,45 @@ export function MembersPage() { load().catch((err) => setError(memberError(err))); }, [load]); - if (!orgId || !role || !hasRole(role, "ADMIN")) + if (!orgId || !organization || !role || !hasRole(role, "ADMIN")) return

{t.noAccess}

; const grantable = ROLES.filter((r) => hasRole(role, r)); + const catalog = organization.moduleCatalog ?? [...APP_MODULES]; + const orgEnabled = organization.modules ?? catalog.filter((id) => id !== "siteGallery"); + + const setOrgModule = async (id: AppModule, on: boolean) => { + const next = on ? [...orgEnabled, id] : orgEnabled.filter((item) => item !== id); + setError(null); + try { + await api.updateOrgModules(orgId, catalog.filter((item) => next.includes(item))); + await reload(); + await load(); + } catch (err) { + setError(memberError(err)); + } + }; + + const setMemberModule = async (member: Member, id: AppModule, on: boolean) => { + const current = member.modules ?? []; + const next = on ? [...current, id] : current.filter((item) => item !== id); + setError(null); + try { + await api.updateMemberModules(orgId, member.userId, orgEnabled.filter((item) => next.includes(item))); + await load(); + } catch (err) { + setError(memberError(err)); + } + }; + + const followRole = async (userId: string) => { + setError(null); + try { + await api.updateMemberModules(orgId, userId, null); + await load(); + } catch (err) { + setError(memberError(err)); + } + }; const add = async (e: FormEvent) => { e.preventDefault(); @@ -83,6 +151,11 @@ export function MembersPage() { return ( <> + {error && ( +
+ {error} +
+ )}
@@ -135,6 +208,38 @@ export function MembersPage() {
+
+

{t.orgModulesTitle}

+

{t.orgModulesHelp}

+ void setOrgModule(id, on)} /> +
+
+
+

{t.memberModulesTitle}

+

{t.memberModulesHelp}

+
+ {members.map((m) => ( +
+
+

+ {m.name} · {t.roles[m.role]} +

+ {m.role !== "OWNER" && m.appModules == null && {t.followsRole}} + {m.role !== "OWNER" && m.appModules != null && ( + + )} +
+ void setMemberModule(m, id, on)} + /> +
+ ))} +
@@ -143,7 +248,6 @@ export function MembersPage() { className="h-fit space-y-3 rounded-lg border border-line bg-panel p-4" >

{t.addMember}

- {error && {error}} `px-3 py-1 font-display text-[19px] max-sm:px-2 max-sm:text-[15px] font-semibold uppercase tracking-wide transition-colors ${ isActive ? "text-ink" : "text-[#6a6a6a] hover:text-muted" @@ -23,10 +38,10 @@ const moduleClass = ({ isActive }: { isActive: boolean }) => * Account pages (members, preferences) live in the user menu. */ export function Shell() { - const { me, organization, role, selectOrganization, signOut } = useAuth(); + const { me, organization, role, modules, selectOrganization, signOut } = useAuth(); if (!me) return null; const canManage = role !== null && hasRole(role, "ADMIN"); - const canCull = role !== null && hasRole(role, "INGESTER"); + const visible = NAV.filter((item) => modules.includes(item.id)); return (
@@ -60,61 +75,18 @@ export function Shell() {
@@ -162,16 +134,21 @@ export function Shell() { /** Follows the assistant: the open window changes module, photo or tool. */ function DeskHost() { const navigate = useNavigate(); + const { modules } = useAuth(); + const open = modules.join(","); useEffect(() => { + const allowed = new Set(open.split(",").filter(Boolean)); const onDesk = (ev: Event) => { const command = (ev as CustomEvent).detail; if (!command || typeof command.module !== "string") return; + const account = command.module === "help" || command.module === "preferences" || command.module === "members"; + if (!account && !allowed.has(command.module)) return; navigate(deskPath(command), { state: deskState(command) }); if (command.eventId) window.dispatchEvent(new CustomEvent("photoreport-open-event", { detail: command.eventId })); }; window.addEventListener("photoreport-desk", onDesk); return () => window.removeEventListener("photoreport-desk", onDesk); - }, [navigate]); + }, [open, navigate]); return null; } diff --git a/apps/app/src/pages/SiteGalleriesPage.tsx b/apps/app/src/pages/SiteGalleriesPage.tsx new file mode 100644 index 0000000..0b5e5f0 --- /dev/null +++ b/apps/app/src/pages/SiteGalleriesPage.tsx @@ -0,0 +1,580 @@ +import type { CoverTemplate, GalleryFont, GalleryGrid, GalleryPalette, GallerySize, GallerySpacing, PhotoSummary, SiteGalleryBrand, SiteGalleryDetail, SiteGallerySummary } from "@photoreport/contracts"; +import { ApiError, hasRole } from "@photoreport/sdk"; +import { useEffect, useState } from "react"; +import { useAuth } from "../auth.js"; +import { t } from "../i18n.js"; +import { EVENTS_URL } from "../api.js"; +import { flushSiteGalleries, forgetSiteGallery, pendingSiteGalleries, rememberSiteGallery, type PendingSiteGallery } from "../offline/siteGalleries.js"; +import { isNetworkError } from "../offline/queue.js"; +import { PageHeader } from "./Shell.js"; + +const fieldClass = "mt-1 h-9 w-full border border-line bg-canvas px-2 text-sm"; +const labelClass = "block text-xs text-muted"; + +function sessionDate(iso: string): string { + const when = new Date(iso); + if (Number.isNaN(when.getTime())) return ""; + return when.toLocaleDateString("pt-PT", { day: "numeric", month: "long", year: "numeric" }); +} + +function messageFor(err: unknown): string { + if (err instanceof ApiError) { + const known = t.siteGalleries.errors[err.code as keyof typeof t.siteGalleries.errors]; + if (known) return known; + } + return t.siteGalleries.errors.generic; +} + +/** + * Client galleries: a delivery into a page on the site. + * Separate from the sports shop and from file delivery. + * A gallery typed without a network waits on this computer and is created when the link returns. + */ +export function SiteGalleriesPage() { + const { api, organization, role } = useAuth(); + const orgId = organization?.id ?? ""; + const copy = t.siteGalleries; + const [galleries, setGalleries] = useState([]); + const [pending, setPending] = useState([]); + const [linkBase, setLinkBase] = useState(""); + const [brand, setBrand] = useState(null); + const [events, setEvents] = useState<{ id: string; title: string; startsAt: string }[]>([]); + const [openId, setOpenId] = useState(null); + const [error, setError] = useState(null); + const [title, setTitle] = useState(""); + const [dateLabel, setDateLabel] = useState(""); + const [eventId, setEventId] = useState(""); + const [busy, setBusy] = useState(false); + + async function reload() { + if (!orgId) return; + await flushSiteGalleries(api, orgId); + const [list, mark, agenda] = await Promise.all([ + api.listSiteGalleries(orgId), + api.siteGalleryBrand(orgId), + api.listEvents(orgId), + ]); + setGalleries(list.galleries); + setLinkBase(list.linkBase); + setBrand(mark); + setEvents(agenda.events.map((event) => ({ id: event.id, title: event.title, startsAt: event.startsAt }))); + setPending(pendingSiteGalleries(orgId)); + } + + useEffect(() => { + if (!orgId) return; + void reload().catch((err: unknown) => setError(messageFor(err))); + }, [orgId]); + + async function createGallery() { + if (!orgId || title.trim().length === 0) return; + setBusy(true); + setError(null); + const body = { title: title.trim(), dateLabel: dateLabel.trim(), eventId: eventId || null }; + try { + const created = await api.createSiteGallery(orgId, body); + setTitle(""); + setDateLabel(""); + setEventId(""); + await reload(); + setOpenId(created.id); + } catch (err) { + if (isNetworkError(err)) { + const localId = `local:${crypto.randomUUID()}`; + rememberSiteGallery(orgId, { localId, title: body.title, dateLabel: body.dateLabel, eventId: body.eventId }); + setPending(pendingSiteGalleries(orgId)); + setTitle(""); + setDateLabel(""); + setEventId(""); + } else { + setError(messageFor(err)); + } + } finally { + setBusy(false); + } + } + + if (openId && orgId) { + return ( + { + setOpenId(null); + void reload(); + }} + /> + ); + } + + const isAdmin = role !== null && hasRole(role, "ADMIN"); + + return ( + <> + +
+

{copy.lead}

+ {error &&

{error}

} +
{ + event.preventDefault(); + void createGallery(); + }} + > + + + +
+ +
+
+ {galleries.length === 0 && pending.length === 0 ? ( +
+

{copy.emptyTitle}

+

{copy.empty}

+

{copy.example}

+ {import.meta.env.DEV && ( +

+ {copy.openExample} +

+ )} +
+ ) : ( +
    + {pending.map((row) => ( +
  • + + {row.title} + {copy.waiting} + + +
  • + ))} + {galleries.map((gallery) => ( +
  • + +
  • + ))} +
+ )} + {isAdmin && brand && } +
+ + ); +} + +function BrandForm({ orgId, brand, onSaved }: { orgId: string; brand: SiteGalleryBrand; onSaved: (brand: SiteGalleryBrand) => void }) { + const { api } = useAuth(); + const copy = t.siteGalleries; + const [studio, setStudio] = useState(brand.studio); + const [contactEmail, setContactEmail] = useState(brand.contactEmail ?? ""); + const [instagram, setInstagram] = useState(brand.instagram ?? ""); + const [website, setWebsite] = useState(brand.website ?? ""); + const [termsUrl, setTermsUrl] = useState(brand.termsUrl ?? ""); + const [privacyUrl, setPrivacyUrl] = useState(brand.privacyUrl ?? ""); + const [error, setError] = useState(null); + + return ( +
{ + event.preventDefault(); + void api.saveSiteGalleryBrand(orgId, { + studio: studio.trim(), + contactEmail: contactEmail.trim() || null, + instagram: instagram.trim() || null, + website: website.trim() || null, + termsUrl: termsUrl.trim() || null, + privacyUrl: privacyUrl.trim() || null, + }).then(onSaved, (err: unknown) => setError(messageFor(err))); + }} + > +

{copy.studio}

+ + + + + + + {error &&

{error}

} + +
+ ); +} + +function Editor({ orgId, galleryId, linkBase, events, onBack }: { orgId: string; galleryId: string; linkBase: string; events: { id: string; title: string }[]; onBack: () => void }) { + const { api } = useAuth(); + const copy = t.siteGalleries; + const [detail, setDetail] = useState(null); + const [tab, setTab] = useState<"general" | "sets" | "design" | "share">("general"); + const [error, setError] = useState(null); + const [notice, setNotice] = useState(null); + const [photos, setPhotos] = useState([]); + + useEffect(() => { + void api.siteGallery(orgId, galleryId).then(setDetail, (err: unknown) => setError(messageFor(err))); + }, [api, orgId, galleryId]); + + useEffect(() => { + const query = { status: "READY" as const, limit: 200, ...(detail?.eventId ? { event: detail.eventId } : {}) }; + void api.listPhotos(orgId, query).then((page) => setPhotos(page.photos), () => setPhotos([])); + }, [api, orgId, detail?.eventId]); + + if (!detail) { + return ( + <> + +

{error ?? ""}

+ + ); + } + + const link = `${linkBase}/${detail.slug}`; + const tabs = [ + ["general", copy.general], + ["sets", copy.sets], + ["design", copy.design], + ["share", copy.share], + ] as const; + + return ( + <> + +
+ +
+ {tabs.map(([id, label]) => ( + + ))} +
+ {error &&

{error}

} + {notice &&

{notice}

} + {tab === "general" && ( + { setDetail(next); setNotice(copy.saved); }} + onError={setError} + onRemove={async () => { + await api.deleteSiteGallery(orgId, galleryId); + onBack(); + }} + /> + )} + {tab === "sets" && ( + { setDetail(next); setNotice(copy.saved); }} + onError={setError} + /> + )} + {tab === "design" && { setDetail(next); setNotice(copy.saved); }} onError={setError} />} + {tab === "share" && { setDetail(next); setNotice(copy.saved); }} onError={setError} />} +

{copy.views}: {detail.views} · {copy.reviewCount}: {detail.reviewCount} · {copy.downloadsUsed}: {detail.downloads.used}

+
+ + ); +} + +function General({ detail, events, link, onSaved, onError, onRemove }: { detail: SiteGalleryDetail; events: { id: string; title: string }[]; link: string; onSaved: (detail: SiteGalleryDetail) => void; onError: (message: string) => void; onRemove: () => Promise }) { + const { api, organization } = useAuth(); + const copy = t.siteGalleries; + const orgId = organization?.id ?? ""; + const [title, setTitle] = useState(detail.title); + const [dateLabel, setDateLabel] = useState(detail.dateLabel); + const [slug, setSlug] = useState(detail.slug); + const [language, setLanguage] = useState(detail.language); + const [eventId, setEventId] = useState(detail.eventId ?? ""); + const [password, setPassword] = useState(""); + const [clearPassword, setClearPassword] = useState(false); + const [favorites, setFavorites] = useState(detail.favorites); + const [reviews, setReviews] = useState(detail.reviews); + const [offline, setOffline] = useState(detail.offlineAt ? detail.offlineAt.slice(0, 16) : ""); + const [galleryDownload, setGalleryDownload] = useState(detail.downloads.gallery); + const [singleDownload, setSingleDownload] = useState(detail.downloads.single); + const [size, setSize] = useState(detail.downloads.size); + const [limit, setLimit] = useState(detail.downloads.limit === null ? "" : String(detail.downloads.limit)); + const [pin, setPin] = useState(""); + const [clearPin, setClearPin] = useState(false); + + return ( +
{ + event.preventDefault(); + const downloads = { + gallery: galleryDownload, + single: singleDownload, + size, + limit: limit.trim() === "" ? null : Number(limit), + ...(clearPin ? { pin: null } : pin.trim() ? { pin: pin.trim() } : {}), + }; + void api.updateSiteGallery(orgId, detail.id, { + title, + dateLabel, + slug, + language, + eventId: eventId || null, + favorites, + reviews, + offlineAt: offline ? new Date(offline) : null, + downloads, + ...(clearPassword ? { password: null } : password.trim() ? { password: password.trim() } : {}), + }).then(onSaved, (err: unknown) => onError(messageFor(err))); + }} + > + + + + + + + +

{copy.passwordHint}

+ + + + + + + + +

{copy.pinHint}

+ +

+ {copy.link}: {link} +

+
+ + + +
+
+ ); +} + +function Sets({ detail, photos, onSaved, onError }: { detail: SiteGalleryDetail; photos: PhotoSummary[]; onSaved: (detail: SiteGalleryDetail) => void; onError: (message: string) => void }) { + const { api, organization } = useAuth(); + const copy = t.siteGalleries; + const orgId = organization?.id ?? ""; + const [sets, setSets] = useState(detail.sets.map((set) => ({ name: set.name, photoIds: set.photoIds }))); + const [index, setIndex] = useState(0); + const [name, setName] = useState(""); + const current = sets[index]; + + function toggle(photoId: string) { + setSets((prev) => prev.map((set, i) => { + if (i !== index) return set; + const has = set.photoIds.includes(photoId); + const photoIds = has ? set.photoIds.filter((id) => id !== photoId) : [...set.photoIds, photoId]; + return { ...set, photoIds }; + })); + } + + return ( +
+ {photos.length === 0 &&

{detail.eventId ? copy.pickEvent : copy.noPhotos}

} +
+ {sets.map((set, i) => ( + + ))} +
+
{ + event.preventDefault(); + if (name.trim().length === 0) return; + const nextName = name.trim(); + setIndex(sets.length); + setSets((prev) => [...prev, { name: nextName, photoIds: [] }]); + setName(""); + }} + > + setName(event.target.value)} placeholder={copy.setName} aria-label={copy.setName} /> + +
+ {current && ( +
+ {photos.map((photo) => { + const on = current.photoIds.includes(photo.id); + return ( +
+ + {on && ( + + )} +
+ ); + })} +
+ )} + +
+ ); +} + +function Design({ detail, onSaved, onError }: { detail: SiteGalleryDetail; onSaved: (detail: SiteGalleryDetail) => void; onError: (message: string) => void }) { + const { api, organization } = useAuth(); + const copy = t.siteGalleries; + const orgId = organization?.id ?? ""; + const [design, setDesign] = useState(detail.design); + + function choose(key: K, value: (typeof design)[K]) { + setDesign({ ...design, [key]: value }); + } + + return ( +
{ + event.preventDefault(); + void api.updateSiteGallery(orgId, detail.id, { design }).then(onSaved, (err: unknown) => onError(messageFor(err))); + }} + > + choose("palette", value as GalleryPalette)} /> + choose("grid", value as GalleryGrid)} /> + choose("spacing", value as GallerySpacing)} /> + + + +
+ ); +} + +function Select({ label, value, options, onChange }: { label: string; value: string; options: Record; onChange: (value: string) => void }) { + return ( + + ); +} + +function Share({ detail, link, onSaved, onError }: { detail: SiteGalleryDetail; link: string; onSaved: (detail: SiteGalleryDetail) => void; onError: (message: string) => void }) { + const { api, organization } = useAuth(); + const copy = t.siteGalleries; + const orgId = organization?.id ?? ""; + const [email, setEmail] = useState(""); + const [subject, setSubject] = useState(detail.title); + const [message, setMessage] = useState(""); + const [copied, setCopied] = useState(false); + + return ( +
+

+ {copy.link}: +

+
{ + event.preventDefault(); + void api.shareSiteGallery(orgId, detail.id, { email, subject, message }).then((next) => { + setEmail(""); + onSaved(next); + }, (err: unknown) => onError(messageFor(err))); + }} + > + + +