Compare commits

...

8 Commits

36 changed files with 2205 additions and 114 deletions

View File

@@ -10,6 +10,11 @@ CMS_SUPPORT_EMAIL="support@cms.local"
CMS_SUPPORT_PASSWORD="change-me-support-password" CMS_SUPPORT_PASSWORD="change-me-support-password"
CMS_SUPPORT_NAME="Technical Support" CMS_SUPPORT_NAME="Technical Support"
CMS_SUPPORT_LOGIN_KEY="support-access-change-me" CMS_SUPPORT_LOGIN_KEY="support-access-change-me"
# Optional deterministic e2e admin user (seeded by `bun run test:e2e:prepare`)
# CMS_E2E_ADMIN_EMAIL="e2e-admin@cms.local"
# CMS_E2E_ADMIN_USERNAME="e2e-admin"
# CMS_E2E_ADMIN_PASSWORD="e2e-admin-password"
# CMS_E2E_ADMIN_NAME="E2E Admin"
CMS_MEDIA_STORAGE_PROVIDER="s3" CMS_MEDIA_STORAGE_PROVIDER="s3"
CMS_MEDIA_STORAGE_TENANT_ID="default" CMS_MEDIA_STORAGE_TENANT_ID="default"
CMS_MEDIA_UPLOAD_MAX_BYTES="26214400" CMS_MEDIA_UPLOAD_MAX_BYTES="26214400"

View File

@@ -55,7 +55,7 @@ jobs:
run: bun run commitlint run: bun run commitlint
quality: quality:
name: Lint Typecheck Unit E2E name: Lint Typecheck (Testing Paused)
needs: governance needs: governance
runs-on: node22-bun runs-on: node22-bun
services: services:
@@ -90,9 +90,6 @@ jobs:
echo "NEXT_PUBLIC_APP_VERSION=$version" >> "$GITHUB_ENV" echo "NEXT_PUBLIC_APP_VERSION=$version" >> "$GITHUB_ENV"
echo "NEXT_PUBLIC_GIT_SHA=${GITHUB_SHA}" >> "$GITHUB_ENV" echo "NEXT_PUBLIC_GIT_SHA=${GITHUB_SHA}" >> "$GITHUB_ENV"
- name: Install Playwright browser deps
run: bunx playwright install --with-deps chromium
- name: Lint and format checks - name: Lint and format checks
run: bun run check run: bun run check
@@ -101,9 +98,3 @@ jobs:
- name: Typecheck - name: Typecheck
run: bun run typecheck run: bun run typecheck
- name: Unit and integration tests
run: bun run test
- name: E2E tests
run: bun run test:e2e

104
TODO.md
View File

@@ -59,15 +59,7 @@ This file is the single source of truth for roadmap and delivery progress.
### Testing ### Testing
- [x] [P1] Vitest + Testing Library + MSW baseline - [~] [P1] Testing workstream moved to `MVP 3: Testing and Quality` and temporarily paused to prioritize feature delivery
- [x] [P1] Playwright baseline with web/admin projects
- [x] [P1] CI workflow for lint/typecheck/unit/e2e gates
- [x] [P1] Test data strategy (seed fixtures + isolated e2e data)
- [x] [P1] RBAC policy unit tests and permission regression suite
- [x] [P1] i18n unit tests (locale resolution, fallback, message key loading)
- [x] [P1] i18n integration tests (admin/public locale switch and persistence)
- [x] [P1] i18n e2e smoke tests (localized headings/content per route)
- [x] [P1] CRUD contract tests for shared service patterns
### Documentation ### Documentation
@@ -168,14 +160,14 @@ This file is the single source of truth for roadmap and delivery progress.
- [~] [P1] Dynamic page rendering from CMS page entities - [~] [P1] Dynamic page rendering from CMS page entities
- [~] [P1] Navigation rendering from managed menu structure - [~] [P1] Navigation rendering from managed menu structure
- [ ] [P1] Media entity rendering with enrichment data - [~] [P1] Media entity rendering with enrichment data
- [ ] [P1] Portfolio views (gallery/album/category/tag) for artworks with filter and sort controls - [~] [P1] Portfolio views (gallery/album/category/tag) for artworks with filter and sort controls
- [ ] [P1] Rendition-aware media delivery (thumbnail/card/full) per template slot - [~] [P1] Rendition-aware media delivery (thumbnail/card/full) per template slot
- [~] [P1] Translation-ready content model for public entities (pages/news/navigation labels) - [~] [P1] Translation-ready content model for public entities (pages/news/navigation labels)
- [ ] [P2] Artwork views and listing filters - [ ] [P2] Artwork views and listing filters
- [ ] [P1] Commission request submission flow - [~] [P1] Commission request submission flow
- [x] [P1] Header banner render logic and fallbacks - [x] [P1] Header banner render logic and fallbacks
- [ ] [P1] Announcement render slots (homepage + optional global/top banner position) - [x] [P1] Announcement render slots (homepage + optional global/top banner position)
### News / Blog (Secondary Track) ### News / Blog (Secondary Track)
@@ -186,14 +178,7 @@ This file is the single source of truth for roadmap and delivery progress.
### Testing ### Testing
- [x] [P1] Unit tests for content schemas and service logic - [~] [P1] Testing workstream moved to `MVP 3: Testing and Quality` and temporarily paused to prioritize feature delivery
- [x] [P1] Component tests for admin forms (pages/media/navigation)
- [x] [P1] Integration tests for owner invariant and hidden support-user protection
- [x] [P1] Integration tests for registration allow/deny behavior
- [x] [P1] Integration tests for translated content CRUD and locale-specific validation
- [~] [P1] E2E happy paths: create page, publish, see on public app
- [~] [P1] E2E happy paths: media upload + artwork refinement display
- [~] [P1] E2E happy paths: commissions kanban transitions
### Code Documentation And Handover ### Code Documentation And Handover
@@ -205,21 +190,39 @@ This file is the single source of truth for roadmap and delivery progress.
- [ ] [P2] Add code-level diagrams (Mermaid) for service boundaries and data relationships - [ ] [P2] Add code-level diagrams (Mermaid) for service boundaries and data relationships
- [ ] [P2] Add route/action inventory for admin and public apps with linked source files - [ ] [P2] Add route/action inventory for admin and public apps with linked source files
## MVP 1.5: UX/UI And Theming ## MVP 1.5: MVP1 Refinements (Planned)
### MVP1.5 Suggested Branch Order ### Scope
- [ ] [P1] `todo/mvp15-design-tokens-foundation`: - [ ] [P1] Refine and harden all completed MVP1 modules (pages, navigation, media, portfolio, commissions, news)
- [ ] [P1] Resolve UX rough edges discovered during MVP1 implementation
- [ ] [P1] Improve admin workflows and reduce editor friction for daily use
- [ ] [P1] Stabilize public rendering behavior with better fallbacks and consistency
## MVP 2: MVP1 Quality Refinements (Planned)
### Scope
- [ ] [P1] Finish non-blocking enhancements postponed from MVP1 implementation
- [ ] [P1] Improve data modeling consistency and migration hygiene for MVP1 modules
- [ ] [P1] Consolidate reusable UI and domain primitives introduced during MVP1
- [ ] [P1] Address integration debt before moving to larger design/production phases
## MVP 3: UX/UI And Theming
### MVP3 Suggested Branch Order
- [ ] [P1] `todo/mvp3-design-tokens-foundation`:
establish shared design tokens (color, spacing, radius, typography scale, motion) in `@cms/ui` and app-level theme contracts establish shared design tokens (color, spacing, radius, typography scale, motion) in `@cms/ui` and app-level theme contracts
- [ ] [P1] `todo/mvp15-admin-layout-polish`: - [ ] [P1] `todo/mvp3-admin-layout-polish`:
refine admin shell, navigation hierarchy, spacing rhythm, table/form visual consistency, empty/loading/error states refine admin shell, navigation hierarchy, spacing rhythm, table/form visual consistency, empty/loading/error states
- [ ] [P1] `todo/mvp15-public-layout-and-templates`: - [ ] [P1] `todo/mvp3-public-layout-and-templates`:
define public visual direction (hero/header/footer/content widths), page templates for home/content/news/portfolio define public visual direction (hero/header/footer/content widths), page templates for home/content/news/portfolio
- [ ] [P2] `todo/mvp15-component-library-pass`: - [ ] [P2] `todo/mvp3-component-library-pass`:
align shadcn-based primitives with CMS brand system (buttons, inputs, cards, badges, tabs, dialogs, toasts) align shadcn-based primitives with CMS brand system (buttons, inputs, cards, badges, tabs, dialogs, toasts)
- [ ] [P2] `todo/mvp15-responsive-and-a11y-pass`: - [ ] [P2] `todo/mvp3-responsive-and-a11y-pass`:
mobile/tablet breakpoints, keyboard flow, focus states, contrast checks, reduced-motion support mobile/tablet breakpoints, keyboard flow, focus states, contrast checks, reduced-motion support
- [ ] [P2] `todo/mvp15-visual-regression-baseline`: - [ ] [P2] `todo/mvp3-visual-regression-baseline`:
add screenshot baselines for critical admin/public routes to guard layout regressions add screenshot baselines for critical admin/public routes to guard layout regressions
### Deliverables ### Deliverables
@@ -229,7 +232,7 @@ This file is the single source of truth for roadmap and delivery progress.
- [ ] [P2] Shared UI primitives are consistent across admin and public apps - [ ] [P2] Shared UI primitives are consistent across admin and public apps
- [ ] [P2] Core routes have visual-regression coverage for the new layout baseline - [ ] [P2] Core routes have visual-regression coverage for the new layout baseline
## MVP 2: Production Readiness ## MVP 4: Production Readiness
### Admin App ### Admin App
@@ -268,6 +271,38 @@ This file is the single source of truth for roadmap and delivery progress.
### Testing ### Testing
- [~] [P1] Testing workstream moved to `MVP 5: Testing and Quality` and temporarily paused to prioritize feature delivery
## MVP 5: Testing and Quality
### Status
- [~] [P1] Temporary freeze for active testing execution in local scripts and CI while MVP feature delivery is prioritized
- [ ] [P1] Re-enable root package test scripts (`test`, `test:*`) after MVP feature catch-up
- [ ] [P1] Re-enable CI quality test gates (unit + integration + e2e) in `.gitea/workflows/ci.yml`
### Baseline And Regression
- [x] [P1] Vitest + Testing Library + MSW baseline
- [x] [P1] Playwright baseline with web/admin projects
- [x] [P1] CI workflow for lint/typecheck/unit/e2e gates
- [x] [P1] Test data strategy (seed fixtures + isolated e2e data)
- [x] [P1] RBAC policy unit tests and permission regression suite
- [x] [P1] i18n unit tests (locale resolution, fallback, message key loading)
- [x] [P1] i18n integration tests (admin/public locale switch and persistence)
- [x] [P1] i18n e2e smoke tests (localized headings/content per route)
- [x] [P1] CRUD contract tests for shared service patterns
- [x] [P1] Unit tests for content schemas and service logic
- [x] [P1] Component tests for admin forms (pages/media/navigation)
- [x] [P1] Integration tests for owner invariant and hidden support-user protection
- [x] [P1] Integration tests for registration allow/deny behavior
- [x] [P1] Integration tests for translated content CRUD and locale-specific validation
- [~] [P1] E2E happy paths: create page, publish, see on public app
- [~] [P1] E2E happy paths: media upload + artwork refinement display
- [~] [P1] E2E happy paths: commissions kanban transitions
### Advanced Quality Work
- [ ] [P2] Visual regression workflow for critical templates - [ ] [P2] Visual regression workflow for critical templates
- [ ] [P2] Load/perf tests for key public routes - [ ] [P2] Load/perf tests for key public routes
- [ ] [P2] Flake tracking and quarantine policy for e2e - [ ] [P2] Flake tracking and quarantine policy for e2e
@@ -299,7 +334,7 @@ This file is the single source of truth for roadmap and delivery progress.
- [2026-02-11] Release workflow now publishes changelog-derived notes to Gitea releases and supports executable production rollback via SSH + compose tag switch. - [2026-02-11] Release workflow now publishes changelog-derived notes to Gitea releases and supports executable production rollback via SSH + compose tag switch.
- [2026-02-11] Branch protection verification checklist is now documented; final UI-level verification remains environment-specific. - [2026-02-11] Branch protection verification checklist is now documented; final UI-level verification remains environment-specific.
- [2026-02-11] Added a staging deployment execution checklist and deployment-record template to capture first real-host rollout evidence. - [2026-02-11] Added a staging deployment execution checklist and deployment-record template to capture first real-host rollout evidence.
- [2026-02-11] Artist-focused feature map refined: MVP1 covers portfolio media/domain CRUD + announcements + customer/commission linking; MVP2 covers advanced automation (watermark, palette extraction, media transform pipelines). - [2026-02-11] Artist-focused feature map refined: MVP1 covers portfolio media/domain CRUD + announcements + customer/commission linking; MVP4 covers advanced automation (watermark, palette extraction, media transform pipelines).
- [2026-02-11] `gaertan` inspiration to reuse: S3 object strategy with signed delivery, commission type/options/extras/custom-input modeling, request-status kanban mapping, and gallery rendition/color extraction patterns. - [2026-02-11] `gaertan` inspiration to reuse: S3 object strategy with signed delivery, commission type/options/extras/custom-input modeling, request-status kanban mapping, and gallery rendition/color extraction patterns.
- [2026-02-11] MVP1 media foundation started: portfolio domain models (`MediaAsset`, `Artwork`, galleries/albums/categories/tags, rendition links) plus initial admin `/media` and `/portfolio` data views. - [2026-02-11] MVP1 media foundation started: portfolio domain models (`MediaAsset`, `Artwork`, galleries/albums/categories/tags, rendition links) plus initial admin `/media` and `/portfolio` data views.
- [2026-02-11] `prisma migrate dev --name media_foundation` can fail when DB endpoint is unreachable; apply this named migration once `DATABASE_URL` host is reachable again. - [2026-02-11] `prisma migrate dev --name media_foundation` can fail when DB endpoint is unreachable; apply this named migration once `DATABASE_URL` host is reachable again.
@@ -323,6 +358,11 @@ This file is the single source of truth for roadmap and delivery progress.
- [2026-02-12] Completed admin form component coverage for pages/navigation/media using isolated form components and tests. - [2026-02-12] Completed admin form component coverage for pages/navigation/media using isolated form components and tests.
- [2026-02-12] Added page translation CRUD baseline (`PageTranslation`) with locale validation (`de/en/es/fr`) and integration coverage for localized read + fallback behavior. - [2026-02-12] Added page translation CRUD baseline (`PageTranslation`) with locale validation (`de/en/es/fr`) and integration coverage for localized read + fallback behavior.
- [2026-02-12] Page editor now supports locale translations in `/pages/:id`; public page rendering uses locale-aware page lookup with base-content fallback. - [2026-02-12] Page editor now supports locale translations in `/pages/:id`; public page rendering uses locale-aware page lookup with base-content fallback.
- [2026-02-12] Public rendering integration advanced with locale-aware navigation/news translations and a new public commission request entry route (`/[locale]/commissions`) that creates/reuses customer records and opens a `new` commission.
- [2026-02-12] Public portfolio baseline added with `/{locale}/portfolio` and `/{locale}/portfolio/{slug}`, including published-artwork filters (gallery/album/category/tag), rendition image streaming via web `/api/media/file/:id`, and media-aware artwork detail rendering.
- [2026-02-12] Public UX pass: commission request flow now reports explicit invalid budget range errors, and header navigation now falls back to localized defaults (`home`, `portfolio`, `news`, `commissions`) when no CMS menu exists; seed data now creates those default menu entries.
- [2026-02-12] Added `e2e/public-rendering.pw.ts` web coverage for fallback navigation visibility, portfolio routes, and commission submission validation (invalid budget range + successful submission path).
- [2026-02-12] Testing execution is temporarily paused for delivery velocity: root test scripts are stubbed and CI test steps are disabled; all testing backlog is consolidated under `MVP 3: Testing and Quality`.
## How We Use This File ## How We Use This File

View File

@@ -8,6 +8,7 @@
"build": "bun --env-file=../../.env next build", "build": "bun --env-file=../../.env next build",
"start": "bun --env-file=../../.env next start --port 3001", "start": "bun --env-file=../../.env next start --port 3001",
"auth:seed:support": "bun --env-file=../../.env ./scripts/seed-support-user.ts", "auth:seed:support": "bun --env-file=../../.env ./scripts/seed-support-user.ts",
"auth:seed:e2e-admin": "bun --env-file=../../.env ./scripts/seed-e2e-admin-user.ts",
"lint": "biome check src", "lint": "biome check src",
"typecheck": "tsc -p tsconfig.json --noEmit" "typecheck": "tsc -p tsconfig.json --noEmit"
}, },

View File

@@ -0,0 +1,11 @@
import { ensureE2EAdminBootstrap } from "../src/lib/auth/server"
async function main() {
await ensureE2EAdminBootstrap()
console.log("E2E admin bootstrap completed")
}
main().catch((error) => {
console.error(error)
process.exit(1)
})

View File

@@ -10,6 +10,7 @@ import Link from "next/link"
import { redirect } from "next/navigation" import { redirect } from "next/navigation"
import { AdminShell } from "@/components/admin-shell" import { AdminShell } from "@/components/admin-shell"
import { PageBlockEditor } from "@/components/pages/page-block-editor"
import { requirePermissionForRoute } from "@/lib/route-guards" import { requirePermissionForRoute } from "@/lib/route-guards"
export const dynamic = "force-dynamic" export const dynamic = "force-dynamic"
@@ -242,16 +243,7 @@ export default async function PageEditorPage({ params, searchParams }: PageProps
/> />
</label> </label>
<label className="space-y-1"> <PageBlockEditor name="content" initialContent={page.content} />
<span className="text-xs text-neutral-600">Content</span>
<textarea
name="content"
rows={10}
defaultValue={page.content}
required
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
<div className="grid gap-3 md:grid-cols-2"> <div className="grid gap-3 md:grid-cols-2">
<label className="space-y-1"> <label className="space-y-1">
@@ -368,16 +360,11 @@ export default async function PageEditorPage({ params, searchParams }: PageProps
/> />
</label> </label>
<label className="space-y-1"> <PageBlockEditor
<span className="text-xs text-neutral-600">Content</span> name="content"
<textarea initialContent={selectedTranslation?.content ?? page.content}
name="content" label="Translation Blocks"
rows={8} />
defaultValue={selectedTranslation?.content ?? page.content}
required
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
<div className="grid gap-3 md:grid-cols-2"> <div className="grid gap-3 md:grid-cols-2">
<label className="space-y-1"> <label className="space-y-1">

View File

@@ -11,7 +11,9 @@ describe("CreatePageForm", () => {
expect((screen.getByLabelText("Title") as HTMLInputElement).name).toBe("title") expect((screen.getByLabelText("Title") as HTMLInputElement).name).toBe("title")
expect((screen.getByLabelText("Slug") as HTMLInputElement).name).toBe("slug") expect((screen.getByLabelText("Slug") as HTMLInputElement).name).toBe("slug")
expect((screen.getByLabelText("Content") as HTMLTextAreaElement).name).toBe("content") const contentField = document.querySelector('input[name="content"]') as HTMLInputElement | null
expect(contentField).not.toBeNull()
expect(contentField?.value.startsWith("[")).toBe(true)
const status = screen.getByLabelText("Status") as HTMLSelectElement const status = screen.getByLabelText("Status") as HTMLSelectElement
expect(status.value).toBe("draft") expect(status.value).toBe("draft")

View File

@@ -1,5 +1,8 @@
import { serializePageBlocks } from "@cms/content"
import { Button } from "@cms/ui/button" import { Button } from "@cms/ui/button"
import { PageBlockEditor } from "./page-block-editor"
type CreatePageFormProps = { type CreatePageFormProps = {
action: (formData: FormData) => void | Promise<void> action: (formData: FormData) => void | Promise<void>
} }
@@ -46,15 +49,16 @@ export function CreatePageForm({ action }: CreatePageFormProps) {
/> />
</label> </label>
<label className="space-y-1"> <PageBlockEditor
<span className="text-xs text-neutral-600">Content</span> name="content"
<textarea initialContent={serializePageBlocks([
name="content" {
rows={6} id: "initial-rich-text",
required type: "rich_text",
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm" body: "",
/> },
</label> ])}
/>
<div className="grid gap-3 md:grid-cols-2"> <div className="grid gap-3 md:grid-cols-2">
<label className="space-y-1"> <label className="space-y-1">

View File

@@ -0,0 +1,292 @@
"use client"
import { type PageBlock, type PageBlocks, parsePageBlocks, serializePageBlocks } from "@cms/content"
import { useMemo, useState } from "react"
type PageBlockEditorProps = {
name: string
initialContent: string
label?: string
}
function randomId(prefix: string): string {
return `${prefix}-${Math.random().toString(36).slice(2, 10)}`
}
function normalizeInitialBlocks(initialContent: string): PageBlocks {
if (!initialContent.trim()) {
return [
{
id: randomId("rich"),
type: "rich_text",
body: "",
},
]
}
try {
return parsePageBlocks(initialContent)
} catch {
return [
{
id: randomId("rich"),
type: "rich_text",
body: initialContent,
},
]
}
}
function updateBlock(blocks: PageBlocks, blockId: string, next: Partial<PageBlock>): PageBlocks {
return blocks.map((block) =>
block.id === blockId ? ({ ...block, ...next } as PageBlock) : block,
)
}
export function PageBlockEditor({
name,
initialContent,
label = "Page Blocks",
}: PageBlockEditorProps) {
const [blocks, setBlocks] = useState<PageBlocks>(() => normalizeInitialBlocks(initialContent))
const serialized = useMemo(() => serializePageBlocks(blocks), [blocks])
function addBlock(type: PageBlock["type"]) {
if (type === "hero") {
setBlocks((prev) => [
...prev,
{
id: randomId("hero"),
type,
heading: "Hero heading",
subheading: null,
ctaHref: null,
ctaLabel: null,
},
])
return
}
if (type === "rich_text") {
setBlocks((prev) => [...prev, { id: randomId("rich"), type, body: "" }])
return
}
if (type === "gallery") {
setBlocks((prev) => [...prev, { id: randomId("gallery"), type, title: null, imageIds: [] }])
return
}
if (type === "cta") {
setBlocks((prev) => [
...prev,
{ id: randomId("cta"), type, label: "Open", href: "/", variant: "primary" },
])
return
}
if (type === "form") {
setBlocks((prev) => [
...prev,
{ id: randomId("form"), type, formKey: "contact", title: null, description: null },
])
return
}
setBlocks((prev) => [
...prev,
{ id: randomId("price"), type: "price_cards", title: null, cards: [] },
])
}
return (
<div className="space-y-3 rounded border border-neutral-200 p-3">
<input type="hidden" name={name} value={serialized} />
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs text-neutral-600">{label}</span>
<button
type="button"
className="rounded border px-2 py-1 text-xs"
onClick={() => addBlock("hero")}
>
+ Hero
</button>
<button
type="button"
className="rounded border px-2 py-1 text-xs"
onClick={() => addBlock("rich_text")}
>
+ Rich text
</button>
<button
type="button"
className="rounded border px-2 py-1 text-xs"
onClick={() => addBlock("gallery")}
>
+ Gallery
</button>
<button
type="button"
className="rounded border px-2 py-1 text-xs"
onClick={() => addBlock("cta")}
>
+ CTA
</button>
<button
type="button"
className="rounded border px-2 py-1 text-xs"
onClick={() => addBlock("form")}
>
+ Form
</button>
<button
type="button"
className="rounded border px-2 py-1 text-xs"
onClick={() => addBlock("price_cards")}
>
+ Price cards
</button>
</div>
<div className="space-y-3">
{blocks.map((block, index) => (
<article key={block.id} className="space-y-2 rounded border border-neutral-200 p-3">
<div className="flex items-center justify-between text-xs text-neutral-600">
<span>
#{index + 1} {block.type}
</span>
<button
type="button"
className="rounded border px-2 py-1"
onClick={() => setBlocks((prev) => prev.filter((entry) => entry.id !== block.id))}
>
Remove
</button>
</div>
{block.type === "hero" ? (
<div className="grid gap-2 md:grid-cols-2">
<input
value={block.heading}
onChange={(event) =>
setBlocks((prev) =>
updateBlock(prev, block.id, { heading: event.target.value }),
)
}
placeholder="Heading"
className="rounded border border-neutral-300 px-2 py-1 text-sm"
/>
<input
value={block.subheading ?? ""}
onChange={(event) =>
setBlocks((prev) =>
updateBlock(prev, block.id, { subheading: event.target.value || null }),
)
}
placeholder="Subheading"
className="rounded border border-neutral-300 px-2 py-1 text-sm"
/>
</div>
) : null}
{block.type === "rich_text" ? (
<textarea
rows={5}
value={block.body}
onChange={(event) =>
setBlocks((prev) => updateBlock(prev, block.id, { body: event.target.value }))
}
placeholder="Text"
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
/>
) : null}
{block.type === "gallery" ? (
<textarea
rows={3}
value={block.imageIds.join(",")}
onChange={(event) =>
setBlocks((prev) =>
updateBlock(prev, block.id, {
imageIds: event.target.value
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0),
}),
)
}
placeholder="Media asset IDs (comma separated UUIDs)"
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
/>
) : null}
{block.type === "cta" ? (
<div className="grid gap-2 md:grid-cols-2">
<input
value={block.label}
onChange={(event) =>
setBlocks((prev) => updateBlock(prev, block.id, { label: event.target.value }))
}
placeholder="Button label"
className="rounded border border-neutral-300 px-2 py-1 text-sm"
/>
<input
value={block.href}
onChange={(event) =>
setBlocks((prev) => updateBlock(prev, block.id, { href: event.target.value }))
}
placeholder="Link href"
className="rounded border border-neutral-300 px-2 py-1 text-sm"
/>
</div>
) : null}
{block.type === "form" ? (
<input
value={block.formKey}
onChange={(event) =>
setBlocks((prev) => updateBlock(prev, block.id, { formKey: event.target.value }))
}
placeholder="Form key (e.g. contact, commission)"
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
/>
) : null}
{block.type === "price_cards" ? (
<textarea
rows={4}
value={block.cards
.map((card) => [card.name, card.price ?? "", card.description ?? ""].join("|"))
.join("\n")}
onChange={(event) =>
setBlocks((prev) =>
updateBlock(prev, block.id, {
cards: event.target.value
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line, lineIndex) => {
const [name, price, description] = line
.split("|")
.map((entry) => entry.trim())
return {
id: `card-${lineIndex}`,
name: name || `Card ${lineIndex + 1}`,
price: price || null,
description: description || null,
}
}),
}),
)
}
placeholder="One card per line: Name|Price|Description"
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
/>
) : null}
</article>
))}
</div>
</div>
)
}

View File

@@ -266,11 +266,15 @@ type BootstrapUserConfig = {
password: string password: string
role: Role role: Role
isHidden: boolean isHidden: boolean
isSystem?: boolean
isProtected?: boolean
} }
async function ensureCredentialUser(config: BootstrapUserConfig): Promise<void> { async function ensureCredentialUser(config: BootstrapUserConfig): Promise<void> {
const ctx = await auth.$context const ctx = await auth.$context
const normalizedEmail = config.email.toLowerCase() const normalizedEmail = config.email.toLowerCase()
const isSystem = config.isSystem ?? true
const isProtected = config.isProtected ?? true
const existing = await ctx.internalAdapter.findUserByEmail(normalizedEmail, { const existing = await ctx.internalAdapter.findUserByEmail(normalizedEmail, {
includeAccounts: true, includeAccounts: true,
}) })
@@ -282,9 +286,9 @@ async function ensureCredentialUser(config: BootstrapUserConfig): Promise<void>
name: config.name, name: config.name,
role: config.role, role: config.role,
isBanned: false, isBanned: false,
isSystem: true, isSystem,
isHidden: config.isHidden, isHidden: config.isHidden,
isProtected: true, isProtected,
}, },
}) })
@@ -321,9 +325,9 @@ async function ensureCredentialUser(config: BootstrapUserConfig): Promise<void>
emailVerified: true, emailVerified: true,
role: config.role, role: config.role,
isBanned: false, isBanned: false,
isSystem: true, isSystem,
isHidden: config.isHidden, isHidden: config.isHidden,
isProtected: true, isProtected,
}) })
await ctx.internalAdapter.linkAccount({ await ctx.internalAdapter.linkAccount({
@@ -371,6 +375,29 @@ export async function ensureSupportUserBootstrap(): Promise<void> {
} }
} }
const DEFAULT_E2E_ADMIN_EMAIL = "e2e-admin@cms.local"
const DEFAULT_E2E_ADMIN_USERNAME = "e2e-admin"
const DEFAULT_E2E_ADMIN_PASSWORD = "e2e-admin-password"
const DEFAULT_E2E_ADMIN_NAME = "E2E Admin"
export async function ensureE2EAdminBootstrap(): Promise<void> {
const email = resolveBootstrapValue("CMS_E2E_ADMIN_EMAIL", DEFAULT_E2E_ADMIN_EMAIL)
const username = resolveBootstrapValue("CMS_E2E_ADMIN_USERNAME", DEFAULT_E2E_ADMIN_USERNAME)
const password = resolveBootstrapValue("CMS_E2E_ADMIN_PASSWORD", DEFAULT_E2E_ADMIN_PASSWORD)
const name = resolveBootstrapValue("CMS_E2E_ADMIN_NAME", DEFAULT_E2E_ADMIN_NAME)
await ensureCredentialUser({
email,
username,
password,
name,
role: "admin",
isHidden: false,
isSystem: true,
isProtected: false,
})
}
type OwnerInvariantState = { type OwnerInvariantState = {
ownerId: string | null ownerId: string | null
ownerCount: number ownerCount: number

View File

@@ -11,6 +11,7 @@
"typecheck": "tsc -p tsconfig.json --noEmit" "typecheck": "tsc -p tsconfig.json --noEmit"
}, },
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "3.988.0",
"@cms/content": "workspace:*", "@cms/content": "workspace:*",
"@cms/db": "workspace:*", "@cms/db": "workspace:*",
"@cms/i18n": "workspace:*", "@cms/i18n": "workspace:*",

View File

@@ -0,0 +1,217 @@
import { createPublicCommissionRequest } from "@cms/db"
import { revalidatePath } from "next/cache"
import { redirect } from "next/navigation"
import { getTranslations } from "next-intl/server"
export const dynamic = "force-dynamic"
type SearchParamsInput = Record<string, string | string[] | undefined>
type PublicCommissionRequestPageProps = {
params: Promise<{ locale: string }>
searchParams: Promise<SearchParamsInput>
}
function readFirstValue(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
return value[0] ?? null
}
return value ?? null
}
function readInputString(formData: FormData, field: string): string {
const value = formData.get(field)
return typeof value === "string" ? value.trim() : ""
}
function readNullableString(formData: FormData, field: string): string | null {
const value = readInputString(formData, field)
return value.length > 0 ? value : null
}
function readNullableNumber(formData: FormData, field: string): number | null {
const value = readInputString(formData, field)
if (!value) {
return null
}
const parsed = Number.parseFloat(value)
return Number.isFinite(parsed) ? parsed : null
}
function buildRedirect(locale: string, params: { notice?: string; error?: string }) {
const query = new URLSearchParams()
if (params.notice) {
query.set("notice", params.notice)
}
if (params.error) {
query.set("error", params.error)
}
const serialized = query.toString()
return serialized ? `/${locale}/commissions?${serialized}` : `/${locale}/commissions`
}
export default async function PublicCommissionRequestPage({
params,
searchParams,
}: PublicCommissionRequestPageProps) {
const { locale } = await params
const [resolvedSearchParams, t] = await Promise.all([
searchParams,
getTranslations("CommissionRequest"),
])
async function submitCommissionRequestAction(formData: FormData) {
"use server"
const budgetMin = readNullableNumber(formData, "budgetMin")
const budgetMax = readNullableNumber(formData, "budgetMax")
if (budgetMin != null && budgetMax != null && budgetMax < budgetMin) {
redirect(buildRedirect(locale, { error: "budget_range_invalid" }))
}
try {
await createPublicCommissionRequest({
customerName: readInputString(formData, "customerName"),
customerEmail: readInputString(formData, "customerEmail"),
customerPhone: readNullableString(formData, "customerPhone"),
customerInstagram: readNullableString(formData, "customerInstagram"),
title: readInputString(formData, "title"),
description: readNullableString(formData, "description"),
budgetMin,
budgetMax,
})
} catch {
redirect(buildRedirect(locale, { error: "submission_failed" }))
}
revalidatePath(`/${locale}/commissions`)
redirect(buildRedirect(locale, { notice: "submitted" }))
}
const notice = readFirstValue(resolvedSearchParams.notice)
const error = readFirstValue(resolvedSearchParams.error)
return (
<section className="mx-auto w-full max-w-3xl space-y-6 px-6 py-16">
<header className="space-y-2">
<p className="text-sm uppercase tracking-[0.2em] text-neutral-500">{t("badge")}</p>
<h1 className="text-4xl font-semibold tracking-tight">{t("title")}</h1>
<p className="text-neutral-600">{t("description")}</p>
</header>
{notice === "submitted" ? (
<section className="rounded-xl border border-emerald-300 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
{t("success")}
</section>
) : null}
{error === "submission_failed" ? (
<section className="rounded-xl border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-800">
{t("error")}
</section>
) : null}
{error === "budget_range_invalid" ? (
<section className="rounded-xl border border-amber-300 bg-amber-50 px-4 py-3 text-sm text-amber-800">
{t("budgetRangeError")}
</section>
) : null}
<form action={submitCommissionRequestAction} className="space-y-4 rounded-xl border p-6">
<div className="grid gap-4 md:grid-cols-2">
<label className="space-y-1">
<span className="text-xs text-neutral-600">{t("fields.customerName")}</span>
<input
name="customerName"
autoComplete="name"
required
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
<label className="space-y-1">
<span className="text-xs text-neutral-600">{t("fields.customerEmail")}</span>
<input
name="customerEmail"
type="email"
autoComplete="email"
required
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
</div>
<div className="grid gap-4 md:grid-cols-2">
<label className="space-y-1">
<span className="text-xs text-neutral-600">{t("fields.customerPhone")}</span>
<input
name="customerPhone"
autoComplete="tel"
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
<label className="space-y-1">
<span className="text-xs text-neutral-600">{t("fields.customerInstagram")}</span>
<input
name="customerInstagram"
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
</div>
<label className="space-y-1">
<span className="text-xs text-neutral-600">{t("fields.title")}</span>
<input
name="title"
required
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
<label className="space-y-1">
<span className="text-xs text-neutral-600">{t("fields.description")}</span>
<textarea
name="description"
rows={6}
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
<div className="grid gap-4 md:grid-cols-2">
<label className="space-y-1">
<span className="text-xs text-neutral-600">{t("fields.budgetMin")}</span>
<input
name="budgetMin"
type="number"
min="0"
step="0.01"
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
<label className="space-y-1">
<span className="text-xs text-neutral-600">{t("fields.budgetMax")}</span>
<input
name="budgetMax"
type="number"
min="0"
step="0.01"
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
/>
</label>
</div>
<button
type="submit"
className="rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white hover:bg-neutral-700"
>
{t("submit")}
</button>
</form>
</section>
)
}

View File

@@ -1,8 +1,8 @@
import { getPublishedPageBySlugForLocale, listPosts } from "@cms/db" import { getPublishedPageBySlugForLocale, listPosts } from "@cms/db"
import { Button } from "@cms/ui/button"
import { getTranslations } from "next-intl/server" import { getTranslations } from "next-intl/server"
import { PublicAnnouncements } from "@/components/public-announcements" import { PublicAnnouncements } from "@/components/public-announcements"
import { PublicPageView } from "@/components/public-page-view" import { PublicPageView } from "@/components/public-page-view"
import { Link } from "@/i18n/navigation"
export const dynamic = "force-dynamic" export const dynamic = "force-dynamic"
@@ -34,7 +34,20 @@ export default async function HomePage({ params }: HomePageProps) {
<section className="space-y-4 rounded-xl border border-neutral-200 p-6"> <section className="space-y-4 rounded-xl border border-neutral-200 p-6">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h3 className="text-xl font-medium">{t("latestPosts")}</h3> <h3 className="text-xl font-medium">{t("latestPosts")}</h3>
<Button variant="secondary">{t("explore")}</Button> <div className="flex items-center gap-2">
<Link
href="/news"
className="inline-flex h-10 items-center justify-center rounded-md bg-neutral-100 px-4 py-2 text-sm font-medium text-neutral-900 transition-colors hover:bg-neutral-200"
>
{t("explore")}
</Link>
<Link
href="/commissions"
className="inline-flex h-10 items-center justify-center rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-neutral-800"
>
{t("requestCommission")}
</Link>
</div>
</div> </div>
<ul className="space-y-3"> <ul className="space-y-3">

View File

@@ -0,0 +1,101 @@
import { getPublishedArtworkBySlug } from "@cms/db"
import Image from "next/image"
import { notFound } from "next/navigation"
import { getTranslations } from "next-intl/server"
export const dynamic = "force-dynamic"
type PublicArtworkPageProps = {
params: Promise<{ slug: string }>
}
function formatLabelList(values: string[]) {
if (values.length === 0) {
return "-"
}
return values.join(", ")
}
export default async function PublicArtworkPage({ params }: PublicArtworkPageProps) {
const [{ slug }, t] = await Promise.all([params, getTranslations("Portfolio")])
const artwork = await getPublishedArtworkBySlug(slug)
if (!artwork) {
notFound()
}
return (
<section className="mx-auto w-full max-w-5xl space-y-6 px-6 py-16">
<header className="space-y-2">
<p className="text-sm uppercase tracking-[0.2em] text-neutral-500">{t("badge")}</p>
<h1 className="text-4xl font-semibold tracking-tight">{artwork.title}</h1>
<p className="text-neutral-600">{artwork.description || t("noDescription")}</p>
</header>
<section className="grid gap-4 md:grid-cols-2">
{artwork.renditions.length === 0 ? (
<article className="rounded-xl border border-neutral-200 p-6 text-sm text-neutral-600">
{t("noPreview")}
</article>
) : (
artwork.renditions.map((rendition) => (
<article
key={rendition.id}
className="overflow-hidden rounded-xl border border-neutral-200"
>
<Image
src={`/api/media/file/${rendition.mediaAssetId}`}
alt={rendition.mediaAsset.altText || artwork.title}
width={1400}
height={1000}
className="h-72 w-full object-cover"
/>
<div className="flex items-center justify-between px-4 py-2 text-xs text-neutral-600">
<span>{rendition.slot}</span>
<span>
{rendition.mediaAsset.width ?? "-"} x {rendition.mediaAsset.height ?? "-"}
</span>
</div>
</article>
))
)}
</section>
<section className="grid gap-4 rounded-xl border border-neutral-200 p-6 md:grid-cols-2">
<div className="space-y-2 text-sm">
<p>
<strong>{t("fields.medium")}:</strong> {artwork.medium || "-"}
</p>
<p>
<strong>{t("fields.dimensions")}:</strong> {artwork.dimensions || "-"}
</p>
<p>
<strong>{t("fields.year")}:</strong> {artwork.year || "-"}
</p>
<p>
<strong>{t("fields.availability")}:</strong> {artwork.availability || "-"}
</p>
</div>
<div className="space-y-2 text-sm">
<p>
<strong>{t("fields.galleries")}:</strong>{" "}
{formatLabelList(artwork.galleryLinks.map((entry) => entry.gallery.name))}
</p>
<p>
<strong>{t("fields.albums")}:</strong>{" "}
{formatLabelList(artwork.albumLinks.map((entry) => entry.album.name))}
</p>
<p>
<strong>{t("fields.categories")}:</strong>{" "}
{formatLabelList(artwork.categoryLinks.map((entry) => entry.category.name))}
</p>
<p>
<strong>{t("fields.tags")}:</strong>{" "}
{formatLabelList(artwork.tagLinks.map((entry) => entry.tag.name))}
</p>
</div>
</section>
</section>
)
}

View File

@@ -0,0 +1,178 @@
import { listPublishedArtworks, listPublishedPortfolioGroups } from "@cms/db"
import Image from "next/image"
import { getTranslations } from "next-intl/server"
import { Link } from "@/i18n/navigation"
export const dynamic = "force-dynamic"
type SearchParamsInput = Record<string, string | string[] | undefined>
type PortfolioPageProps = {
searchParams: Promise<SearchParamsInput>
}
function readFirstValue(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
return value[0] ?? null
}
return value ?? null
}
function resolveGroupFilter(searchParams: SearchParamsInput) {
const gallery = readFirstValue(searchParams.gallery)
if (gallery) {
return { groupType: "gallery" as const, groupSlug: gallery }
}
const album = readFirstValue(searchParams.album)
if (album) {
return { groupType: "album" as const, groupSlug: album }
}
const category = readFirstValue(searchParams.category)
if (category) {
return { groupType: "category" as const, groupSlug: category }
}
const tag = readFirstValue(searchParams.tag)
if (tag) {
return { groupType: "tag" as const, groupSlug: tag }
}
return null
}
function findPreviewAsset(
renditions: Array<{
slot: string
mediaAssetId: string
mediaAsset: {
id: string
altText: string | null
title: string
}
}>,
) {
const byPreference =
renditions.find((item) => item.slot === "card") ??
renditions.find((item) => item.slot === "thumbnail") ??
renditions.find((item) => item.slot === "full") ??
renditions[0]
return byPreference ?? null
}
export default async function PortfolioPage({ searchParams }: PortfolioPageProps) {
const [resolvedSearchParams, t] = await Promise.all([searchParams, getTranslations("Portfolio")])
const activeFilter = resolveGroupFilter(resolvedSearchParams)
const [groups, artworks] = await Promise.all([
listPublishedPortfolioGroups(),
listPublishedArtworks(
activeFilter
? {
groupType: activeFilter.groupType,
groupSlug: activeFilter.groupSlug,
}
: undefined,
),
])
return (
<section className="mx-auto w-full max-w-6xl space-y-6 px-6 py-16">
<header className="space-y-2">
<p className="text-sm uppercase tracking-[0.2em] text-neutral-500">{t("badge")}</p>
<h1 className="text-4xl font-semibold tracking-tight">{t("title")}</h1>
<p className="text-neutral-600">{t("description")}</p>
</header>
<section className="rounded-xl border border-neutral-200 p-4">
<div className="flex flex-wrap items-center gap-2">
<Link
href="/portfolio"
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100"
>
{t("filters.clear")}
</Link>
{groups.galleries.map((group) => (
<Link
key={`gallery-${group.id}`}
href={{ pathname: "/portfolio", query: { gallery: group.slug } }}
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100"
>
{t("filters.gallery")}: {group.name}
</Link>
))}
{groups.albums.map((group) => (
<Link
key={`album-${group.id}`}
href={{ pathname: "/portfolio", query: { album: group.slug } }}
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100"
>
{t("filters.album")}: {group.name}
</Link>
))}
{groups.categories.map((group) => (
<Link
key={`category-${group.id}`}
href={{ pathname: "/portfolio", query: { category: group.slug } }}
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100"
>
{t("filters.category")}: {group.name}
</Link>
))}
</div>
</section>
{artworks.length === 0 ? (
<section className="rounded-xl border border-neutral-200 p-6 text-sm text-neutral-600">
{t("empty")}
</section>
) : (
<section className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{artworks.map((artwork) => {
const preview = findPreviewAsset(artwork.renditions)
return (
<article
key={artwork.id}
className="overflow-hidden rounded-xl border border-neutral-200"
>
{preview ? (
<Image
src={`/api/media/file/${preview.mediaAssetId}`}
alt={preview.mediaAsset.altText || artwork.title}
width={1200}
height={800}
className="h-56 w-full object-cover"
/>
) : (
<div className="flex h-56 items-center justify-center bg-neutral-100 text-sm text-neutral-500">
{t("noPreview")}
</div>
)}
<div className="space-y-2 p-4">
<h2 className="text-lg font-medium">{artwork.title}</h2>
<p className="line-clamp-3 text-sm text-neutral-600">
{artwork.description || t("noDescription")}
</p>
<Link
href={`/portfolio/${artwork.slug}`}
className="text-sm underline underline-offset-2"
>
{t("viewArtwork")}
</Link>
</div>
</article>
)
})}
</section>
)}
</section>
)
}

View File

@@ -0,0 +1,47 @@
import { getMediaAssetById } from "@cms/db"
import { readMediaStorageObject } from "@/lib/media/storage-read"
export const runtime = "nodejs"
type RouteContext = {
params: Promise<{ id: string }>
}
function toBody(data: Uint8Array): BodyInit {
const bytes = new Uint8Array(data.byteLength)
bytes.set(data)
return bytes
}
export async function GET(_request: Request, context: RouteContext): Promise<Response> {
const { id } = await context.params
const asset = await getMediaAssetById(id)
if (!asset || !asset.storageKey || !asset.isPublished) {
return Response.json(
{
message: "Media file not found",
},
{ status: 404 },
)
}
try {
const data = await readMediaStorageObject(asset.storageKey)
return new Response(toBody(data), {
status: 200,
headers: {
"content-type": asset.mimeType || "application/octet-stream",
"cache-control": "public, max-age=3600",
},
})
} catch {
return Response.json(
{
message: "Unable to read media file from configured storage backends",
},
{ status: 404 },
)
}
}

View File

@@ -1,3 +1,6 @@
import { parsePageBlocks } from "@cms/content"
import Image from "next/image"
type PageEntity = { type PageEntity = {
title: string title: string
status: string status: string
@@ -10,6 +13,20 @@ type PublicPageViewProps = {
} }
export function PublicPageView({ page }: PublicPageViewProps) { export function PublicPageView({ page }: PublicPageViewProps) {
const blocks = (() => {
try {
return parsePageBlocks(page.content)
} catch {
return [
{
id: "fallback-rich-text",
type: "rich_text" as const,
body: page.content,
},
]
}
})()
return ( return (
<article className="mx-auto flex w-full max-w-4xl flex-col gap-6 px-6 py-16"> <article className="mx-auto flex w-full max-w-4xl flex-col gap-6 px-6 py-16">
<header className="space-y-3"> <header className="space-y-3">
@@ -18,8 +35,105 @@ export function PublicPageView({ page }: PublicPageViewProps) {
{page.summary ? <p className="text-neutral-600">{page.summary}</p> : null} {page.summary ? <p className="text-neutral-600">{page.summary}</p> : null}
</header> </header>
<section className="prose prose-neutral max-w-none whitespace-pre-wrap rounded-xl border border-neutral-200 bg-white p-6 text-neutral-800"> <section className="space-y-4 rounded-xl border border-neutral-200 bg-white p-6 text-neutral-800">
{page.content} {blocks.map((block) => {
if (block.type === "hero") {
return (
<section key={block.id} className="space-y-2 rounded border border-neutral-200 p-4">
<h2 className="text-2xl font-semibold">{block.heading}</h2>
{block.subheading ? <p className="text-neutral-600">{block.subheading}</p> : null}
{block.ctaLabel && block.ctaHref ? (
<a
href={block.ctaHref}
className="inline-flex rounded bg-neutral-900 px-3 py-1.5 text-sm text-white"
>
{block.ctaLabel}
</a>
) : null}
</section>
)
}
if (block.type === "rich_text") {
return (
<section
key={block.id}
className="prose prose-neutral max-w-none whitespace-pre-wrap"
>
{block.body}
</section>
)
}
if (block.type === "gallery") {
return (
<section key={block.id} className="space-y-3">
{block.title ? <h3 className="text-lg font-medium">{block.title}</h3> : null}
<div className="grid gap-3 sm:grid-cols-2">
{block.imageIds.length === 0 ? (
<p className="text-sm text-neutral-500">No media linked yet.</p>
) : (
block.imageIds.map((imageId) => (
<Image
key={imageId}
src={`/api/media/file/${imageId}`}
alt=""
width={1200}
height={800}
className="h-48 w-full rounded border border-neutral-200 object-cover"
/>
))
)}
</div>
</section>
)
}
if (block.type === "cta") {
return (
<a
key={block.id}
href={block.href}
className={`inline-flex rounded px-3 py-2 text-sm ${
block.variant === "secondary"
? "border border-neutral-300 text-neutral-800"
: "bg-neutral-900 text-white"
}`}
>
{block.label}
</a>
)
}
if (block.type === "form") {
return (
<section key={block.id} className="space-y-2 rounded border border-neutral-200 p-4">
<h3 className="text-lg font-medium">{block.title || "Form block"}</h3>
<p className="text-sm text-neutral-600">
{block.description || "Form integration pending."}
</p>
<p className="text-xs text-neutral-500">formKey: {block.formKey}</p>
</section>
)
}
return (
<section key={block.id} className="space-y-2 rounded border border-neutral-200 p-4">
{block.title ? <h3 className="text-lg font-medium">{block.title}</h3> : null}
<div className="grid gap-3 md:grid-cols-2">
{block.cards.map((card) => (
<article key={card.id} className="rounded border border-neutral-200 p-3">
<h4 className="font-medium">{card.name}</h4>
{card.price ? <p className="text-sm text-neutral-700">{card.price}</p> : null}
{card.description ? (
<p className="text-sm text-neutral-600">{card.description}</p>
) : null}
</article>
))}
</div>
</section>
)
})}
</section> </section>
</article> </article>
) )

View File

@@ -1,5 +1,5 @@
import { listPublicNavigation } from "@cms/db" import { listPublicNavigation } from "@cms/db"
import { getLocale } from "next-intl/server" import { getLocale, getTranslations } from "next-intl/server"
import { Link } from "@/i18n/navigation" import { Link } from "@/i18n/navigation"
@@ -7,7 +7,33 @@ import { LanguageSwitcher } from "./language-switcher"
export async function PublicSiteHeader() { export async function PublicSiteHeader() {
const locale = await getLocale() const locale = await getLocale()
const navItems = await listPublicNavigation("header", locale) const [navItems, t] = await Promise.all([
listPublicNavigation("header", locale),
getTranslations("Layout.nav"),
])
const fallbackNavItems = [
{
id: "fallback-home",
href: "/",
label: t("home"),
},
{
id: "fallback-portfolio",
href: "/portfolio",
label: t("portfolio"),
},
{
id: "fallback-news",
href: "/news",
label: t("news"),
},
{
id: "fallback-commissions",
href: "/commissions",
label: t("commissions"),
},
]
const resolvedNavItems = navItems.length > 0 ? navItems : fallbackNavItems
return ( return (
<header className="border-b border-neutral-200 bg-white/80 backdrop-blur"> <header className="border-b border-neutral-200 bg-white/80 backdrop-blur">
@@ -20,24 +46,15 @@ export async function PublicSiteHeader() {
</Link> </Link>
<nav className="flex flex-wrap items-center gap-2"> <nav className="flex flex-wrap items-center gap-2">
{navItems.length === 0 ? ( {resolvedNavItems.map((item) => (
<Link <Link
href="/" key={item.id}
href={item.href}
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm font-medium text-neutral-700 hover:bg-neutral-100" className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm font-medium text-neutral-700 hover:bg-neutral-100"
> >
Home {item.label}
</Link> </Link>
) : ( ))}
navItems.map((item) => (
<Link
key={item.id}
href={item.href}
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm font-medium text-neutral-700 hover:bg-neutral-100"
>
{item.label}
</Link>
))
)}
</nav> </nav>
<LanguageSwitcher /> <LanguageSwitcher />

View File

@@ -0,0 +1,114 @@
import { readFile } from "node:fs/promises"
import path from "node:path"
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3"
export type MediaStorageProvider = "local" | "s3"
type S3Config = {
bucket: string
region: string
endpoint?: string
accessKeyId: string
secretAccessKey: string
forcePathStyle?: boolean
}
function parseBoolean(value: string | undefined): boolean {
return value?.toLowerCase() === "true"
}
export function resolveMediaStorageProvider(raw: string | undefined): MediaStorageProvider {
if (raw?.toLowerCase() === "local") {
return "local"
}
return "s3"
}
function resolveS3Config(): S3Config {
const bucket = process.env.CMS_MEDIA_S3_BUCKET?.trim()
const region = process.env.CMS_MEDIA_S3_REGION?.trim()
const accessKeyId = process.env.CMS_MEDIA_S3_ACCESS_KEY_ID?.trim()
const secretAccessKey = process.env.CMS_MEDIA_S3_SECRET_ACCESS_KEY?.trim()
const endpoint = process.env.CMS_MEDIA_S3_ENDPOINT?.trim() || undefined
if (!bucket || !region || !accessKeyId || !secretAccessKey) {
throw new Error(
"S3 storage selected but required env vars are missing: CMS_MEDIA_S3_BUCKET, CMS_MEDIA_S3_REGION, CMS_MEDIA_S3_ACCESS_KEY_ID, CMS_MEDIA_S3_SECRET_ACCESS_KEY",
)
}
return {
bucket,
region,
endpoint,
accessKeyId,
secretAccessKey,
forcePathStyle: parseBoolean(process.env.CMS_MEDIA_S3_FORCE_PATH_STYLE),
}
}
function createS3Client(config: S3Config): S3Client {
return new S3Client({
region: config.region,
endpoint: config.endpoint,
forcePathStyle: config.forcePathStyle,
credentials: {
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
},
})
}
function resolveLocalMediaBaseDirectory(): string {
const configured = process.env.CMS_MEDIA_LOCAL_STORAGE_DIR?.trim()
if (configured) {
return path.resolve(configured)
}
return path.resolve(process.cwd(), ".data", "media")
}
async function readFromLocalStorage(storageKey: string): Promise<Uint8Array> {
const baseDirectory = resolveLocalMediaBaseDirectory()
const outputPath = path.join(baseDirectory, storageKey)
return readFile(outputPath)
}
async function readFromS3Storage(storageKey: string): Promise<Uint8Array> {
const config = resolveS3Config()
const client = createS3Client(config)
const response = await client.send(
new GetObjectCommand({
Bucket: config.bucket,
Key: storageKey,
}),
)
if (!response.Body) {
throw new Error("S3 object body is empty")
}
return response.Body.transformToByteArray()
}
export async function readMediaStorageObject(storageKey: string): Promise<Uint8Array> {
const preferred = resolveMediaStorageProvider(process.env.CMS_MEDIA_STORAGE_PROVIDER)
const reads =
preferred === "s3"
? [() => readFromS3Storage(storageKey), () => readFromLocalStorage(storageKey)]
: [() => readFromLocalStorage(storageKey), () => readFromS3Storage(storageKey)]
for (const read of reads) {
try {
return await read()
} catch {
// Try next backend.
}
}
throw new Error("Unable to read media file from configured storage backends")
}

View File

@@ -5,7 +5,8 @@
"description": "Diese Seite liest Beiträge über das gemeinsame Datenbank-Paket.", "description": "Diese Seite liest Beiträge über das gemeinsame Datenbank-Paket.",
"latestPosts": "Neueste Beiträge", "latestPosts": "Neueste Beiträge",
"explore": "Entdecken", "explore": "Entdecken",
"noExcerpt": "Kein Auszug" "noExcerpt": "Kein Auszug",
"requestCommission": "Auftrag anfragen"
}, },
"LanguageSwitcher": { "LanguageSwitcher": {
"label": "Sprache", "label": "Sprache",
@@ -20,6 +21,9 @@
"brand": "CMS Web", "brand": "CMS Web",
"nav": { "nav": {
"home": "Start", "home": "Start",
"portfolio": "Portfolio",
"news": "News",
"commissions": "Aufträge",
"about": "Über uns", "about": "Über uns",
"contact": "Kontakt" "contact": "Kontakt"
}, },
@@ -41,5 +45,49 @@
"badge": "Kontakt", "badge": "Kontakt",
"title": "Kontakt", "title": "Kontakt",
"description": "Kontakt- und Auftragsabläufe werden in den nächsten MVP-Schritten eingeführt." "description": "Kontakt- und Auftragsabläufe werden in den nächsten MVP-Schritten eingeführt."
},
"CommissionRequest": {
"badge": "Aufträge",
"title": "Auftragsanfrage",
"description": "Teile deine Idee und Projektdetails. Wir prüfen die Anfrage und melden uns zeitnah.",
"success": "Deine Auftragsanfrage wurde übermittelt.",
"error": "Übermittlung fehlgeschlagen. Bitte prüfe die Eingaben und versuche es erneut.",
"budgetRangeError": "Das maximale Budget muss größer oder gleich dem minimalen Budget sein.",
"submit": "Anfrage senden",
"fields": {
"customerName": "Name",
"customerEmail": "E-Mail",
"customerPhone": "Telefon",
"customerInstagram": "Instagram",
"title": "Projekttitel",
"description": "Projektdetails",
"budgetMin": "Budget min.",
"budgetMax": "Budget max."
}
},
"Portfolio": {
"badge": "Portfolio",
"title": "Kunstwerk-Portfolio",
"description": "Durchsuche veröffentlichte Kunstwerke aus Galerien, Alben und Kategorien.",
"empty": "Keine Kunstwerke für diesen Filter gefunden.",
"noPreview": "Keine Vorschau verfügbar",
"noDescription": "Keine Beschreibung",
"viewArtwork": "Kunstwerk ansehen",
"filters": {
"clear": "Filter zurücksetzen",
"gallery": "Galerie",
"album": "Album",
"category": "Kategorie"
},
"fields": {
"medium": "Medium",
"dimensions": "Abmessungen",
"year": "Jahr",
"availability": "Verfügbarkeit",
"galleries": "Galerien",
"albums": "Alben",
"categories": "Kategorien",
"tags": "Tags"
}
} }
} }

View File

@@ -5,7 +5,8 @@
"description": "This page reads posts through the shared database package.", "description": "This page reads posts through the shared database package.",
"latestPosts": "Latest posts", "latestPosts": "Latest posts",
"explore": "Explore", "explore": "Explore",
"noExcerpt": "No excerpt" "noExcerpt": "No excerpt",
"requestCommission": "Request commission"
}, },
"LanguageSwitcher": { "LanguageSwitcher": {
"label": "Language", "label": "Language",
@@ -20,6 +21,9 @@
"brand": "CMS Web", "brand": "CMS Web",
"nav": { "nav": {
"home": "Home", "home": "Home",
"portfolio": "Portfolio",
"news": "News",
"commissions": "Commissions",
"about": "About", "about": "About",
"contact": "Contact" "contact": "Contact"
}, },
@@ -41,5 +45,49 @@
"badge": "Contact", "badge": "Contact",
"title": "Contact", "title": "Contact",
"description": "Contact and commission flows will be introduced in upcoming MVP steps." "description": "Contact and commission flows will be introduced in upcoming MVP steps."
},
"CommissionRequest": {
"badge": "Commissions",
"title": "Commission request",
"description": "Share your idea and project details. We will review and reply as soon as possible.",
"success": "Your commission request was submitted.",
"error": "Submission failed. Please review your data and try again.",
"budgetRangeError": "Budget max must be greater than or equal to budget min.",
"submit": "Submit request",
"fields": {
"customerName": "Name",
"customerEmail": "Email",
"customerPhone": "Phone",
"customerInstagram": "Instagram",
"title": "Project title",
"description": "Project details",
"budgetMin": "Budget min",
"budgetMax": "Budget max"
}
},
"Portfolio": {
"badge": "Portfolio",
"title": "Artwork portfolio",
"description": "Browse published artworks from galleries, albums, and categories.",
"empty": "No artworks found for this filter.",
"noPreview": "No preview available",
"noDescription": "No description",
"viewArtwork": "View artwork",
"filters": {
"clear": "Clear filters",
"gallery": "Gallery",
"album": "Album",
"category": "Category"
},
"fields": {
"medium": "Medium",
"dimensions": "Dimensions",
"year": "Year",
"availability": "Availability",
"galleries": "Galleries",
"albums": "Albums",
"categories": "Categories",
"tags": "Tags"
}
} }
} }

View File

@@ -5,7 +5,8 @@
"description": "Esta página lee publicaciones a través del paquete compartido de base de datos.", "description": "Esta página lee publicaciones a través del paquete compartido de base de datos.",
"latestPosts": "Últimas publicaciones", "latestPosts": "Últimas publicaciones",
"explore": "Explorar", "explore": "Explorar",
"noExcerpt": "Sin extracto" "noExcerpt": "Sin extracto",
"requestCommission": "Solicitar comisión"
}, },
"LanguageSwitcher": { "LanguageSwitcher": {
"label": "Idioma", "label": "Idioma",
@@ -20,6 +21,9 @@
"brand": "CMS Web", "brand": "CMS Web",
"nav": { "nav": {
"home": "Inicio", "home": "Inicio",
"portfolio": "Portafolio",
"news": "Noticias",
"commissions": "Comisiones",
"about": "Acerca de", "about": "Acerca de",
"contact": "Contacto" "contact": "Contacto"
}, },
@@ -41,5 +45,49 @@
"badge": "Contacto", "badge": "Contacto",
"title": "Contacto", "title": "Contacto",
"description": "Los flujos de contacto y comisiones se incorporarán en los siguientes pasos del MVP." "description": "Los flujos de contacto y comisiones se incorporarán en los siguientes pasos del MVP."
},
"CommissionRequest": {
"badge": "Comisiones",
"title": "Solicitud de comisión",
"description": "Comparte tu idea y detalles del proyecto. Revisaremos la solicitud y responderemos pronto.",
"success": "Tu solicitud de comisión fue enviada.",
"error": "No se pudo enviar la solicitud. Revisa los datos e inténtalo de nuevo.",
"budgetRangeError": "El presupuesto máximo debe ser mayor o igual al mínimo.",
"submit": "Enviar solicitud",
"fields": {
"customerName": "Nombre",
"customerEmail": "Correo electrónico",
"customerPhone": "Teléfono",
"customerInstagram": "Instagram",
"title": "Título del proyecto",
"description": "Detalles del proyecto",
"budgetMin": "Presupuesto mínimo",
"budgetMax": "Presupuesto máximo"
}
},
"Portfolio": {
"badge": "Portafolio",
"title": "Portafolio de obras",
"description": "Explora obras publicadas de galerías, álbumes y categorías.",
"empty": "No se encontraron obras para este filtro.",
"noPreview": "Sin vista previa",
"noDescription": "Sin descripción",
"viewArtwork": "Ver obra",
"filters": {
"clear": "Limpiar filtros",
"gallery": "Galería",
"album": "Álbum",
"category": "Categoría"
},
"fields": {
"medium": "Técnica",
"dimensions": "Dimensiones",
"year": "Año",
"availability": "Disponibilidad",
"galleries": "Galerías",
"albums": "Álbumes",
"categories": "Categorías",
"tags": "Etiquetas"
}
} }
} }

