diff --git a/__tests__/actions/sprints-cascade.test.ts b/__tests__/actions/sprints-cascade.test.ts new file mode 100644 index 0000000..b302716 --- /dev/null +++ b/__tests__/actions/sprints-cascade.test.ts @@ -0,0 +1,238 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +vi.mock('next/cache', () => ({ revalidatePath: 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/product-access', () => ({ + productAccessFilter: vi.fn().mockReturnValue({}), + getAccessibleProduct: vi.fn().mockResolvedValue({ id: 'product-1' }), +})) +vi.mock('@/lib/prisma', () => ({ + prisma: { + sprint: { + findFirst: vi.fn(), + update: vi.fn(), + }, + story: { + findMany: vi.fn(), + update: vi.fn(), + }, + pbi: { + findMany: vi.fn(), + update: vi.fn(), + }, + $transaction: vi.fn().mockResolvedValue([]), + }, +})) + +import { prisma } from '@/lib/prisma' +import { completeSprintAction } from '@/actions/sprints' + +const mockPrisma = prisma as unknown as { + sprint: { + findFirst: ReturnType + update: ReturnType + } + story: { + findMany: ReturnType + update: ReturnType + } + pbi: { + findMany: ReturnType + update: ReturnType + } + $transaction: ReturnType +} + +const SPRINT = { id: 'sprint-1', product_id: 'product-1', status: 'ACTIVE' } + +beforeEach(() => { + vi.clearAllMocks() + mockPrisma.sprint.findFirst.mockResolvedValue(SPRINT) + mockPrisma.$transaction.mockResolvedValue([]) +}) + +describe('completeSprintAction β€” PBI auto-DONE cascade', () => { + it('marks PBI DONE when all its stories are decided DONE', async () => { + mockPrisma.story.findMany.mockResolvedValue([ + { id: 'story-a', pbi_id: 'pbi-1' }, + { id: 'story-b', pbi_id: 'pbi-1' }, + ]) + mockPrisma.pbi.findMany.mockResolvedValue([ + { + id: 'pbi-1', + stories: [ + { id: 'story-a', status: 'IN_SPRINT' }, + { id: 'story-b', status: 'IN_SPRINT' }, + ], + }, + ]) + + const result = await completeSprintAction('sprint-1', { + 'story-a': 'DONE', + 'story-b': 'DONE', + }) + + expect(result).toEqual({ success: true }) + expect(mockPrisma.pbi.update).toHaveBeenCalledTimes(1) + expect(mockPrisma.pbi.update).toHaveBeenCalledWith({ + where: { id: 'pbi-1' }, + data: { status: 'DONE' }, + }) + }) + + it('does not mark PBI DONE when a story is decided OPEN', async () => { + mockPrisma.story.findMany.mockResolvedValue([ + { id: 'story-a', pbi_id: 'pbi-1' }, + { id: 'story-b', pbi_id: 'pbi-1' }, + ]) + mockPrisma.pbi.findMany.mockResolvedValue([ + { + id: 'pbi-1', + stories: [ + { id: 'story-a', status: 'IN_SPRINT' }, + { id: 'story-b', status: 'IN_SPRINT' }, + ], + }, + ]) + + const result = await completeSprintAction('sprint-1', { + 'story-a': 'DONE', + 'story-b': 'OPEN', + }) + + expect(result).toEqual({ success: true }) + expect(mockPrisma.pbi.update).not.toHaveBeenCalled() + }) + + it('does not mark PBI DONE when it has stories outside this sprint that are not DONE', async () => { + mockPrisma.story.findMany.mockResolvedValue([ + { id: 'story-a', pbi_id: 'pbi-1' }, + ]) + mockPrisma.pbi.findMany.mockResolvedValue([ + { + id: 'pbi-1', + stories: [ + { id: 'story-a', status: 'IN_SPRINT' }, + { id: 'story-b', status: 'OPEN' }, + ], + }, + ]) + + const result = await completeSprintAction('sprint-1', { + 'story-a': 'DONE', + }) + + expect(result).toEqual({ success: true }) + expect(mockPrisma.pbi.update).not.toHaveBeenCalled() + }) + + it('marks PBI DONE when its in-sprint stories are DONE and out-of-sprint stories are already DONE', async () => { + mockPrisma.story.findMany.mockResolvedValue([ + { id: 'story-a', pbi_id: 'pbi-1' }, + ]) + mockPrisma.pbi.findMany.mockResolvedValue([ + { + id: 'pbi-1', + stories: [ + { id: 'story-a', status: 'IN_SPRINT' }, + { id: 'story-b', status: 'DONE' }, + ], + }, + ]) + + const result = await completeSprintAction('sprint-1', { + 'story-a': 'DONE', + }) + + expect(result).toEqual({ success: true }) + expect(mockPrisma.pbi.update).toHaveBeenCalledWith({ + where: { id: 'pbi-1' }, + data: { status: 'DONE' }, + }) + }) + + it('skips PBIs that are already DONE (promote-only)', async () => { + mockPrisma.story.findMany.mockResolvedValue([ + { id: 'story-a', pbi_id: 'pbi-1' }, + ]) + // pbi.findMany filters via { status: { not: 'DONE' } } in the action, + // so an already-DONE PBI just doesn't appear in candidatePbis. + mockPrisma.pbi.findMany.mockResolvedValue([]) + + const result = await completeSprintAction('sprint-1', { + 'story-a': 'DONE', + }) + + expect(result).toEqual({ success: true }) + expect(mockPrisma.pbi.update).not.toHaveBeenCalled() + expect(mockPrisma.pbi.findMany).toHaveBeenCalledWith({ + where: { id: { in: ['pbi-1'] }, status: { not: 'DONE' } }, + select: { id: true, stories: { select: { id: true, status: true } } }, + }) + }) + + it('cascades across multiple PBIs in one sprint close', async () => { + mockPrisma.story.findMany.mockResolvedValue([ + { id: 'story-a', pbi_id: 'pbi-1' }, + { id: 'story-b', pbi_id: 'pbi-2' }, + ]) + mockPrisma.pbi.findMany.mockResolvedValue([ + { id: 'pbi-1', stories: [{ id: 'story-a', status: 'IN_SPRINT' }] }, + { id: 'pbi-2', stories: [{ id: 'story-b', status: 'IN_SPRINT' }] }, + ]) + + const result = await completeSprintAction('sprint-1', { + 'story-a': 'DONE', + 'story-b': 'DONE', + }) + + expect(result).toEqual({ success: true }) + expect(mockPrisma.pbi.update).toHaveBeenCalledTimes(2) + expect(mockPrisma.pbi.update).toHaveBeenCalledWith({ + where: { id: 'pbi-1' }, + data: { status: 'DONE' }, + }) + expect(mockPrisma.pbi.update).toHaveBeenCalledWith({ + where: { id: 'pbi-2' }, + data: { status: 'DONE' }, + }) + }) + + it('does not include 0-story PBIs in cascade', async () => { + mockPrisma.story.findMany.mockResolvedValue([ + { id: 'story-a', pbi_id: 'pbi-1' }, + ]) + mockPrisma.pbi.findMany.mockResolvedValue([ + { id: 'pbi-1', stories: [] }, + ]) + + const result = await completeSprintAction('sprint-1', { + 'story-a': 'DONE', + }) + + expect(result).toEqual({ success: true }) + expect(mockPrisma.pbi.update).not.toHaveBeenCalled() + }) + + it('blocks sprint close for demo users', async () => { + const { getIronSession } = await import('iron-session') + ;(getIronSession as ReturnType).mockResolvedValueOnce({ + userId: 'user-demo', + isDemo: true, + }) + + const result = await completeSprintAction('sprint-1', { + 'story-a': 'DONE', + }) + + expect(result).toEqual({ error: 'Niet beschikbaar in demo-modus' }) + expect(mockPrisma.$transaction).not.toHaveBeenCalled() + expect(mockPrisma.pbi.update).not.toHaveBeenCalled() + }) +}) diff --git a/__tests__/lib/task-status.test.ts b/__tests__/lib/task-status.test.ts new file mode 100644 index 0000000..870b632 --- /dev/null +++ b/__tests__/lib/task-status.test.ts @@ -0,0 +1,85 @@ +import { describe, it, expect } from 'vitest' + +import { + taskStatusToApi, + taskStatusFromApi, + storyStatusToApi, + storyStatusFromApi, + pbiStatusToApi, + pbiStatusFromApi, + TASK_STATUS_API_VALUES, + STORY_STATUS_API_VALUES, + PBI_STATUS_API_VALUES, +} from '@/lib/task-status' + +describe('task-status mappers', () => { + describe('taskStatus', () => { + it('round-trips every API value', () => { + for (const api of TASK_STATUS_API_VALUES) { + const db = taskStatusFromApi(api) + expect(db).not.toBeNull() + expect(taskStatusToApi(db!)).toBe(api) + } + }) + + it('returns null for invalid input', () => { + expect(taskStatusFromApi('NOT_A_STATUS')).toBeNull() + }) + + it('is case-insensitive on the API side', () => { + expect(taskStatusFromApi('IN_PROGRESS')).toBe('IN_PROGRESS') + expect(taskStatusFromApi('In_Progress')).toBe('IN_PROGRESS') + }) + }) + + describe('storyStatus', () => { + it('round-trips every API value', () => { + for (const api of STORY_STATUS_API_VALUES) { + const db = storyStatusFromApi(api) + expect(db).not.toBeNull() + expect(storyStatusToApi(db!)).toBe(api) + } + }) + + it('returns null for invalid input', () => { + expect(storyStatusFromApi('archived')).toBeNull() + }) + }) + + describe('pbiStatus', () => { + it('round-trips every API value', () => { + for (const api of PBI_STATUS_API_VALUES) { + const db = pbiStatusFromApi(api) + expect(db).not.toBeNull() + expect(pbiStatusToApi(db!)).toBe(api) + } + }) + + it('maps DB to lowercase API', () => { + expect(pbiStatusToApi('READY')).toBe('ready') + expect(pbiStatusToApi('BLOCKED')).toBe('blocked') + expect(pbiStatusToApi('DONE')).toBe('done') + }) + + it('maps API to UPPER_SNAKE DB', () => { + expect(pbiStatusFromApi('ready')).toBe('READY') + expect(pbiStatusFromApi('blocked')).toBe('BLOCKED') + expect(pbiStatusFromApi('done')).toBe('DONE') + }) + + it('is case-insensitive on the API side', () => { + expect(pbiStatusFromApi('READY')).toBe('READY') + expect(pbiStatusFromApi('Blocked')).toBe('BLOCKED') + }) + + it('returns null for invalid input', () => { + expect(pbiStatusFromApi('archived')).toBeNull() + expect(pbiStatusFromApi('')).toBeNull() + expect(pbiStatusFromApi('todo')).toBeNull() + }) + + it('exposes exactly three API values', () => { + expect(PBI_STATUS_API_VALUES).toEqual(['ready', 'blocked', 'done']) + }) + }) +}) diff --git a/actions/pbis.ts b/actions/pbis.ts index b0bce8c..f2221e8 100644 --- a/actions/pbis.ts +++ b/actions/pbis.ts @@ -9,6 +9,7 @@ import { SessionData, sessionOptions } from '@/lib/session' import { getAccessibleProduct } from '@/lib/product-access' import { isValidCode, MAX_CODE_LENGTH, normalizeCode } from '@/lib/code' import { createWithCodeRetry, generateNextPbiCode } from '@/lib/code-server' +import { pbiStatusFromApi } from '@/lib/task-status' async function getSession() { return getIronSession(await cookies(), sessionOptions) @@ -16,12 +17,15 @@ async function getSession() { const codeField = z.string().max(MAX_CODE_LENGTH).optional() +const statusField = z.enum(['ready', 'blocked', 'done']).optional() + const createPbiSchema = z.object({ productId: z.string(), code: codeField, title: z.string().min(1, 'Titel is verplicht').max(200), description: z.string().max(2000).optional(), priority: z.coerce.number().int().min(1).max(4), + status: statusField, }) const updatePbiSchema = z.object({ @@ -30,6 +34,7 @@ const updatePbiSchema = z.object({ title: z.string().min(1, 'Titel is verplicht').max(200), description: z.string().max(2000).optional(), priority: z.coerce.number().int().min(1).max(4), + status: statusField, }) export async function createPbiAction(_prevState: unknown, formData: FormData) { @@ -43,6 +48,7 @@ export async function createPbiAction(_prevState: unknown, formData: FormData) { title: formData.get('title'), description: formData.get('description') || undefined, priority: formData.get('priority'), + status: (formData.get('status') as string) || undefined, }) if (!parsed.success) return { error: parsed.error.flatten().fieldErrors } @@ -64,6 +70,8 @@ export async function createPbiAction(_prevState: unknown, formData: FormData) { }) const sort_order = (last?.sort_order ?? 0) + 1.0 + const status = parsed.data.status ? pbiStatusFromApi(parsed.data.status) ?? undefined : undefined + const insert = (code: string | null) => prisma.pbi.create({ data: { @@ -73,6 +81,7 @@ export async function createPbiAction(_prevState: unknown, formData: FormData) { description: parsed.data.description ?? null, priority: parsed.data.priority, sort_order, + ...(status ? { status } : {}), }, }) @@ -103,6 +112,7 @@ export async function updatePbiAction(_prevState: unknown, formData: FormData) { title: formData.get('title'), description: formData.get('description') || undefined, priority: formData.get('priority'), + status: (formData.get('status') as string) || undefined, }) if (!parsed.success) return { error: parsed.error.flatten().fieldErrors } @@ -125,6 +135,8 @@ export async function updatePbiAction(_prevState: unknown, formData: FormData) { if (dup) return { error: { code: ['Deze code is al in gebruik binnen dit product'] } } } + const status = parsed.data.status ? pbiStatusFromApi(parsed.data.status) ?? undefined : undefined + await prisma.pbi.update({ where: { id: parsed.data.id }, data: { @@ -132,6 +144,7 @@ export async function updatePbiAction(_prevState: unknown, formData: FormData) { title: parsed.data.title, description: parsed.data.description ?? null, priority: parsed.data.priority, + ...(status ? { status } : {}), }, }) diff --git a/actions/sprints.ts b/actions/sprints.ts index ed8857d..7eb7229 100644 --- a/actions/sprints.ts +++ b/actions/sprints.ts @@ -171,10 +171,28 @@ export async function completeSprintAction( const stories = await prisma.story.findMany({ where: { id: { in: storyIds }, sprint_id: sprintId, product_id: sprint.product_id }, - select: { id: true }, + select: { id: true, pbi_id: true }, }) if (stories.length !== storyIds.length) return { error: 'Ongeldige Sprint-afronding' } + const affectedPbiIds = [...new Set(stories.map((s) => s.pbi_id))] + const candidatePbis = await prisma.pbi.findMany({ + where: { id: { in: affectedPbiIds }, status: { not: 'DONE' } }, + select: { id: true, stories: { select: { id: true, status: true } } }, + }) + + const decisionByStoryId = new Map(entries) + const pbiIdsToMarkDone = candidatePbis + .filter( + (pbi) => + pbi.stories.length > 0 && + pbi.stories.every((s) => { + const next = decisionByStoryId.get(s.id) ?? s.status + return next === 'DONE' + }) + ) + .map((p) => p.id) + await prisma.$transaction([ ...entries.map(([storyId, status]) => prisma.story.update({ @@ -185,6 +203,9 @@ export async function completeSprintAction( }, }) ), + ...pbiIdsToMarkDone.map((id) => + prisma.pbi.update({ where: { id }, data: { status: 'DONE' } }) + ), prisma.sprint.update({ where: { id: sprintId }, data: { status: 'COMPLETED', completed_at: new Date() }, diff --git a/app/(app)/products/[id]/page.tsx b/app/(app)/products/[id]/page.tsx index b6e110b..426cd03 100644 --- a/app/(app)/products/[id]/page.tsx +++ b/app/(app)/products/[id]/page.tsx @@ -2,6 +2,7 @@ import { notFound, redirect } from 'next/navigation' import { getSession } from '@/lib/auth' import { getAccessibleProduct } from '@/lib/product-access' import { prisma } from '@/lib/prisma' +import { pbiStatusToApi } from '@/lib/task-status' import { SplitPane } from '@/components/split-pane/split-pane' import { PbiList } from '@/components/backlog/pbi-list' import { StoryPanel } from '@/components/backlog/story-panel' @@ -94,7 +95,7 @@ export default async function ProductBacklogPage({ params }: Props) { left={ ({ id: p.id, code: p.code, title: p.title, priority: p.priority, description: p.description, created_at: p.created_at }))} + pbis={pbis.map((p: (typeof pbis)[number]) => ({ id: p.id, code: p.code, title: p.title, priority: p.priority, description: p.description, created_at: p.created_at, status: pbiStatusToApi(p.status) }))} isDemo={isDemo} /> } diff --git a/components/backlog/pbi-dialog.tsx b/components/backlog/pbi-dialog.tsx index b93de29..6af393a 100644 --- a/components/backlog/pbi-dialog.tsx +++ b/components/backlog/pbi-dialog.tsx @@ -16,7 +16,9 @@ import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Textarea } from '@/components/ui/textarea' import { PrioritySelect } from '@/components/shared/priority-select' +import { PbiStatusSelect } from '@/components/shared/pbi-status-select' import { createPbiAction, updatePbiAction } from '@/actions/pbis' +import type { PbiStatusApi } from '@/lib/task-status' export interface PbiDialogPbi { id: string @@ -24,6 +26,7 @@ export interface PbiDialogPbi { priority: number description?: string | null code?: string | null + status?: PbiStatusApi } type CreateState = { mode: 'create'; productId: string; defaultPriority?: number } @@ -51,11 +54,16 @@ export function PbiDialog({ state, onClose }: PbiDialogProps) { const initialPriority = isEdit ? pbi!.priority : (state?.defaultPriority ?? 2) const [priority, setPriority] = useState(initialPriority) - // Sync priority when dialog opens for a different PBI or switches create/edit mode + const initialStatus: PbiStatusApi = isEdit ? (pbi!.status ?? 'ready') : 'ready' + const [status, setStatus] = useState(initialStatus) + + // Sync priority + status when dialog opens for a different PBI or switches create/edit mode useEffect(() => { if (state) { // eslint-disable-next-line react-hooks/set-state-in-effect setPriority(isEdit ? (state as EditState).pbi.priority : ((state as CreateState).defaultPriority ?? 2)) + + setStatus(isEdit ? ((state as EditState).pbi.status ?? 'ready') : 'ready') } }, [state, isEdit]) @@ -105,6 +113,7 @@ export function PbiDialog({ state, onClose }: PbiDialogProps) { {isEdit && } {!isEdit && } +
@@ -135,9 +144,15 @@ export function PbiDialog({ state, onClose }: PbiDialogProps) {
-
- - +
+
+ + +
+
+ + +
diff --git a/components/backlog/pbi-list.tsx b/components/backlog/pbi-list.tsx index 588706a..9586fd8 100644 --- a/components/backlog/pbi-list.tsx +++ b/components/backlog/pbi-list.tsx @@ -23,7 +23,7 @@ import { CSS } from '@dnd-kit/utilities' import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { PanelNavBar } from '@/components/shared/panel-nav-bar' import { useSelectionStore } from '@/stores/selection-store' import { usePlannerStore } from '@/stores/planner-store' @@ -33,6 +33,8 @@ import { cn } from '@/lib/utils' import { PbiDialog, type PbiDialogState } from './pbi-dialog' import { BacklogCard } from './backlog-card' import { PRIORITY_COLORS } from '@/components/shared/priority-select' +import { PBI_STATUS_LABELS, PBI_STATUS_COLORS } from '@/components/shared/pbi-status-select' +import type { PbiStatusApi } from '@/lib/task-status' const PRIORITY_LABELS: Record = { 1: 'Kritiek', @@ -44,6 +46,62 @@ const PRIORITY_LABELS: Record = { type SortMode = 'priority' | 'code' | 'date' +const SORT_OPTIONS: Array<{ value: SortMode; label: string }> = [ + { value: 'priority', label: 'Prioriteit' }, + { value: 'code', label: 'Code' }, + { value: 'date', label: 'Datum' }, +] + +const PRIORITY_OPTIONS: Array<{ value: number | 'all'; label: string }> = [ + { value: 'all', label: 'Alle' }, + { value: 1, label: 'Kritiek' }, + { value: 2, label: 'Hoog' }, + { value: 3, label: 'Gemiddeld' }, + { value: 4, label: 'Laag' }, +] + +const STATUS_OPTIONS: Array<{ value: PbiStatusApi | 'all'; label: string }> = [ + { value: 'all', label: 'Alle' }, + { value: 'ready', label: 'Klaar' }, + { value: 'blocked', label: 'Geblokkeerd' }, + { value: 'done', label: 'Afgerond' }, +] + +function FilterPills({ + label, + options, + value, + onChange, +}: { + label: string + options: Array<{ value: T; label: string }> + value: T + onChange: (v: T) => void +}) { + return ( +
+

{label}

+
+ {options.map((opt) => ( + + ))} +
+
+ ) +} + interface Pbi { id: string code: string | null @@ -51,6 +109,7 @@ interface Pbi { priority: number description?: string | null created_at: Date + status: PbiStatusApi } interface PbiListProps { @@ -100,6 +159,11 @@ function SortablePbiRow({ aria-selected={isSelected} onClick={onSelect} onKeyDown={(e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onSelect() } }} + badge={ + + {PBI_STATUS_LABELS[pbi.status]} + + } actions={!isDemo ? (
)} - - + {filterStatus !== 'all' && ( + + )} + + + {`Filters${activeFilterCount > 0 ? ` (${activeFilterCount})` : ''}`} + + } + /> + + + + +
+ +
+
+
{!isDemo && (