Scrum4Me/actions/sprints.ts
Janpeter Visser 8a9fb9d32b
M12 / ST-1109: PBI krijgt een status (Ready / Blocked / Done) (#16)
* feat(ST-1109.2): add PbiStatus enum and status field to Pbi model

- New PbiStatus enum (READY/BLOCKED/DONE) for PBI lifecycle tracking
- Pbi.status PbiStatus @default(READY)
- Index on (product_id, status) for filter queries
- Migration: 20260429150643_add_pbi_status
- ERD regenerated via prisma generate

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ST-1109.3): add PBI status API mappers

- pbiStatusToApi / pbiStatusFromApi following same pattern as task/story
- PbiStatusApi type derived from PBI_DB_TO_API
- PBI_STATUS_API_VALUES export for downstream Zod schemas
- Lowercase API surface (ready/blocked/done), DB stays UPPER_SNAKE

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ST-1109.4): support status in PBI create/update actions

- Optional status field in Zod schemas (lowercase API: ready/blocked/done)
- pbiStatusFromApi() maps to DB enum before persistence
- Status omitted on create => Prisma @default(READY) takes effect
- Update preserves existing status when not provided
- Demo-check unchanged

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ST-1109.5): auto-mark PBI as DONE when all its stories are DONE on sprint close

Extends completeSprintAction's $transaction with PBI status cascade:
- Pre-transaction: identify PBIs touched by this close (via stories.pbi_id),
  fetch each with all its stories
- Skip PBIs already DONE; skip PBIs with 0 stories
- Mark PBI DONE only when every story (post-decision) is DONE — stories
  outside the sprint are evaluated against their current DB status
- Promote-only: never demotes a PBI that becomes "incomplete" again

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ST-1109.6): add Popover primitive (base-ui wrapper)

- Mirrors the Tooltip pattern: render-prop composition, data-slot attrs
- Exports Popover (Root), PopoverTrigger, PopoverContent (Portal+Positioner+Popup)
- MD3 popover/popover-foreground tokens, animated open/close states
- Will be used to consolidate the backlog filter UI in ST-1109.8

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ST-1109.7): add status select to PBI dialog

- New components/shared/pbi-status-select.tsx mirrors PrioritySelect:
  PBI_STATUS_LABELS (NL), PBI_STATUS_COLORS, PbiStatusSelect component
- Reuses existing --status-todo/blocked/done MD3 tokens
- PbiDialog: status state with sync-on-open; default 'ready' for create,
  pbi.status for edit; hidden input submits lowercase API value
- Priority + Status sit side-by-side in 2-col grid
- PbiDialogPbi.status is optional; pbi-list.tsx will populate in ST-1109.8

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ST-1109.8): show PBI status badge and consolidate filters into popover

- Pbi.status (lowercase API) flows from page.tsx via pbiStatusToApi
- Status badge rendered in BacklogCard's badge slot using PBI_STATUS_COLORS
- Two old Select dropdowns replaced by single Popover with three pill-button
  sections (Sorteren, Prioriteit, Status) and a "Wis filters" footer
- Filter trigger shows active count "(n)" badge in label
- Active priority/status filters still surface as dismissable chips next to
  the trigger for at-a-glance feedback
- onEdit passes the full Pbi (incl. status) so the dialog opens with the
  correct current status — closes the data flow loop opened in ST-1109.7

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(ST-1109.9): cover PBI status mappers and sprint-close cascade

- __tests__/lib/task-status.test.ts: 11 cases incl. round-trip + invalid
  input for task/story/pbi mappers; verifies PBI_STATUS_API_VALUES shape
- __tests__/actions/sprints-cascade.test.ts: 8 cases for completeSprintAction:
  promote on all-DONE, no promote on partial OPEN, respect out-of-sprint
  story status, skip already-DONE PBIs, multi-PBI cascade, 0-story guard,
  demo-user block
- Full vitest run: 170/170 green across 21 files

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(ST-1109.10): document PbiStatus enum, sprint-close cascade, and filter UI

- docs/scrum4me-architecture.md: pbis-table updated with status column +
  index; PbiStatus enum + Pbi model in the Prisma schema sample;
  cascade-on-sprint-close rule documented inline
- docs/scrum4me-styling.md: short note pointing to PBI_STATUS_LABELS /
  PBI_STATUS_COLORS in components/shared/pbi-status-select.tsx so future
  components don't ad-hoc-copy the color map
- docs/plans/ST-1109-pbi-status.md: in-repo mirror of the approved plan
  (per feedback_plan_location memory) with cascade pseudo-code and
  end-to-end verification checklist

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ST-1109.11): persist backlog filters in localStorage

Filters reset op reload was verwarrend. Nu net als sortMode:
- scrum4me:pbi_filter_priority — 'all' | '1' | '2' | '3' | '4'
- scrum4me:pbi_filter_status — 'all' | 'ready' | 'blocked' | 'done'

useState-init met SSR-guard; ongeldige waarden vallen terug op 'all'.
Wis filters reset alle drie de keys correct (sortMode -> 'priority',
beide filters -> 'all'), waardoor de localStorage-staat consistent wordt.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 17:52:34 +02:00

218 lines
7.5 KiB
TypeScript

'use server'
import { revalidatePath } from 'next/cache'
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 { getAccessibleProduct, productAccessFilter } from '@/lib/product-access'
async function getSession() {
return getIronSession<SessionData>(await cookies(), sessionOptions)
}
function hasDuplicateIds(ids: string[]) {
return new Set(ids).size !== ids.length
}
export async function createSprintAction(_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 = z.object({
productId: z.string(),
sprint_goal: z.string().min(1, 'Sprint Goal is verplicht').max(500),
}).safeParse({
productId: formData.get('productId'),
sprint_goal: formData.get('sprint_goal'),
})
if (!parsed.success) return { error: parsed.error.flatten().fieldErrors }
const product = await getAccessibleProduct(parsed.data.productId, session.userId)
if (!product) return { error: 'Product niet gevonden' }
const existing = await prisma.sprint.findFirst({
where: { product_id: parsed.data.productId, status: 'ACTIVE' },
})
if (existing) return { error: 'Er is al een actieve Sprint voor dit product', sprintId: existing.id }
const sprint = await prisma.sprint.create({
data: {
product_id: parsed.data.productId,
sprint_goal: parsed.data.sprint_goal,
status: 'ACTIVE',
},
})
revalidatePath(`/products/${parsed.data.productId}`)
return { success: true, sprintId: sprint.id }
}
export async function updateSprintGoalAction(_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
const sprint_goal = formData.get('sprint_goal') as string
if (!sprint_goal?.trim()) return { error: 'Sprint Goal is verplicht' }
const sprint = await prisma.sprint.findFirst({
where: { id, product: productAccessFilter(session.userId) },
})
if (!sprint) return { error: 'Sprint niet gevonden' }
await prisma.sprint.update({ where: { id }, data: { sprint_goal } })
revalidatePath(`/products/${sprint.product_id}/sprint`)
return { success: true }
}
export async function addStoryToSprintAction(sprintId: string, storyId: string) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const sprint = await prisma.sprint.findFirst({
where: { id: sprintId, product: productAccessFilter(session.userId) },
})
if (!sprint) return { error: 'Sprint niet gevonden' }
const story = await prisma.story.findFirst({
where: { id: storyId, product: productAccessFilter(session.userId) },
})
if (!story) return { error: 'Story niet gevonden' }
if (story.product_id !== sprint.product_id) return { error: 'Story hoort niet bij deze Sprint' }
const last = await prisma.story.findFirst({
where: { sprint_id: sprintId },
orderBy: { sort_order: 'desc' },
})
await prisma.story.update({
where: { id: storyId },
data: { sprint_id: sprintId, status: 'IN_SPRINT', sort_order: (last?.sort_order ?? 0) + 1.0 },
})
revalidatePath(`/products/${sprint.product_id}/sprint`)
revalidatePath(`/products/${sprint.product_id}`)
return { success: true }
}
export async function removeStoryFromSprintAction(storyId: string) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const story = await prisma.story.findFirst({
where: { id: storyId, product: productAccessFilter(session.userId) },
include: { sprint: true },
})
if (!story) return { error: 'Story niet gevonden' }
await prisma.story.update({
where: { id: storyId },
data: { sprint_id: null, status: 'OPEN' },
})
revalidatePath(`/products/${story.product_id}/sprint`)
revalidatePath(`/products/${story.product_id}`)
return { success: true }
}
export async function reorderSprintStoriesAction(sprintId: string, orderedIds: string[]) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
if (hasDuplicateIds(orderedIds)) return { error: 'Ongeldige Sprint Backlog-volgorde' }
const sprint = await prisma.sprint.findFirst({
where: { id: sprintId, product: productAccessFilter(session.userId) },
})
if (!sprint) return { error: 'Sprint niet gevonden' }
const stories = await prisma.story.findMany({
where: { id: { in: orderedIds }, sprint_id: sprintId, product_id: sprint.product_id },
select: { id: true },
})
if (stories.length !== orderedIds.length) return { error: 'Ongeldige Sprint Backlog-volgorde' }
await prisma.$transaction(
orderedIds.map((id, i) =>
prisma.story.update({ where: { id }, data: { sort_order: i + 1.0 } })
)
)
revalidatePath(`/products/${sprint.product_id}/sprint`)
return { success: true }
}
export async function completeSprintAction(
sprintId: string,
decisions: Record<string, 'DONE' | 'OPEN'>
) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const sprint = await prisma.sprint.findFirst({
where: { id: sprintId, product: productAccessFilter(session.userId) },
})
if (!sprint) return { error: 'Sprint niet gevonden' }
const entries = Object.entries(decisions)
if (entries.some(([, status]) => status !== 'DONE' && status !== 'OPEN')) {
return { error: 'Ongeldige Sprint-afronding' }
}
const storyIds = entries.map(([storyId]) => storyId)
if (hasDuplicateIds(storyIds)) return { error: 'Ongeldige Sprint-afronding' }
const stories = await prisma.story.findMany({
where: { id: { in: storyIds }, sprint_id: sprintId, product_id: sprint.product_id },
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({
where: { id: storyId },
data: {
status,
sprint_id: status === 'OPEN' ? null : undefined,
},
})
),
...pbiIdsToMarkDone.map((id) =>
prisma.pbi.update({ where: { id }, data: { status: 'DONE' } })
),
prisma.sprint.update({
where: { id: sprintId },
data: { status: 'COMPLETED', completed_at: new Date() },
}),
])
revalidatePath(`/products/${sprint.product_id}`)
revalidatePath(`/products/${sprint.product_id}/sprint`)
return { success: true }
}