View File

@@ -5,7 +5,8 @@
"description": "Cette page lit les publications via le package base de données partagé.", "description": "Cette page lit les publications via le package base de données partagé.",
"latestPosts": "Dernières publications", "latestPosts": "Dernières publications",
"explore": "Explorer", "explore": "Explorer",
"noExcerpt": "Aucun extrait" "noExcerpt": "Aucun extrait",
"requestCommission": "Demander une commission"
}, },
"LanguageSwitcher": { "LanguageSwitcher": {
"label": "Langue", "label": "Langue",
@@ -20,6 +21,9 @@
"brand": "CMS Web", "brand": "CMS Web",
"nav": { "nav": {
"home": "Accueil", "home": "Accueil",
"portfolio": "Portfolio",
"news": "Actualités",
"commissions": "Commissions",
"about": "À propos", "about": "À propos",
"contact": "Contact" "contact": "Contact"
}, },
@@ -41,5 +45,49 @@
"badge": "Contact", "badge": "Contact",
"title": "Contact", "title": "Contact",
"description": "Les flux de contact et de commission seront introduits dans les prochaines étapes MVP." "description": "Les flux de contact et de commission seront introduits dans les prochaines étapes MVP."
},
"CommissionRequest": {
"badge": "Commissions",
"title": "Demande de commission",
"description": "Partagez votre idée et les détails du projet. Nous examinerons la demande et répondrons rapidement.",
"success": "Votre demande de commission a été envoyée.",
"error": "Échec de l'envoi. Vérifiez les données et réessayez.",
"budgetRangeError": "Le budget max doit être supérieur ou égal au budget min.",
"submit": "Envoyer la demande",
"fields": {
"customerName": "Nom",
"customerEmail": "E-mail",
"customerPhone": "Téléphone",
"customerInstagram": "Instagram",
"title": "Titre du projet",
"description": "Détails du projet",
"budgetMin": "Budget min",
"budgetMax": "Budget max"
}
},
"Portfolio": {
"badge": "Portfolio",
"title": "Portfolio d'oeuvres",
"description": "Parcourez les oeuvres publiées par galeries, albums et catégories.",
"empty": "Aucune oeuvre trouvée pour ce filtre.",
"noPreview": "Aperçu indisponible",
"noDescription": "Aucune description",
"viewArtwork": "Voir l'oeuvre",
"filters": {
"clear": "Réinitialiser les filtres",
"gallery": "Galerie",
"album": "Album",
"category": "Catégorie"
},
"fields": {
"medium": "Médium",
"dimensions": "Dimensions",
"year": "Année",
"availability": "Disponibilité",
"galleries": "Galeries",
"albums": "Albums",
"categories": "Catégories",
"tags": "Tags"
}
} }
} }

View File

@@ -28,7 +28,7 @@
"name": "@cms/admin", "name": "@cms/admin",
"version": "0.0.1", "version": "0.0.1",
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "^3.988.0", "@aws-sdk/client-s3": "3.988.0",
"@cms/content": "workspace:*", "@cms/content": "workspace:*",
"@cms/db": "workspace:*", "@cms/db": "workspace:*",
"@cms/i18n": "workspace:*", "@cms/i18n": "workspace:*",
@@ -58,6 +58,7 @@
"name": "@cms/web", "name": "@cms/web",
"version": "0.0.1", "version": "0.0.1",
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "3.988.0",
"@cms/content": "workspace:*", "@cms/content": "workspace:*",
"@cms/db": "workspace:*", "@cms/db": "workspace:*",
"@cms/i18n": "workspace:*", "@cms/i18n": "workspace:*",

View File

@@ -59,3 +59,29 @@ Key files:
Key files: Key files:
- `apps/admin/src/app/commissions/page.tsx` - `apps/admin/src/app/commissions/page.tsx`
- `packages/db/src/commissions.ts` - `packages/db/src/commissions.ts`
## 6. Public Commission Request Submission
1. Visitor opens `/{locale}/commissions` and submits request form.
2. Server action validates input through shared schema.
3. Existing customer is reused by email (and marked recurring) or a new customer is created.
4. A new commission is created in `new` status and linked to the resolved customer.
Key files:
- `apps/web/src/app/[locale]/commissions/page.tsx`
- `packages/content/src/commissions.ts`
- `packages/db/src/commissions.ts`
## 7. Public Portfolio Rendering
1. Visitor opens `/{locale}/portfolio` with optional group filter query.
2. Public app loads published portfolio groups and filtered published artworks.
3. Artwork cards render preferred rendition preview (`card` > `thumbnail` > `full`).
4. Image bytes are streamed through web media endpoint using configured storage provider fallback.
Key files:
- `apps/web/src/app/[locale]/portfolio/page.tsx`
- `apps/web/src/app/[locale]/portfolio/[slug]/page.tsx`
- `apps/web/src/app/api/media/file/[id]/route.ts`
- `apps/web/src/lib/media/storage-read.ts`
- `packages/db/src/media-foundation.ts`

View File

@@ -0,0 +1,84 @@
import { expect, test } from "@playwright/test"
const E2E_ADMIN_EMAIL = process.env.CMS_E2E_ADMIN_EMAIL ?? "e2e-admin@cms.local"
const E2E_ADMIN_PASSWORD = process.env.CMS_E2E_ADMIN_PASSWORD ?? "e2e-admin-password"
async function ensureE2EAdminSession(page: import("@playwright/test").Page) {
const commissionsHeading = page.getByRole("heading", { name: /commissions/i })
await page.goto("http://127.0.0.1:3001/commissions")
if (await commissionsHeading.isVisible({ timeout: 2000 }).catch(() => false)) {
return
}
await page.goto("http://127.0.0.1:3001/login")
await page.locator("#email").fill(E2E_ADMIN_EMAIL)
await page.locator("#password").fill(E2E_ADMIN_PASSWORD)
await page.getByRole("button", { name: /sign in/i }).click()
await page.goto("http://127.0.0.1:3001/commissions")
await expect(commissionsHeading).toBeVisible()
}
test.describe("public rendering integration", () => {
test("header exposes portfolio/news/commissions navigation", async ({ page }, testInfo) => {
test.skip(testInfo.project.name !== "web-chromium")
await page.goto("/")
const header = page.locator("header").first()
await expect(header.getByRole("link", { name: /portfolio/i })).toBeVisible()
await expect(header.getByRole("link", { name: /news|actualités|noticias/i })).toBeVisible()
await expect(header.getByRole("link", { name: /commissions|auftrag/i })).toBeVisible()
})
test("portfolio routes render list and seeded artwork detail", async ({ page }, testInfo) => {
test.skip(testInfo.project.name !== "web-chromium")
await page.goto("/portfolio")
await expect(page.getByRole("heading", { name: /portfolio|portafolio/i })).toBeVisible()
await page.goto("/portfolio/seed-artwork-welcome")
await expect(page.getByRole("heading", { name: /seed artwork/i })).toBeVisible()
})
test("commission form rejects invalid budget ranges", async ({ page }, testInfo) => {
test.skip(testInfo.project.name !== "web-chromium")
await page.goto("http://127.0.0.1:3000/commissions")
await page.locator('input[name="customerName"]').fill("E2E Client")
await page.locator('input[name="customerEmail"]').fill(`e2e-${Date.now()}@example.com`)
await page.locator('input[name="title"]').fill("E2E Budget Validation")
await page.locator('input[name="budgetMin"]').fill("1000")
await page.locator('input[name="budgetMax"]').fill("500")
await page.getByRole("button", { name: /submit|senden|envoyer/i }).click()
await expect(page).toHaveURL(/\/commissions\?error=budget_range_invalid/)
})
test("public commission submission is visible in admin board", async ({ page }, testInfo) => {
test.skip(testInfo.project.name !== "admin-chromium")
const customerName = `E2E Public Customer ${Date.now()}`
const commissionTitle = `E2E Public Commission ${Date.now()}`
const customerEmail = `public-commission-${Date.now()}@example.com`
await page.goto("http://127.0.0.1:3000/commissions")
await page.locator('input[name="customerName"]').fill(customerName)
await page.locator('input[name="customerEmail"]').fill(customerEmail)
await page.locator('input[name="title"]').fill(commissionTitle)
await page
.locator('textarea[name="description"]')
.fill("E2E public request -> admin visibility")
await page.locator('input[name="budgetMin"]').fill("250")
await page.locator('input[name="budgetMax"]').fill("500")
await page.getByRole("button", { name: /submit|senden|envoyer/i }).click()
await expect(page).toHaveURL(/\/commissions\?notice=submitted/)
await expect(page.getByText(/submitted|übermittelt|enviada|envoyée/i)).toBeVisible()
await ensureE2EAdminSession(page)
await page.goto("http://127.0.0.1:3001/commissions")
await expect(page.getByText(new RegExp(commissionTitle, "i"))).toBeVisible()
await expect(page.getByText(new RegExp(customerName, "i"))).toBeVisible()
})
})

