feat(ST-?): createProductAction + updateProductAction (data-object API)
Voegt data-object-gebaseerde createProductAction(data) en updateProductAction(id, data) toe aan actions/products.ts voor gebruik door ProductDialog. Bevat Zod-validatie (incl. github-regex op repo_url), productAccessFilter voor update, pg_notify bij update, en productMember- aanleg bij create. FormData-varianten hernoemd naar ...FormAction; callers bijgewerkt. 9 nieuwe tests groen. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
60e2b62bbe
commit
ae66c21109
4 changed files with 278 additions and 6 deletions
160
__tests__/actions/products.test.ts
Normal file
160
__tests__/actions/products.test.ts
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const {
|
||||
mockGetSession,
|
||||
mockFindFirstProduct,
|
||||
mockCreateProduct,
|
||||
mockUpdateProduct,
|
||||
mockCreateMember,
|
||||
mockExecuteRaw,
|
||||
mockTransaction,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetSession: vi.fn(),
|
||||
mockFindFirstProduct: vi.fn(),
|
||||
mockCreateProduct: vi.fn(),
|
||||
mockUpdateProduct: vi.fn(),
|
||||
mockCreateMember: vi.fn(),
|
||||
mockExecuteRaw: vi.fn().mockResolvedValue(undefined),
|
||||
mockTransaction: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
|
||||
vi.mock('next/navigation', () => ({ redirect: vi.fn() }))
|
||||
vi.mock('next/headers', () => ({ cookies: vi.fn().mockResolvedValue({}) }))
|
||||
vi.mock('iron-session', () => ({
|
||||
getIronSession: vi.fn().mockResolvedValue({ userId: 'user-1', isDemo: false }),
|
||||
}))
|
||||
vi.mock('@/lib/session', () => ({
|
||||
sessionOptions: { cookieName: 'test', password: 'test' },
|
||||
}))
|
||||
vi.mock('@/lib/auth', () => ({ getSession: mockGetSession }))
|
||||
vi.mock('@/lib/product-access', () => ({
|
||||
productAccessFilter: vi.fn().mockReturnValue({ OR: [{ user_id: 'user-1' }] }),
|
||||
}))
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
product: { findFirst: mockFindFirstProduct, create: mockCreateProduct, update: mockUpdateProduct },
|
||||
productMember: { create: mockCreateMember },
|
||||
$executeRaw: mockExecuteRaw,
|
||||
$transaction: mockTransaction,
|
||||
},
|
||||
}))
|
||||
|
||||
import { createProductAction, updateProductAction } from '@/actions/products'
|
||||
import { getIronSession } from 'iron-session'
|
||||
|
||||
const mockSession = getIronSession as ReturnType<typeof vi.fn>
|
||||
|
||||
const SESSION_USER = { userId: 'user-1', isDemo: false }
|
||||
const SESSION_DEMO = { userId: 'demo-1', isDemo: true }
|
||||
const PRODUCT_ID = 'product-1'
|
||||
|
||||
const VALID_DATA = {
|
||||
name: 'Test Product',
|
||||
code: 'TP',
|
||||
description: 'Een product',
|
||||
repo_url: 'https://github.com/org/repo',
|
||||
definition_of_done: 'Alles groen',
|
||||
auto_pr: false,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockExecuteRaw.mockResolvedValue(undefined)
|
||||
mockSession.mockResolvedValue(SESSION_USER)
|
||||
})
|
||||
|
||||
// =============================================================
|
||||
// createProductAction
|
||||
// =============================================================
|
||||
describe('createProductAction', () => {
|
||||
it('happy path: maakt product + member aan en retourneert productId', async () => {
|
||||
mockFindFirstProduct.mockResolvedValue(null) // geen dubbele code
|
||||
mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) => {
|
||||
return fn({
|
||||
product: {
|
||||
create: vi.fn().mockResolvedValue({ id: PRODUCT_ID }),
|
||||
},
|
||||
productMember: {
|
||||
create: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
const result = await createProductAction(VALID_DATA)
|
||||
|
||||
expect(result).toEqual({ success: true, productId: PRODUCT_ID })
|
||||
})
|
||||
|
||||
it('demo-user → error', async () => {
|
||||
mockSession.mockResolvedValue(SESSION_DEMO)
|
||||
|
||||
const result = await createProductAction(VALID_DATA)
|
||||
|
||||
expect(result).toMatchObject({ error: expect.stringContaining('demo') })
|
||||
expect(mockTransaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ongeldige repo_url (niet github) → validatiefout', async () => {
|
||||
const result = await createProductAction({ ...VALID_DATA, repo_url: 'https://gitlab.com/org/repo' })
|
||||
|
||||
expect(result).toMatchObject({ error: expect.any(String) })
|
||||
expect(mockTransaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('dubbele code → error', async () => {
|
||||
mockFindFirstProduct.mockResolvedValue({ id: 'other-product' })
|
||||
|
||||
const result = await createProductAction(VALID_DATA)
|
||||
|
||||
expect(result).toMatchObject({ error: expect.stringContaining('gebruik') })
|
||||
expect(mockTransaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('naam ontbreekt → validatiefout', async () => {
|
||||
const result = await createProductAction({ ...VALID_DATA, name: '' })
|
||||
|
||||
expect(result).toMatchObject({ error: expect.any(String) })
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================
|
||||
// updateProductAction
|
||||
// =============================================================
|
||||
describe('updateProductAction', () => {
|
||||
it('happy path: werkt product bij en stuurt pg_notify', async () => {
|
||||
mockFindFirstProduct.mockResolvedValue({ id: PRODUCT_ID })
|
||||
mockUpdateProduct.mockResolvedValue({ id: PRODUCT_ID })
|
||||
|
||||
const result = await updateProductAction(PRODUCT_ID, VALID_DATA)
|
||||
|
||||
expect(result).toEqual({ success: true })
|
||||
expect(mockUpdateProduct).toHaveBeenCalled()
|
||||
expect(mockExecuteRaw).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('demo-user → error', async () => {
|
||||
mockSession.mockResolvedValue(SESSION_DEMO)
|
||||
|
||||
const result = await updateProductAction(PRODUCT_ID, VALID_DATA)
|
||||
|
||||
expect(result).toMatchObject({ error: expect.stringContaining('demo') })
|
||||
expect(mockUpdateProduct).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('geen toegang tot product → error', async () => {
|
||||
mockFindFirstProduct.mockResolvedValue(null)
|
||||
|
||||
const result = await updateProductAction(PRODUCT_ID, VALID_DATA)
|
||||
|
||||
expect(result).toMatchObject({ error: expect.stringContaining('toegang') })
|
||||
expect(mockUpdateProduct).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ongeldige repo_url → validatiefout', async () => {
|
||||
const result = await updateProductAction(PRODUCT_ID, { ...VALID_DATA, repo_url: 'https://bitbucket.org/x' })
|
||||
|
||||
expect(result).toMatchObject({ error: expect.any(String) })
|
||||
expect(mockUpdateProduct).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -9,6 +9,7 @@ import { prisma } from '@/lib/prisma'
|
|||
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'
|
||||
|
||||
const productSchema = z.object({
|
||||
name: z.string().min(1, 'Naam is verplicht').max(100, 'Naam mag maximaal 100 tekens bevatten'),
|
||||
|
|
@ -28,11 +29,122 @@ 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 }
|
||||
|
||||
async function getSession() {
|
||||
return getIronSession<SessionData>(await cookies(), sessionOptions)
|
||||
}
|
||||
|
||||
export async function createProductAction(_prevState: unknown, formData: FormData) {
|
||||
// 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' }
|
||||
|
||||
const parsed = productInput.safeParse(data)
|
||||
if (!parsed.success) return { error: parsed.error.flatten().formErrors[0] ?? 'Ongeldige invoer' }
|
||||
|
||||
const code = normalizeCode(parsed.data.code)
|
||||
if (code !== null && !isValidCode(code)) {
|
||||
return { error: 'Code mag alleen letters, cijfers, punten, koppeltekens of underscores bevatten' }
|
||||
}
|
||||
|
||||
if (code) {
|
||||
const dup = await prisma.product.findFirst({ where: { user_id: session.userId, code } })
|
||||
if (dup) return { error: 'Code is al in gebruik' }
|
||||
}
|
||||
|
||||
const userId = session.userId
|
||||
const product = await prisma.$transaction(async (tx) => {
|
||||
const p = await tx.product.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
name: parsed.data.name,
|
||||
code: code ?? null,
|
||||
description: parsed.data.description ?? null,
|
||||
repo_url: parsed.data.repo_url ?? null,
|
||||
definition_of_done: parsed.data.definition_of_done ?? '',
|
||||
auto_pr: parsed.data.auto_pr,
|
||||
},
|
||||
})
|
||||
await tx.productMember.create({ data: { product_id: p.id, user_id: userId } })
|
||||
return p
|
||||
})
|
||||
|
||||
revalidatePath('/products')
|
||||
revalidatePath('/dashboard')
|
||||
return { success: true, productId: product.id }
|
||||
}
|
||||
|
||||
// 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' }
|
||||
|
||||
const parsed = productInput.safeParse(data)
|
||||
if (!parsed.success) return { error: parsed.error.flatten().formErrors[0] ?? 'Ongeldige invoer' }
|
||||
|
||||
const product = await prisma.product.findFirst({
|
||||
where: { id, ...productAccessFilter(session.userId) },
|
||||
select: { id: true },
|
||||
})
|
||||
if (!product) return { error: 'Product niet gevonden of geen toegang' }
|
||||
|
||||
const code = normalizeCode(parsed.data.code)
|
||||
if (code !== null && !isValidCode(code)) {
|
||||
return { error: 'Code mag alleen letters, cijfers, punten, koppeltekens of underscores bevatten' }
|
||||
}
|
||||
|
||||
const userId = session.userId
|
||||
|
||||
await prisma.product.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: parsed.data.name,
|
||||
code: code ?? null,
|
||||
description: parsed.data.description ?? null,
|
||||
repo_url: parsed.data.repo_url ?? null,
|
||||
...(parsed.data.definition_of_done !== undefined && {
|
||||
definition_of_done: parsed.data.definition_of_done,
|
||||
}),
|
||||
auto_pr: parsed.data.auto_pr,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$executeRaw`
|
||||
SELECT pg_notify('scrum4me_changes', ${JSON.stringify({
|
||||
type: 'product_updated',
|
||||
product_id: id,
|
||||
user_id: userId,
|
||||
})}::text)
|
||||
`
|
||||
|
||||
revalidatePath(`/products/${id}`)
|
||||
revalidatePath('/dashboard')
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
// FormData-based actions for existing ProductForm components
|
||||
export async function createProductFormAction(_prevState: unknown, formData: FormData) {
|
||||
const session = await getSession()
|
||||
if (!session.userId) return { error: 'Niet ingelogd' }
|
||||
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
|
||||
|
|
@ -78,7 +190,7 @@ export async function createProductAction(_prevState: unknown, formData: FormDat
|
|||
redirect(`/products/${product.id}`)
|
||||
}
|
||||
|
||||
export async function updateProductAction(_prevState: unknown, formData: FormData) {
|
||||
export async function updateProductFormAction(_prevState: unknown, formData: FormData) {
|
||||
const session = await getSession()
|
||||
if (!session.userId) return { error: 'Niet ingelogd' }
|
||||
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { prisma } from '@/lib/prisma'
|
|||
import { ProductForm } from '@/components/products/product-form'
|
||||
import { ArchiveProductButton } from '@/components/products/archive-product-button'
|
||||
import { TeamManager } from '@/components/products/team-manager'
|
||||
import { updateProductAction } from '@/actions/products'
|
||||
import { updateProductFormAction } from '@/actions/products'
|
||||
import { AutoPrToggle } from '@/components/products/auto-pr-toggle'
|
||||
import Link from 'next/link'
|
||||
|
||||
|
|
@ -44,7 +44,7 @@ export default async function ProductSettingsPage({ params }: Props) {
|
|||
</div>
|
||||
|
||||
<ProductForm
|
||||
action={updateProductAction}
|
||||
action={updateProductFormAction}
|
||||
submitLabel="Opslaan"
|
||||
defaultValues={{
|
||||
id: product.id,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { getIronSession } from 'iron-session'
|
|||
import { redirect } from 'next/navigation'
|
||||
import { SessionData, sessionOptions } from '@/lib/session'
|
||||
import { ProductForm } from '@/components/products/product-form'
|
||||
import { createProductAction } from '@/actions/products'
|
||||
import { createProductFormAction } from '@/actions/products'
|
||||
|
||||
export default async function NewProductPage() {
|
||||
const session = await getIronSession<SessionData>(await cookies(), sessionOptions)
|
||||
|
|
@ -12,7 +12,7 @@ export default async function NewProductPage() {
|
|||
return (
|
||||
<div className="p-6 max-w-2xl mx-auto w-full">
|
||||
<h1 className="text-xl font-medium text-foreground mb-6">Nieuw product</h1>
|
||||
<ProductForm action={createProductAction} submitLabel="Product aanmaken" />
|
||||
<ProductForm action={createProductFormAction} submitLabel="Product aanmaken" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue