feat(product-dialog): conform aan dialog-pattern + entity-profile

Story 2 van PBI "Alle dialogen conform docs/patterns/dialog.md".

- lib/schemas/product.ts — gedeeld zod-schema (Dialog API)
- actions/products.ts — createProductAction/updateProductAction returnen
  nu code+fieldErrors voor 422-validatie en code: 403 voor demo/auth
- ProductDialog adopt useDirtyCloseGuard, useDialogSubmitShortcut,
  entityDialog* layout-classes; 422-fieldErrors mappen naar form.setError
- docs/specs/dialogs/product.md — entity-profile

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Janpeter Visser 2026-05-04 07:18:39 +02:00
parent b05c4d241b
commit 03a248b0fb
6 changed files with 310 additions and 181 deletions

View file

@ -107,7 +107,10 @@ describe('createProductAction', () => {
const result = await createProductAction(VALID_DATA)
expect(result).toMatchObject({ error: expect.stringContaining('gebruik') })
expect(result).toMatchObject({
code: 422,
fieldErrors: { code: expect.arrayContaining([expect.stringContaining('gebruik')]) },
})
expect(mockTransaction).not.toHaveBeenCalled()
})

View file

@ -10,8 +10,10 @@ import { SessionData, sessionOptions } from '@/lib/session'
import { Role } from '@prisma/client'
import { isValidCode, MAX_CODE_LENGTH, normalizeCode } from '@/lib/code'
import { productAccessFilter } from '@/lib/product-access'
import { productSchema as productInput, type ProductInput } from '@/lib/schemas/product'
const productSchema = z.object({
// Legacy FormData schema for ProductForm components (other constraints than dialog)
const productFormDataSchema = z.object({
name: z.string().min(1, 'Naam is verplicht').max(100, 'Naam mag maximaal 100 tekens bevatten'),
code: z
.string()
@ -29,25 +31,13 @@ const productSchema = z.object({
.max(500, 'Definition of Done mag maximaal 500 tekens bevatten'),
})
// Dialog-based schema (data-object API)
const productInput = z.object({
name: z.string().min(1).max(200),
code: z.string().max(20).optional(),
description: z.string().max(4000).optional(),
repo_url: z
.string()
.url()
.regex(/^https:\/\/github\.com\//)
.optional()
.nullable(),
definition_of_done: z.string().max(4000).optional(),
auto_pr: z.boolean().default(false),
})
export type ProductInput = z.infer<typeof productInput>
type ProductActionResult = { success: true; productId: string } | { error: string }
type UpdateProductResult = { success: true } | { error: string }
type ProductFieldErrors = Partial<Record<keyof ProductInput, string[]>>
type ProductActionResult =
| { success: true; productId: string }
| { error: string; code?: number; fieldErrors?: ProductFieldErrors }
type UpdateProductResult =
| { success: true }
| { error: string; code?: number; fieldErrors?: ProductFieldErrors }
async function getSession() {
return getIronSession<SessionData>(await cookies(), sessionOptions)
@ -56,20 +46,30 @@ async function getSession() {
// Data-object API used by ProductDialog
export async function createProductAction(data: ProductInput): Promise<ProductActionResult> {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
if (!session.userId) return { error: 'Niet ingelogd', code: 403 }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus', code: 403 }
const parsed = productInput.safeParse(data)
if (!parsed.success) return { error: parsed.error.flatten().formErrors[0] ?? 'Ongeldige invoer' }
if (!parsed.success) {
return {
error: 'Validatie mislukt',
code: 422,
fieldErrors: parsed.error.flatten().fieldErrors as ProductFieldErrors,
}
}
const code = normalizeCode(parsed.data.code)
if (code !== null && !isValidCode(code)) {
return { error: 'Code mag alleen letters, cijfers, punten, koppeltekens of underscores bevatten' }
return {
error: 'Validatie mislukt',
code: 422,
fieldErrors: { code: ['Alleen letters, cijfers, punten, koppeltekens of underscores'] },
}
}
if (code) {
const dup = await prisma.product.findFirst({ where: { user_id: session.userId, code } })
if (dup) return { error: 'Code is al in gebruik' }
if (dup) return { error: 'Validatie mislukt', code: 422, fieldErrors: { code: ['Code is al in gebruik'] } }
}
const userId = session.userId
@ -97,21 +97,31 @@ export async function createProductAction(data: ProductInput): Promise<ProductAc
// Data-object API used by ProductDialog
export async function updateProductAction(id: string, data: ProductInput): Promise<UpdateProductResult> {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
if (!session.userId) return { error: 'Niet ingelogd', code: 403 }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus', code: 403 }
const parsed = productInput.safeParse(data)
if (!parsed.success) return { error: parsed.error.flatten().formErrors[0] ?? 'Ongeldige invoer' }
if (!parsed.success) {
return {
error: 'Validatie mislukt',
code: 422,
fieldErrors: parsed.error.flatten().fieldErrors as ProductFieldErrors,
}
}
const product = await prisma.product.findFirst({
where: { id, ...productAccessFilter(session.userId) },
select: { id: true },
})
if (!product) return { error: 'Product niet gevonden of geen toegang' }
if (!product) return { error: 'Product niet gevonden of geen toegang', code: 403 }
const code = normalizeCode(parsed.data.code)
if (code !== null && !isValidCode(code)) {
return { error: 'Code mag alleen letters, cijfers, punten, koppeltekens of underscores bevatten' }
return {
error: 'Validatie mislukt',
code: 422,
fieldErrors: { code: ['Alleen letters, cijfers, punten, koppeltekens of underscores'] },
}
}
const userId = session.userId
@ -149,7 +159,7 @@ export async function createProductFormAction(_prevState: unknown, formData: For
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const parsed = productSchema.safeParse({
const parsed = productFormDataSchema.safeParse({
name: formData.get('name'),
code: (formData.get('code') as string) || undefined,
description: formData.get('description') || undefined,
@ -198,7 +208,7 @@ export async function updateProductFormAction(_prevState: unknown, formData: For
const id = formData.get('id') as string
if (!id) return { error: 'Product niet gevonden' }
const parsed = productSchema.safeParse({
const parsed = productFormDataSchema.safeParse({
name: formData.get('name'),
code: (formData.get('code') as string) || undefined,
description: formData.get('description') || undefined,

View file

@ -3,35 +3,32 @@
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
DialogClose,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import {
useDirtyCloseGuard,
DirtyCloseGuardDialog,
} from '@/components/shared/use-dirty-close-guard'
import { useDialogSubmitShortcut } from '@/components/shared/use-dialog-submit-shortcut'
import {
entityDialogBodyClasses,
entityDialogContentClasses,
entityDialogFooterClasses,
entityDialogHeaderClasses,
} from '@/components/shared/entity-dialog-layout'
import { productSchema, type ProductInput } from '@/lib/schemas/product'
import { createProductAction, updateProductAction } from '@/actions/products'
import { useProductsStore } from '@/stores/products-store'
const formSchema = z.object({
name: z.string().min(1, 'Naam is verplicht').max(200),
code: z.string().max(20).optional(),
description: z.string().max(4000).optional(),
repo_url: z.string().max(200).optional(),
definition_of_done: z.string().max(4000).optional(),
auto_pr: z.boolean(),
})
type FormValues = z.infer<typeof formSchema>
export interface ProductDialogProduct {
id: string
name: string
@ -54,8 +51,9 @@ export function ProductDialog(props: Props) {
const [isPending, setIsPending] = useState(false)
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
const form = useForm<ProductInput>({
resolver: zodResolver(productSchema),
mode: 'onTouched',
defaultValues: {
name: product?.name ?? '',
code: product?.code ?? '',
@ -66,7 +64,7 @@ export function ProductDialog(props: Props) {
},
})
// Reset form when dialog opens or switches product
// Reset when opening or switching product
useEffect(() => {
if (open) {
form.reset({
@ -81,14 +79,13 @@ export function ProductDialog(props: Props) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, product?.id])
async function onSubmit(values: FormValues) {
if (isDemo) {
toast.error('Niet beschikbaar in demo-modus')
return
}
const closeGuard = useDirtyCloseGuard(form.formState.isDirty, () => onOpenChange(false))
const handleKeyDown = useDialogSubmitShortcut(() => form.handleSubmit(onSubmit)())
async function onSubmit(values: ProductInput) {
setIsPending(true)
try {
const payload = {
const payload: ProductInput = {
name: values.name,
code: values.code || undefined,
description: values.description || undefined,
@ -97,14 +94,29 @@ export function ProductDialog(props: Props) {
auto_pr: values.auto_pr,
}
function applyError(result: { error: string; code?: number; fieldErrors?: Partial<Record<keyof ProductInput, string[]>> }) {
if (result.code === 422 && result.fieldErrors) {
for (const [field, errors] of Object.entries(result.fieldErrors)) {
if (errors && errors.length > 0) {
form.setError(field as keyof ProductInput, { message: errors[0] })
}
}
const firstError = Object.keys(result.fieldErrors)[0] as keyof ProductInput | undefined
if (firstError) form.setFocus(firstError)
return
}
toast.error(result.error)
}
if (mode === 'create') {
const result = await createProductAction(payload)
if ('error' in result) {
toast.error(result.error)
applyError(result)
return
}
const productId = result.productId
addProduct({
id: result.productId,
id: productId,
name: values.name,
code: values.code ?? null,
description: values.description ?? null,
@ -114,11 +126,11 @@ export function ProductDialog(props: Props) {
})
toast.success('Product aangemaakt')
onOpenChange(false)
props.onSaved?.(result.productId)
props.onSaved?.(productId)
} else {
const result = await updateProductAction(product!.id, payload)
if ('error' in result) {
toast.error(result.error)
applyError(result)
return
}
updateProduct(product!.id, {
@ -141,130 +153,156 @@ export function ProductDialog(props: Props) {
const autoPr = form.watch('auto_pr')
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{mode === 'edit' ? 'Product bewerken' : 'Nieuw product'}</DialogTitle>
</DialogHeader>
<form
id="product-form"
onSubmit={form.handleSubmit(onSubmit)}
className="grid gap-4"
<>
<Dialog open={open} onOpenChange={(v) => { if (!v) closeGuard.attemptClose(); else onOpenChange(v) }}>
<DialogContent
showCloseButton={false}
onKeyDown={handleKeyDown}
className={entityDialogContentClasses}
>
<div className="grid gap-1.5">
<label htmlFor="product-name" className="text-sm font-medium">
Naam <span className="text-error">*</span>
</label>
<Input
id="product-name"
autoFocus={mode === 'create'}
disabled={isDemo}
maxLength={200}
{...form.register('name')}
className={form.formState.errors.name ? 'border-error' : ''}
/>
{form.formState.errors.name && (
<p className="text-xs text-error">{form.formState.errors.name.message}</p>
)}
<div className={entityDialogHeaderClasses}>
<DialogTitle className="text-xl font-semibold">
{mode === 'edit' ? 'Product bewerken' : 'Nieuw product'}
</DialogTitle>
</div>
<div className="grid gap-1.5">
<label htmlFor="product-code" className="text-sm font-medium">
Code <span className="text-muted-foreground font-normal">(optioneel)</span>
</label>
<Input
id="product-code"
disabled={isDemo}
maxLength={20}
placeholder="korte slug, bv. SCRUM4ME"
className="font-mono text-sm"
{...form.register('code')}
/>
</div>
<div className="grid gap-1.5">
<label htmlFor="product-description" className="text-sm font-medium">
Beschrijving <span className="text-muted-foreground font-normal">(optioneel)</span>
</label>
<Textarea
id="product-description"
disabled={isDemo}
rows={3}
maxLength={4000}
className="resize-none"
{...form.register('description')}
/>
</div>
<div className="grid gap-1.5">
<label htmlFor="product-repo-url" className="text-sm font-medium">
Repository URL <span className="text-muted-foreground font-normal">(optioneel)</span>
</label>
<Input
id="product-repo-url"
disabled={isDemo}
placeholder="https://github.com/owner/repo"
{...form.register('repo_url')}
/>
</div>
<div className="grid gap-1.5">
<label htmlFor="product-dod" className="text-sm font-medium">
Definition of Done <span className="text-muted-foreground font-normal">(optioneel)</span>
</label>
<Textarea
id="product-dod"
disabled={isDemo}
rows={4}
maxLength={4000}
className="resize-none"
{...form.register('definition_of_done')}
/>
</div>
<div className="flex items-start gap-3">
<button
type="button"
role="switch"
aria-checked={autoPr}
disabled={isDemo}
onClick={() => form.setValue('auto_pr', !autoPr)}
className={cn(
'relative mt-0.5 inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent',
'transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
'disabled:cursor-not-allowed disabled:opacity-50',
autoPr ? 'bg-primary' : 'bg-input',
)}
>
<span
className={cn(
'pointer-events-none inline-block h-4 w-4 rounded-full bg-background shadow-sm',
'transition-transform duration-200',
autoPr ? 'translate-x-4' : 'translate-x-0',
)}
<form
id="product-form"
onSubmit={form.handleSubmit(onSubmit)}
className={entityDialogBodyClasses}
>
<div className="grid gap-1.5">
<label htmlFor="product-name" className="text-sm font-medium">
Naam <span className="text-error">*</span>
</label>
<Input
id="product-name"
autoFocus={mode === 'create'}
disabled={isDemo}
maxLength={200}
aria-invalid={!!form.formState.errors.name}
{...form.register('name')}
className={form.formState.errors.name ? 'border-error' : ''}
/>
</button>
<div className="grid gap-0.5">
<span className="text-sm font-medium">Automatisch PR aanmaken na voltooide story</span>
<span className="text-xs text-muted-foreground">
Bij elke voltooide story automatisch een PR aanmaken in <code>repo_url</code>
</span>
{form.formState.errors.name && (
<p className="text-xs text-error">{form.formState.errors.name.message}</p>
)}
</div>
<div className="grid gap-1.5">
<label htmlFor="product-code" className="text-sm font-medium">
Code <span className="text-muted-foreground font-normal">(optioneel)</span>
</label>
<Input
id="product-code"
disabled={isDemo}
maxLength={20}
placeholder="korte slug, bv. SCRUM4ME"
aria-invalid={!!form.formState.errors.code}
className={cn('font-mono text-sm', form.formState.errors.code && 'border-error')}
{...form.register('code')}
/>
{form.formState.errors.code && (
<p className="text-xs text-error">{form.formState.errors.code.message}</p>
)}
</div>
<div className="grid gap-1.5">
<label htmlFor="product-description" className="text-sm font-medium">
Beschrijving <span className="text-muted-foreground font-normal">(optioneel)</span>
</label>
<Textarea
id="product-description"
disabled={isDemo}
rows={3}
maxLength={4000}
className="resize-none"
{...form.register('description')}
/>
</div>
<div className="grid gap-1.5">
<label htmlFor="product-repo-url" className="text-sm font-medium">
Repository URL <span className="text-muted-foreground font-normal">(optioneel)</span>
</label>
<Input
id="product-repo-url"
disabled={isDemo}
placeholder="https://github.com/owner/repo"
aria-invalid={!!form.formState.errors.repo_url}
{...form.register('repo_url')}
className={form.formState.errors.repo_url ? 'border-error' : ''}
/>
{form.formState.errors.repo_url && (
<p className="text-xs text-error">{form.formState.errors.repo_url.message}</p>
)}
</div>
<div className="grid gap-1.5">
<label htmlFor="product-dod" className="text-sm font-medium">
Definition of Done <span className="text-muted-foreground font-normal">(optioneel)</span>
</label>
<Textarea
id="product-dod"
disabled={isDemo}
rows={4}
maxLength={4000}
className="resize-none"
{...form.register('definition_of_done')}
/>
</div>
<div className="flex items-start gap-3">
<button
type="button"
role="switch"
aria-checked={autoPr}
disabled={isDemo}
onClick={() => form.setValue('auto_pr', !autoPr, { shouldDirty: true })}
className={cn(
'relative mt-0.5 inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent',
'transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
'disabled:cursor-not-allowed disabled:opacity-50',
autoPr ? 'bg-primary' : 'bg-input',
)}
>
<span
className={cn(
'pointer-events-none inline-block h-4 w-4 rounded-full bg-background shadow-sm',
'transition-transform duration-200',
autoPr ? 'translate-x-4' : 'translate-x-0',
)}
/>
</button>
<div className="grid gap-0.5">
<span className="text-sm font-medium">Automatisch PR aanmaken na voltooide story</span>
<span className="text-xs text-muted-foreground">
Bij elke voltooide story automatisch een PR aanmaken in <code>repo_url</code>
</span>
</div>
</div>
</form>
<div className={entityDialogFooterClasses}>
<div className="flex items-center justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={closeGuard.attemptClose}
disabled={isPending}
>
Annuleren
</Button>
<DemoTooltip show={isDemo}>
<Button type="submit" form="product-form" disabled={isPending || isDemo}>
{isPending ? '…' : mode === 'edit' ? 'Opslaan' : 'Aanmaken'}
</Button>
</DemoTooltip>
</div>
</div>
</form>
<DialogFooter>
<DialogClose render={<Button type="button" variant="outline" />}>
Annuleren
</DialogClose>
<DemoTooltip show={isDemo}>
<Button type="submit" form="product-form" disabled={isPending || isDemo}>
{isPending ? '…' : mode === 'edit' ? 'Opslaan' : 'Aanmaken'}
</Button>
</DemoTooltip>
</DialogFooter>
</DialogContent>
</Dialog>
</DialogContent>
</Dialog>
<DirtyCloseGuardDialog guard={closeGuard} />
</>
)
}

View file

@ -2,7 +2,7 @@
# Documentation Index
Auto-generated on 2026-05-03 from front-matter and headings.
Auto-generated on 2026-05-04 from front-matter and headings.
## Architecture Decision Records
@ -24,6 +24,7 @@ Auto-generated on 2026-05-03 from front-matter and headings.
| Title | Status | Updated |
|---|---|---|
| [PbiDialog Profiel](./specs/dialogs/pbi.md) | active | 2026-05-03 |
| [ProductDialog Profiel](./specs/dialogs/product.md) | active | 2026-05-04 |
| [StoryDialog Profiel](./specs/dialogs/story.md) | active | 2026-05-03 |
| [TaskDialog Profiel](./specs/dialogs/task.md) | active | 2026-05-03 |
| [Scrum4Me — Functionele Specificatie](./specs/functional.md) | active | 2026-05-03 |

View file

@ -0,0 +1,59 @@
---
title: "ProductDialog Profiel"
status: active
audience: [ai-agent, contributor]
language: nl
last_updated: 2026-05-04
---
# ProductDialog Profiel
> Volgt `docs/patterns/dialog.md`. Dit document beschrijft alleen de afwijkingen en entity-specifieke keuzes.
## Velden
| Veld | Type | Mode | Validatie |
|---|---|---|---|
| `name` | string | both | min 1, max 200 |
| `code` | string? | both | max 20, alleen `[a-zA-Z0-9._-]`; uniek per gebruiker |
| `description` | string? | both | max 4000, markdown vrij |
| `repo_url` | string? \| null | both | https URL, moet beginnen met `https://github.com/` |
| `definition_of_done` | string? | both | max 4000, vrije tekst |
| `auto_pr` | boolean | both | default `false` |
## URL- of state-pattern
- Gekozen: **state-based** (§11.2)
- Reden: dialog leeft binnen één parent-component (`ProductList` op `/dashboard` en de product-actions-bar op `/products/[id]`); deep-linking is niet vereist
- Open-state komt uit `ProductList` (lijst-context) of `EditProductButton` (single-item context)
## Status-veld
N.v.t. — Product heeft geen status-enum. `archived` is een boolean buiten dit dialog (eigen archive-flow).
## Server actions
- `createProductAction(data)` in `actions/products.ts` — context-arg via `revalidatePath('/products')` + `revalidatePath('/dashboard')`
- `updateProductAction(id, data)` in `actions/products.ts` — context-arg via `revalidatePath('/products/${id}')` + `revalidatePath('/dashboard')` + `pg_notify('product_updated')`
- Beide hebben `session.userId`-check, `session.isDemo`-check (laag 2 demo-policy) en `productAccessFilter` voor update
- Resultaat-shape: `{ success: true, productId? }` of `{ error: string, code?: 422|403, fieldErrors?: Record<string, string[]> }`
## Foutcodes
| Code | Wanneer | UI |
|---|---|---|
| 422 | zod-validatie of code-uniqueness | `fieldErrors``form.setError`, geen toast, focus naar eerste error-veld |
| 403 | niet ingelogd, demo-modus, of geen toegang tot product | toast met message |
| 500 | onverwacht | huidige behandeling: error wordt door React opgevangen — laat de form open |
## Speciale gedragingen
- **Custom switch voor `auto_pr`**: native `<button role="switch">` met MD3-kleur-tokens (geen aparte primitive in v1; zou gepromoot moeten worden naar `components/shared/switch.tsx` zodra elders nodig).
- **Code-uniqueness server-side**: bij conflict wordt `fieldErrors.code` gezet; veld krijgt rode rand.
- **`useProductsStore` updates**: na succesvolle save wordt de in-memory store synchroon bijgewerkt zodat de productlijst onmiddellijk reageert (lokaal-first).
## Bewust NIET in v1
- Verwijderen vanuit deze dialog (loopt via `archiveProductAction` op een andere knop)
- Bulk edit
- Members beheren (eigen scherm op `/products/[id]/settings`)

18
lib/schemas/product.ts Normal file
View file

@ -0,0 +1,18 @@
import { z } from 'zod'
export const productSchema = z.object({
name: z.string().trim().min(1, 'Naam is verplicht').max(200, 'Maximaal 200 tekens'),
code: z.string().trim().max(20, 'Maximaal 20 tekens').optional(),
description: z.string().max(4000, 'Maximaal 4000 tekens').optional(),
repo_url: z
.string()
.url('Voer een geldige URL in (inclusief https://)')
.regex(/^https:\/\/github\.com\//, 'Alleen GitHub-URLs worden ondersteund')
.optional()
.nullable()
.or(z.literal('')),
definition_of_done: z.string().max(4000, 'Maximaal 4000 tekens').optional(),
auto_pr: z.boolean(),
})
export type ProductInput = z.infer<typeof productSchema>