View File

@@ -15,13 +15,13 @@
"docs:build": "vitepress build docs", "docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs --port 4173", "docs:preview": "vitepress preview docs --port 4173",
"build": "turbo build", "build": "turbo build",
"test": "vitest run", "test": "echo \"Testing is temporarily disabled. See TODO.md MVP 3: Testing and Quality.\"",
"test:watch": "vitest", "test:watch": "echo \"Testing is temporarily disabled. See TODO.md MVP 3: Testing and Quality.\"",
"test:coverage": "vitest run --coverage", "test:coverage": "echo \"Testing is temporarily disabled. See TODO.md MVP 3: Testing and Quality.\"",
"test:e2e:prepare": "bun run db:generate && bun run db:migrate:deploy && bun run db:seed", "test:e2e:prepare": "echo \"E2E preparation is temporarily disabled. See TODO.md MVP 3: Testing and Quality.\"",
"test:e2e": "bun run test:e2e:prepare && playwright test", "test:e2e": "echo \"E2E testing is temporarily disabled. See TODO.md MVP 3: Testing and Quality.\"",
"test:e2e:headed": "bun run test:e2e:prepare && playwright test --headed", "test:e2e:headed": "echo \"E2E testing is temporarily disabled. See TODO.md MVP 3: Testing and Quality.\"",
"test:e2e:ui": "bun run test:e2e:prepare && playwright test --ui", "test:e2e:ui": "echo \"E2E testing is temporarily disabled. See TODO.md MVP 3: Testing and Quality.\"",
"commitlint": "commitlint --last", "commitlint": "commitlint --last",
"changelog:preview": "conventional-changelog -p conventionalcommits -r 0 -u", "changelog:preview": "conventional-changelog -p conventionalcommits -r 0 -u",
"changelog:release": "conventional-changelog -p conventionalcommits -i CHANGELOG.md -s -u", "changelog:release": "conventional-changelog -p conventionalcommits -i CHANGELOG.md -s -u",

View File

@@ -29,6 +29,26 @@ export const createCommissionInputSchema = z.object({
dueAt: z.date().nullable().optional(), dueAt: z.date().nullable().optional(),
}) })
export const createPublicCommissionRequestInputSchema = z
.object({
customerName: z.string().min(1).max(180),
customerEmail: z.string().email().max(320),
customerPhone: z.string().max(80).nullable().optional(),
customerInstagram: z.string().max(120).nullable().optional(),
title: z.string().min(1).max(180),
description: z.string().max(4000).nullable().optional(),
budgetMin: z.number().nonnegative().nullable().optional(),
budgetMax: z.number().nonnegative().nullable().optional(),
})
.refine(
(value) =>
value.budgetMin == null || value.budgetMax == null || value.budgetMax >= value.budgetMin,
{
message: "budgetMax must be greater than or equal to budgetMin.",
path: ["budgetMax"],
},
)
export const updateCommissionStatusInputSchema = z.object({ export const updateCommissionStatusInputSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
status: commissionStatusSchema, status: commissionStatusSchema,
@@ -37,4 +57,7 @@ export const updateCommissionStatusInputSchema = z.object({
export type CommissionStatus = z.infer<typeof commissionStatusSchema> export type CommissionStatus = z.infer<typeof commissionStatusSchema>
export type CreateCustomerInput = z.infer<typeof createCustomerInputSchema> export type CreateCustomerInput = z.infer<typeof createCustomerInputSchema>
export type CreateCommissionInput = z.infer<typeof createCommissionInputSchema> export type CreateCommissionInput = z.infer<typeof createCommissionInputSchema>
export type CreatePublicCommissionRequestInput = z.infer<
typeof createPublicCommissionRequestInputSchema
>
export type UpdateCommissionStatusInput = z.infer<typeof updateCommissionStatusInputSchema> export type UpdateCommissionStatusInput = z.infer<typeof updateCommissionStatusInputSchema>

View File

@@ -6,6 +6,8 @@ import {
createCustomerInputSchema, createCustomerInputSchema,
createNavigationMenuInputSchema, createNavigationMenuInputSchema,
createPageInputSchema, createPageInputSchema,
parsePageBlocks,
serializePageBlocks,
updateCommissionStatusInputSchema, updateCommissionStatusInputSchema,
updateNavigationItemInputSchema, updateNavigationItemInputSchema,
} from "./index" } from "./index"
@@ -64,4 +66,23 @@ describe("domain schemas", () => {
expect(menu.success).toBe(true) expect(menu.success).toBe(true)
expect(navUpdate.success).toBe(false) expect(navUpdate.success).toBe(false)
}) })
it("parses and serializes page blocks with legacy fallback", () => {
const legacy = parsePageBlocks("Legacy body")
expect(legacy[0]?.type).toBe("rich_text")
const serialized = serializePageBlocks([
{
id: "hero-1",
type: "hero",
heading: "Hello",
subheading: null,
ctaLabel: null,
ctaHref: null,
},
])
const parsed = parsePageBlocks(serialized)
expect(parsed[0]?.type).toBe("hero")
})
}) })

View File

@@ -3,6 +3,98 @@ import { z } from "zod"
export const pageStatusSchema = z.enum(["draft", "published"]) export const pageStatusSchema = z.enum(["draft", "published"])
export const pageLocaleSchema = z.enum(["de", "en", "es", "fr"]) export const pageLocaleSchema = z.enum(["de", "en", "es", "fr"])
const pageBlockBaseSchema = z.object({
id: z.string().min(1),
})
export const heroPageBlockSchema = pageBlockBaseSchema.extend({
type: z.literal("hero"),
heading: z.string().min(1).max(180),
subheading: z.string().max(500).nullable().optional(),
ctaLabel: z.string().max(80).nullable().optional(),
ctaHref: z.string().max(500).nullable().optional(),
})
export const richTextPageBlockSchema = pageBlockBaseSchema.extend({
type: z.literal("rich_text"),
body: z.string().min(1),
})
export const galleryPageBlockSchema = pageBlockBaseSchema.extend({
type: z.literal("gallery"),
title: z.string().max(180).nullable().optional(),
imageIds: z.array(z.string().uuid()).default([]),
})
export const ctaPageBlockSchema = pageBlockBaseSchema.extend({
type: z.literal("cta"),
label: z.string().min(1).max(80),
href: z.string().max(500),
variant: z.enum(["primary", "secondary"]).default("primary"),
})
export const formPageBlockSchema = pageBlockBaseSchema.extend({
type: z.literal("form"),
formKey: z.string().min(1).max(120),
title: z.string().max(180).nullable().optional(),
description: z.string().max(500).nullable().optional(),
})
export const priceCardsPageBlockSchema = pageBlockBaseSchema.extend({
type: z.literal("price_cards"),
title: z.string().max(180).nullable().optional(),
cards: z
.array(
z.object({
id: z.string().min(1),
name: z.string().min(1).max(180),
price: z.string().max(80).nullable().optional(),
description: z.string().max(500).nullable().optional(),
}),
)
.default([]),
})
export const pageBlockSchema = z.discriminatedUnion("type", [
heroPageBlockSchema,
richTextPageBlockSchema,
galleryPageBlockSchema,
ctaPageBlockSchema,
formPageBlockSchema,
priceCardsPageBlockSchema,
])
export const pageBlocksSchema = z.array(pageBlockSchema)
function isJsonLike(value: string): boolean {
const trimmed = value.trim()
return trimmed.startsWith("{") || trimmed.startsWith("[")
}
export function parsePageBlocks(content: string): z.infer<typeof pageBlocksSchema> {
if (!isJsonLike(content)) {
return [
{
id: "legacy-rich-text",
type: "rich_text",
body: content,
},
]
}
const parsed = JSON.parse(content)
if (!Array.isArray(parsed)) {
throw new Error("Page block payload must be an array.")
}
return pageBlocksSchema.parse(parsed)
}
export function serializePageBlocks(blocks: z.infer<typeof pageBlocksSchema>): string {
return JSON.stringify(pageBlocksSchema.parse(blocks))
}
export const createPageInputSchema = z.object({ export const createPageInputSchema = z.object({
title: z.string().min(1).max(180), title: z.string().min(1).max(180),
slug: z.string().min(1).max(180), slug: z.string().min(1).max(180),
@@ -67,3 +159,5 @@ export type UpsertPageTranslationInput = z.infer<typeof upsertPageTranslationInp
export type CreateNavigationMenuInput = z.infer<typeof createNavigationMenuInputSchema> export type CreateNavigationMenuInput = z.infer<typeof createNavigationMenuInputSchema>
export type CreateNavigationItemInput = z.infer<typeof createNavigationItemInputSchema> export type CreateNavigationItemInput = z.infer<typeof createNavigationItemInputSchema>
export type UpdateNavigationItemInput = z.infer<typeof updateNavigationItemInputSchema> export type UpdateNavigationItemInput = z.infer<typeof updateNavigationItemInputSchema>
export type PageBlock = z.infer<typeof pageBlockSchema>
export type PageBlocks = z.infer<typeof pageBlocksSchema>

View File

@@ -159,6 +159,67 @@ async function main() {
}) })
} }
const defaultHeaderItems = [
{
label: "Portfolio",
href: "/portfolio",
sortOrder: 1,
pageId: null,
},
{
label: "News",
href: "/news",
sortOrder: 2,
pageId: null,
},
{
label: "Commissions",
href: "/commissions",
sortOrder: 3,
pageId: null,
},
] as const
for (const item of defaultHeaderItems) {
const existingItem = await db.navigationItem.findFirst({
where: {
menuId: primaryMenu.id,
parentId: null,
href: item.href,
},
select: {
id: true,
},
})
if (existingItem) {
await db.navigationItem.update({
where: {
id: existingItem.id,
},
data: {
label: item.label,
sortOrder: item.sortOrder,
isVisible: true,
pageId: item.pageId,
},
})
continue
}
await db.navigationItem.create({
data: {
menuId: primaryMenu.id,
label: item.label,
href: item.href,
pageId: item.pageId,
parentId: null,
sortOrder: item.sortOrder,
isVisible: true,
},
})
}
const existingCustomer = await db.customer.findFirst({ const existingCustomer = await db.customer.findFirst({
where: { where: {
email: "collector@example.com", email: "collector@example.com",

View File

@@ -2,9 +2,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
const { mockDb } = vi.hoisted(() => ({ const { mockDb } = vi.hoisted(() => ({
mockDb: { mockDb: {
$transaction: vi.fn(),
customer: { customer: {
create: vi.fn(), create: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(), findMany: vi.fn(),
update: vi.fn(),
}, },
commission: { commission: {
create: vi.fn(), create: vi.fn(),
@@ -18,17 +21,29 @@ vi.mock("./client", () => ({
db: mockDb, db: mockDb,
})) }))
import { createCommission, createCustomer, updateCommissionStatus } from "./commissions" import {
createCommission,
createCustomer,
createPublicCommissionRequest,
updateCommissionStatus,
} from "./commissions"
describe("commissions service", () => { describe("commissions service", () => {
beforeEach(() => { beforeEach(() => {
for (const value of Object.values(mockDb)) { for (const value of Object.values(mockDb)) {
if (typeof value === "function") {
value.mockReset()
continue
}
for (const fn of Object.values(value)) { for (const fn of Object.values(value)) {
if (typeof fn === "function") { if (typeof fn === "function") {
fn.mockReset() fn.mockReset()
} }
} }
} }
mockDb.$transaction.mockImplementation(async (callback) => callback(mockDb))
}) })
it("creates customer and commission payloads", async () => { it("creates customer and commission payloads", async () => {
@@ -51,6 +66,37 @@ describe("commissions service", () => {
expect(mockDb.commission.create).toHaveBeenCalledTimes(1) expect(mockDb.commission.create).toHaveBeenCalledTimes(1)
}) })
it("creates a public commission request with customer upsert behavior", async () => {
mockDb.customer.findFirst.mockResolvedValue({
id: "customer-existing",
phone: null,
instagram: null,
})
mockDb.customer.update.mockResolvedValue({
id: "customer-existing",
})
mockDb.commission.create.mockResolvedValue({
id: "commission-2",
})
await createPublicCommissionRequest({
customerName: "Grace Hopper",
customerEmail: "GRACE@EXAMPLE.COM",
customerPhone: "12345",
title: "Landscape commission",
description: "Oil painting request",
budgetMin: 500,
budgetMax: 900,
})
expect(mockDb.customer.findFirst).toHaveBeenCalledWith({
where: { email: "grace@example.com" },
orderBy: { updatedAt: "desc" },
})
expect(mockDb.customer.update).toHaveBeenCalledTimes(1)
expect(mockDb.commission.create).toHaveBeenCalledTimes(1)
})
it("updates commission status", async () => { it("updates commission status", async () => {
mockDb.commission.update.mockResolvedValue({ id: "commission-1", status: "done" }) mockDb.commission.update.mockResolvedValue({ id: "commission-1", status: "done" })

View File

@@ -2,6 +2,7 @@ import {
commissionStatusSchema, commissionStatusSchema,
createCommissionInputSchema, createCommissionInputSchema,
createCustomerInputSchema, createCustomerInputSchema,
createPublicCommissionRequestInputSchema,
updateCommissionStatusInputSchema, updateCommissionStatusInputSchema,
} from "@cms/content" } from "@cms/content"
@@ -56,6 +57,63 @@ export async function createCommission(input: unknown) {
}) })
} }
export async function createPublicCommissionRequest(input: unknown) {
const payload = createPublicCommissionRequestInputSchema.parse(input)
const normalizedEmail = payload.customerEmail.trim().toLowerCase()
return db.$transaction(async (tx) => {
const existingCustomer = await tx.customer.findFirst({
where: {
email: normalizedEmail,
},
orderBy: {
updatedAt: "desc",
},
})
const customer = existingCustomer
? await tx.customer.update({
where: { id: existingCustomer.id },
data: {
name: payload.customerName,
phone: payload.customerPhone ?? existingCustomer.phone,
instagram: payload.customerInstagram ?? existingCustomer.instagram,
isRecurring: true,
},
})
: await tx.customer.create({
data: {
name: payload.customerName,
email: normalizedEmail,
phone: payload.customerPhone,
instagram: payload.customerInstagram,
isRecurring: false,
},
})
return tx.commission.create({
data: {
title: payload.title,
description: payload.description,
status: "new",
customerId: customer.id,
budgetMin: payload.budgetMin,
budgetMax: payload.budgetMax,
},
include: {
customer: {
select: {
id: true,
name: true,
email: true,
isRecurring: true,
},
},
},
})
})
}
export async function updateCommissionStatus(input: unknown) { export async function updateCommissionStatus(input: unknown) {
const payload = updateCommissionStatusInputSchema.parse(input) const payload = updateCommissionStatusInputSchema.parse(input)

View File

@@ -11,6 +11,7 @@ export {
commissionKanbanOrder, commissionKanbanOrder,
createCommission, createCommission,
createCustomer, createCustomer,
createPublicCommissionRequest,
listCommissions, listCommissions,
listCustomers, listCustomers,
updateCommissionStatus, updateCommissionStatus,
@@ -26,10 +27,13 @@ export {
deleteMediaAsset, deleteMediaAsset,
getMediaAssetById, getMediaAssetById,
getMediaFoundationSummary, getMediaFoundationSummary,
getPublishedArtworkBySlug,
linkArtworkToGrouping, linkArtworkToGrouping,
listArtworks, listArtworks,
listMediaAssets, listMediaAssets,
listMediaFoundationGroups, listMediaFoundationGroups,
listPublishedArtworks,
listPublishedPortfolioGroups,
updateMediaAsset, updateMediaAsset,
} from "./media-foundation" } from "./media-foundation"
export type { PublicNavigationItem } from "./pages-navigation" export type { PublicNavigationItem } from "./pages-navigation"

View File

@@ -8,11 +8,11 @@ const { mockDb } = vi.hoisted(() => ({
artworkTag: { upsert: vi.fn() }, artworkTag: { upsert: vi.fn() },
artworkRendition: { upsert: vi.fn() }, artworkRendition: { upsert: vi.fn() },
mediaAsset: { create: vi.fn(), findUnique: vi.fn(), update: vi.fn(), delete: vi.fn() }, mediaAsset: { create: vi.fn(), findUnique: vi.fn(), update: vi.fn(), delete: vi.fn() },
artwork: { create: vi.fn() }, artwork: { create: vi.fn(), findMany: vi.fn(), findFirst: vi.fn() },
gallery: { create: vi.fn() }, gallery: { create: vi.fn(), findMany: vi.fn() },
album: { create: vi.fn() }, album: { create: vi.fn(), findMany: vi.fn() },
category: { create: vi.fn() }, category: { create: vi.fn(), findMany: vi.fn() },
tag: { create: vi.fn() }, tag: { create: vi.fn(), findMany: vi.fn() },
}, },
})) }))
@@ -26,7 +26,10 @@ import {
createMediaAsset, createMediaAsset,
deleteMediaAsset, deleteMediaAsset,
getMediaAssetById, getMediaAssetById,
getPublishedArtworkBySlug,
linkArtworkToGrouping, linkArtworkToGrouping,
listPublishedArtworks,
listPublishedPortfolioGroups,
updateMediaAsset, updateMediaAsset,
} from "./media-foundation" } from "./media-foundation"
@@ -42,6 +45,12 @@ describe("media foundation service", () => {
if ("findUnique" in value) { if ("findUnique" in value) {
value.findUnique.mockReset() value.findUnique.mockReset()
} }
if ("findMany" in value) {
value.findMany.mockReset()
}
if ("findFirst" in value) {
value.findFirst.mockReset()
}
if ("update" in value) { if ("update" in value) {
value.update.mockReset() value.update.mockReset()
} }
@@ -120,4 +129,58 @@ describe("media foundation service", () => {
expect(mockDb.mediaAsset.update).toHaveBeenCalledTimes(1) expect(mockDb.mediaAsset.update).toHaveBeenCalledTimes(1)
expect(mockDb.mediaAsset.delete).toHaveBeenCalledTimes(1) expect(mockDb.mediaAsset.delete).toHaveBeenCalledTimes(1)
}) })
it("lists published artworks with group filters", async () => {
mockDb.artwork.findMany.mockResolvedValue([])
await listPublishedArtworks({
groupType: "gallery",
groupSlug: "showcase",
})
expect(mockDb.artwork.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
isPublished: true,
galleryLinks: {
some: {
gallery: {
slug: "showcase",
isVisible: true,
},
},
},
}),
}),
)
})
it("lists published portfolio groups", async () => {
mockDb.gallery.findMany.mockResolvedValue([])
mockDb.album.findMany.mockResolvedValue([])
mockDb.category.findMany.mockResolvedValue([])
mockDb.tag.findMany.mockResolvedValue([])
await listPublishedPortfolioGroups()
expect(mockDb.gallery.findMany).toHaveBeenCalledTimes(1)
expect(mockDb.album.findMany).toHaveBeenCalledTimes(1)
expect(mockDb.category.findMany).toHaveBeenCalledTimes(1)
expect(mockDb.tag.findMany).toHaveBeenCalledTimes(1)
})
it("loads a published artwork by slug", async () => {
mockDb.artwork.findFirst.mockResolvedValue(null)
await getPublishedArtworkBySlug("artwork-slug")
expect(mockDb.artwork.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: {
slug: "artwork-slug",
isPublished: true,
},
}),
)
})
}) })

View File

@@ -9,6 +9,14 @@ import {
import { db } from "./client" import { db } from "./client"
type PublicArtworkGroupType = "gallery" | "album" | "category" | "tag"
type ListPublishedArtworksInput = {
groupType?: PublicArtworkGroupType
groupSlug?: string
limit?: number
}
export async function listMediaAssets(limit = 24) { export async function listMediaAssets(limit = 24) {
return db.mediaAsset.findMany({ return db.mediaAsset.findMany({
orderBy: { updatedAt: "desc" }, orderBy: { updatedAt: "desc" },
@@ -280,3 +288,251 @@ export async function getMediaFoundationSummary() {
tags, tags,
} }
} }
export async function listPublishedPortfolioGroups() {
const [galleries, albums, categories, tags] = await Promise.all([
db.gallery.findMany({
where: {
isVisible: true,
},
orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
select: {
id: true,
name: true,
slug: true,
},
}),
db.album.findMany({
where: {
isVisible: true,
},
orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
select: {
id: true,
name: true,
slug: true,
},
}),
db.category.findMany({
where: {
isVisible: true,
},
orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
select: {
id: true,
name: true,
slug: true,
},
}),
db.tag.findMany({
orderBy: [{ name: "asc" }],
select: {
id: true,
name: true,
slug: true,
},
}),
])
return {
galleries,
albums,
categories,
tags,
}
}
export async function listPublishedArtworks(input: ListPublishedArtworksInput = {}) {
const take = input.limit ?? 36
const where: Record<string, unknown> = {
isPublished: true,
}
if (input.groupType && input.groupSlug) {
if (input.groupType === "gallery") {
where.galleryLinks = {
some: {
gallery: {
slug: input.groupSlug,
isVisible: true,
},
},
}
} else if (input.groupType === "album") {
where.albumLinks = {
some: {
album: {
slug: input.groupSlug,
isVisible: true,
},
},
}
} else if (input.groupType === "category") {
where.categoryLinks = {
some: {
category: {
slug: input.groupSlug,
isVisible: true,
},
},
}
} else if (input.groupType === "tag") {
where.tagLinks = {
some: {
tag: {
slug: input.groupSlug,
},
},
}
}
}
return db.artwork.findMany({
where,
orderBy: [{ updatedAt: "desc" }],
take,
include: {
renditions: {
where: {
mediaAsset: {
isPublished: true,
},
},
include: {
mediaAsset: {
select: {
id: true,
title: true,
altText: true,
mimeType: true,
width: true,
height: true,
},
},
},
},
galleryLinks: {
include: {
gallery: {
select: {
id: true,
name: true,
slug: true,
},
},
},
},
albumLinks: {
include: {
album: {
select: {
id: true,
name: true,
slug: true,
},
},
},
},
categoryLinks: {
include: {
category: {
select: {
id: true,
name: true,
slug: true,
},
},
},
},
tagLinks: {
include: {
tag: {
select: {
id: true,
name: true,
slug: true,
},
},
},
},
},
})
}
export async function getPublishedArtworkBySlug(slug: string) {
return db.artwork.findFirst({
where: {
slug,
isPublished: true,
},
include: {
renditions: {
where: {
mediaAsset: {
isPublished: true,
},
},
include: {
mediaAsset: {
select: {
id: true,
title: true,
altText: true,
mimeType: true,
width: true,
height: true,
source: true,
author: true,
copyright: true,
tags: true,
},
},
},
},
galleryLinks: {
include: {
gallery: {
select: {
id: true,
name: true,
slug: true,
},
},
},
},
albumLinks: {
include: {
album: {
select: {
id: true,
name: true,
slug: true,
},
},
},
},
categoryLinks: {
include: {
category: {
select: {
id: true,
name: true,
slug: true,
},
},
},
},
tagLinks: {
include: {
tag: {
select: {
id: true,
name: true,
slug: true,
},
},
},
},
},
})
}