Compare commits
9 Commits
todo/mvp1-
...
todo/mvp1-
| Author | SHA1 | Date | |
|---|---|---|---|
|
103c45c926
|
|||
|
d2a645df6f
|
|||
|
18b709b4b0
|
|||
|
a2bea6326e
|
|||
|
60c9035743
|
|||
|
741883465c
|
|||
|
7a82934fe7
|
|||
|
473433b220
|
|||
|
987843d96b
|
64
TODO.md
64
TODO.md
@@ -112,15 +112,15 @@ This file is the single source of truth for roadmap and delivery progress.
|
||||
|
||||
- [x] [P1] `todo/mvp1-media-foundation`:
|
||||
media model, artwork entity, grouping primitives (gallery/album/category/tag), rendition slots
|
||||
- [~] [P1] `todo/mvp1-media-upload-pipeline`:
|
||||
- [x] [P1] `todo/mvp1-media-upload-pipeline`:
|
||||
S3/local upload adapter, media processing presets, metadata input flows, admin media CRUD UI
|
||||
- [~] [P1] `todo/mvp1-pages-navigation-builder`:
|
||||
- [x] [P1] `todo/mvp1-pages-navigation-builder`:
|
||||
page CRUD, navigation tree, reusable page blocks (forms/price cards/gallery embeds)
|
||||
- [~] [P1] `todo/mvp1-commissions-customers`:
|
||||
- [x] [P1] `todo/mvp1-commissions-customers`:
|
||||
commission request intake + admin CRUD + kanban + customer entity/linking
|
||||
- [~] [P1] `todo/mvp1-announcements-news`:
|
||||
- [x] [P1] `todo/mvp1-announcements-news`:
|
||||
announcement management/rendering + news/blog CRUD and public rendering
|
||||
- [~] [P1] `todo/mvp1-public-rendering-integration`:
|
||||
- [x] [P1] `todo/mvp1-public-rendering-integration`:
|
||||
public rendering for pages/navigation/media/portfolio/announcements and commissioning entrypoints
|
||||
- [~] [P1] `todo/mvp1-e2e-happy-paths`:
|
||||
end-to-end scenarios for page publish, media flow, announcement display, commission flow
|
||||
@@ -136,44 +136,44 @@ This file is the single source of truth for roadmap and delivery progress.
|
||||
|
||||
### Admin App (Primary Focus)
|
||||
|
||||
- [~] [P1] Page management (create/edit/publish/unpublish/schedule)
|
||||
- [ ] [P1] Page builder with reusable content blocks (hero, rich text, gallery, CTA, forms, price cards)
|
||||
- [~] [P1] Navigation management (menus, nested items, order, visibility)
|
||||
- [~] [P1] Media library (upload, browse, replace, delete) with media-type classification (artwork, banner, promo, generic, video/gif)
|
||||
- [x] [P1] Page management (create/edit/publish/unpublish/schedule)
|
||||
- [x] [P1] Page builder with reusable content blocks (hero, rich text, gallery, CTA, forms, price cards)
|
||||
- [x] [P1] Navigation management (menus, nested items, order, visibility)
|
||||
- [x] [P1] Media library (upload, browse, replace, delete) with media-type classification (artwork, banner, promo, generic, video/gif)
|
||||
- [x] [P1] Media enrichment metadata (alt text, copyright, author, source, tags, licensing, usage context)
|
||||
- [x] [P1] Portfolio grouping primitives (galleries, albums, categories, tags) with ordering/visibility controls
|
||||
- [x] [P1] Artwork refinement fields (medium, dimensions, year, framing, availability, price visibility)
|
||||
- [x] [P1] Artwork rendition management (thumbnail, card, full, retina/custom sizes)
|
||||
- [x] [P1] Type-specific processing presets (artwork/banner/promo/video/gif) with validation rules
|
||||
- [ ] [P1] Users management (invite, roles, status)
|
||||
- [ ] [P1] Disable/ban user function and enforcement in auth/session checks
|
||||
- [~] [P1] Owner/support protection rules in user management actions (cannot delete/demote)
|
||||
- [~] [P1] Commissions management (request intake, owner, due date, notes, linked customer, linked artworks)
|
||||
- [~] [P1] Customer records (contact profile, notes, consent flags, recurrence marker)
|
||||
- [~] [P1] Customer-to-commission linkage and reuse workflow (no re-entry for recurring customers)
|
||||
- [~] [P1] Kanban workflow for commissions (new, scoped, in-progress, review, done)
|
||||
- [x] [P1] Users management (invite, roles, status)
|
||||
- [x] [P1] Disable/ban user function and enforcement in auth/session checks
|
||||
- [x] [P1] Owner/support protection rules in user management actions (cannot delete/demote)
|
||||
- [x] [P1] Commissions management (request intake, owner, due date, notes, linked customer, linked artworks)
|
||||
- [x] [P1] Customer records (contact profile, notes, consent flags, recurrence marker)
|
||||
- [x] [P1] Customer-to-commission linkage and reuse workflow (no re-entry for recurring customers)
|
||||
- [x] [P1] Kanban workflow for commissions (new, scoped, in-progress, review, done)
|
||||
- [x] [P1] Header banner management (message, CTA, active window)
|
||||
- [~] [P1] Announcements management (prominent site notices with schedule, priority, and audience targeting)
|
||||
- [x] [P1] Announcements management (prominent site notices with schedule, priority, and audience targeting)
|
||||
- [~] [P2] News/blog editorial workflow (draft/review/publish, authoring metadata)
|
||||
|
||||
### Public App
|
||||
|
||||
- [~] [P1] Dynamic page rendering from CMS page entities
|
||||
- [~] [P1] Navigation rendering from managed menu structure
|
||||
- [~] [P1] Media entity rendering with enrichment data
|
||||
- [~] [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] Translation-ready content model for public entities (pages/news/navigation labels)
|
||||
- [ ] [P2] Artwork views and listing filters
|
||||
- [~] [P1] Commission request submission flow
|
||||
- [x] [P1] Dynamic page rendering from CMS page entities
|
||||
- [x] [P1] Navigation rendering from managed menu structure
|
||||
- [x] [P1] Media entity rendering with enrichment data
|
||||
- [x] [P1] Portfolio views (gallery/album/category/tag) for artworks with filter and sort controls
|
||||
- [x] [P1] Rendition-aware media delivery (thumbnail/card/full) per template slot
|
||||
- [x] [P1] Translation-ready content model for public entities (pages/news/navigation labels)
|
||||
- [x] [P2] Artwork views and listing filters
|
||||
- [x] [P1] Commission request submission flow
|
||||
- [x] [P1] Header banner render logic and fallbacks
|
||||
- [x] [P1] Announcement render slots (homepage + optional global/top banner position)
|
||||
|
||||
### News / Blog (Secondary Track)
|
||||
|
||||
- [~] [P1] News/blog content type (editorial content for artist updates and process posts)
|
||||
- [~] [P1] Admin list/editor for news posts
|
||||
- [~] [P1] Public news index + detail pages
|
||||
- [x] [P1] News/blog content type (editorial content for artist updates and process posts)
|
||||
- [x] [P1] Admin list/editor for news posts
|
||||
- [x] [P1] Public news index + detail pages
|
||||
- [ ] [P2] Tag/category and basic archive support
|
||||
|
||||
### Testing
|
||||
@@ -365,6 +365,14 @@ This file is the single source of truth for roadmap and delivery progress.
|
||||
- [2026-02-12] Artwork refinement baseline completed: admin `/portfolio` now captures/edits medium, dimensions, year, framing, availability, publish state, and optional price visibility (`priceAmountCents` + `priceCurrency`), with public artwork detail rendering visible prices only.
|
||||
- [2026-02-12] Artwork rendition management completed: admin `/portfolio` supports `thumbnail/card/full/retina/custom` slot assignment with dimensions and primary flag, plus per-artwork rendition listing and delete controls.
|
||||
- [2026-02-12] Media type presets baseline completed in upload API: server-side validation now uses shared per-type rules (mime + max size) for `artwork/banner/promotion/video/gif/generic`, with optional env cap override via `CMS_MEDIA_UPLOAD_MAX_BYTES`.
|
||||
- [2026-02-12] Page builder reusable blocks completed: admin block editor now supports full field editing + ordering controls for hero/rich-text/gallery/cta/form/price-cards; public renderer includes form-link behavior for `contact`/`commission` keys.
|
||||
- [2026-02-12] Navigation management completed: admin `/navigation` now supports menu update/delete controls, nested item parent selection via menu-local dropdown, and full order/visibility updates across menus and items.
|
||||
- [2026-02-12] Users management baseline completed: admin `/users` now supports managed user creation, role changes (`admin/editor/manager`), status changes (ban/unban), and protected/system guardrails for role-change/delete/ban actions.
|
||||
- [2026-02-12] Commissions management completed: admin kanban cards now include inline detail editing (assignee/customer/budget/due date/notes), linked-artwork references via `linkedArtworkIds`, and creation/edit flows use assignable users instead of raw ID entry.
|
||||
- [2026-02-12] Announcements/news completed: announcements now support locale audience targeting (`targetLocales`) with public locale-aware rendering, and homepage news list now uses locale-aware published posts only.
|
||||
- [2026-02-12] Public rendering integration completed: portfolio now supports locale-aware tag filters and explicit sort controls, while db/service sorting and rendition selection align public listing/detail media delivery.
|
||||
- [2026-02-12] Page scheduling completed: `Page.scheduledPublishAt` added with admin create/edit support and public page resolution now treating due scheduled pages as published.
|
||||
- [2026-02-12] Media library replace flow completed: admin `/media/:id` can now replace an asset’s source file in-place, update `storageKey`/MIME/size metadata, and clean up old storage objects with fallback notices.
|
||||
- [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`.
|
||||
|
||||
@@ -14,6 +14,7 @@ import { requirePermissionForRoute } from "@/lib/route-guards"
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
type SearchParamsInput = Record<string, string | string[] | undefined>
|
||||
const SUPPORTED_LOCALES = ["de", "en", "es", "fr"] as const
|
||||
|
||||
function readFirstValue(value: string | string[] | undefined): string | null {
|
||||
if (Array.isArray(value)) {
|
||||
@@ -49,6 +50,22 @@ function readNullableDate(formData: FormData, field: string): Date | null {
|
||||
return parsed
|
||||
}
|
||||
|
||||
function readLocaleSelections(formData: FormData, field: string): string[] {
|
||||
const values = formData.getAll(field)
|
||||
const locales = new Set<string>()
|
||||
|
||||
for (const value of values) {
|
||||
if (
|
||||
typeof value === "string" &&
|
||||
SUPPORTED_LOCALES.includes(value as (typeof SUPPORTED_LOCALES)[number])
|
||||
) {
|
||||
locales.add(value)
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(locales)
|
||||
}
|
||||
|
||||
function readInt(formData: FormData, field: string, fallback = 100): number {
|
||||
const value = readInputString(formData, field)
|
||||
|
||||
@@ -94,6 +111,7 @@ async function createAnnouncementAction(formData: FormData) {
|
||||
title: readInputString(formData, "title"),
|
||||
message: readInputString(formData, "message"),
|
||||
placement: readInputString(formData, "placement"),
|
||||
targetLocales: readLocaleSelections(formData, "targetLocales"),
|
||||
priority: readInt(formData, "priority", 100),
|
||||
ctaLabel: readNullableString(formData, "ctaLabel"),
|
||||
ctaHref: readNullableString(formData, "ctaHref"),
|
||||
@@ -125,6 +143,7 @@ async function updateAnnouncementAction(formData: FormData) {
|
||||
title: readInputString(formData, "title"),
|
||||
message: readInputString(formData, "message"),
|
||||
placement: readInputString(formData, "placement"),
|
||||
targetLocales: readLocaleSelections(formData, "targetLocales"),
|
||||
priority: readInt(formData, "priority", 100),
|
||||
ctaLabel: readNullableString(formData, "ctaLabel"),
|
||||
ctaHref: readNullableString(formData, "ctaHref"),
|
||||
@@ -277,6 +296,20 @@ export default async function AnnouncementsPage({
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-neutral-600">Target locales (empty = all locales)</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{SUPPORTED_LOCALES.map((locale) => (
|
||||
<label
|
||||
key={`create-locale-${locale}`}
|
||||
className="inline-flex items-center gap-2 text-sm"
|
||||
>
|
||||
<input name="targetLocales" type="checkbox" value={locale} className="size-4" />
|
||||
{locale.toUpperCase()}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-neutral-600">Starts at</span>
|
||||
@@ -390,6 +423,26 @@ export default async function AnnouncementsPage({
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-3 space-y-1">
|
||||
<p className="text-xs text-neutral-600">Target locales (empty = all locales)</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{SUPPORTED_LOCALES.map((locale) => (
|
||||
<label
|
||||
key={`${announcement.id}-locale-${locale}`}
|
||||
className="inline-flex items-center gap-2 text-sm"
|
||||
>
|
||||
<input
|
||||
name="targetLocales"
|
||||
type="checkbox"
|
||||
value={locale}
|
||||
defaultChecked={announcement.targetLocales.includes(locale)}
|
||||
className="size-4"
|
||||
/>
|
||||
{locale.toUpperCase()}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-3">
|
||||
<label className="inline-flex items-center gap-2 text-sm text-neutral-700">
|
||||
<input
|
||||
|
||||
@@ -2,8 +2,11 @@ import {
|
||||
commissionKanbanOrder,
|
||||
createCommission,
|
||||
createCustomer,
|
||||
db,
|
||||
listArtworks,
|
||||
listCommissions,
|
||||
listCustomers,
|
||||
updateCommission,
|
||||
updateCommissionStatus,
|
||||
} from "@cms/db"
|
||||
import { Button } from "@cms/ui/button"
|
||||
@@ -67,6 +70,19 @@ function readNullableDate(formData: FormData, field: string): Date | null {
|
||||
return parsed
|
||||
}
|
||||
|
||||
function readUuidList(formData: FormData, field: string): string[] {
|
||||
const raw = readInputString(formData, field)
|
||||
|
||||
if (!raw) {
|
||||
return []
|
||||
}
|
||||
|
||||
return raw
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
}
|
||||
|
||||
function redirectWithState(params: { notice?: string; error?: string }) {
|
||||
const query = new URLSearchParams()
|
||||
|
||||
@@ -124,6 +140,7 @@ async function createCommissionAction(formData: FormData) {
|
||||
status: readInputString(formData, "status"),
|
||||
customerId: readNullableString(formData, "customerId"),
|
||||
assignedUserId: readNullableString(formData, "assignedUserId"),
|
||||
linkedArtworkIds: readUuidList(formData, "linkedArtworkIds"),
|
||||
budgetMin: readNullableNumber(formData, "budgetMin"),
|
||||
budgetMax: readNullableNumber(formData, "budgetMax"),
|
||||
dueAt: readNullableDate(formData, "dueAt"),
|
||||
@@ -136,6 +153,35 @@ async function createCommissionAction(formData: FormData) {
|
||||
redirectWithState({ notice: "Commission created." })
|
||||
}
|
||||
|
||||
async function updateCommissionAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
await requirePermissionForRoute({
|
||||
nextPath: "/commissions",
|
||||
permission: "commissions:write",
|
||||
scope: "own",
|
||||
})
|
||||
|
||||
try {
|
||||
await updateCommission({
|
||||
id: readInputString(formData, "id"),
|
||||
title: readInputString(formData, "title"),
|
||||
description: readNullableString(formData, "description"),
|
||||
customerId: readNullableString(formData, "customerId"),
|
||||
assignedUserId: readNullableString(formData, "assignedUserId"),
|
||||
linkedArtworkIds: readUuidList(formData, "linkedArtworkIds"),
|
||||
budgetMin: readNullableNumber(formData, "budgetMin"),
|
||||
budgetMax: readNullableNumber(formData, "budgetMax"),
|
||||
dueAt: readNullableDate(formData, "dueAt"),
|
||||
})
|
||||
} catch {
|
||||
redirectWithState({ error: "Failed to update commission details." })
|
||||
}
|
||||
|
||||
revalidatePath("/commissions")
|
||||
redirectWithState({ notice: "Commission updated." })
|
||||
}
|
||||
|
||||
async function updateCommissionStatusAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
@@ -166,6 +212,14 @@ function formatDate(value: Date | null) {
|
||||
return value.toLocaleDateString("en-US")
|
||||
}
|
||||
|
||||
function formatDateInput(value: Date | null) {
|
||||
if (!value) {
|
||||
return ""
|
||||
}
|
||||
|
||||
return value.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
export default async function CommissionsManagementPage({
|
||||
searchParams,
|
||||
}: {
|
||||
@@ -177,10 +231,22 @@ export default async function CommissionsManagementPage({
|
||||
scope: "own",
|
||||
})
|
||||
|
||||
const [resolvedSearchParams, customers, commissions] = await Promise.all([
|
||||
const [resolvedSearchParams, customers, commissions, assignees, artworks] = await Promise.all([
|
||||
searchParams,
|
||||
listCustomers(200),
|
||||
listCommissions(300),
|
||||
db.user.findMany({
|
||||
where: {
|
||||
isBanned: false,
|
||||
},
|
||||
orderBy: [{ createdAt: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
username: true,
|
||||
},
|
||||
}),
|
||||
listArtworks(300),
|
||||
])
|
||||
|
||||
const notice = readFirstValue(resolvedSearchParams.notice)
|
||||
@@ -309,11 +375,18 @@ export default async function CommissionsManagementPage({
|
||||
</div>
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-neutral-600">Assigned user id</span>
|
||||
<input
|
||||
<span className="text-xs text-neutral-600">Assigned user</span>
|
||||
<select
|
||||
name="assignedUserId"
|
||||
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
>
|
||||
<option value="">(none)</option>
|
||||
{assignees.map((assignee) => (
|
||||
<option key={assignee.id} value={assignee.id}>
|
||||
{assignee.name} @{assignee.username ?? "no-user"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-neutral-600">Budget min</span>
|
||||
@@ -344,6 +417,14 @@ export default async function CommissionsManagementPage({
|
||||
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">Linked artwork IDs (comma separated)</span>
|
||||
<textarea
|
||||
name="linkedArtworkIds"
|
||||
rows={2}
|
||||
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<Button type="submit">Create commission</Button>
|
||||
</form>
|
||||
</article>
|
||||
@@ -383,6 +464,9 @@ export default async function CommissionsManagementPage({
|
||||
<p className="text-xs text-neutral-600">
|
||||
{commission.customer?.name ?? "No customer"}
|
||||
</p>
|
||||
<p className="text-xs text-neutral-500">
|
||||
Assignee: {commission.assignedUser?.name ?? "none"}
|
||||
</p>
|
||||
<p className="text-xs text-neutral-500">
|
||||
Due: {formatDate(commission.dueAt)}
|
||||
</p>
|
||||
@@ -406,6 +490,99 @@ export default async function CommissionsManagementPage({
|
||||
Move
|
||||
</button>
|
||||
</div>
|
||||
<details className="mt-2 rounded border border-neutral-200 p-2 text-xs">
|
||||
<summary className="cursor-pointer text-neutral-700">
|
||||
Edit details
|
||||
</summary>
|
||||
<form action={updateCommissionAction} className="mt-2 space-y-2">
|
||||
<input type="hidden" name="id" value={commission.id} />
|
||||
<input
|
||||
name="title"
|
||||
defaultValue={commission.title}
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1"
|
||||
/>
|
||||
<textarea
|
||||
name="description"
|
||||
rows={2}
|
||||
defaultValue={commission.description ?? ""}
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1"
|
||||
/>
|
||||
<select
|
||||
name="customerId"
|
||||
defaultValue={commission.customerId ?? ""}
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1"
|
||||
>
|
||||
<option value="">(no customer)</option>
|
||||
{customers.map((customer) => (
|
||||
<option
|
||||
key={`${commission.id}-customer-${customer.id}`}
|
||||
value={customer.id}
|
||||
>
|
||||
{customer.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
name="assignedUserId"
|
||||
defaultValue={commission.assignedUserId ?? ""}
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1"
|
||||
>
|
||||
<option value="">(no assignee)</option>
|
||||
{assignees.map((assignee) => (
|
||||
<option
|
||||
key={`${commission.id}-assignee-${assignee.id}`}
|
||||
value={assignee.id}
|
||||
>
|
||||
{assignee.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<input
|
||||
name="budgetMin"
|
||||
type="number"
|
||||
min={0}
|
||||
step="0.01"
|
||||
defaultValue={commission.budgetMin ?? ""}
|
||||
placeholder="Budget min"
|
||||
className="rounded border border-neutral-300 px-2 py-1"
|
||||
/>
|
||||
<input
|
||||
name="budgetMax"
|
||||
type="number"
|
||||
min={0}
|
||||
step="0.01"
|
||||
defaultValue={commission.budgetMax ?? ""}
|
||||
placeholder="Budget max"
|
||||
className="rounded border border-neutral-300 px-2 py-1"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
name="dueAt"
|
||||
type="date"
|
||||
defaultValue={formatDateInput(commission.dueAt)}
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1"
|
||||
/>
|
||||
<textarea
|
||||
name="linkedArtworkIds"
|
||||
rows={2}
|
||||
defaultValue={commission.linkedArtworkIds.join(",")}
|
||||
placeholder="Artwork IDs"
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded border border-neutral-300 px-2 py-1 text-xs"
|
||||
>
|
||||
Save details
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
{commission.linkedArtworkIds.length > 0 ? (
|
||||
<p className="mt-2 text-[11px] text-neutral-500">
|
||||
Linked artworks: {commission.linkedArtworkIds.length}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
))
|
||||
)}
|
||||
@@ -449,6 +626,24 @@ export default async function CommissionsManagementPage({
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border border-neutral-200 p-6">
|
||||
<h2 className="text-xl font-medium">Artwork Reference</h2>
|
||||
<p className="mt-1 text-sm text-neutral-600">
|
||||
Use these IDs when linking artworks to commissions.
|
||||
</p>
|
||||
<div className="mt-3 max-h-64 overflow-auto rounded border border-neutral-200 p-3 text-xs">
|
||||
{artworks.length === 0 ? (
|
||||
<p className="text-neutral-500">No artworks available.</p>
|
||||
) : (
|
||||
artworks.map((artwork) => (
|
||||
<p key={artwork.id} className="font-mono text-neutral-700">
|
||||
{artwork.id} - {artwork.title}
|
||||
</p>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</AdminShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import {
|
||||
getMediaUploadMaxBytes,
|
||||
isMimeAllowedForMediaType,
|
||||
mediaAssetTypeSchema,
|
||||
} from "@cms/content"
|
||||
import { deleteMediaAsset, getMediaAssetById, updateMediaAsset } from "@cms/db"
|
||||
import { Button } from "@cms/ui/button"
|
||||
import Link from "next/link"
|
||||
import { redirect } from "next/navigation"
|
||||
|
||||
import { AdminShell } from "@/components/admin-shell"
|
||||
import { deleteStoredMediaObject } from "@/lib/media/storage"
|
||||
import { deleteStoredMediaObject, storeUpload } from "@/lib/media/storage"
|
||||
import { requirePermissionForRoute } from "@/lib/route-guards"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
@@ -79,7 +84,10 @@ function readTags(formData: FormData): string[] {
|
||||
.filter((item) => item.length > 0)
|
||||
}
|
||||
|
||||
function redirectWithState(mediaAssetId: string, params: { notice?: string; error?: string }) {
|
||||
function redirectWithState(
|
||||
mediaAssetId: string,
|
||||
params: { notice?: string; error?: string },
|
||||
): never {
|
||||
const query = new URLSearchParams()
|
||||
|
||||
if (params.notice) {
|
||||
@@ -189,6 +197,80 @@ export default async function MediaAssetEditorPage({ params, searchParams }: Pag
|
||||
redirect("/media?notice=Media+asset+deleted")
|
||||
}
|
||||
|
||||
async function replaceMediaFileAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
await requirePermissionForRoute({
|
||||
nextPath: "/media",
|
||||
permission: "media:write",
|
||||
scope: "team",
|
||||
})
|
||||
|
||||
const fileEntry = formData.get("file")
|
||||
|
||||
if (!(fileEntry instanceof File) || fileEntry.size === 0) {
|
||||
redirectWithState(mediaAssetId, { error: "Select a replacement file first." })
|
||||
}
|
||||
|
||||
const parsedType = mediaAssetTypeSchema.safeParse(mediaAsset.type)
|
||||
|
||||
if (!parsedType.success) {
|
||||
redirectWithState(mediaAssetId, { error: "Media type is invalid for replacement." })
|
||||
}
|
||||
const mediaType = parsedType.data
|
||||
const maxBytes = getMediaUploadMaxBytes(mediaType)
|
||||
|
||||
if (fileEntry.size > maxBytes) {
|
||||
redirectWithState(mediaAssetId, {
|
||||
error: `Replacement file is too large for ${mediaType}. Max ${Math.floor(maxBytes / 1024 / 1024)} MB.`,
|
||||
})
|
||||
}
|
||||
|
||||
if (!isMimeAllowedForMediaType(mediaType, fileEntry.type)) {
|
||||
redirectWithState(mediaAssetId, {
|
||||
error: `File type ${fileEntry.type || "unknown"} is not allowed for ${mediaType}.`,
|
||||
})
|
||||
}
|
||||
|
||||
const previousStorageKey = mediaAsset.storageKey
|
||||
|
||||
try {
|
||||
const stored = await storeUpload({
|
||||
file: fileEntry,
|
||||
assetId: mediaAssetId,
|
||||
variant: "original",
|
||||
fileRole: "original",
|
||||
})
|
||||
|
||||
await updateMediaAsset({
|
||||
id: mediaAssetId,
|
||||
storageKey: stored.storageKey,
|
||||
mimeType: fileEntry.type || null,
|
||||
sizeBytes: fileEntry.size,
|
||||
width: null,
|
||||
height: null,
|
||||
})
|
||||
|
||||
if (previousStorageKey && previousStorageKey !== stored.storageKey) {
|
||||
try {
|
||||
await deleteStoredMediaObject(previousStorageKey)
|
||||
} catch {
|
||||
redirectWithState(mediaAssetId, {
|
||||
notice: "Media file replaced, but old file cleanup failed in storage backend.",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const replacementNotice = stored.fallbackReason
|
||||
? `Media file replaced. ${stored.fallbackReason}`
|
||||
: `Media file replaced via ${stored.provider}.`
|
||||
|
||||
redirectWithState(mediaAssetId, { notice: replacementNotice })
|
||||
} catch {
|
||||
redirectWithState(mediaAssetId, { error: "Failed to replace media file." })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminShell
|
||||
role={role}
|
||||
@@ -254,6 +336,25 @@ export default async function MediaAssetEditorPage({ params, searchParams }: Pag
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border border-neutral-200 p-6">
|
||||
<h3 className="text-lg font-medium">Replace File</h3>
|
||||
<p className="mt-1 text-sm text-neutral-600">
|
||||
Upload a new source file for this media asset while keeping the same metadata and asset
|
||||
ID.
|
||||
</p>
|
||||
<form action={replaceMediaFileAction} className="mt-4 flex flex-wrap items-center gap-3">
|
||||
<input
|
||||
name="file"
|
||||
type="file"
|
||||
required
|
||||
className="rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
<Button type="submit" variant="secondary">
|
||||
Replace media file
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border border-neutral-200 p-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
|
||||
@@ -2,9 +2,11 @@ import {
|
||||
createNavigationItem,
|
||||
createNavigationMenu,
|
||||
deleteNavigationItem,
|
||||
deleteNavigationMenu,
|
||||
listNavigationMenus,
|
||||
listPages,
|
||||
updateNavigationItem,
|
||||
updateNavigationMenu,
|
||||
upsertNavigationItemTranslation,
|
||||
} from "@cms/db"
|
||||
import { Button } from "@cms/ui/button"
|
||||
@@ -131,6 +133,50 @@ async function createItemAction(formData: FormData) {
|
||||
redirectWithState({ notice: "Navigation item created." })
|
||||
}
|
||||
|
||||
async function updateMenuAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
await requirePermissionForRoute({
|
||||
nextPath: "/navigation",
|
||||
permission: "navigation:write",
|
||||
scope: "team",
|
||||
})
|
||||
|
||||
try {
|
||||
await updateNavigationMenu({
|
||||
id: readInputString(formData, "id"),
|
||||
name: readInputString(formData, "name"),
|
||||
slug: readInputString(formData, "slug"),
|
||||
location: readInputString(formData, "location"),
|
||||
isVisible: readInputString(formData, "isVisible") === "true",
|
||||
})
|
||||
} catch {
|
||||
redirectWithState({ error: "Failed to update navigation menu." })
|
||||
}
|
||||
|
||||
revalidatePath("/navigation")
|
||||
redirectWithState({ notice: "Navigation menu updated." })
|
||||
}
|
||||
|
||||
async function deleteMenuAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
await requirePermissionForRoute({
|
||||
nextPath: "/navigation",
|
||||
permission: "navigation:write",
|
||||
scope: "team",
|
||||
})
|
||||
|
||||
try {
|
||||
await deleteNavigationMenu(readInputString(formData, "id"))
|
||||
} catch {
|
||||
redirectWithState({ error: "Failed to delete navigation menu." })
|
||||
}
|
||||
|
||||
revalidatePath("/navigation")
|
||||
redirectWithState({ notice: "Navigation menu deleted." })
|
||||
}
|
||||
|
||||
async function updateItemAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
@@ -279,14 +325,58 @@ export default async function NavigationManagementPage({
|
||||
) : (
|
||||
menus.map((menu) => (
|
||||
<article key={menu.id} className="rounded-xl border border-neutral-200 p-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h3 className="text-lg font-medium">
|
||||
{menu.name} <span className="text-sm text-neutral-500">({menu.location})</span>
|
||||
</h3>
|
||||
<span className="text-xs text-neutral-500">
|
||||
{menu.isVisible ? "visible" : "hidden"}
|
||||
</span>
|
||||
</div>
|
||||
<form action={updateMenuAction} className="rounded border border-neutral-200 p-3">
|
||||
<input type="hidden" name="id" value={menu.id} />
|
||||
<div className="grid gap-3 md:grid-cols-4">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-neutral-600">Menu name</span>
|
||||
<input
|
||||
name="name"
|
||||
defaultValue={menu.name}
|
||||
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">Slug</span>
|
||||
<input
|
||||
name="slug"
|
||||
defaultValue={menu.slug}
|
||||
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">Location</span>
|
||||
<input
|
||||
name="location"
|
||||
defaultValue={menu.location}
|
||||
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">Visible</span>
|
||||
<select
|
||||
name="isVisible"
|
||||
defaultValue={menu.isVisible ? "true" : "false"}
|
||||
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="true">Visible</option>
|
||||
<option value="false">Hidden</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<Button type="submit" size="sm">
|
||||
Save menu
|
||||
</Button>
|
||||
<button
|
||||
type="submit"
|
||||
formAction={deleteMenuAction}
|
||||
className="rounded-md border border-red-300 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
Delete menu
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="mt-4 space-y-3">
|
||||
{menu.items.length === 0 ? (
|
||||
@@ -348,11 +438,20 @@ export default async function NavigationManagementPage({
|
||||
</label>
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-neutral-600">Parent id</span>
|
||||
<input
|
||||
<select
|
||||
name="parentId"
|
||||
defaultValue={item.parentId ?? ""}
|
||||
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
>
|
||||
<option value="">(none)</option>
|
||||
{menu.items
|
||||
.filter((entry) => entry.id !== item.id)
|
||||
.map((entry) => (
|
||||
<option key={`${item.id}-parent-${entry.id}`} value={entry.id}>
|
||||
{entry.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -42,6 +42,31 @@ function readNullableString(formData: FormData, field: string): string | null {
|
||||
return value.length > 0 ? value : null
|
||||
}
|
||||
|
||||
function readNullableDate(formData: FormData, field: string): Date | null {
|
||||
const value = readInputString(formData, field)
|
||||
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = new Date(value)
|
||||
return Number.isNaN(parsed.getTime()) ? null : parsed
|
||||
}
|
||||
|
||||
function formatDateTimeLocalInput(value: Date | null): string {
|
||||
if (!value) {
|
||||
return ""
|
||||
}
|
||||
|
||||
const year = value.getFullYear()
|
||||
const month = String(value.getMonth() + 1).padStart(2, "0")
|
||||
const day = String(value.getDate()).padStart(2, "0")
|
||||
const hour = String(value.getHours()).padStart(2, "0")
|
||||
const minute = String(value.getMinutes()).padStart(2, "0")
|
||||
|
||||
return `${year}-${month}-${day}T${hour}:${minute}`
|
||||
}
|
||||
|
||||
function redirectWithState(pageId: string, params: { notice?: string; error?: string }) {
|
||||
const query = new URLSearchParams()
|
||||
|
||||
@@ -109,6 +134,7 @@ export default async function PageEditorPage({ params, searchParams }: PageProps
|
||||
content: readInputString(formData, "content"),
|
||||
seoTitle: readNullableString(formData, "seoTitle"),
|
||||
seoDescription: readNullableString(formData, "seoDescription"),
|
||||
scheduledPublishAt: readNullableDate(formData, "scheduledPublishAt"),
|
||||
})
|
||||
} catch {
|
||||
redirectWithState(pageId, {
|
||||
@@ -224,6 +250,16 @@ export default async function PageEditorPage({ params, searchParams }: PageProps
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-neutral-600">Scheduled publish (optional)</span>
|
||||
<input
|
||||
name="scheduledPublishAt"
|
||||
type="datetime-local"
|
||||
defaultValue={formatDateTimeLocalInput(page.scheduledPublishAt)}
|
||||
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">Slug</span>
|
||||
<input
|
||||
|
||||
@@ -29,6 +29,17 @@ function readNullableString(formData: FormData, field: string): string | null {
|
||||
return value.length > 0 ? value : null
|
||||
}
|
||||
|
||||
function readNullableDate(formData: FormData, field: string): Date | null {
|
||||
const value = readInputString(formData, field)
|
||||
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = new Date(value)
|
||||
return Number.isNaN(parsed.getTime()) ? null : parsed
|
||||
}
|
||||
|
||||
function redirectWithState(params: { notice?: string; error?: string }) {
|
||||
const query = new URLSearchParams()
|
||||
|
||||
@@ -62,6 +73,7 @@ async function createPageAction(formData: FormData) {
|
||||
content: readInputString(formData, "content"),
|
||||
seoTitle: readNullableString(formData, "seoTitle"),
|
||||
seoDescription: readNullableString(formData, "seoDescription"),
|
||||
scheduledPublishAt: readNullableDate(formData, "scheduledPublishAt"),
|
||||
})
|
||||
} catch {
|
||||
redirectWithState({
|
||||
@@ -122,6 +134,7 @@ export default async function PagesManagementPage({
|
||||
<th className="py-2 pr-4">Title</th>
|
||||
<th className="py-2 pr-4">Slug</th>
|
||||
<th className="py-2 pr-4">Status</th>
|
||||
<th className="py-2 pr-4">Scheduled</th>
|
||||
<th className="py-2 pr-4">Updated</th>
|
||||
<th className="py-2 pr-4">Action</th>
|
||||
</tr>
|
||||
@@ -129,7 +142,7 @@ export default async function PagesManagementPage({
|
||||
<tbody>
|
||||
{pages.length === 0 ? (
|
||||
<tr>
|
||||
<td className="py-3 text-neutral-500" colSpan={5}>
|
||||
<td className="py-3 text-neutral-500" colSpan={6}>
|
||||
No pages yet.
|
||||
</td>
|
||||
</tr>
|
||||
@@ -139,6 +152,11 @@ export default async function PagesManagementPage({
|
||||
<td className="py-3 pr-4">{page.title}</td>
|
||||
<td className="py-3 pr-4 text-neutral-600">/{page.slug}</td>
|
||||
<td className="py-3 pr-4">{page.status}</td>
|
||||
<td className="py-3 pr-4 text-neutral-600">
|
||||
{page.scheduledPublishAt
|
||||
? page.scheduledPublishAt.toLocaleString("en-US")
|
||||
: "-"}
|
||||
</td>
|
||||
<td className="py-3 pr-4 text-neutral-600">
|
||||
{page.updatedAt.toLocaleDateString("en-US")}
|
||||
</td>
|
||||
|
||||
@@ -1,34 +1,425 @@
|
||||
import { AdminSectionPlaceholder } from "@/components/admin-section-placeholder"
|
||||
import { hasPermission, normalizeRole, type Role } from "@cms/content/rbac"
|
||||
import { db } from "@cms/db"
|
||||
import { Button } from "@cms/ui/button"
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { headers } from "next/headers"
|
||||
import { redirect } from "next/navigation"
|
||||
|
||||
import { AdminShell } from "@/components/admin-shell"
|
||||
import {
|
||||
auth,
|
||||
canDeleteUserAccount,
|
||||
createManagedUserAccount,
|
||||
enforceOwnerInvariant,
|
||||
} from "@/lib/auth/server"
|
||||
import { requirePermissionForRoute } from "@/lib/route-guards"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
export default async function UsersManagementPage() {
|
||||
const MANAGED_ROLES: Role[] = ["admin", "editor", "manager"]
|
||||
|
||||
type SearchParamsInput = Record<string, string | string[] | undefined>
|
||||
|
||||
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 redirectWithState(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 value = query.toString()
|
||||
redirect(value ? `/users?${value}` : "/users")
|
||||
}
|
||||
|
||||
async function createUserAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
await requirePermissionForRoute({
|
||||
nextPath: "/users",
|
||||
permission: "users:write",
|
||||
scope: "team",
|
||||
})
|
||||
|
||||
const role = normalizeRole(readInputString(formData, "role"))
|
||||
|
||||
if (!role || !MANAGED_ROLES.includes(role)) {
|
||||
return redirectWithState({ error: "Invalid role for managed user creation." })
|
||||
}
|
||||
|
||||
try {
|
||||
await createManagedUserAccount({
|
||||
email: readInputString(formData, "email"),
|
||||
username: readInputString(formData, "username") || undefined,
|
||||
name: readInputString(formData, "name"),
|
||||
password: readInputString(formData, "password"),
|
||||
role,
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to create user."
|
||||
redirectWithState({ error: message })
|
||||
}
|
||||
|
||||
revalidatePath("/users")
|
||||
redirectWithState({ notice: "User account created." })
|
||||
}
|
||||
|
||||
async function updateUserRoleAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
await requirePermissionForRoute({
|
||||
nextPath: "/users",
|
||||
permission: "users:manage_roles",
|
||||
scope: "global",
|
||||
})
|
||||
|
||||
const userId = readInputString(formData, "userId")
|
||||
const role = normalizeRole(readInputString(formData, "role"))
|
||||
|
||||
if (!role || !MANAGED_ROLES.includes(role)) {
|
||||
return redirectWithState({ error: "Only admin/editor/manager can be assigned here." })
|
||||
}
|
||||
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { id: true, isProtected: true, isSystem: true },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return redirectWithState({ error: "User not found." })
|
||||
}
|
||||
|
||||
if (user.isProtected || user.isSystem) {
|
||||
return redirectWithState({ error: "Protected/system users cannot be role-edited." })
|
||||
}
|
||||
|
||||
try {
|
||||
await db.user.update({
|
||||
where: { id: userId },
|
||||
data: { role },
|
||||
})
|
||||
await enforceOwnerInvariant()
|
||||
} catch {
|
||||
redirectWithState({ error: "Failed to update user role." })
|
||||
}
|
||||
|
||||
revalidatePath("/users")
|
||||
redirectWithState({ notice: "User role updated." })
|
||||
}
|
||||
|
||||
async function updateUserBanAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
await requirePermissionForRoute({
|
||||
nextPath: "/users",
|
||||
permission: "users:write",
|
||||
scope: "team",
|
||||
})
|
||||
|
||||
const userId = readInputString(formData, "userId")
|
||||
const isBanned = readInputString(formData, "isBanned") === "true"
|
||||
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { id: true, isProtected: true, isSystem: true },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return redirectWithState({ error: "User not found." })
|
||||
}
|
||||
|
||||
if ((user.isProtected || user.isSystem) && isBanned) {
|
||||
return redirectWithState({ error: "Protected/system users cannot be banned." })
|
||||
}
|
||||
|
||||
try {
|
||||
await db.user.update({
|
||||
where: { id: userId },
|
||||
data: { isBanned },
|
||||
})
|
||||
await enforceOwnerInvariant()
|
||||
} catch {
|
||||
redirectWithState({ error: "Failed to update user status." })
|
||||
}
|
||||
|
||||
revalidatePath("/users")
|
||||
redirectWithState({ notice: isBanned ? "User banned." : "User unbanned." })
|
||||
}
|
||||
|
||||
async function deleteUserAction(formData: FormData) {
|
||||
"use server"
|
||||
|
||||
await requirePermissionForRoute({
|
||||
nextPath: "/users",
|
||||
permission: "users:write",
|
||||
scope: "team",
|
||||
})
|
||||
|
||||
const userId = readInputString(formData, "userId")
|
||||
const isAllowed = await canDeleteUserAccount(userId)
|
||||
|
||||
if (!isAllowed) {
|
||||
return redirectWithState({
|
||||
error: "User cannot be deleted due to protection or owner constraints.",
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
await db.user.delete({
|
||||
where: { id: userId },
|
||||
})
|
||||
await enforceOwnerInvariant()
|
||||
} catch {
|
||||
redirectWithState({ error: "Failed to delete user." })
|
||||
}
|
||||
|
||||
revalidatePath("/users")
|
||||
redirectWithState({ notice: "User deleted." })
|
||||
}
|
||||
|
||||
export default async function UsersManagementPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<SearchParamsInput>
|
||||
}) {
|
||||
const role = await requirePermissionForRoute({
|
||||
nextPath: "/users",
|
||||
permission: "users:read",
|
||||
scope: "own",
|
||||
})
|
||||
|
||||
const session = await auth.api
|
||||
.getSession({
|
||||
headers: await headers(),
|
||||
})
|
||||
.catch(() => null)
|
||||
const viewerId = session?.user?.id ?? null
|
||||
const canWriteUsers = hasPermission(role, "users:write", "team")
|
||||
const canManageRoles = hasPermission(role, "users:manage_roles", "global")
|
||||
const canReadGlobal = hasPermission(role, "users:read", "global")
|
||||
|
||||
const [resolvedSearchParams, users] = await Promise.all([
|
||||
searchParams,
|
||||
db.user.findMany({
|
||||
where: canReadGlobal
|
||||
? undefined
|
||||
: viewerId
|
||||
? {
|
||||
id: viewerId,
|
||||
}
|
||||
: {
|
||||
id: "__none__",
|
||||
},
|
||||
orderBy: [{ createdAt: "desc" }],
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
name: true,
|
||||
role: true,
|
||||
isBanned: true,
|
||||
isSystem: true,
|
||||
isHidden: true,
|
||||
isProtected: true,
|
||||
createdAt: true,
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
const notice = readFirstValue(resolvedSearchParams.notice)
|
||||
const error = readFirstValue(resolvedSearchParams.error)
|
||||
|
||||
return (
|
||||
<AdminShell
|
||||
role={role}
|
||||
activePath="/users"
|
||||
badge="Admin App"
|
||||
title="Users"
|
||||
description="Prepare user lifecycle and role management operations."
|
||||
description="Manage internal users, roles, and account status."
|
||||
>
|
||||
<AdminSectionPlaceholder
|
||||
feature="Users Management"
|
||||
summary="This route sets the guardrail and UX entrypoint for role assignment, status, and invitation flows."
|
||||
requiredPermission="users:read (own)"
|
||||
nextSteps={[
|
||||
"Add user list, filter, and detail views.",
|
||||
"Add role and permission editing actions with owner/support safety rules.",
|
||||
"Add disable/ban and invite workflows.",
|
||||
]}
|
||||
/>
|
||||
{notice ? (
|
||||
<section className="rounded-xl border border-emerald-300 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
|
||||
{notice}
|
||||
</section>
|
||||
) : null}
|
||||
{error ? (
|
||||
<section className="rounded-xl border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-800">
|
||||
{error}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{canWriteUsers ? (
|
||||
<section className="rounded-xl border border-neutral-200 p-6">
|
||||
<h2 className="text-xl font-medium">Create managed user</h2>
|
||||
<form action={createUserAction} className="mt-4 grid gap-3 md:grid-cols-2 lg:grid-cols-3">
|
||||
<input
|
||||
name="name"
|
||||
required
|
||||
placeholder="Name"
|
||||
className="rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
<input
|
||||
name="email"
|
||||
required
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
className="rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
<input
|
||||
name="username"
|
||||
placeholder="Username (optional)"
|
||||
className="rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
<input
|
||||
name="password"
|
||||
required
|
||||
type="password"
|
||||
placeholder="Temporary password"
|
||||
className="rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
<select
|
||||
name="role"
|
||||
defaultValue="editor"
|
||||
className="rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="editor">editor</option>
|
||||
<option value="manager">manager</option>
|
||||
<option value="admin">admin</option>
|
||||
</select>
|
||||
<div className="md:col-span-2 lg:col-span-3">
|
||||
<Button type="submit">Create user</Button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<section className="rounded-xl border border-neutral-200 p-6">
|
||||
<h2 className="text-xl font-medium">User accounts</h2>
|
||||
<div className="mt-4 overflow-x-auto">
|
||||
<table className="min-w-full text-left text-sm">
|
||||
<thead className="text-xs uppercase tracking-wide text-neutral-500">
|
||||
<tr>
|
||||
<th className="py-2 pr-4">User</th>
|
||||
<th className="py-2 pr-4">Role</th>
|
||||
<th className="py-2 pr-4">Status</th>
|
||||
<th className="py-2 pr-4">Flags</th>
|
||||
<th className="py-2 pr-4">Created</th>
|
||||
<th className="py-2 pr-4">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.length === 0 ? (
|
||||
<tr>
|
||||
<td className="py-3 text-neutral-500" colSpan={6}>
|
||||
No users found.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
users.map((user) => (
|
||||
<tr key={user.id} className="border-t border-neutral-200 align-top">
|
||||
<td className="py-3 pr-4">
|
||||
<p className="font-medium">{user.name}</p>
|
||||
<p className="text-xs text-neutral-600">{user.email}</p>
|
||||
<p className="text-xs text-neutral-500">@{user.username ?? "no-username"}</p>
|
||||
</td>
|
||||
<td className="py-3 pr-4">{user.role}</td>
|
||||
<td className="py-3 pr-4">{user.isBanned ? "banned" : "active"}</td>
|
||||
<td className="py-3 pr-4 text-xs text-neutral-600">
|
||||
{user.isProtected ? "protected " : ""}
|
||||
{user.isSystem ? "system " : ""}
|
||||
{user.isHidden ? "hidden" : ""}
|
||||
</td>
|
||||
<td className="py-3 pr-4 text-xs text-neutral-600">
|
||||
{user.createdAt.toLocaleString("en-US")}
|
||||
</td>
|
||||
<td className="py-3 pr-4">
|
||||
<div className="grid min-w-56 gap-2">
|
||||
{canManageRoles ? (
|
||||
<form action={updateUserRoleAction} className="flex gap-2">
|
||||
<input type="hidden" name="userId" value={user.id} />
|
||||
<select
|
||||
name="role"
|
||||
defaultValue={
|
||||
MANAGED_ROLES.includes(user.role as Role) ? user.role : "editor"
|
||||
}
|
||||
disabled={user.isProtected || user.isSystem}
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1 text-xs"
|
||||
>
|
||||
<option value="editor">editor</option>
|
||||
<option value="manager">manager</option>
|
||||
<option value="admin">admin</option>
|
||||
</select>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
disabled={user.isProtected || user.isSystem}
|
||||
>
|
||||
Role
|
||||
</Button>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{canWriteUsers ? (
|
||||
<form action={updateUserBanAction} className="flex gap-2">
|
||||
<input type="hidden" name="userId" value={user.id} />
|
||||
<select
|
||||
name="isBanned"
|
||||
defaultValue={user.isBanned ? "true" : "false"}
|
||||
disabled={user.isProtected || user.isSystem}
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1 text-xs"
|
||||
>
|
||||
<option value="false">active</option>
|
||||
<option value="true">banned</option>
|
||||
</select>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
disabled={user.isProtected || user.isSystem}
|
||||
>
|
||||
Status
|
||||
</Button>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{canWriteUsers ? (
|
||||
<form action={deleteUserAction}>
|
||||
<input type="hidden" name="userId" value={user.id} />
|
||||
<button
|
||||
type="submit"
|
||||
disabled={user.isProtected || user.isSystem}
|
||||
className="rounded border border-red-300 px-3 py-1.5 text-xs text-red-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Delete user
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</AdminShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -77,6 +77,15 @@ export function CreatePageForm({ action }: CreatePageFormProps) {
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-neutral-600">Scheduled publish (optional)</span>
|
||||
<input
|
||||
name="scheduledPublishAt"
|
||||
type="datetime-local"
|
||||
className="w-full rounded border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<Button type="submit">Create page</Button>
|
||||
</form>
|
||||
)
|
||||
|
||||
@@ -43,6 +43,25 @@ function updateBlock(blocks: PageBlocks, blockId: string, next: Partial<PageBloc
|
||||
)
|
||||
}
|
||||
|
||||
function moveBlock(blocks: PageBlocks, blockId: string, direction: "up" | "down"): PageBlocks {
|
||||
const index = blocks.findIndex((entry) => entry.id === blockId)
|
||||
|
||||
if (index < 0) {
|
||||
return blocks
|
||||
}
|
||||
|
||||
const nextIndex = direction === "up" ? index - 1 : index + 1
|
||||
if (nextIndex < 0 || nextIndex >= blocks.length) {
|
||||
return blocks
|
||||
}
|
||||
|
||||
const next = [...blocks]
|
||||
const current = next[index]
|
||||
next[index] = next[nextIndex]
|
||||
next[nextIndex] = current
|
||||
return next
|
||||
}
|
||||
|
||||
export function PageBlockEditor({
|
||||
name,
|
||||
initialContent,
|
||||
@@ -156,13 +175,29 @@ export function PageBlockEditor({
|
||||
<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 className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-2 py-1"
|
||||
onClick={() => setBlocks((prev) => moveBlock(prev, block.id, "up"))}
|
||||
>
|
||||
Up
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-2 py-1"
|
||||
onClick={() => setBlocks((prev) => moveBlock(prev, block.id, "down"))}
|
||||
>
|
||||
Down
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-2 py-1"
|
||||
onClick={() => setBlocks((prev) => prev.filter((entry) => entry.id !== block.id))}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{block.type === "hero" ? (
|
||||
@@ -187,6 +222,26 @@ export function PageBlockEditor({
|
||||
placeholder="Subheading"
|
||||
className="rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
/>
|
||||
<input
|
||||
value={block.ctaLabel ?? ""}
|
||||
onChange={(event) =>
|
||||
setBlocks((prev) =>
|
||||
updateBlock(prev, block.id, { ctaLabel: event.target.value || null }),
|
||||
)
|
||||
}
|
||||
placeholder="CTA label"
|
||||
className="rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
/>
|
||||
<input
|
||||
value={block.ctaHref ?? ""}
|
||||
onChange={(event) =>
|
||||
setBlocks((prev) =>
|
||||
updateBlock(prev, block.id, { ctaHref: event.target.value || null }),
|
||||
)
|
||||
}
|
||||
placeholder="CTA href"
|
||||
className="rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -203,22 +258,34 @@ export function PageBlockEditor({
|
||||
) : 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"
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
value={block.title ?? ""}
|
||||
onChange={(event) =>
|
||||
setBlocks((prev) =>
|
||||
updateBlock(prev, block.id, { title: event.target.value || null }),
|
||||
)
|
||||
}
|
||||
placeholder="Gallery title"
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
/>
|
||||
<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"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{block.type === "cta" ? (
|
||||
@@ -239,50 +306,101 @@ export function PageBlockEditor({
|
||||
placeholder="Link href"
|
||||
className="rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
/>
|
||||
<select
|
||||
value={block.variant}
|
||||
onChange={(event) =>
|
||||
setBlocks((prev) =>
|
||||
updateBlock(prev, block.id, {
|
||||
variant: event.target.value as "primary" | "secondary",
|
||||
}),
|
||||
)
|
||||
}
|
||||
className="rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
>
|
||||
<option value="primary">Primary</option>
|
||||
<option value="secondary">Secondary</option>
|
||||
</select>
|
||||
</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"
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<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"
|
||||
/>
|
||||
<input
|
||||
value={block.title ?? ""}
|
||||
onChange={(event) =>
|
||||
setBlocks((prev) =>
|
||||
updateBlock(prev, block.id, { title: event.target.value || null }),
|
||||
)
|
||||
}
|
||||
placeholder="Form title"
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
/>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={block.description ?? ""}
|
||||
onChange={(event) =>
|
||||
setBlocks((prev) =>
|
||||
updateBlock(prev, block.id, { description: event.target.value || null }),
|
||||
)
|
||||
}
|
||||
placeholder="Form description"
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
/>
|
||||
</div>
|
||||
) : 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"
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
value={block.title ?? ""}
|
||||
onChange={(event) =>
|
||||
setBlocks((prev) =>
|
||||
updateBlock(prev, block.id, { title: event.target.value || null }),
|
||||
)
|
||||
}
|
||||
placeholder="Price card section title"
|
||||
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
|
||||
/>
|
||||
<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"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
))}
|
||||
|
||||
@@ -375,6 +375,63 @@ export async function ensureSupportUserBootstrap(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
const MANAGED_USER_ROLE_ALLOWLIST = new Set<Role>(["admin", "editor", "manager"])
|
||||
|
||||
export async function createManagedUserAccount(input: {
|
||||
email: string
|
||||
username?: string | null
|
||||
name: string
|
||||
password: string
|
||||
role: string
|
||||
}): Promise<{ id: string; email: string; username: string | null; role: string }> {
|
||||
const normalizedEmail = input.email.trim().toLowerCase()
|
||||
const normalizedRole = normalizeRole(input.role)
|
||||
|
||||
if (!normalizedRole || !MANAGED_USER_ROLE_ALLOWLIST.has(normalizedRole)) {
|
||||
throw new Error("Unsupported role for managed user account")
|
||||
}
|
||||
|
||||
const existing = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true, isProtected: true, isSystem: true },
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
if (existing.isProtected || existing.isSystem) {
|
||||
throw new Error("Cannot mutate protected/system account via managed user provisioning")
|
||||
}
|
||||
|
||||
throw new Error("A user with this email already exists")
|
||||
}
|
||||
|
||||
const preferredUsername =
|
||||
normalizeUsernameCandidate(input.username) ??
|
||||
normalizeUsernameCandidate(extractEmailLocalPart(normalizedEmail)) ??
|
||||
"user"
|
||||
|
||||
await ensureCredentialUser({
|
||||
email: normalizedEmail,
|
||||
username: preferredUsername,
|
||||
name: input.name.trim(),
|
||||
password: input.password,
|
||||
role: normalizedRole,
|
||||
isHidden: false,
|
||||
isSystem: false,
|
||||
isProtected: false,
|
||||
})
|
||||
|
||||
const created = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true, email: true, username: true, role: true },
|
||||
})
|
||||
|
||||
if (!created) {
|
||||
throw new Error("Managed user provisioning failed")
|
||||
}
|
||||
|
||||
return created
|
||||
}
|
||||
|
||||
const DEFAULT_E2E_ADMIN_EMAIL = "e2e-admin@cms.local"
|
||||
const DEFAULT_E2E_ADMIN_USERNAME = "e2e-admin"
|
||||
const DEFAULT_E2E_ADMIN_PASSWORD = "e2e-admin-password"
|
||||
|
||||
@@ -52,7 +52,7 @@ export default async function LocaleLayout({ children, params }: LocaleLayoutPro
|
||||
<NextIntlClientProvider locale={locale}>
|
||||
<Providers>
|
||||
<PublicHeaderBanner banner={banner} />
|
||||
<PublicAnnouncements placement="global_top" />
|
||||
<PublicAnnouncements placement="global_top" locale={locale} />
|
||||
<PublicSiteHeader />
|
||||
<main>{children}</main>
|
||||
<PublicSiteFooter />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getPublishedPageBySlugForLocale, listPosts } from "@cms/db"
|
||||
import { getPublishedPageBySlugForLocale, listPostsForLocale } from "@cms/db"
|
||||
import { getTranslations } from "next-intl/server"
|
||||
import { PublicAnnouncements } from "@/components/public-announcements"
|
||||
import { PublicPageView } from "@/components/public-page-view"
|
||||
@@ -15,14 +15,14 @@ export default async function HomePage({ params }: HomePageProps) {
|
||||
|
||||
const [homePage, posts, t] = await Promise.all([
|
||||
getPublishedPageBySlugForLocale("home", locale),
|
||||
listPosts(),
|
||||
listPostsForLocale(locale),
|
||||
getTranslations("Home"),
|
||||
])
|
||||
|
||||
return (
|
||||
<section>
|
||||
{homePage ? <PublicPageView page={homePage} /> : null}
|
||||
<PublicAnnouncements placement="homepage" />
|
||||
<PublicAnnouncements placement="homepage" locale={locale} />
|
||||
|
||||
<section className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 py-6 pb-16">
|
||||
<header className="space-y-3">
|
||||
|
||||
@@ -44,6 +44,33 @@ function resolveGroupFilter(searchParams: SearchParamsInput) {
|
||||
return null
|
||||
}
|
||||
|
||||
function resolveSort(searchParams: SearchParamsInput): "latest" | "title_asc" | "title_desc" {
|
||||
const sort = readFirstValue(searchParams.sort)
|
||||
|
||||
if (sort === "title_asc" || sort === "title_desc") {
|
||||
return sort
|
||||
}
|
||||
|
||||
return "latest"
|
||||
}
|
||||
|
||||
function buildPortfolioQuery(
|
||||
filter: ReturnType<typeof resolveGroupFilter>,
|
||||
sort: ReturnType<typeof resolveSort>,
|
||||
) {
|
||||
const query: Record<string, string> = {}
|
||||
|
||||
if (filter) {
|
||||
query[filter.groupType] = filter.groupSlug
|
||||
}
|
||||
|
||||
if (sort !== "latest") {
|
||||
query.sort = sort
|
||||
}
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
function findPreviewAsset(
|
||||
renditions: Array<{
|
||||
slot: string
|
||||
@@ -67,6 +94,7 @@ function findPreviewAsset(
|
||||
export default async function PortfolioPage({ searchParams }: PortfolioPageProps) {
|
||||
const [resolvedSearchParams, t] = await Promise.all([searchParams, getTranslations("Portfolio")])
|
||||
const activeFilter = resolveGroupFilter(resolvedSearchParams)
|
||||
const activeSort = resolveSort(resolvedSearchParams)
|
||||
|
||||
const [groups, artworks] = await Promise.all([
|
||||
listPublishedPortfolioGroups(),
|
||||
@@ -75,8 +103,11 @@ export default async function PortfolioPage({ searchParams }: PortfolioPageProps
|
||||
? {
|
||||
groupType: activeFilter.groupType,
|
||||
groupSlug: activeFilter.groupSlug,
|
||||
sort: activeSort,
|
||||
}
|
||||
: undefined,
|
||||
: {
|
||||
sort: activeSort,
|
||||
},
|
||||
),
|
||||
])
|
||||
|
||||
@@ -91,7 +122,10 @@ export default async function PortfolioPage({ searchParams }: PortfolioPageProps
|
||||
<section className="rounded-xl border border-neutral-200 p-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Link
|
||||
href="/portfolio"
|
||||
href={{
|
||||
pathname: "/portfolio",
|
||||
query: activeSort === "latest" ? undefined : { sort: activeSort },
|
||||
}}
|
||||
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100"
|
||||
>
|
||||
{t("filters.clear")}
|
||||
@@ -100,7 +134,16 @@ export default async function PortfolioPage({ searchParams }: PortfolioPageProps
|
||||
{groups.galleries.map((group) => (
|
||||
<Link
|
||||
key={`gallery-${group.id}`}
|
||||
href={{ pathname: "/portfolio", query: { gallery: group.slug } }}
|
||||
href={{
|
||||
pathname: "/portfolio",
|
||||
query: {
|
||||
...buildPortfolioQuery(activeFilter, activeSort),
|
||||
gallery: group.slug,
|
||||
album: undefined,
|
||||
category: undefined,
|
||||
tag: undefined,
|
||||
},
|
||||
}}
|
||||
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}
|
||||
@@ -110,7 +153,16 @@ export default async function PortfolioPage({ searchParams }: PortfolioPageProps
|
||||
{groups.albums.map((group) => (
|
||||
<Link
|
||||
key={`album-${group.id}`}
|
||||
href={{ pathname: "/portfolio", query: { album: group.slug } }}
|
||||
href={{
|
||||
pathname: "/portfolio",
|
||||
query: {
|
||||
...buildPortfolioQuery(activeFilter, activeSort),
|
||||
gallery: undefined,
|
||||
album: group.slug,
|
||||
category: undefined,
|
||||
tag: undefined,
|
||||
},
|
||||
}}
|
||||
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}
|
||||
@@ -120,12 +172,73 @@ export default async function PortfolioPage({ searchParams }: PortfolioPageProps
|
||||
{groups.categories.map((group) => (
|
||||
<Link
|
||||
key={`category-${group.id}`}
|
||||
href={{ pathname: "/portfolio", query: { category: group.slug } }}
|
||||
href={{
|
||||
pathname: "/portfolio",
|
||||
query: {
|
||||
...buildPortfolioQuery(activeFilter, activeSort),
|
||||
gallery: undefined,
|
||||
album: undefined,
|
||||
category: group.slug,
|
||||
tag: undefined,
|
||||
},
|
||||
}}
|
||||
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>
|
||||
))}
|
||||
|
||||
{groups.tags.map((group) => (
|
||||
<Link
|
||||
key={`tag-${group.id}`}
|
||||
href={{
|
||||
pathname: "/portfolio",
|
||||
query: {
|
||||
...buildPortfolioQuery(activeFilter, activeSort),
|
||||
gallery: undefined,
|
||||
album: undefined,
|
||||
category: undefined,
|
||||
tag: 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.tag")}: {group.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<span className="text-xs uppercase tracking-wide text-neutral-500">
|
||||
{t("sort.label")}:
|
||||
</span>
|
||||
<Link
|
||||
href={{
|
||||
pathname: "/portfolio",
|
||||
query: buildPortfolioQuery(activeFilter, "latest"),
|
||||
}}
|
||||
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100"
|
||||
>
|
||||
{t("sort.latest")}
|
||||
</Link>
|
||||
<Link
|
||||
href={{
|
||||
pathname: "/portfolio",
|
||||
query: buildPortfolioQuery(activeFilter, "title_asc"),
|
||||
}}
|
||||
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100"
|
||||
>
|
||||
{t("sort.titleAsc")}
|
||||
</Link>
|
||||
<Link
|
||||
href={{
|
||||
pathname: "/portfolio",
|
||||
query: buildPortfolioQuery(activeFilter, "title_desc"),
|
||||
}}
|
||||
className="rounded-md border border-neutral-300 px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100"
|
||||
>
|
||||
{t("sort.titleDesc")}
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import Link from "next/link"
|
||||
|
||||
type PublicAnnouncementsProps = {
|
||||
placement: "global_top" | "homepage"
|
||||
locale?: string
|
||||
}
|
||||
|
||||
function AnnouncementCard({ announcement }: { announcement: PublicAnnouncement }) {
|
||||
@@ -22,8 +23,8 @@ function AnnouncementCard({ announcement }: { announcement: PublicAnnouncement }
|
||||
)
|
||||
}
|
||||
|
||||
export async function PublicAnnouncements({ placement }: PublicAnnouncementsProps) {
|
||||
const announcements = await listActiveAnnouncements(placement)
|
||||
export async function PublicAnnouncements({ placement, locale }: PublicAnnouncementsProps) {
|
||||
const announcements = await listActiveAnnouncements(placement, new Date(), locale)
|
||||
|
||||
if (announcements.length === 0) {
|
||||
return null
|
||||
|
||||
@@ -12,6 +12,16 @@ type PublicPageViewProps = {
|
||||
page: PageEntity
|
||||
}
|
||||
|
||||
function resolveFormLink(formKey: string): { href: string; label: string } {
|
||||
const normalized = formKey.trim().toLowerCase()
|
||||
|
||||
if (normalized === "commission" || normalized === "commissions") {
|
||||
return { href: "/commissions", label: "Open commission form" }
|
||||
}
|
||||
|
||||
return { href: `/#form-${normalized || "contact"}`, label: "Open contact form" }
|
||||
}
|
||||
|
||||
export function PublicPageView({ page }: PublicPageViewProps) {
|
||||
const blocks = (() => {
|
||||
try {
|
||||
@@ -106,6 +116,7 @@ export function PublicPageView({ page }: PublicPageViewProps) {
|
||||
}
|
||||
|
||||
if (block.type === "form") {
|
||||
const formLink = resolveFormLink(block.formKey)
|
||||
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>
|
||||
@@ -113,6 +124,12 @@ export function PublicPageView({ page }: PublicPageViewProps) {
|
||||
{block.description || "Form integration pending."}
|
||||
</p>
|
||||
<p className="text-xs text-neutral-500">formKey: {block.formKey}</p>
|
||||
<a
|
||||
href={formLink.href}
|
||||
className="inline-flex rounded border border-neutral-300 px-3 py-1.5 text-sm"
|
||||
>
|
||||
{formLink.label}
|
||||
</a>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -77,7 +77,14 @@
|
||||
"clear": "Filter zurücksetzen",
|
||||
"gallery": "Galerie",
|
||||
"album": "Album",
|
||||
"category": "Kategorie"
|
||||
"category": "Kategorie",
|
||||
"tag": "Tag"
|
||||
},
|
||||
"sort": {
|
||||
"label": "Sortierung",
|
||||
"latest": "Neueste",
|
||||
"titleAsc": "Titel A-Z",
|
||||
"titleDesc": "Titel Z-A"
|
||||
},
|
||||
"fields": {
|
||||
"medium": "Medium",
|
||||
|
||||
@@ -77,7 +77,14 @@
|
||||
"clear": "Clear filters",
|
||||
"gallery": "Gallery",
|
||||
"album": "Album",
|
||||
"category": "Category"
|
||||
"category": "Category",
|
||||
"tag": "Tag"
|
||||
},
|
||||
"sort": {
|
||||
"label": "Sort",
|
||||
"latest": "Latest",
|
||||
"titleAsc": "Title A-Z",
|
||||
"titleDesc": "Title Z-A"
|
||||
},
|
||||
"fields": {
|
||||
"medium": "Medium",
|
||||
|
||||
@@ -77,7 +77,14 @@
|
||||
"clear": "Limpiar filtros",
|
||||
"gallery": "Galería",
|
||||
"album": "Álbum",
|
||||
"category": "Categoría"
|
||||
"category": "Categoría",
|
||||
"tag": "Etiqueta"
|
||||
},
|
||||
"sort": {
|
||||
"label": "Orden",
|
||||
"latest": "Más recientes",
|
||||
"titleAsc": "Título A-Z",
|
||||
"titleDesc": "Título Z-A"
|
||||
},
|
||||
"fields": {
|
||||
"medium": "Técnica",
|
||||
|
||||
@@ -77,7 +77,14 @@
|
||||
"clear": "Réinitialiser les filtres",
|
||||
"gallery": "Galerie",
|
||||
"album": "Album",
|
||||
"category": "Catégorie"
|
||||
"category": "Catégorie",
|
||||
"tag": "Tag"
|
||||
},
|
||||
"sort": {
|
||||
"label": "Tri",
|
||||
"latest": "Plus récents",
|
||||
"titleAsc": "Titre A-Z",
|
||||
"titleDesc": "Titre Z-A"
|
||||
},
|
||||
"fields": {
|
||||
"medium": "Médium",
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const announcementPlacementSchema = z.enum(["global_top", "homepage"])
|
||||
export const announcementLocaleSchema = z.enum(["de", "en", "es", "fr"])
|
||||
|
||||
export const createAnnouncementInputSchema = z.object({
|
||||
title: z.string().min(1).max(180),
|
||||
message: z.string().min(1).max(500),
|
||||
placement: announcementPlacementSchema.default("global_top"),
|
||||
targetLocales: z.array(announcementLocaleSchema).default([]),
|
||||
priority: z.number().int().min(0).default(100),
|
||||
ctaLabel: z.string().max(120).nullable().optional(),
|
||||
ctaHref: z.string().max(500).nullable().optional(),
|
||||
@@ -19,6 +21,7 @@ export const updateAnnouncementInputSchema = z.object({
|
||||
title: z.string().min(1).max(180).optional(),
|
||||
message: z.string().min(1).max(500).optional(),
|
||||
placement: announcementPlacementSchema.optional(),
|
||||
targetLocales: z.array(announcementLocaleSchema).optional(),
|
||||
priority: z.number().int().min(0).optional(),
|
||||
ctaLabel: z.string().max(120).nullable().optional(),
|
||||
ctaHref: z.string().max(500).nullable().optional(),
|
||||
|
||||
@@ -23,7 +23,21 @@ export const createCommissionInputSchema = z.object({
|
||||
description: z.string().max(4000).nullable().optional(),
|
||||
status: commissionStatusSchema.default("new"),
|
||||
customerId: z.string().uuid().nullable().optional(),
|
||||
assignedUserId: z.string().max(120).nullable().optional(),
|
||||
assignedUserId: z.string().uuid().nullable().optional(),
|
||||
linkedArtworkIds: z.array(z.string().uuid()).default([]),
|
||||
budgetMin: z.number().nonnegative().nullable().optional(),
|
||||
budgetMax: z.number().nonnegative().nullable().optional(),
|
||||
dueAt: z.date().nullable().optional(),
|
||||
})
|
||||
|
||||
export const updateCommissionInputSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
title: z.string().min(1).max(180).optional(),
|
||||
description: z.string().max(4000).nullable().optional(),
|
||||
status: commissionStatusSchema.optional(),
|
||||
customerId: z.string().uuid().nullable().optional(),
|
||||
assignedUserId: z.string().uuid().nullable().optional(),
|
||||
linkedArtworkIds: z.array(z.string().uuid()).optional(),
|
||||
budgetMin: z.number().nonnegative().nullable().optional(),
|
||||
budgetMax: z.number().nonnegative().nullable().optional(),
|
||||
dueAt: z.date().nullable().optional(),
|
||||
@@ -57,6 +71,7 @@ export const updateCommissionStatusInputSchema = z.object({
|
||||
export type CommissionStatus = z.infer<typeof commissionStatusSchema>
|
||||
export type CreateCustomerInput = z.infer<typeof createCustomerInputSchema>
|
||||
export type CreateCommissionInput = z.infer<typeof createCommissionInputSchema>
|
||||
export type UpdateCommissionInput = z.infer<typeof updateCommissionInputSchema>
|
||||
export type CreatePublicCommissionRequestInput = z.infer<
|
||||
typeof createPublicCommissionRequestInputSchema
|
||||
>
|
||||
|
||||
@@ -99,6 +99,7 @@ export const updateMediaAssetInputSchema = z.object({
|
||||
location: z.string().max(180).nullable().optional(),
|
||||
capturedAt: z.date().nullable().optional(),
|
||||
tags: z.array(z.string().min(1).max(100)).optional(),
|
||||
storageKey: z.string().max(500).nullable().optional(),
|
||||
mimeType: z.string().max(180).nullable().optional(),
|
||||
width: z.number().int().positive().nullable().optional(),
|
||||
height: z.number().int().positive().nullable().optional(),
|
||||
|
||||
@@ -103,6 +103,7 @@ export const createPageInputSchema = z.object({
|
||||
content: z.string().min(1),
|
||||
seoTitle: z.string().max(180).nullable().optional(),
|
||||
seoDescription: z.string().max(320).nullable().optional(),
|
||||
scheduledPublishAt: z.date().nullable().optional(),
|
||||
})
|
||||
|
||||
export const updatePageInputSchema = z.object({
|
||||
@@ -114,6 +115,7 @@ export const updatePageInputSchema = z.object({
|
||||
content: z.string().min(1).optional(),
|
||||
seoTitle: z.string().max(180).nullable().optional(),
|
||||
seoDescription: z.string().max(320).nullable().optional(),
|
||||
scheduledPublishAt: z.date().nullable().optional(),
|
||||
})
|
||||
|
||||
export const upsertPageTranslationInputSchema = z.object({
|
||||
@@ -133,6 +135,14 @@ export const createNavigationMenuInputSchema = z.object({
|
||||
isVisible: z.boolean().default(true),
|
||||
})
|
||||
|
||||
export const updateNavigationMenuInputSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1).max(180).optional(),
|
||||
slug: z.string().min(1).max(180).optional(),
|
||||
location: z.string().min(1).max(80).optional(),
|
||||
isVisible: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export const createNavigationItemInputSchema = z.object({
|
||||
menuId: z.string().uuid(),
|
||||
label: z.string().min(1).max(180),
|
||||
@@ -157,6 +167,7 @@ export type CreatePageInput = z.infer<typeof createPageInputSchema>
|
||||
export type UpdatePageInput = z.infer<typeof updatePageInputSchema>
|
||||
export type UpsertPageTranslationInput = z.infer<typeof upsertPageTranslationInputSchema>
|
||||
export type CreateNavigationMenuInput = z.infer<typeof createNavigationMenuInputSchema>
|
||||
export type UpdateNavigationMenuInput = z.infer<typeof updateNavigationMenuInputSchema>
|
||||
export type CreateNavigationItemInput = z.infer<typeof createNavigationItemInputSchema>
|
||||
export type UpdateNavigationItemInput = z.infer<typeof updateNavigationItemInputSchema>
|
||||
export type PageBlock = z.infer<typeof pageBlockSchema>
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "Commission"
|
||||
ADD COLUMN "linkedArtworkIds" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "Announcement"
|
||||
ADD COLUMN "targetLocales" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE "Page"
|
||||
ADD COLUMN "scheduledPublishAt" TIMESTAMP(3);
|
||||
|
||||
CREATE INDEX "Page_scheduledPublishAt_idx" ON "Page"("scheduledPublishAt");
|
||||
@@ -291,6 +291,7 @@ model Page {
|
||||
seoTitle String?
|
||||
seoDescription String?
|
||||
publishedAt DateTime?
|
||||
scheduledPublishAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
navItems NavigationItem[]
|
||||
@@ -386,6 +387,7 @@ model Commission {
|
||||
status String
|
||||
customerId String?
|
||||
assignedUserId String?
|
||||
linkedArtworkIds String[] @default([])
|
||||
budgetMin Float?
|
||||
budgetMax Float?
|
||||
dueAt DateTime?
|
||||
@@ -404,6 +406,7 @@ model Announcement {
|
||||
title String
|
||||
message String
|
||||
placement String
|
||||
targetLocales String[] @default([])
|
||||
priority Int @default(100)
|
||||
ctaLabel String?
|
||||
ctaHref String?
|
||||
|
||||
@@ -41,13 +41,18 @@ describe("announcements service", () => {
|
||||
it("queries only visible announcements in the given placement", async () => {
|
||||
mockDb.announcement.findMany.mockResolvedValue([])
|
||||
|
||||
await listActiveAnnouncements("homepage")
|
||||
await listActiveAnnouncements("homepage", new Date("2026-02-12T10:00:00.000Z"), "en")
|
||||
|
||||
expect(mockDb.announcement.findMany).toHaveBeenCalledTimes(1)
|
||||
expect(mockDb.announcement.findMany.mock.calls[0]?.[0]).toMatchObject({
|
||||
where: {
|
||||
placement: "homepage",
|
||||
isVisible: true,
|
||||
AND: [
|
||||
{
|
||||
OR: [{ targetLocales: { isEmpty: true } }, { targetLocales: { has: "en" } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -13,6 +13,7 @@ export type PublicAnnouncement = {
|
||||
ctaLabel: string | null
|
||||
ctaHref: string | null
|
||||
placement: string
|
||||
targetLocales: string[]
|
||||
priority: number
|
||||
}
|
||||
|
||||
@@ -50,13 +51,26 @@ export async function deleteAnnouncement(id: string) {
|
||||
export async function listActiveAnnouncements(
|
||||
placement: AnnouncementPlacement,
|
||||
now = new Date(),
|
||||
locale?: string,
|
||||
): Promise<PublicAnnouncement[]> {
|
||||
const localeFilter =
|
||||
locale && locale.length > 0
|
||||
? {
|
||||
AND: [
|
||||
{
|
||||
OR: [{ targetLocales: { isEmpty: true } }, { targetLocales: { has: locale } }],
|
||||
},
|
||||
],
|
||||
}
|
||||
: undefined
|
||||
|
||||
const announcements = await db.announcement.findMany({
|
||||
where: {
|
||||
placement,
|
||||
isVisible: true,
|
||||
OR: [{ startsAt: null }, { startsAt: { lte: now } }],
|
||||
AND: [{ OR: [{ endsAt: null }, { endsAt: { gte: now } }] }],
|
||||
...(localeFilter ?? {}),
|
||||
},
|
||||
orderBy: [{ priority: "asc" }, { createdAt: "desc" }],
|
||||
select: {
|
||||
@@ -66,6 +80,7 @@ export async function listActiveAnnouncements(
|
||||
ctaLabel: true,
|
||||
ctaHref: true,
|
||||
placement: true,
|
||||
targetLocales: true,
|
||||
priority: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createCommissionInputSchema,
|
||||
createCustomerInputSchema,
|
||||
createPublicCommissionRequestInputSchema,
|
||||
updateCommissionInputSchema,
|
||||
updateCommissionStatusInputSchema,
|
||||
} from "@cms/content"
|
||||
|
||||
@@ -57,6 +58,16 @@ export async function createCommission(input: unknown) {
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateCommission(input: unknown) {
|
||||
const payload = updateCommissionInputSchema.parse(input)
|
||||
const { id, ...data } = payload
|
||||
|
||||
return db.commission.update({
|
||||
where: { id },
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export async function createPublicCommissionRequest(input: unknown) {
|
||||
const payload = createPublicCommissionRequestInputSchema.parse(input)
|
||||
const normalizedEmail = payload.customerEmail.trim().toLowerCase()
|
||||
|
||||
@@ -14,6 +14,7 @@ export {
|
||||
createPublicCommissionRequest,
|
||||
listCommissions,
|
||||
listCustomers,
|
||||
updateCommission,
|
||||
updateCommissionStatus,
|
||||
} from "./commissions"
|
||||
export {
|
||||
@@ -46,6 +47,7 @@ export {
|
||||
createNavigationMenu,
|
||||
createPage,
|
||||
deleteNavigationItem,
|
||||
deleteNavigationMenu,
|
||||
deletePage,
|
||||
getPageById,
|
||||
getPublishedPageBySlug,
|
||||
@@ -56,6 +58,7 @@ export {
|
||||
listPublicNavigation,
|
||||
listPublishedPageSlugs,
|
||||
updateNavigationItem,
|
||||
updateNavigationMenu,
|
||||
updatePage,
|
||||
upsertNavigationItemTranslation,
|
||||
upsertPageTranslation,
|
||||
|
||||
@@ -9,15 +9,18 @@ import {
|
||||
updateGroupingInputSchema,
|
||||
updateMediaAssetInputSchema,
|
||||
} from "@cms/content"
|
||||
import type { Prisma } from "@prisma/client"
|
||||
|
||||
import { db } from "./client"
|
||||
|
||||
type PublicArtworkGroupType = "gallery" | "album" | "category" | "tag"
|
||||
type PublicArtworkSort = "latest" | "title_asc" | "title_desc"
|
||||
|
||||
type ListPublishedArtworksInput = {
|
||||
groupType?: PublicArtworkGroupType
|
||||
groupSlug?: string
|
||||
limit?: number
|
||||
sort?: PublicArtworkSort
|
||||
}
|
||||
|
||||
export async function listMediaAssets(limit = 24) {
|
||||
@@ -431,6 +434,12 @@ export async function listPublishedArtworks(input: ListPublishedArtworksInput =
|
||||
const where: Record<string, unknown> = {
|
||||
isPublished: true,
|
||||
}
|
||||
const orderBy: Prisma.ArtworkOrderByWithRelationInput[] =
|
||||
input.sort === "title_asc"
|
||||
? [{ title: "asc" }, { updatedAt: "desc" }]
|
||||
: input.sort === "title_desc"
|
||||
? [{ title: "desc" }, { updatedAt: "desc" }]
|
||||
: [{ updatedAt: "desc" }]
|
||||
|
||||
if (input.groupType && input.groupSlug) {
|
||||
if (input.groupType === "gallery") {
|
||||
@@ -474,7 +483,7 @@ export async function listPublishedArtworks(input: ListPublishedArtworksInput =
|
||||
|
||||
return db.artwork.findMany({
|
||||
where,
|
||||
orderBy: [{ updatedAt: "desc" }],
|
||||
orderBy,
|
||||
take,
|
||||
include: {
|
||||
renditions: {
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createNavigationMenuInputSchema,
|
||||
createPageInputSchema,
|
||||
updateNavigationItemInputSchema,
|
||||
updateNavigationMenuInputSchema,
|
||||
updatePageInputSchema,
|
||||
upsertPageTranslationInputSchema,
|
||||
} from "@cms/content"
|
||||
@@ -28,6 +29,15 @@ function resolvePublishedAt(status: string): Date | null {
|
||||
return status === "published" ? new Date() : null
|
||||
}
|
||||
|
||||
function resolvePublicPageWhere(slug?: string) {
|
||||
const now = new Date()
|
||||
|
||||
return {
|
||||
...(slug ? { slug } : {}),
|
||||
OR: [{ status: "published" }, { scheduledPublishAt: { lte: now } }],
|
||||
}
|
||||
}
|
||||
|
||||
export async function listPages(limit = 50) {
|
||||
return db.page.findMany({
|
||||
orderBy: [{ updatedAt: "desc" }],
|
||||
@@ -37,7 +47,7 @@ export async function listPages(limit = 50) {
|
||||
|
||||
export async function listPublishedPageSlugs() {
|
||||
const pages = await db.page.findMany({
|
||||
where: { status: "published" },
|
||||
where: resolvePublicPageWhere(),
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: {
|
||||
slug: true,
|
||||
@@ -56,19 +66,13 @@ export async function getPageById(id: string) {
|
||||
|
||||
export async function getPublishedPageBySlug(slug: string) {
|
||||
return db.page.findFirst({
|
||||
where: {
|
||||
slug,
|
||||
status: "published",
|
||||
},
|
||||
where: resolvePublicPageWhere(slug),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getPublishedPageBySlugForLocale(slug: string, locale: string) {
|
||||
const page = await db.page.findFirst({
|
||||
where: {
|
||||
slug,
|
||||
status: "published",
|
||||
},
|
||||
where: resolvePublicPageWhere(slug),
|
||||
include: {
|
||||
translations: {
|
||||
where: {
|
||||
@@ -97,11 +101,13 @@ export async function getPublishedPageBySlugForLocale(slug: string, locale: stri
|
||||
|
||||
export async function createPage(input: unknown) {
|
||||
const payload = createPageInputSchema.parse(input)
|
||||
const isImmediatelyPublished = payload.status === "published"
|
||||
|
||||
return db.page.create({
|
||||
data: {
|
||||
...payload,
|
||||
publishedAt: resolvePublishedAt(payload.status),
|
||||
scheduledPublishAt: isImmediatelyPublished ? null : (payload.scheduledPublishAt ?? null),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -109,6 +115,7 @@ export async function createPage(input: unknown) {
|
||||
export async function updatePage(input: unknown) {
|
||||
const payload = updatePageInputSchema.parse(input)
|
||||
const { id, ...data } = payload
|
||||
const isImmediatelyPublished = data.status === "published"
|
||||
|
||||
return db.page.update({
|
||||
where: { id },
|
||||
@@ -116,6 +123,12 @@ export async function updatePage(input: unknown) {
|
||||
...data,
|
||||
publishedAt:
|
||||
data.status === undefined ? undefined : data.status === "published" ? new Date() : null,
|
||||
scheduledPublishAt:
|
||||
data.scheduledPublishAt === undefined
|
||||
? undefined
|
||||
: isImmediatelyPublished
|
||||
? null
|
||||
: data.scheduledPublishAt,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -297,6 +310,22 @@ export async function createNavigationMenu(input: unknown) {
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateNavigationMenu(input: unknown) {
|
||||
const payload = updateNavigationMenuInputSchema.parse(input)
|
||||
const { id, ...data } = payload
|
||||
|
||||
return db.navigationMenu.update({
|
||||
where: { id },
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteNavigationMenu(id: string) {
|
||||
return db.navigationMenu.delete({
|
||||
where: { id },
|
||||
})
|
||||
}
|
||||
|
||||
export async function createNavigationItem(input: unknown) {
|
||||
const payload = createNavigationItemInputSchema.parse(input)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user