Scrum4Me/actions/products.ts
Janpeter Visser 88dca4102c
feat(M9): active product backlog — persistent active PB, NavBar splits, sprint card styling (#10)
* feat(tooling): extend backlog parser to support PBI-x milestone headers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(backlog): mark ST-801–806 as done

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(backlog): sorteer PBI's en stories op prio/code/datum, onthoud keuze in localStorage; vergroot sprint-afronden dialoog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-901): add user.active_product_id with FK to Product

- Nullable relation User → Product with onDelete: SetNull
- Index on active_product_id for join performance
- Migration: 20260427165329_add_user_active_product_id
- Install @tanstack/react-table (was missing from node_modules)
- Fix PRIORITY_COLORS ref removed in earlier refactor
- Note: User schema change affects vendor/scrum4me-mcp submodule — run prisma generate + tsc --noEmit there after merge

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: restore priority color on PBI filter pill

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-902): add setActiveProduct + clearActiveProduct server actions

- actions/active-product.ts: setActiveProductAction validates access via
  productAccessFilter, rejects archived products and demo users
- archiveProductAction: clears active_product_id for all affected users in transaction
- removeProductMemberAction: clears active_product_id for removed member
- leaveProductAction: clears active_product_id for leaving user

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-903): load active product in layout, replace cookie with DB lookup in solo

- layout.tsx: fetch active_product_id, resolve product, clear stale ref server-side
- NavBar: add activeProduct prop (rendering changes in ST-904)
- solo/page.tsx: redirect via user.active_product_id instead of lastProductId cookie
- proxy.ts: remove lastProductId cookie logic
- lib/cookies.ts: deleted (no longer used)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-904): split NavBar into 5 tabs with disabled-states and product-switcher dropdown

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-905): add Activeer button per product row in dashboard and product header

* feat(ST-906): redirect to dashboard with toast when active product becomes inaccessible

* feat(ST-907): tests for active-product actions and functional spec update for M9

* docs(M9): add implementation plan document and link from backlog

* feat: active PB indicator, Maak actief button and new product link in settings

* feat: apply priority-color card style to sprint story rows

* fix: move add-to-sprint click from entire card to + Toevoegen button

* feat: apply priority-color card style to sprint task rows

* fix(sprint-backlog): prevent text selection on PBI collapse button

* chore: bump version to 0.4.0 (M9 active product backlog)

* fix(landing): align logged-in nav left to match app NavBar

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 20:25:13 +02:00

252 lines
8.7 KiB
TypeScript

'use server'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { z } from 'zod'
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'
const productSchema = z.object({
name: z.string().min(1, 'Naam is verplicht').max(100, 'Naam mag maximaal 100 tekens bevatten'),
code: z
.string()
.max(MAX_CODE_LENGTH, `Code mag maximaal ${MAX_CODE_LENGTH} tekens bevatten`)
.optional(),
description: z.string().max(1000, 'Beschrijving mag maximaal 1000 tekens bevatten').optional(),
repo_url: z
.string()
.url('Voer een geldige URL in (inclusief https://)')
.optional()
.or(z.literal('')),
definition_of_done: z
.string()
.min(1, 'Definition of Done is verplicht')
.max(500, 'Definition of Done mag maximaal 500 tekens bevatten'),
})
async function getSession() {
return getIronSession<SessionData>(await cookies(), sessionOptions)
}
export async function createProductAction(_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' }
const parsed = productSchema.safeParse({
name: formData.get('name'),
code: (formData.get('code') as string) || undefined,
description: formData.get('description') || undefined,
repo_url: formData.get('repo_url') || undefined,
definition_of_done: formData.get('definition_of_done'),
})
if (!parsed.success) {
return { error: parsed.error.flatten().fieldErrors }
}
const code = normalizeCode(parsed.data.code)
if (code !== null && !isValidCode(code)) {
return { error: { code: ['Code mag alleen letters, cijfers, punten, koppeltekens of underscores bevatten'] } }
}
const existing = await prisma.product.findFirst({
where: { user_id: session.userId, name: parsed.data.name },
})
if (existing) return { error: { name: ['Een product met deze naam bestaat al'] } }
if (code) {
const dup = await prisma.product.findFirst({ where: { user_id: session.userId, code } })
if (dup) return { error: { code: ['Deze code is al in gebruik'] } }
}
const product = await prisma.product.create({
data: {
user_id: session.userId,
name: parsed.data.name,
code,
description: parsed.data.description ?? null,
repo_url: parsed.data.repo_url || null,
definition_of_done: parsed.data.definition_of_done,
},
})
redirect(`/products/${product.id}`)
}
export async function updateProductAction(_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' }
const id = formData.get('id') as string
if (!id) return { error: 'Product niet gevonden' }
const parsed = productSchema.safeParse({
name: formData.get('name'),
code: (formData.get('code') as string) || undefined,
description: formData.get('description') || undefined,
repo_url: formData.get('repo_url') || undefined,
definition_of_done: formData.get('definition_of_done'),
})
if (!parsed.success) {
return { error: parsed.error.flatten().fieldErrors }
}
const code = normalizeCode(parsed.data.code)
if (code !== null && !isValidCode(code)) {
return { error: { code: ['Code mag alleen letters, cijfers, punten, koppeltekens of underscores bevatten'] } }
}
// Verify ownership
const product = await prisma.product.findFirst({
where: { id, user_id: session.userId },
})
if (!product) return { error: 'Product niet gevonden' }
// Check unique name (excluding self)
const duplicate = await prisma.product.findFirst({
where: { user_id: session.userId, name: parsed.data.name, NOT: { id } },
})
if (duplicate) return { error: { name: ['Een product met deze naam bestaat al'] } }
if (code) {
const dupCode = await prisma.product.findFirst({
where: { user_id: session.userId, code, NOT: { id } },
})
if (dupCode) return { error: { code: ['Deze code is al in gebruik'] } }
}
await prisma.product.update({
where: { id },
data: {
name: parsed.data.name,
code,
description: parsed.data.description ?? null,
repo_url: parsed.data.repo_url || null,
definition_of_done: parsed.data.definition_of_done,
},
})
revalidatePath(`/products/${id}`)
revalidatePath('/dashboard')
return { success: true }
}
export async function archiveProductAction(id: string) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const product = await prisma.product.findFirst({
where: { id, user_id: session.userId },
})
if (!product) return { error: 'Product niet gevonden' }
await prisma.$transaction([
// Clear active_product_id for all users who had this product active
prisma.user.updateMany({
where: { active_product_id: id },
data: { active_product_id: null },
}),
prisma.product.update({ where: { id }, data: { archived: true } }),
])
revalidatePath('/', 'layout')
redirect('/dashboard')
}
export async function restoreProductAction(id: string) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const product = await prisma.product.findFirst({
where: { id, user_id: session.userId },
})
if (!product) return { error: 'Product niet gevonden' }
await prisma.product.update({ where: { id }, data: { archived: false } })
revalidatePath('/dashboard')
return { success: true }
}
export async function addProductMemberAction(_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' }
const productId = formData.get('productId') as string
const username = (formData.get('username') as string)?.trim().toLowerCase()
if (!username) return { error: 'Gebruikersnaam is verplicht' }
const product = await prisma.product.findFirst({ where: { id: productId, user_id: session.userId } })
if (!product) return { error: 'Product niet gevonden of geen eigenaar' }
const targetUser = await prisma.user.findUnique({
where: { username },
include: { roles: true },
})
if (!targetUser) return { error: 'Gebruiker niet gevonden' }
if (targetUser.is_demo) return { error: 'Demo-gebruiker kan niet worden toegevoegd' }
if (targetUser.id === session.userId) return { error: 'Je bent al eigenaar van dit product' }
const hasDeveloperRole = targetUser.roles.some(r => r.role === Role.DEVELOPER)
if (!hasDeveloperRole) return { error: `Gebruiker "${username}" heeft geen Developer-rol` }
const existing = await prisma.productMember.findUnique({
where: { product_id_user_id: { product_id: productId, user_id: targetUser.id } },
})
if (existing) return { error: 'Gebruiker is al lid van dit product' }
await prisma.productMember.create({
data: { product_id: productId, user_id: targetUser.id },
})
revalidatePath(`/products/${productId}/settings`)
return { success: true }
}
export async function removeProductMemberAction(productId: string, memberId: string) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const product = await prisma.product.findFirst({ where: { id: productId, user_id: session.userId } })
if (!product) return { error: 'Product niet gevonden of geen eigenaar' }
await prisma.$transaction([
prisma.user.updateMany({
where: { id: memberId, active_product_id: productId },
data: { active_product_id: null },
}),
prisma.productMember.deleteMany({ where: { product_id: productId, user_id: memberId } }),
])
revalidatePath(`/products/${productId}/settings`)
return { success: true }
}
export async function leaveProductAction(productId: string) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
await prisma.$transaction([
prisma.user.updateMany({
where: { id: session.userId, active_product_id: productId },
data: { active_product_id: null },
}),
prisma.productMember.deleteMany({ where: { product_id: productId, user_id: session.userId } }),
])
revalidatePath('/', 'layout')
revalidatePath('/settings')
return { success: true }
}