feat(PBI-74): product-workspace store skelet + test-infra (Story 1)
Skelet voor de nieuwe `product-workspace-store` die op termijn de gefragmenteerde
`backlog-store`/`planner-store`/`selection-store`/`product-store` vervangt. Deze
PR levert alleen het skelet + tests; UI-consumers worden in latere stories
omgezet.
- vitest naar jsdom + tests/setup.ts (MemoryStorage, default fetch-stub) — G6/G8
- stores/product-workspace/{types,store,selectors,restore}.ts — immer-middleware,
alle slices en acties (hydrate, setActive*, ensure*Loaded met activeRequestId-
guard, applyRealtimeEvent, resyncActiveScopes/loadedScopes, optimistic
mutations). Restore-wiring in setters volgt in Story 4 (T-857/T-858).
- selectors gebruiken module-level EMPTY refs (G1) en documenteren useShallow-
vereiste (G2)
- 34 nieuwe unit-tests dekken §Testing setup-checklist uit het ontwerp:
hydrateSnapshot, selection-cascade, applyRealtimeEvent (I/U/D + parent-move +
ander-product + unknown-entity → resync), delete-cleanup, race-safe loaders,
ensureTaskLoaded _detail-flag, resyncActiveScopes ensure-keten, restore-hints
read/write/clear, optimistic mutation rollback/settle/SSE-echo idempotent
- docs/api/rest-contract.md: audit-sectie met de vier ontbrekende
ensure*Loaded-endpoints (worden toegevoegd in Story 7 / T-870)
Refs: PBI-74, ST-1318, T-837..T-843
Bron-ontwerp: docs/plans/zustand-store-rearchitecture.md
Implementatieplan: docs/plans/zustand-workspace-store-implementation.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
0d126695db
commit
48d1e11a2a
12 changed files with 2247 additions and 1 deletions
117
__tests__/stores/product-workspace/restore.test.ts
Normal file
117
__tests__/stores/product-workspace/restore.test.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
clearHints,
|
||||
readHints,
|
||||
writePbiHint,
|
||||
writeProductHint,
|
||||
writeStoryHint,
|
||||
writeTaskHint,
|
||||
} from '@/stores/product-workspace/restore'
|
||||
|
||||
describe('readHints', () => {
|
||||
it('retourneert lege defaults wanneer localStorage leeg is', () => {
|
||||
const hints = readHints()
|
||||
expect(hints.lastActiveProductId).toBeNull()
|
||||
expect(hints.perProduct).toEqual({})
|
||||
})
|
||||
|
||||
it('herstelt hints uit localStorage', () => {
|
||||
localStorage.setItem(
|
||||
'product-workspace-hints',
|
||||
JSON.stringify({
|
||||
lastActiveProductId: 'p1',
|
||||
perProduct: { p1: { lastActivePbiId: 'pbi-1' } },
|
||||
}),
|
||||
)
|
||||
const hints = readHints()
|
||||
expect(hints.lastActiveProductId).toBe('p1')
|
||||
expect(hints.perProduct.p1.lastActivePbiId).toBe('pbi-1')
|
||||
})
|
||||
|
||||
it('valt terug op defaults bij ongeldige JSON', () => {
|
||||
localStorage.setItem('product-workspace-hints', '{not-json')
|
||||
const hints = readHints()
|
||||
expect(hints.lastActiveProductId).toBeNull()
|
||||
expect(hints.perProduct).toEqual({})
|
||||
})
|
||||
|
||||
it('valt terug op defaults bij verkeerde shape', () => {
|
||||
localStorage.setItem('product-workspace-hints', '"just a string"')
|
||||
const hints = readHints()
|
||||
expect(hints.perProduct).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeProductHint', () => {
|
||||
it('schrijft lastActiveProductId', () => {
|
||||
writeProductHint('p1')
|
||||
expect(readHints().lastActiveProductId).toBe('p1')
|
||||
})
|
||||
|
||||
it('overschrijft bestaande waarde', () => {
|
||||
writeProductHint('p1')
|
||||
writeProductHint('p2')
|
||||
expect(readHints().lastActiveProductId).toBe('p2')
|
||||
})
|
||||
|
||||
it('accepteert null om hint te wissen', () => {
|
||||
writeProductHint('p1')
|
||||
writeProductHint(null)
|
||||
expect(readHints().lastActiveProductId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('writePbiHint', () => {
|
||||
it('schrijft lastActivePbiId per productId', () => {
|
||||
writePbiHint('prod-1', 'pbi-a')
|
||||
writePbiHint('prod-2', 'pbi-b')
|
||||
const hints = readHints()
|
||||
expect(hints.perProduct['prod-1'].lastActivePbiId).toBe('pbi-a')
|
||||
expect(hints.perProduct['prod-2'].lastActivePbiId).toBe('pbi-b')
|
||||
})
|
||||
|
||||
it('null wist child story- en task-hints', () => {
|
||||
writePbiHint('prod-1', 'pbi-1')
|
||||
writeStoryHint('prod-1', 's-1')
|
||||
writeTaskHint('prod-1', 't-1')
|
||||
writePbiHint('prod-1', null)
|
||||
const hints = readHints()
|
||||
expect(hints.perProduct['prod-1'].lastActivePbiId).toBeNull()
|
||||
expect(hints.perProduct['prod-1'].lastActiveStoryId).toBeNull()
|
||||
expect(hints.perProduct['prod-1'].lastActiveTaskId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeStoryHint', () => {
|
||||
it('schrijft lastActiveStoryId per productId', () => {
|
||||
writeStoryHint('prod-1', 's-1')
|
||||
expect(readHints().perProduct['prod-1'].lastActiveStoryId).toBe('s-1')
|
||||
})
|
||||
|
||||
it('null wist child task-hint', () => {
|
||||
writeStoryHint('prod-1', 's-1')
|
||||
writeTaskHint('prod-1', 't-1')
|
||||
writeStoryHint('prod-1', null)
|
||||
expect(readHints().perProduct['prod-1'].lastActiveStoryId).toBeNull()
|
||||
expect(readHints().perProduct['prod-1'].lastActiveTaskId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeTaskHint', () => {
|
||||
it('schrijft lastActiveTaskId per productId', () => {
|
||||
writeTaskHint('prod-1', 't-1')
|
||||
expect(readHints().perProduct['prod-1'].lastActiveTaskId).toBe('t-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('clearHints', () => {
|
||||
it('verwijdert alle hints', () => {
|
||||
writeProductHint('p1')
|
||||
writePbiHint('p1', 'pbi-1')
|
||||
clearHints()
|
||||
const hints = readHints()
|
||||
expect(hints.lastActiveProductId).toBeNull()
|
||||
expect(hints.perProduct).toEqual({})
|
||||
})
|
||||
})
|
||||
689
__tests__/stores/product-workspace/store.test.ts
Normal file
689
__tests__/stores/product-workspace/store.test.ts
Normal file
|
|
@ -0,0 +1,689 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
|
||||
import type {
|
||||
BacklogPbi,
|
||||
BacklogStory,
|
||||
BacklogTask,
|
||||
ProductBacklogSnapshot,
|
||||
TaskDetail,
|
||||
} from '@/stores/product-workspace/types'
|
||||
|
||||
// G5: snapshot original actions on module-load; restore in beforeEach.
|
||||
// vi.fn-spies on actions could leak across tests otherwise.
|
||||
const originalActions = (() => {
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
return {
|
||||
hydrateSnapshot: s.hydrateSnapshot,
|
||||
setActiveProduct: s.setActiveProduct,
|
||||
setActivePbi: s.setActivePbi,
|
||||
setActiveStory: s.setActiveStory,
|
||||
setActiveTask: s.setActiveTask,
|
||||
ensureProductLoaded: s.ensureProductLoaded,
|
||||
ensurePbiLoaded: s.ensurePbiLoaded,
|
||||
ensureStoryLoaded: s.ensureStoryLoaded,
|
||||
ensureTaskLoaded: s.ensureTaskLoaded,
|
||||
applyRealtimeEvent: s.applyRealtimeEvent,
|
||||
resyncActiveScopes: s.resyncActiveScopes,
|
||||
resyncLoadedScopes: s.resyncLoadedScopes,
|
||||
applyOptimisticMutation: s.applyOptimisticMutation,
|
||||
rollbackMutation: s.rollbackMutation,
|
||||
settleMutation: s.settleMutation,
|
||||
setRealtimeStatus: s.setRealtimeStatus,
|
||||
}
|
||||
})()
|
||||
|
||||
function resetStore() {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = null
|
||||
s.context.activePbiId = null
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
s.entities.pbisById = {}
|
||||
s.entities.storiesById = {}
|
||||
s.entities.tasksById = {}
|
||||
s.relations.pbiIds = []
|
||||
s.relations.storyIdsByPbi = {}
|
||||
s.relations.taskIdsByStory = {}
|
||||
s.loading.loadedProductId = null
|
||||
s.loading.loadingProductId = null
|
||||
s.loading.loadedPbiIds = {}
|
||||
s.loading.loadedStoryIds = {}
|
||||
s.loading.loadedTaskIds = {}
|
||||
s.loading.activeRequestId = null
|
||||
s.sync.realtimeStatus = 'connecting'
|
||||
s.sync.lastEventAt = null
|
||||
s.sync.lastResyncAt = null
|
||||
s.sync.resyncReason = null
|
||||
s.pendingMutations = {}
|
||||
Object.assign(s, originalActions)
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetStore()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function makePbi(overrides: Partial<BacklogPbi> & { id: string }): BacklogPbi {
|
||||
return {
|
||||
id: overrides.id,
|
||||
code: overrides.code ?? overrides.id,
|
||||
title: overrides.title ?? `PBI ${overrides.id}`,
|
||||
priority: overrides.priority ?? 2,
|
||||
sort_order: overrides.sort_order ?? 1,
|
||||
description: overrides.description ?? null,
|
||||
created_at: overrides.created_at ?? new Date('2026-01-01'),
|
||||
status: overrides.status ?? 'ready',
|
||||
}
|
||||
}
|
||||
|
||||
function makeStory(overrides: Partial<BacklogStory> & { id: string; pbi_id: string }): BacklogStory {
|
||||
return {
|
||||
id: overrides.id,
|
||||
code: overrides.code ?? overrides.id,
|
||||
title: overrides.title ?? `Story ${overrides.id}`,
|
||||
description: overrides.description ?? null,
|
||||
acceptance_criteria: overrides.acceptance_criteria ?? null,
|
||||
priority: overrides.priority ?? 2,
|
||||
sort_order: overrides.sort_order ?? 1,
|
||||
status: overrides.status ?? 'open',
|
||||
pbi_id: overrides.pbi_id,
|
||||
sprint_id: overrides.sprint_id ?? null,
|
||||
created_at: overrides.created_at ?? new Date('2026-01-01'),
|
||||
}
|
||||
}
|
||||
|
||||
function makeTask(overrides: Partial<BacklogTask> & { id: string; story_id: string }): BacklogTask {
|
||||
return {
|
||||
id: overrides.id,
|
||||
title: overrides.title ?? `Task ${overrides.id}`,
|
||||
description: overrides.description ?? null,
|
||||
priority: overrides.priority ?? 2,
|
||||
sort_order: overrides.sort_order ?? 1,
|
||||
status: overrides.status ?? 'todo',
|
||||
story_id: overrides.story_id,
|
||||
created_at: overrides.created_at ?? new Date('2026-01-01'),
|
||||
}
|
||||
}
|
||||
|
||||
function snapshotWith(
|
||||
pbis: BacklogPbi[],
|
||||
storiesByPbi: Record<string, BacklogStory[]> = {},
|
||||
tasksByStory: Record<string, BacklogTask[]> = {},
|
||||
product?: { id: string; name: string },
|
||||
): ProductBacklogSnapshot {
|
||||
return { product, pbis, storiesByPbi, tasksByStory }
|
||||
}
|
||||
|
||||
// G7: mock fetch — never let it fall through to real network
|
||||
// G8: mockImplementation per call so each fetch gets a fresh Response
|
||||
function mockFetchSequence(
|
||||
responses: Array<unknown | ((url: string, init?: RequestInit) => unknown)>,
|
||||
) {
|
||||
let i = 0
|
||||
return vi.spyOn(globalThis, 'fetch').mockImplementation((async (url: string, init?: RequestInit) => {
|
||||
const r = responses[Math.min(i, responses.length - 1)]
|
||||
i += 1
|
||||
const body = typeof r === 'function' ? (r as (u: string, i?: RequestInit) => unknown)(url, init) : r
|
||||
return new Response(JSON.stringify(body ?? null), { status: 200 })
|
||||
}) as unknown as typeof fetch)
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// hydrateSnapshot
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('hydrateSnapshot', () => {
|
||||
it('vult entities en relations met gesorteerde id-lijsten', () => {
|
||||
const pbiA = makePbi({ id: 'pbi-a', priority: 2, sort_order: 2 })
|
||||
const pbiB = makePbi({ id: 'pbi-b', priority: 1, sort_order: 5 })
|
||||
const pbiC = makePbi({ id: 'pbi-c', priority: 2, sort_order: 1 })
|
||||
const storyB1 = makeStory({ id: 'st-1', pbi_id: 'pbi-b', sort_order: 2 })
|
||||
const storyB2 = makeStory({ id: 'st-2', pbi_id: 'pbi-b', sort_order: 1 })
|
||||
const taskA = makeTask({ id: 'tk-2', story_id: 'st-1', sort_order: 2 })
|
||||
const taskB = makeTask({ id: 'tk-1', story_id: 'st-1', sort_order: 1 })
|
||||
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
[pbiA, pbiB, pbiC],
|
||||
{ 'pbi-b': [storyB1, storyB2] },
|
||||
{ 'st-1': [taskA, taskB] },
|
||||
{ id: 'prod-1', name: 'Product 1' },
|
||||
),
|
||||
)
|
||||
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.entities.pbisById['pbi-a']).toBe(pbiA)
|
||||
expect(s.entities.pbisById['pbi-b']).toBe(pbiB)
|
||||
expect(s.entities.pbisById['pbi-c']).toBe(pbiC)
|
||||
// pbi-b heeft priority 1 (komt eerst), dan pbi-c (sort_order 1) en pbi-a (sort_order 2)
|
||||
expect(s.relations.pbiIds).toEqual(['pbi-b', 'pbi-c', 'pbi-a'])
|
||||
expect(s.relations.storyIdsByPbi['pbi-b']).toEqual(['st-2', 'st-1'])
|
||||
expect(s.relations.taskIdsByStory['st-1']).toEqual(['tk-1', 'tk-2'])
|
||||
expect(s.context.activeProduct).toEqual({ id: 'prod-1', name: 'Product 1' })
|
||||
expect(s.loading.loadedProductId).toBe('prod-1')
|
||||
})
|
||||
|
||||
it('reset bestaande entities en relations bij her-hydratie', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([makePbi({ id: 'old-pbi' })]),
|
||||
)
|
||||
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(['old-pbi'])
|
||||
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([makePbi({ id: 'new-pbi' })]),
|
||||
)
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.entities.pbisById['old-pbi']).toBeUndefined()
|
||||
expect(s.entities.pbisById['new-pbi']).toBeDefined()
|
||||
expect(s.relations.pbiIds).toEqual(['new-pbi'])
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// Selection cascade
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('selection cascade', () => {
|
||||
it('setActivePbi reset story+task; setActiveStory reset task', () => {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activePbiId = 'pbi-old'
|
||||
s.context.activeStoryId = 'st-old'
|
||||
s.context.activeTaskId = 'tk-old'
|
||||
})
|
||||
|
||||
useProductWorkspaceStore.getState().setActivePbi('pbi-new')
|
||||
let s = useProductWorkspaceStore.getState()
|
||||
expect(s.context.activePbiId).toBe('pbi-new')
|
||||
expect(s.context.activeStoryId).toBeNull()
|
||||
expect(s.context.activeTaskId).toBeNull()
|
||||
|
||||
useProductWorkspaceStore.setState((draft) => {
|
||||
draft.context.activeStoryId = 'st-old'
|
||||
draft.context.activeTaskId = 'tk-old'
|
||||
})
|
||||
useProductWorkspaceStore.getState().setActiveStory('st-new')
|
||||
s = useProductWorkspaceStore.getState()
|
||||
expect(s.context.activeStoryId).toBe('st-new')
|
||||
expect(s.context.activeTaskId).toBeNull()
|
||||
})
|
||||
|
||||
it('setActiveProduct(null) ruimt entities en relations op', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
[makePbi({ id: 'p-1' })],
|
||||
{ 'p-1': [makeStory({ id: 's-1', pbi_id: 'p-1' })] },
|
||||
{ 's-1': [makeTask({ id: 't-1', story_id: 's-1' })] },
|
||||
{ id: 'prod-1', name: 'Product 1' },
|
||||
),
|
||||
)
|
||||
|
||||
useProductWorkspaceStore.getState().setActiveProduct(null)
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.context.activeProduct).toBeNull()
|
||||
expect(s.context.activePbiId).toBeNull()
|
||||
expect(s.context.activeStoryId).toBeNull()
|
||||
expect(s.context.activeTaskId).toBeNull()
|
||||
expect(s.entities.pbisById).toEqual({})
|
||||
expect(s.entities.storiesById).toEqual({})
|
||||
expect(s.entities.tasksById).toEqual({})
|
||||
expect(s.relations.pbiIds).toEqual([])
|
||||
expect(s.relations.storyIdsByPbi).toEqual({})
|
||||
expect(s.relations.taskIdsByStory).toEqual({})
|
||||
expect(s.loading.loadedProductId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// applyRealtimeEvent
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('applyRealtimeEvent — pbi', () => {
|
||||
beforeEach(() => {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
})
|
||||
|
||||
it('I — voegt PBI toe en sorteert', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([makePbi({ id: 'a', priority: 2, sort_order: 5 })]),
|
||||
)
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'pbi',
|
||||
op: 'I',
|
||||
id: 'b',
|
||||
product_id: 'prod-1',
|
||||
code: 'B',
|
||||
title: 'New PBI',
|
||||
priority: 1,
|
||||
sort_order: 1,
|
||||
created_at: new Date('2026-02-01').toISOString(),
|
||||
status: 'ready',
|
||||
})
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.entities.pbisById['b']).toBeDefined()
|
||||
expect(s.relations.pbiIds).toEqual(['b', 'a'])
|
||||
})
|
||||
|
||||
it('I — idempotent voor bestaande id', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([makePbi({ id: 'a' })]),
|
||||
)
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'pbi',
|
||||
op: 'I',
|
||||
id: 'a',
|
||||
product_id: 'prod-1',
|
||||
title: 'mutated',
|
||||
})
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.entities.pbisById['a'].title).toBe('PBI a') // niet overschreven
|
||||
expect(s.relations.pbiIds).toEqual(['a'])
|
||||
})
|
||||
|
||||
it('U — patch + her-sorteert', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([
|
||||
makePbi({ id: 'a', priority: 2, sort_order: 1 }),
|
||||
makePbi({ id: 'b', priority: 2, sort_order: 2 }),
|
||||
]),
|
||||
)
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'pbi',
|
||||
op: 'U',
|
||||
id: 'b',
|
||||
product_id: 'prod-1',
|
||||
priority: 1,
|
||||
})
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.relations.pbiIds).toEqual(['b', 'a'])
|
||||
})
|
||||
|
||||
it('D — verwijdert PBI inclusief child stories en tasks', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
[makePbi({ id: 'p1' })],
|
||||
{ p1: [makeStory({ id: 's1', pbi_id: 'p1' })] },
|
||||
{ s1: [makeTask({ id: 't1', story_id: 's1' })] },
|
||||
),
|
||||
)
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'pbi',
|
||||
op: 'D',
|
||||
id: 'p1',
|
||||
product_id: 'prod-1',
|
||||
})
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.entities.pbisById['p1']).toBeUndefined()
|
||||
expect(s.entities.storiesById['s1']).toBeUndefined()
|
||||
expect(s.entities.tasksById['t1']).toBeUndefined()
|
||||
expect(s.relations.pbiIds).toEqual([])
|
||||
expect(s.relations.storyIdsByPbi['p1']).toBeUndefined()
|
||||
expect(s.relations.taskIdsByStory['s1']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('D — clear actieve PBI selectie als die onder de verwijderde PBI viel', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([makePbi({ id: 'p1' })]),
|
||||
)
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activePbiId = 'p1'
|
||||
s.context.activeStoryId = 's-x'
|
||||
s.context.activeTaskId = 't-x'
|
||||
})
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'pbi',
|
||||
op: 'D',
|
||||
id: 'p1',
|
||||
product_id: 'prod-1',
|
||||
})
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.context.activePbiId).toBeNull()
|
||||
expect(s.context.activeStoryId).toBeNull()
|
||||
expect(s.context.activeTaskId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRealtimeEvent — story parent-move', () => {
|
||||
beforeEach(() => {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
[makePbi({ id: 'p1' }), makePbi({ id: 'p2' })],
|
||||
{
|
||||
p1: [makeStory({ id: 's1', pbi_id: 'p1' })],
|
||||
p2: [],
|
||||
},
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('U met andere pbi_id verplaatst story naar nieuwe parent-lijst', () => {
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'story',
|
||||
op: 'U',
|
||||
id: 's1',
|
||||
product_id: 'prod-1',
|
||||
pbi_id: 'p2',
|
||||
})
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.relations.storyIdsByPbi['p1']).toEqual([])
|
||||
expect(s.relations.storyIdsByPbi['p2']).toEqual(['s1'])
|
||||
expect(s.entities.storiesById['s1'].pbi_id).toBe('p2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRealtimeEvent — task parent-move', () => {
|
||||
beforeEach(() => {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
[makePbi({ id: 'p1' })],
|
||||
{ p1: [makeStory({ id: 's1', pbi_id: 'p1' }), makeStory({ id: 's2', pbi_id: 'p1' })] },
|
||||
{
|
||||
s1: [makeTask({ id: 't1', story_id: 's1' })],
|
||||
s2: [],
|
||||
},
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('U met andere story_id verplaatst task naar nieuwe parent', () => {
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'task',
|
||||
op: 'U',
|
||||
id: 't1',
|
||||
product_id: 'prod-1',
|
||||
story_id: 's2',
|
||||
})
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.relations.taskIdsByStory['s1']).toEqual([])
|
||||
expect(s.relations.taskIdsByStory['s2']).toEqual(['t1'])
|
||||
expect(s.entities.tasksById['t1'].story_id).toBe('s2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRealtimeEvent — andere product genegeerd', () => {
|
||||
it('event met ander product_id raakt de store niet', () => {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([makePbi({ id: 'a' })]),
|
||||
)
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'pbi',
|
||||
op: 'I',
|
||||
id: 'b',
|
||||
product_id: 'prod-2',
|
||||
title: 'Other product',
|
||||
priority: 1,
|
||||
sort_order: 1,
|
||||
})
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.entities.pbisById['b']).toBeUndefined()
|
||||
expect(s.relations.pbiIds).toEqual(['a'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRealtimeEvent — unknown entity → resync trigger', () => {
|
||||
it('payload met entity buiten pbi/story/task triggert resyncActiveScopes', () => {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
const spy = vi.fn().mockResolvedValue(undefined)
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.resyncActiveScopes = spy as unknown as typeof s.resyncActiveScopes
|
||||
})
|
||||
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'comment',
|
||||
op: 'I',
|
||||
id: 'cm-1',
|
||||
product_id: 'prod-1',
|
||||
} as unknown as Record<string, unknown>)
|
||||
|
||||
expect(spy).toHaveBeenCalledWith('unknown-event')
|
||||
})
|
||||
|
||||
it('payload met type-veld (job/worker) triggert geen resync', () => {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
const spy = vi.fn().mockResolvedValue(undefined)
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.resyncActiveScopes = spy as unknown as typeof s.resyncActiveScopes
|
||||
})
|
||||
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
type: 'claude_job_status',
|
||||
job_id: 'job-1',
|
||||
product_id: 'prod-1',
|
||||
} as unknown as Record<string, unknown>)
|
||||
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// ensure*Loaded fetches + race-safe guard + sortering
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('ensureProductLoaded', () => {
|
||||
it('fetcht backlog snapshot en hydreert met sortering', async () => {
|
||||
const snapshot: ProductBacklogSnapshot = {
|
||||
product: { id: 'prod-1', name: 'Product 1' },
|
||||
pbis: [
|
||||
makePbi({ id: 'a', priority: 2, sort_order: 5 }),
|
||||
makePbi({ id: 'b', priority: 1, sort_order: 9 }),
|
||||
],
|
||||
storiesByPbi: {},
|
||||
tasksByStory: {},
|
||||
}
|
||||
const fetchSpy = mockFetchSequence([snapshot])
|
||||
|
||||
await useProductWorkspaceStore.getState().ensureProductLoaded('prod-1')
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'/api/products/prod-1/backlog',
|
||||
expect.objectContaining({ cache: 'no-store' }),
|
||||
)
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.relations.pbiIds).toEqual(['b', 'a'])
|
||||
expect(s.loading.loadedProductId).toBe('prod-1')
|
||||
expect(s.loading.loadedPbiIds['a']).toBe(true)
|
||||
expect(s.loading.loadedPbiIds['b']).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('race-safe ensure*Loaded — activeRequestId guard', () => {
|
||||
it('oudere in-flight ensurePbiLoaded mag nieuwere selectie niet overschrijven', async () => {
|
||||
let resolveOld: ((stories: BacklogStory[]) => void) | null = null
|
||||
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation((async (url: string) => {
|
||||
if (url === '/api/pbis/pbi-old/stories') {
|
||||
const stories = await new Promise<BacklogStory[]>((resolve) => {
|
||||
resolveOld = resolve
|
||||
})
|
||||
return new Response(JSON.stringify(stories), { status: 200 })
|
||||
}
|
||||
if (url === '/api/pbis/pbi-new/stories') {
|
||||
return new Response(
|
||||
JSON.stringify([makeStory({ id: 'new-st', pbi_id: 'pbi-new' })]),
|
||||
{ status: 200 },
|
||||
)
|
||||
}
|
||||
return new Response('null', { status: 200 })
|
||||
}) as unknown as typeof fetch)
|
||||
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
s.context.activePbiId = 'pbi-old'
|
||||
s.loading.activeRequestId = 'req-old'
|
||||
})
|
||||
const oldPromise = useProductWorkspaceStore
|
||||
.getState()
|
||||
.ensurePbiLoaded('pbi-old', 'req-old')
|
||||
|
||||
// gebruiker selecteert ondertussen pbi-new
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activePbiId = 'pbi-new'
|
||||
s.loading.activeRequestId = 'req-new'
|
||||
})
|
||||
await useProductWorkspaceStore.getState().ensurePbiLoaded('pbi-new', 'req-new')
|
||||
|
||||
expect(useProductWorkspaceStore.getState().entities.storiesById['new-st']).toBeDefined()
|
||||
|
||||
// resolve de oude fetch — guard moet de stale data weigeren
|
||||
resolveOld!([makeStory({ id: 'old-st', pbi_id: 'pbi-old' })])
|
||||
await oldPromise
|
||||
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.context.activePbiId).toBe('pbi-new')
|
||||
expect(s.entities.storiesById['old-st']).toBeUndefined()
|
||||
expect(s.entities.storiesById['new-st']).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureTaskLoaded — zet detail-flag', () => {
|
||||
it('verrijkt task naar TaskDetail met _detail: true', async () => {
|
||||
mockFetchSequence([
|
||||
{
|
||||
id: 't-1',
|
||||
title: 'Task 1',
|
||||
description: 'desc',
|
||||
priority: 1,
|
||||
sort_order: 1,
|
||||
status: 'todo',
|
||||
story_id: 's-1',
|
||||
created_at: new Date('2026-02-01').toISOString(),
|
||||
implementation_plan: 'detailed plan here',
|
||||
},
|
||||
])
|
||||
|
||||
await useProductWorkspaceStore.getState().ensureTaskLoaded('t-1')
|
||||
const task = useProductWorkspaceStore.getState().entities.tasksById['t-1'] as TaskDetail
|
||||
expect(task._detail).toBe(true)
|
||||
expect(task.implementation_plan).toBe('detailed plan here')
|
||||
expect(useProductWorkspaceStore.getState().loading.loadedTaskIds['t-1']).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// resyncActiveScopes
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('resyncActiveScopes', () => {
|
||||
it('triggert ensure-keten voor alle actieve scopes en zet sync velden', async () => {
|
||||
const fetchSpy = mockFetchSequence([
|
||||
// ensureProductLoaded
|
||||
{ product: { id: 'prod-1', name: 'P' }, pbis: [], storiesByPbi: {}, tasksByStory: {} },
|
||||
// ensurePbiLoaded
|
||||
[],
|
||||
// ensureStoryLoaded
|
||||
[],
|
||||
// ensureTaskLoaded
|
||||
{
|
||||
id: 't-1',
|
||||
title: 'T',
|
||||
description: null,
|
||||
priority: 1,
|
||||
sort_order: 1,
|
||||
status: 'todo',
|
||||
story_id: 's-1',
|
||||
created_at: '2026-02-01',
|
||||
},
|
||||
])
|
||||
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'P' }
|
||||
s.context.activePbiId = 'pbi-1'
|
||||
s.context.activeStoryId = 's-1'
|
||||
s.context.activeTaskId = 't-1'
|
||||
})
|
||||
|
||||
await useProductWorkspaceStore.getState().resyncActiveScopes('manual')
|
||||
|
||||
const calls = fetchSpy.mock.calls.map(([url]) => url)
|
||||
expect(calls).toContain('/api/products/prod-1/backlog')
|
||||
expect(calls).toContain('/api/pbis/pbi-1/stories')
|
||||
expect(calls).toContain('/api/stories/s-1/tasks')
|
||||
expect(calls).toContain('/api/tasks/t-1')
|
||||
|
||||
const s = useProductWorkspaceStore.getState()
|
||||
expect(s.sync.lastResyncAt).toBeTypeOf('number')
|
||||
expect(s.sync.resyncReason).toBe('manual')
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// Optimistic mutations
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('optimistic mutations', () => {
|
||||
it('rollback herstelt vorige pbi-order', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([
|
||||
makePbi({ id: 'a', priority: 2, sort_order: 1 }),
|
||||
makePbi({ id: 'b', priority: 2, sort_order: 2 }),
|
||||
]),
|
||||
)
|
||||
const prevOrder = [...useProductWorkspaceStore.getState().relations.pbiIds]
|
||||
|
||||
const id = useProductWorkspaceStore.getState().applyOptimisticMutation({
|
||||
kind: 'pbi-order',
|
||||
prevPbiIds: prevOrder,
|
||||
})
|
||||
// simuleer de optimistic order-wijziging buiten de mutation
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.relations.pbiIds = ['b', 'a']
|
||||
})
|
||||
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(['b', 'a'])
|
||||
|
||||
useProductWorkspaceStore.getState().rollbackMutation(id)
|
||||
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(prevOrder)
|
||||
expect(useProductWorkspaceStore.getState().pendingMutations[id]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('settle ruimt pending op zonder state te wijzigen', () => {
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([makePbi({ id: 'a' })]),
|
||||
)
|
||||
const id = useProductWorkspaceStore.getState().applyOptimisticMutation({
|
||||
kind: 'pbi-order',
|
||||
prevPbiIds: ['a'],
|
||||
})
|
||||
expect(useProductWorkspaceStore.getState().pendingMutations[id]).toBeDefined()
|
||||
|
||||
useProductWorkspaceStore.getState().settleMutation(id)
|
||||
expect(useProductWorkspaceStore.getState().pendingMutations[id]).toBeUndefined()
|
||||
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(['a'])
|
||||
})
|
||||
|
||||
it('SSE-echo van een al-bestaande PBI is idempotent', () => {
|
||||
useProductWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'P' }
|
||||
})
|
||||
useProductWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith([makePbi({ id: 'a', title: 'Origineel' })]),
|
||||
)
|
||||
useProductWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'pbi',
|
||||
op: 'I',
|
||||
id: 'a',
|
||||
product_id: 'prod-1',
|
||||
title: 'echo',
|
||||
})
|
||||
expect(useProductWorkspaceStore.getState().entities.pbisById['a'].title).toBe('Origineel')
|
||||
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(['a'])
|
||||
})
|
||||
})
|
||||
|
|
@ -62,6 +62,7 @@ Auto-generated on 2026-05-09 from front-matter and headings.
|
|||
| [Tweede Claude Agent — Planning Agent](./plans/tweede-claude-agent-planning.md) | proposal | 2026-05-03 |
|
||||
| [Scrum4Me — v1.0 readiness](./plans/v1-readiness.md) | active | 2026-05-04 |
|
||||
| [Zustand store rearchitecture - active context, realtime en resync](./plans/zustand-store-rearchitecture.md) | ready-to-execute | 2026-05-09 |
|
||||
| [Zustand workspace-store implementatieplan (PBI-74)](./plans/zustand-workspace-store-implementation.md) | ready-to-execute | 2026-05-09 |
|
||||
|
||||
### Archive
|
||||
|
||||
|
|
|
|||
|
|
@ -527,6 +527,38 @@ curl -X POST -H "Authorization: Bearer $CRON_SECRET" \
|
|||
|
||||
---
|
||||
|
||||
## Workspace store endpoint audit (PBI-74)
|
||||
|
||||
`product-workspace-store` heeft vier `ensure*Loaded`-loaders. Deze tabel
|
||||
documenteert welke routes al bestaan en welke in Story 7 (T-870) toegevoegd
|
||||
worden. Tot dan retourneert de stub-default in vitest een lege response.
|
||||
|
||||
| Loader | URL | Status | Op te leveren in |
|
||||
|---|---|---|---|
|
||||
| `ensureProductLoaded(productId)` | `GET /api/products/:id/backlog` | **ontbreekt** | T-870 (Story 7) |
|
||||
| `ensurePbiLoaded(pbiId)` | `GET /api/pbis/:id/stories` | **ontbreekt** (en `/api/pbis` route-folder bestaat nog niet) | T-870 (Story 7) |
|
||||
| `ensureStoryLoaded(storyId)` | `GET /api/stories/:id/tasks` | **ontbreekt** (alleen `tasks/reorder` bestaat) | T-870 (Story 7) |
|
||||
| `ensureTaskLoaded(taskId)` | `GET /api/tasks/:id` | **ontbreekt** (alleen `PATCH` bestaat) | T-870 (Story 7) |
|
||||
|
||||
Vereisten voor de toe te voegen routes:
|
||||
|
||||
- Auth via `authenticateApiRequest` (Bearer-token), conform bestaande patroon.
|
||||
- Access-control via `getAccessibleProduct(productId, userId)` uit
|
||||
`lib/product-access.ts` waar de route product-context heeft.
|
||||
- `export const dynamic = 'force-dynamic'` zodat Next geen response-cache
|
||||
introduceert (T-869 in Story 7).
|
||||
- Response-shape:
|
||||
- `GET /api/products/:id/backlog` → `ProductBacklogSnapshot` (`{ product?, pbis[], storiesByPbi, tasksByStory }`).
|
||||
- `GET /api/pbis/:id/stories` → `BacklogStory[]`.
|
||||
- `GET /api/stories/:id/tasks` → `BacklogTask[]`.
|
||||
- `GET /api/tasks/:id` → `TaskDetail` (extends `BacklogTask` met `_detail: true` plus extra velden zoals `implementation_plan`, `acceptance_criteria`, `requires_opus`, `estimated_minutes`).
|
||||
- Type-bron: `stores/product-workspace/types.ts`.
|
||||
|
||||
Auth/access-control wijzigt niet — de rearchitecture raakt alleen
|
||||
client-state, niet serverlaag-security.
|
||||
|
||||
---
|
||||
|
||||
## Voorbeeldworkflow voor Claude Code
|
||||
|
||||
1. **Probe:** `GET /api/health?db=1` — bevestig dat de service en DB bereikbaar zijn.
|
||||
|
|
|
|||
177
docs/plans/zustand-workspace-store-implementation.md
Normal file
177
docs/plans/zustand-workspace-store-implementation.md
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
---
|
||||
title: "Zustand workspace-store implementatieplan (PBI-74)"
|
||||
status: ready-to-execute
|
||||
audience: [maintainer, contributor, ai-agent]
|
||||
language: nl
|
||||
last_updated: 2026-05-09
|
||||
revision: 1
|
||||
---
|
||||
|
||||
# Zustand workspace-store implementatieplan
|
||||
|
||||
PBI in Scrum4Me-MCP: **PBI-74** — _Zustand store rearchitecture — product- en sprint-workspace_.
|
||||
|
||||
Bron-ontwerp (architectuur en gotchas): [zustand-store-rearchitecture.md](./zustand-store-rearchitecture.md) revisie 3.
|
||||
|
||||
Dit document koppelt de stories en taken in MCP aan de implementatie. Per story acceptatiecriteria; per taak een concrete deliverable. Alle items staan in MCP op `OPEN`/`TO_DO`. Geen executie tot expliciete trigger ("voer Story 1 uit").
|
||||
|
||||
## Context
|
||||
|
||||
De client-state ligt over vier los gegroeide stores: `backlog-store`, `planner-store`, `selection-store`, `product-store`. Vier zwakheden:
|
||||
|
||||
- SSE sluit op tab `hidden` zonder resync bij `visible` — gemiste events blijven gemist.
|
||||
- Geen reconcile bij reconnect (Postgres NOTIFY heeft geen replay).
|
||||
- Onbekende entity-events worden stil genegeerd.
|
||||
- LocalStorage soms behandeld als waarheid i.p.v. restore-hint.
|
||||
- Geen race-safe loaders — trage fetch van oude selectie kan nieuwste overschrijven.
|
||||
|
||||
De rearchitecture lost dit op via één `product-workspace-store` (en analoog `sprint-workspace-store`) met genormaliseerde entity-maps, race-safe `ensure*Loaded` met `activeRequestId`-guard, expliciete resync-laag (visible/reconnect/unknown-event), idempotente SSE-application en localStorage als pure restore-hint.
|
||||
|
||||
## Aanpak
|
||||
|
||||
- Eén PBI ([PBI-74](./zustand-store-rearchitecture.md)).
|
||||
- Negen stories die mappen op de stappen 1-9 in het bron-ontwerp.
|
||||
- Granulariteit Story 3 = één story met taken per component.
|
||||
- Story 5 in één PR (visibility-handling + resync horen samen).
|
||||
- Per story: PR, `npm run verify && npm run build` groen, status DONE pas na merge.
|
||||
- Branch: `feat/zustand-workspace-store` (één branch voor alle stories).
|
||||
|
||||
## Stories en taken
|
||||
|
||||
| # | Story | MCP | Taken |
|
||||
|---|---|---|---|
|
||||
| 1 | Skelet + test-infrastructuur | [ST-1318](./zustand-store-rearchitecture.md) | T-837 … T-843 (7) |
|
||||
| 2 | Hydratie overstappen (parallel-running) | ST-1319 | T-844 … T-847 (4) |
|
||||
| 3 | Componenten omzetten naar workspace-store | ST-1320 | T-848 … T-855 (8) |
|
||||
| 4 | Race-safe loaders en restore-hints | ST-1321 | T-856 … T-860 (5) |
|
||||
| 5 | Hidden-tab + reconnect resync (één PR) | ST-1322 | T-861 … T-864 (4) |
|
||||
| 6 | Unknown-event fallback | ST-1323 | T-865 … T-867 (3) |
|
||||
| 7 | Cache-headers en read-routes | ST-1324 | T-868 … T-871 (4) |
|
||||
| 8 | Oude stores opruimen | ST-1325 | T-872 … T-878 (7) |
|
||||
| 9 | Sprint-workspace-store | ST-1326 | T-879 … T-884 (6) |
|
||||
|
||||
Totaal: 48 taken.
|
||||
|
||||
### Story 1 — Skelet + test-infrastructuur
|
||||
|
||||
**Doel:** nieuwe store + selectors + restore-utils met volledige unit-test-suite, nog zonder UI-consumenten.
|
||||
|
||||
**Belangrijkste taken:**
|
||||
- T-837 — Vitest naar jsdom + `tests/setup.ts` met MemoryStorage (G6).
|
||||
- T-838/839/840/841 — `stores/product-workspace/{types,store,selectors,restore}.ts`.
|
||||
- T-842 — Volledige test-suite per §Testing setup-checklist (G5/G7/G8).
|
||||
- T-843 — API endpoint-audit voor `ensure*Loaded` URLs.
|
||||
|
||||
**Acceptatie:** alle test-cases groen, geen UI-impact.
|
||||
|
||||
### Story 2 — Hydratie overstappen
|
||||
|
||||
**Doel:** `BacklogHydrationWrapper` en `useBacklogRealtime` voeden zowel oude store als nieuwe store. Componenten lezen nog uit oude.
|
||||
|
||||
**Taken:** T-844 (wrapper dual-dispatch), T-845 (realtime dual-dispatch), T-846 (dev-only fingerprint verifyer), T-847 (productpicker → setActiveProduct).
|
||||
|
||||
**Acceptatie:** schaduw-store inhoud matcht oude store na elk SSE-event.
|
||||
|
||||
### Story 3 — Componenten omzetten
|
||||
|
||||
**Doel:** componenten lezen uit nieuwe workspace-store; oude stores hebben geen UI-consumenten meer.
|
||||
|
||||
**Taken per component:** T-848 (split-pane), T-849 (pbi-list), T-850 (story-panel), T-851 (task-panel), T-852 (start-sprint-button), T-853 (set-current-product). Plus T-854 (G1/G2-audit) en T-855 (integration-tests bijwerken).
|
||||
|
||||
**Acceptatie:** geen "Maximum update depth" warnings; oude store-imports alleen nog in tests die in Story 8 verdwijnen.
|
||||
|
||||
### Story 4 — Race-safe loaders en restore-hints
|
||||
|
||||
**Doel:** `ensure*Loaded` met `activeRequestId`-guard; localStorage hints met validatie.
|
||||
|
||||
**Taken:** T-856 (guard), T-857 (restore-flow met await ensure-chain), T-858 (hint-persistentie), T-859 (URL-prioriteit), T-860 (race-safety tests).
|
||||
|
||||
**Acceptatie:** trage fetch + her-selectie corrumpeert nooit; cold reload restoret zonder fout.
|
||||
|
||||
### Story 5 — Hidden-tab + reconnect resync (één PR)
|
||||
|
||||
**Doel:** SSE blijft open op hidden; resync via expliciete laag.
|
||||
|
||||
**Taken:** T-861 (geen close op hidden), T-862 (ready-event triggert resync na reconnect), T-863 (`useWorkspaceResync` hook), T-864 (tests).
|
||||
|
||||
**Acceptatie:** hidden→visible en reconnect herstellen gemiste wijzigingen in één cyclus.
|
||||
|
||||
### Story 6 — Unknown-event fallback
|
||||
|
||||
**Doel:** onbekende entity-events triggeren resync; job/worker noise wordt genegeerd.
|
||||
|
||||
**Taken:** T-865 (`isUnknownEntityEvent` filter), T-866 (resync-trigger), T-867 (negatieve filter-tests).
|
||||
|
||||
**Acceptatie:** directe DB UPDATE zonder herkenbare delta-event wordt zichtbaar binnen één resync; job-events triggeren geen resync.
|
||||
|
||||
### Story 7 — Cache-headers en read-routes
|
||||
|
||||
**Doel:** geen stale data uit Next/browser cache.
|
||||
|
||||
**Taken:** T-868 (`cache: 'no-store'`), T-869 (`force-dynamic` audit), T-870 (LIST-endpoints toevoegen waar nodig), T-871 (SSE-route ready-event coverage).
|
||||
|
||||
**Acceptatie:** response headers in productie tonen `cache-control: no-store`; LIST-endpoints bestaan voor alle `ensure*Loaded`.
|
||||
|
||||
### Story 8 — Oude stores opruimen
|
||||
|
||||
**Doel:** vier oude stores verwijderd.
|
||||
|
||||
**Taken:** T-872 (grep), T-873/874/875/876 (delete vier files), T-877 (oude tests migreren), T-878 (`stores/products-store.ts` blijft + dev-fingerprint cleanup).
|
||||
|
||||
**Acceptatie:** grep `useBacklogStore|usePlannerStore|useSelectionStore|useProductStore` = 0; `npm run verify && npm run build` groen.
|
||||
|
||||
### Story 9 — Sprint-workspace-store
|
||||
|
||||
**Doel:** zelfde patroon op sprint-workflow toegepast.
|
||||
|
||||
**Taken:** T-879 (skelet), T-880 (hydratie+realtime), T-881 (componenten), T-882 (race-safe + restore + resync + unknown-event in één keer), T-883 (cleanup oude sprint-state), T-884 (E2E sprint-board verificatie).
|
||||
|
||||
> **Aanbeveling per ontwerpdoc:** start Story 9 pas nadat product-workspace enkele weken stabiel in productie staat. PBI-74 sluit pas wanneer Story 9 ook merged is.
|
||||
|
||||
## Critical files
|
||||
|
||||
**Te wijzigen:**
|
||||
- `vitest.config.ts` — env naar jsdom, setupFiles
|
||||
- nieuw: `tests/setup.ts` — MemoryStorage, restoreAllMocks
|
||||
- nieuw: `stores/product-workspace/{types,store,selectors,restore}.ts`
|
||||
- nieuw: `stores/sprint-workspace/{types,store,selectors,restore}.ts`
|
||||
- nieuw: `lib/realtime/use-workspace-resync.ts`
|
||||
- `components/backlog/backlog-hydration-wrapper.tsx`
|
||||
- `lib/realtime/use-backlog-realtime.ts`
|
||||
- `components/backlog/backlog-split-pane.tsx`, `pbi-list.tsx`, `story-panel.tsx`, `task-panel.tsx`
|
||||
- `components/.../start-sprint-button.tsx`, `set-current-product.tsx`
|
||||
- read-routes onder `app/api/...` voor PBI/story/task LIST + detail
|
||||
- te verwijderen in Story 8: `stores/{backlog,planner,selection,product}-store.ts`
|
||||
|
||||
**Te hergebruiken (geen wijziging):**
|
||||
- `lib/product-access.ts` — `getAccessibleProduct`, blijft auth/access-bron
|
||||
- `app/api/realtime/backlog/route.ts` — `ready`-event al aanwezig
|
||||
- `docs/patterns/realtime-notify-payload.md` — payload-contract
|
||||
- `docs/patterns/route-handler.md` — REST patroon
|
||||
- `stores/products-store.ts`, `stores/solo-store.ts`, `stores/notifications-store.ts`, `stores/idea-store.ts`, `stores/jobs-store.ts` — blijven ongewijzigd
|
||||
|
||||
## Verificatie per story
|
||||
|
||||
- **Story 1:** Vitest groen voor alle test-cases (hydrate, cascade, realtime, ensureLoaded race, resync, restore-hints, optimistic mutation).
|
||||
- **Story 2:** dev-server, productpagina, fingerprint match in console.
|
||||
- **Story 3:** klik door 3 panels, DnD test, geen "Maximum update depth"-warnings.
|
||||
- **Story 4:** staging — cold reload, throttle fetch + her-selecteer.
|
||||
- **Story 5:** tab hidden > 30s + terug → resync zichtbaar; netwerk uit/aan → reconnect+resync.
|
||||
- **Story 6:** DB UPDATE op story zonder delta-event → zichtbaar binnen 1 resync; job-events negeren resync.
|
||||
- **Story 7:** response headers `cache-control: no-store`; tweede pageload toont verse data.
|
||||
- **Story 8:** grep oude store-imports = 0; `npm run verify && npm run build` groen.
|
||||
- **Story 9:** sprint-board flow analoog Story 1-8 verifications.
|
||||
|
||||
**Eind-acceptatie PBI-74:** alle items uit §Acceptatiecriteria van [zustand-store-rearchitecture.md](./zustand-store-rearchitecture.md) (regels 727-746) behaald.
|
||||
|
||||
## Workflow per story
|
||||
|
||||
1. `git checkout -b feat/zustand-workspace-store` (eerste story); blijf op deze branch tot expliciete cut.
|
||||
2. `mcp__scrum4me__get_claude_context` → pak next story uit PBI-74.
|
||||
3. Voer taken uit in `sort_order`; update status per taak via `mcp__scrum4me__update_task_status`.
|
||||
4. Lees relevante bestanden + patronen vóór begin (zie §Critical files).
|
||||
5. `npm run verify && npm run build` per laag.
|
||||
6. Commit per laag (`git add -A && git commit`); geen push tussendoor.
|
||||
7. Story-status sluit zodra alle taken `DONE`.
|
||||
8. Lege story-queue → `git push -u origin feat/zustand-workspace-store` + `gh pr create`.
|
||||
9. Per story een eigen PR; merge één voor één.
|
||||
110
stores/product-workspace/restore.ts
Normal file
110
stores/product-workspace/restore.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
const STORAGE_KEY = 'product-workspace-hints'
|
||||
|
||||
interface PerProductHint {
|
||||
lastActivePbiId?: string | null
|
||||
lastActiveStoryId?: string | null
|
||||
lastActiveTaskId?: string | null
|
||||
}
|
||||
|
||||
export interface WorkspaceHints {
|
||||
lastActiveProductId: string | null
|
||||
perProduct: Record<string, PerProductHint>
|
||||
}
|
||||
|
||||
const EMPTY_HINTS: WorkspaceHints = {
|
||||
lastActiveProductId: null,
|
||||
perProduct: {},
|
||||
}
|
||||
|
||||
function safeStorage(): Storage | null {
|
||||
if (typeof globalThis === 'undefined') return null
|
||||
try {
|
||||
const ls = (globalThis as { localStorage?: Storage }).localStorage
|
||||
return ls ?? null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function readHints(): WorkspaceHints {
|
||||
const storage = safeStorage()
|
||||
if (!storage) return { ...EMPTY_HINTS, perProduct: {} }
|
||||
try {
|
||||
const raw = storage.getItem(STORAGE_KEY)
|
||||
if (!raw) return { ...EMPTY_HINTS, perProduct: {} }
|
||||
const parsed = JSON.parse(raw) as Partial<WorkspaceHints> | null
|
||||
if (!parsed || typeof parsed !== 'object') {
|
||||
return { ...EMPTY_HINTS, perProduct: {} }
|
||||
}
|
||||
return {
|
||||
lastActiveProductId: parsed.lastActiveProductId ?? null,
|
||||
perProduct:
|
||||
parsed.perProduct && typeof parsed.perProduct === 'object'
|
||||
? parsed.perProduct
|
||||
: {},
|
||||
}
|
||||
} catch {
|
||||
return { ...EMPTY_HINTS, perProduct: {} }
|
||||
}
|
||||
}
|
||||
|
||||
function writeHints(hints: WorkspaceHints): void {
|
||||
const storage = safeStorage()
|
||||
if (!storage) return
|
||||
try {
|
||||
storage.setItem(STORAGE_KEY, JSON.stringify(hints))
|
||||
} catch {
|
||||
// ignore quota or serialization errors
|
||||
}
|
||||
}
|
||||
|
||||
export function writeProductHint(productId: string | null): void {
|
||||
const hints = readHints()
|
||||
hints.lastActiveProductId = productId
|
||||
writeHints(hints)
|
||||
}
|
||||
|
||||
function ensurePerProduct(hints: WorkspaceHints, productId: string): PerProductHint {
|
||||
if (!hints.perProduct[productId]) {
|
||||
hints.perProduct[productId] = {}
|
||||
}
|
||||
return hints.perProduct[productId]
|
||||
}
|
||||
|
||||
export function writePbiHint(productId: string, pbiId: string | null): void {
|
||||
const hints = readHints()
|
||||
const entry = ensurePerProduct(hints, productId)
|
||||
entry.lastActivePbiId = pbiId
|
||||
if (pbiId === null) {
|
||||
entry.lastActiveStoryId = null
|
||||
entry.lastActiveTaskId = null
|
||||
}
|
||||
writeHints(hints)
|
||||
}
|
||||
|
||||
export function writeStoryHint(productId: string, storyId: string | null): void {
|
||||
const hints = readHints()
|
||||
const entry = ensurePerProduct(hints, productId)
|
||||
entry.lastActiveStoryId = storyId
|
||||
if (storyId === null) {
|
||||
entry.lastActiveTaskId = null
|
||||
}
|
||||
writeHints(hints)
|
||||
}
|
||||
|
||||
export function writeTaskHint(productId: string, taskId: string | null): void {
|
||||
const hints = readHints()
|
||||
const entry = ensurePerProduct(hints, productId)
|
||||
entry.lastActiveTaskId = taskId
|
||||
writeHints(hints)
|
||||
}
|
||||
|
||||
export function clearHints(): void {
|
||||
const storage = safeStorage()
|
||||
if (!storage) return
|
||||
try {
|
||||
storage.removeItem(STORAGE_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
102
stores/product-workspace/selectors.ts
Normal file
102
stores/product-workspace/selectors.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import type { ProductWorkspaceStore } from './store'
|
||||
import type { BacklogPbi, BacklogStory, BacklogTask, TaskDetail } from './types'
|
||||
|
||||
// G1: stable EMPTY-references zodat selectors geen nieuwe array per call retourneren.
|
||||
const EMPTY_PBIS: BacklogPbi[] = []
|
||||
const EMPTY_STORIES: BacklogStory[] = []
|
||||
const EMPTY_TASKS: (BacklogTask | TaskDetail)[] = []
|
||||
|
||||
/**
|
||||
* Lijst-selector. Vereist `useShallow` in componenten (G2) — anders re-rendert
|
||||
* elke ongerelateerde store-mutatie het component.
|
||||
*/
|
||||
export function selectVisiblePbis(s: ProductWorkspaceStore): BacklogPbi[] {
|
||||
if (s.relations.pbiIds.length === 0) return EMPTY_PBIS
|
||||
const out: BacklogPbi[] = []
|
||||
for (const id of s.relations.pbiIds) {
|
||||
const pbi = s.entities.pbisById[id]
|
||||
if (pbi) out.push(pbi)
|
||||
}
|
||||
return out.length === 0 ? EMPTY_PBIS : out
|
||||
}
|
||||
|
||||
/**
|
||||
* Lijst-selector. Vereist `useShallow` in componenten (G2).
|
||||
*/
|
||||
export function selectStoriesForActivePbi(s: ProductWorkspaceStore): BacklogStory[] {
|
||||
const pbiId = s.context.activePbiId
|
||||
if (!pbiId) return EMPTY_STORIES
|
||||
const ids = s.relations.storyIdsByPbi[pbiId]
|
||||
if (!ids || ids.length === 0) return EMPTY_STORIES
|
||||
const out: BacklogStory[] = []
|
||||
for (const id of ids) {
|
||||
const story = s.entities.storiesById[id]
|
||||
if (story) out.push(story)
|
||||
}
|
||||
return out.length === 0 ? EMPTY_STORIES : out
|
||||
}
|
||||
|
||||
/**
|
||||
* Lijst-selector. Vereist `useShallow` in componenten (G2).
|
||||
*/
|
||||
export function selectTasksForActiveStory(
|
||||
s: ProductWorkspaceStore,
|
||||
): (BacklogTask | TaskDetail)[] {
|
||||
const storyId = s.context.activeStoryId
|
||||
if (!storyId) return EMPTY_TASKS
|
||||
const ids = s.relations.taskIdsByStory[storyId]
|
||||
if (!ids || ids.length === 0) return EMPTY_TASKS
|
||||
const out: (BacklogTask | TaskDetail)[] = []
|
||||
for (const id of ids) {
|
||||
const task = s.entities.tasksById[id]
|
||||
if (task) out.push(task)
|
||||
}
|
||||
return out.length === 0 ? EMPTY_TASKS : out
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-value selector. `useShallow` niet vereist — retourneert stable
|
||||
* entity-reference (zelfde object zolang entity ongewijzigd).
|
||||
*/
|
||||
export function selectActivePbi(s: ProductWorkspaceStore): BacklogPbi | null {
|
||||
const id = s.context.activePbiId
|
||||
if (!id) return null
|
||||
return s.entities.pbisById[id] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-value selector. `useShallow` niet vereist.
|
||||
*/
|
||||
export function selectActiveStory(s: ProductWorkspaceStore): BacklogStory | null {
|
||||
const id = s.context.activeStoryId
|
||||
if (!id) return null
|
||||
return s.entities.storiesById[id] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-value selector. `useShallow` niet vereist.
|
||||
*/
|
||||
export function selectActiveTask(
|
||||
s: ProductWorkspaceStore,
|
||||
): BacklogTask | TaskDetail | null {
|
||||
const id = s.context.activeTaskId
|
||||
if (!id) return null
|
||||
return s.entities.tasksById[id] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-value selector voor stories binnen een specifiek PBI (niet per se actief).
|
||||
*/
|
||||
export function selectStoriesForPbi(
|
||||
s: ProductWorkspaceStore,
|
||||
pbiId: string,
|
||||
): BacklogStory[] {
|
||||
const ids = s.relations.storyIdsByPbi[pbiId]
|
||||
if (!ids || ids.length === 0) return EMPTY_STORIES
|
||||
const out: BacklogStory[] = []
|
||||
for (const id of ids) {
|
||||
const story = s.entities.storiesById[id]
|
||||
if (story) out.push(story)
|
||||
}
|
||||
return out.length === 0 ? EMPTY_STORIES : out
|
||||
}
|
||||
791
stores/product-workspace/store.ts
Normal file
791
stores/product-workspace/store.ts
Normal file
|
|
@ -0,0 +1,791 @@
|
|||
import { create } from 'zustand'
|
||||
import { immer } from 'zustand/middleware/immer'
|
||||
|
||||
import {
|
||||
isDetail,
|
||||
type ActiveProduct,
|
||||
type BacklogPbi,
|
||||
type BacklogStory,
|
||||
type BacklogTask,
|
||||
type OptimisticMutation,
|
||||
type PendingOptimisticMutation,
|
||||
type ProductBacklogSnapshot,
|
||||
type ProductRealtimeEvent,
|
||||
type RealtimeStatus,
|
||||
type ResyncReason,
|
||||
type TaskDetail,
|
||||
} from './types'
|
||||
|
||||
interface ContextSlice {
|
||||
activeProduct: ActiveProduct | null
|
||||
activePbiId: string | null
|
||||
activeStoryId: string | null
|
||||
activeTaskId: string | null
|
||||
}
|
||||
|
||||
interface EntitiesSlice {
|
||||
pbisById: Record<string, BacklogPbi>
|
||||
storiesById: Record<string, BacklogStory>
|
||||
tasksById: Record<string, BacklogTask | TaskDetail>
|
||||
}
|
||||
|
||||
interface RelationsSlice {
|
||||
pbiIds: string[]
|
||||
storyIdsByPbi: Record<string, string[]>
|
||||
taskIdsByStory: Record<string, string[]>
|
||||
}
|
||||
|
||||
interface LoadingSlice {
|
||||
loadedProductId: string | null
|
||||
loadingProductId: string | null
|
||||
loadedPbiIds: Record<string, true>
|
||||
loadedStoryIds: Record<string, true>
|
||||
loadedTaskIds: Record<string, true>
|
||||
activeRequestId: string | null
|
||||
}
|
||||
|
||||
interface SyncSlice {
|
||||
realtimeStatus: RealtimeStatus
|
||||
lastEventAt: number | null
|
||||
lastResyncAt: number | null
|
||||
resyncReason: ResyncReason | null
|
||||
}
|
||||
|
||||
interface State {
|
||||
context: ContextSlice
|
||||
entities: EntitiesSlice
|
||||
relations: RelationsSlice
|
||||
loading: LoadingSlice
|
||||
sync: SyncSlice
|
||||
pendingMutations: Record<string, PendingOptimisticMutation>
|
||||
}
|
||||
|
||||
interface Actions {
|
||||
hydrateSnapshot(snapshot: ProductBacklogSnapshot): void
|
||||
|
||||
setActiveProduct(product: ActiveProduct | null): void
|
||||
setActivePbi(pbiId: string | null): void
|
||||
setActiveStory(storyId: string | null): void
|
||||
setActiveTask(taskId: string | null): void
|
||||
|
||||
ensureProductLoaded(productId: string, requestId?: string): Promise<void>
|
||||
ensurePbiLoaded(pbiId: string, requestId?: string): Promise<void>
|
||||
ensureStoryLoaded(storyId: string, requestId?: string): Promise<void>
|
||||
ensureTaskLoaded(taskId: string, requestId?: string): Promise<void>
|
||||
|
||||
applyRealtimeEvent(event: ProductRealtimeEvent | Record<string, unknown>): void
|
||||
resyncActiveScopes(reason: ResyncReason): Promise<void>
|
||||
resyncLoadedScopes(reason: ResyncReason): Promise<void>
|
||||
|
||||
applyOptimisticMutation(mutation: OptimisticMutation): string
|
||||
rollbackMutation(mutationId: string): void
|
||||
settleMutation(mutationId: string): void
|
||||
|
||||
setRealtimeStatus(status: RealtimeStatus): void
|
||||
}
|
||||
|
||||
export type ProductWorkspaceStore = State & Actions
|
||||
|
||||
const initialState: State = {
|
||||
context: {
|
||||
activeProduct: null,
|
||||
activePbiId: null,
|
||||
activeStoryId: null,
|
||||
activeTaskId: null,
|
||||
},
|
||||
entities: {
|
||||
pbisById: {},
|
||||
storiesById: {},
|
||||
tasksById: {},
|
||||
},
|
||||
relations: {
|
||||
pbiIds: [],
|
||||
storyIdsByPbi: {},
|
||||
taskIdsByStory: {},
|
||||
},
|
||||
loading: {
|
||||
loadedProductId: null,
|
||||
loadingProductId: null,
|
||||
loadedPbiIds: {},
|
||||
loadedStoryIds: {},
|
||||
loadedTaskIds: {},
|
||||
activeRequestId: null,
|
||||
},
|
||||
sync: {
|
||||
realtimeStatus: 'connecting',
|
||||
lastEventAt: null,
|
||||
lastResyncAt: null,
|
||||
resyncReason: null,
|
||||
},
|
||||
pendingMutations: {},
|
||||
}
|
||||
|
||||
function comparePbi(a: BacklogPbi, b: BacklogPbi): number {
|
||||
if (a.priority !== b.priority) return a.priority - b.priority
|
||||
if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order
|
||||
return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
|
||||
}
|
||||
|
||||
function compareStory(a: BacklogStory, b: BacklogStory): number {
|
||||
if (a.priority !== b.priority) return a.priority - b.priority
|
||||
if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order
|
||||
return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
|
||||
}
|
||||
|
||||
function compareTask(a: BacklogTask, b: BacklogTask): number {
|
||||
if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order
|
||||
return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
|
||||
}
|
||||
|
||||
function newRequestId(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
}
|
||||
|
||||
function isKnownEntity(entity: unknown): entity is 'pbi' | 'story' | 'task' {
|
||||
return entity === 'pbi' || entity === 'story' || entity === 'task'
|
||||
}
|
||||
|
||||
function isUnknownEntityEvent(p: Record<string, unknown>): boolean {
|
||||
if (typeof p.entity !== 'string') return false
|
||||
if (isKnownEntity(p.entity)) return false
|
||||
if ('type' in p) return false
|
||||
return true
|
||||
}
|
||||
|
||||
async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(url, { cache: 'no-store', ...init })
|
||||
if (!response.ok) {
|
||||
throw new Error(`Fetch ${url} failed with ${response.status}`)
|
||||
}
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
|
||||
immer((set, get) => ({
|
||||
...initialState,
|
||||
|
||||
hydrateSnapshot(snapshot) {
|
||||
set((s) => {
|
||||
if (snapshot.product) s.context.activeProduct = snapshot.product
|
||||
|
||||
s.entities.pbisById = {}
|
||||
s.entities.storiesById = {}
|
||||
s.entities.tasksById = {}
|
||||
s.relations.pbiIds = []
|
||||
s.relations.storyIdsByPbi = {}
|
||||
s.relations.taskIdsByStory = {}
|
||||
|
||||
for (const pbi of snapshot.pbis) {
|
||||
s.entities.pbisById[pbi.id] = pbi
|
||||
}
|
||||
s.relations.pbiIds = [...snapshot.pbis].sort(comparePbi).map((p) => p.id)
|
||||
|
||||
for (const [pbiId, stories] of Object.entries(snapshot.storiesByPbi)) {
|
||||
for (const story of stories) {
|
||||
s.entities.storiesById[story.id] = story
|
||||
}
|
||||
s.relations.storyIdsByPbi[pbiId] = [...stories]
|
||||
.sort(compareStory)
|
||||
.map((st) => st.id)
|
||||
}
|
||||
|
||||
for (const [storyId, tasks] of Object.entries(snapshot.tasksByStory)) {
|
||||
for (const task of tasks) {
|
||||
s.entities.tasksById[task.id] = task
|
||||
}
|
||||
s.relations.taskIdsByStory[storyId] = [...tasks]
|
||||
.sort(compareTask)
|
||||
.map((t) => t.id)
|
||||
}
|
||||
|
||||
if (snapshot.product) {
|
||||
s.loading.loadedProductId = snapshot.product.id
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
setActiveProduct(product) {
|
||||
const requestId = newRequestId()
|
||||
const productChanged = get().context.activeProduct?.id !== product?.id
|
||||
|
||||
set((s) => {
|
||||
s.context.activeProduct = product
|
||||
s.context.activePbiId = null
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
s.loading.activeRequestId = requestId
|
||||
|
||||
if (productChanged) {
|
||||
s.entities.pbisById = {}
|
||||
s.entities.storiesById = {}
|
||||
s.entities.tasksById = {}
|
||||
s.relations.pbiIds = []
|
||||
s.relations.storyIdsByPbi = {}
|
||||
s.relations.taskIdsByStory = {}
|
||||
s.loading.loadedProductId = null
|
||||
s.loading.loadedPbiIds = {}
|
||||
s.loading.loadedStoryIds = {}
|
||||
s.loading.loadedTaskIds = {}
|
||||
}
|
||||
})
|
||||
|
||||
if (product) {
|
||||
void get().ensureProductLoaded(product.id, requestId)
|
||||
}
|
||||
},
|
||||
|
||||
setActivePbi(pbiId) {
|
||||
const requestId = newRequestId()
|
||||
|
||||
set((s) => {
|
||||
s.context.activePbiId = pbiId
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
s.loading.activeRequestId = requestId
|
||||
})
|
||||
|
||||
if (pbiId) {
|
||||
void get().ensurePbiLoaded(pbiId, requestId)
|
||||
}
|
||||
},
|
||||
|
||||
setActiveStory(storyId) {
|
||||
const requestId = newRequestId()
|
||||
|
||||
set((s) => {
|
||||
s.context.activeStoryId = storyId
|
||||
s.context.activeTaskId = null
|
||||
s.loading.activeRequestId = requestId
|
||||
})
|
||||
|
||||
if (storyId) {
|
||||
void get().ensureStoryLoaded(storyId, requestId)
|
||||
}
|
||||
},
|
||||
|
||||
setActiveTask(taskId) {
|
||||
set((s) => {
|
||||
s.context.activeTaskId = taskId
|
||||
})
|
||||
|
||||
if (taskId) {
|
||||
void get().ensureTaskLoaded(taskId)
|
||||
}
|
||||
},
|
||||
|
||||
async ensureProductLoaded(productId, requestId) {
|
||||
set((s) => {
|
||||
s.loading.loadingProductId = productId
|
||||
})
|
||||
try {
|
||||
const snapshot = await fetchJson<ProductBacklogSnapshot | null>(
|
||||
`/api/products/${encodeURIComponent(productId)}/backlog`,
|
||||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!snapshot || !Array.isArray(snapshot.pbis)) return
|
||||
get().hydrateSnapshot(snapshot)
|
||||
set((s) => {
|
||||
s.loading.loadedProductId = productId
|
||||
for (const pbi of snapshot.pbis) {
|
||||
s.loading.loadedPbiIds[pbi.id] = true
|
||||
}
|
||||
})
|
||||
} finally {
|
||||
set((s) => {
|
||||
if (s.loading.loadingProductId === productId) {
|
||||
s.loading.loadingProductId = null
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
async ensurePbiLoaded(pbiId, requestId) {
|
||||
const stories = await fetchJson<BacklogStory[] | null>(
|
||||
`/api/pbis/${encodeURIComponent(pbiId)}/stories`,
|
||||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!Array.isArray(stories)) return
|
||||
set((s) => {
|
||||
for (const story of stories) {
|
||||
s.entities.storiesById[story.id] = story
|
||||
}
|
||||
s.relations.storyIdsByPbi[pbiId] = [...stories]
|
||||
.sort(compareStory)
|
||||
.map((st) => st.id)
|
||||
s.loading.loadedPbiIds[pbiId] = true
|
||||
})
|
||||
},
|
||||
|
||||
async ensureStoryLoaded(storyId, requestId) {
|
||||
const tasks = await fetchJson<BacklogTask[] | null>(
|
||||
`/api/stories/${encodeURIComponent(storyId)}/tasks`,
|
||||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!Array.isArray(tasks)) return
|
||||
set((s) => {
|
||||
for (const task of tasks) {
|
||||
const existing = s.entities.tasksById[task.id]
|
||||
if (existing && isDetail(existing)) {
|
||||
s.entities.tasksById[task.id] = { ...existing, ...task }
|
||||
} else {
|
||||
s.entities.tasksById[task.id] = task
|
||||
}
|
||||
}
|
||||
s.relations.taskIdsByStory[storyId] = [...tasks]
|
||||
.sort(compareTask)
|
||||
.map((t) => t.id)
|
||||
s.loading.loadedStoryIds[storyId] = true
|
||||
})
|
||||
},
|
||||
|
||||
async ensureTaskLoaded(taskId, requestId) {
|
||||
const detail = await fetchJson<TaskDetail | null>(
|
||||
`/api/tasks/${encodeURIComponent(taskId)}`,
|
||||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!detail || typeof detail !== 'object') return
|
||||
set((s) => {
|
||||
s.entities.tasksById[taskId] = { ...detail, _detail: true }
|
||||
s.loading.loadedTaskIds[taskId] = true
|
||||
})
|
||||
},
|
||||
|
||||
applyRealtimeEvent(event) {
|
||||
const payload = event as Record<string, unknown>
|
||||
const activeProductId = get().context.activeProduct?.id ?? null
|
||||
|
||||
set((s) => {
|
||||
s.sync.lastEventAt = Date.now()
|
||||
})
|
||||
|
||||
if (
|
||||
typeof payload.product_id === 'string' &&
|
||||
activeProductId &&
|
||||
payload.product_id !== activeProductId
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (isUnknownEntityEvent(payload)) {
|
||||
if (payload.product_id === activeProductId) {
|
||||
void get().resyncActiveScopes('unknown-event')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const entity = payload.entity
|
||||
const op = payload.op
|
||||
if (!isKnownEntity(entity)) return
|
||||
if (op !== 'I' && op !== 'U' && op !== 'D') return
|
||||
|
||||
const id = payload.id
|
||||
if (typeof id !== 'string') return
|
||||
|
||||
if (entity === 'pbi') {
|
||||
applyPbiEvent(id, op, payload, set, get)
|
||||
} else if (entity === 'story') {
|
||||
applyStoryEvent(id, op, payload, set, get)
|
||||
} else if (entity === 'task') {
|
||||
applyTaskEvent(id, op, payload, set, get)
|
||||
}
|
||||
},
|
||||
|
||||
async resyncActiveScopes(reason) {
|
||||
const ctx = get().context
|
||||
const tasks: Promise<void>[] = []
|
||||
if (ctx.activeProduct?.id) {
|
||||
tasks.push(get().ensureProductLoaded(ctx.activeProduct.id))
|
||||
}
|
||||
if (ctx.activePbiId) tasks.push(get().ensurePbiLoaded(ctx.activePbiId))
|
||||
if (ctx.activeStoryId) tasks.push(get().ensureStoryLoaded(ctx.activeStoryId))
|
||||
if (ctx.activeTaskId) tasks.push(get().ensureTaskLoaded(ctx.activeTaskId))
|
||||
set((s) => {
|
||||
s.sync.lastResyncAt = Date.now()
|
||||
s.sync.resyncReason = reason
|
||||
})
|
||||
await Promise.allSettled(tasks)
|
||||
},
|
||||
|
||||
async resyncLoadedScopes(reason) {
|
||||
const loading = get().loading
|
||||
const tasks: Promise<void>[] = []
|
||||
if (loading.loadedProductId) {
|
||||
tasks.push(get().ensureProductLoaded(loading.loadedProductId))
|
||||
}
|
||||
for (const pbiId of Object.keys(loading.loadedPbiIds)) {
|
||||
tasks.push(get().ensurePbiLoaded(pbiId))
|
||||
}
|
||||
for (const storyId of Object.keys(loading.loadedStoryIds)) {
|
||||
tasks.push(get().ensureStoryLoaded(storyId))
|
||||
}
|
||||
for (const taskId of Object.keys(loading.loadedTaskIds)) {
|
||||
tasks.push(get().ensureTaskLoaded(taskId))
|
||||
}
|
||||
set((s) => {
|
||||
s.sync.lastResyncAt = Date.now()
|
||||
s.sync.resyncReason = reason
|
||||
})
|
||||
await Promise.allSettled(tasks)
|
||||
},
|
||||
|
||||
applyOptimisticMutation(mutation) {
|
||||
const id = newRequestId()
|
||||
set((s) => {
|
||||
s.pendingMutations[id] = {
|
||||
id,
|
||||
mutation,
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
switch (mutation.kind) {
|
||||
case 'pbi-order':
|
||||
// store-call passes new order via separate set, snapshot is prevPbiIds
|
||||
break
|
||||
case 'story-order':
|
||||
break
|
||||
case 'task-order':
|
||||
break
|
||||
case 'entity-patch':
|
||||
break
|
||||
}
|
||||
})
|
||||
return id
|
||||
},
|
||||
|
||||
rollbackMutation(mutationId) {
|
||||
const pending = get().pendingMutations[mutationId]
|
||||
if (!pending) return
|
||||
const { mutation } = pending
|
||||
set((s) => {
|
||||
switch (mutation.kind) {
|
||||
case 'pbi-order':
|
||||
s.relations.pbiIds = [...mutation.prevPbiIds]
|
||||
break
|
||||
case 'story-order':
|
||||
s.relations.storyIdsByPbi[mutation.pbiId] = [...mutation.prevStoryIds]
|
||||
break
|
||||
case 'task-order':
|
||||
s.relations.taskIdsByStory[mutation.storyId] = [...mutation.prevTaskIds]
|
||||
break
|
||||
case 'entity-patch': {
|
||||
const { entity, id, prev } = mutation
|
||||
if (prev) {
|
||||
if (entity === 'pbi') s.entities.pbisById[id] = prev as BacklogPbi
|
||||
else if (entity === 'story') s.entities.storiesById[id] = prev as BacklogStory
|
||||
else s.entities.tasksById[id] = prev as BacklogTask | TaskDetail
|
||||
} else {
|
||||
if (entity === 'pbi') delete s.entities.pbisById[id]
|
||||
else if (entity === 'story') delete s.entities.storiesById[id]
|
||||
else delete s.entities.tasksById[id]
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
delete s.pendingMutations[mutationId]
|
||||
})
|
||||
},
|
||||
|
||||
settleMutation(mutationId) {
|
||||
set((s) => {
|
||||
delete s.pendingMutations[mutationId]
|
||||
})
|
||||
},
|
||||
|
||||
setRealtimeStatus(status) {
|
||||
set((s) => {
|
||||
s.sync.realtimeStatus = status
|
||||
})
|
||||
},
|
||||
})),
|
||||
)
|
||||
|
||||
type ImmerSet = Parameters<Parameters<typeof immer<ProductWorkspaceStore>>[0]>[0]
|
||||
type ImmerGet = () => ProductWorkspaceStore
|
||||
|
||||
function applyPbiEvent(
|
||||
id: string,
|
||||
op: 'I' | 'U' | 'D',
|
||||
payload: Record<string, unknown>,
|
||||
set: ImmerSet,
|
||||
get: ImmerGet,
|
||||
) {
|
||||
if (op === 'D') {
|
||||
set((s) => {
|
||||
const childStoryIds = s.relations.storyIdsByPbi[id] ?? []
|
||||
for (const sid of childStoryIds) {
|
||||
const childTaskIds = s.relations.taskIdsByStory[sid] ?? []
|
||||
for (const tid of childTaskIds) {
|
||||
delete s.entities.tasksById[tid]
|
||||
}
|
||||
delete s.relations.taskIdsByStory[sid]
|
||||
delete s.entities.storiesById[sid]
|
||||
}
|
||||
delete s.relations.storyIdsByPbi[id]
|
||||
delete s.entities.pbisById[id]
|
||||
s.relations.pbiIds = s.relations.pbiIds.filter((p) => p !== id)
|
||||
if (s.context.activePbiId === id) {
|
||||
s.context.activePbiId = null
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (op === 'U') {
|
||||
if (!get().entities.pbisById[id]) return
|
||||
set((s) => {
|
||||
const existing = s.entities.pbisById[id]
|
||||
if (!existing) return
|
||||
Object.assign(existing, sanitizePbiPayload(payload))
|
||||
s.relations.pbiIds = sortPbiIds(s.entities.pbisById, s.relations.pbiIds)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// I
|
||||
if (get().entities.pbisById[id]) return
|
||||
set((s) => {
|
||||
const pbi = coercePbiPayload(id, payload)
|
||||
s.entities.pbisById[id] = pbi
|
||||
s.relations.pbiIds.push(id)
|
||||
s.relations.pbiIds = sortPbiIds(s.entities.pbisById, s.relations.pbiIds)
|
||||
})
|
||||
}
|
||||
|
||||
function applyStoryEvent(
|
||||
id: string,
|
||||
op: 'I' | 'U' | 'D',
|
||||
payload: Record<string, unknown>,
|
||||
set: ImmerSet,
|
||||
get: ImmerGet,
|
||||
) {
|
||||
if (op === 'D') {
|
||||
set((s) => {
|
||||
const childTaskIds = s.relations.taskIdsByStory[id] ?? []
|
||||
for (const tid of childTaskIds) {
|
||||
delete s.entities.tasksById[tid]
|
||||
}
|
||||
delete s.relations.taskIdsByStory[id]
|
||||
const story = s.entities.storiesById[id]
|
||||
delete s.entities.storiesById[id]
|
||||
if (story) {
|
||||
const ids = s.relations.storyIdsByPbi[story.pbi_id]
|
||||
if (ids) {
|
||||
s.relations.storyIdsByPbi[story.pbi_id] = ids.filter((sid) => sid !== id)
|
||||
}
|
||||
} else {
|
||||
for (const pbiId of Object.keys(s.relations.storyIdsByPbi)) {
|
||||
s.relations.storyIdsByPbi[pbiId] = s.relations.storyIdsByPbi[pbiId].filter(
|
||||
(sid) => sid !== id,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (s.context.activeStoryId === id) {
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (op === 'U') {
|
||||
const existing = get().entities.storiesById[id]
|
||||
if (!existing) return
|
||||
set((s) => {
|
||||
const story = s.entities.storiesById[id]
|
||||
if (!story) return
|
||||
const oldPbiId = story.pbi_id
|
||||
Object.assign(story, sanitizeStoryPayload(payload))
|
||||
const newPbiId = story.pbi_id
|
||||
if (oldPbiId !== newPbiId) {
|
||||
const oldList = s.relations.storyIdsByPbi[oldPbiId]
|
||||
if (oldList) {
|
||||
s.relations.storyIdsByPbi[oldPbiId] = oldList.filter((sid) => sid !== id)
|
||||
}
|
||||
const targetList = s.relations.storyIdsByPbi[newPbiId] ?? []
|
||||
if (!targetList.includes(id)) targetList.push(id)
|
||||
s.relations.storyIdsByPbi[newPbiId] = sortStoryIds(s.entities.storiesById, targetList)
|
||||
} else if (s.relations.storyIdsByPbi[oldPbiId]) {
|
||||
s.relations.storyIdsByPbi[oldPbiId] = sortStoryIds(
|
||||
s.entities.storiesById,
|
||||
s.relations.storyIdsByPbi[oldPbiId],
|
||||
)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// I
|
||||
if (get().entities.storiesById[id]) return
|
||||
set((s) => {
|
||||
const story = coerceStoryPayload(id, payload)
|
||||
s.entities.storiesById[id] = story
|
||||
const list = s.relations.storyIdsByPbi[story.pbi_id] ?? []
|
||||
list.push(id)
|
||||
s.relations.storyIdsByPbi[story.pbi_id] = sortStoryIds(s.entities.storiesById, list)
|
||||
})
|
||||
}
|
||||
|
||||
function applyTaskEvent(
|
||||
id: string,
|
||||
op: 'I' | 'U' | 'D',
|
||||
payload: Record<string, unknown>,
|
||||
set: ImmerSet,
|
||||
get: ImmerGet,
|
||||
) {
|
||||
if (op === 'D') {
|
||||
set((s) => {
|
||||
const task = s.entities.tasksById[id]
|
||||
delete s.entities.tasksById[id]
|
||||
if (task) {
|
||||
const ids = s.relations.taskIdsByStory[task.story_id]
|
||||
if (ids) {
|
||||
s.relations.taskIdsByStory[task.story_id] = ids.filter((tid) => tid !== id)
|
||||
}
|
||||
} else {
|
||||
for (const storyId of Object.keys(s.relations.taskIdsByStory)) {
|
||||
s.relations.taskIdsByStory[storyId] = s.relations.taskIdsByStory[storyId].filter(
|
||||
(tid) => tid !== id,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (s.context.activeTaskId === id) {
|
||||
s.context.activeTaskId = null
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (op === 'U') {
|
||||
const existing = get().entities.tasksById[id]
|
||||
if (!existing) return
|
||||
set((s) => {
|
||||
const task = s.entities.tasksById[id]
|
||||
if (!task) return
|
||||
const oldStoryId = task.story_id
|
||||
Object.assign(task, sanitizeTaskPayload(payload))
|
||||
const newStoryId = task.story_id
|
||||
if (oldStoryId !== newStoryId) {
|
||||
const oldList = s.relations.taskIdsByStory[oldStoryId]
|
||||
if (oldList) {
|
||||
s.relations.taskIdsByStory[oldStoryId] = oldList.filter((tid) => tid !== id)
|
||||
}
|
||||
const targetList = s.relations.taskIdsByStory[newStoryId] ?? []
|
||||
if (!targetList.includes(id)) targetList.push(id)
|
||||
s.relations.taskIdsByStory[newStoryId] = sortTaskIds(s.entities.tasksById, targetList)
|
||||
} else if (s.relations.taskIdsByStory[oldStoryId]) {
|
||||
s.relations.taskIdsByStory[oldStoryId] = sortTaskIds(
|
||||
s.entities.tasksById,
|
||||
s.relations.taskIdsByStory[oldStoryId],
|
||||
)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// I
|
||||
if (get().entities.tasksById[id]) return
|
||||
set((s) => {
|
||||
const task = coerceTaskPayload(id, payload)
|
||||
s.entities.tasksById[id] = task
|
||||
const list = s.relations.taskIdsByStory[task.story_id] ?? []
|
||||
list.push(id)
|
||||
s.relations.taskIdsByStory[task.story_id] = sortTaskIds(s.entities.tasksById, list)
|
||||
})
|
||||
}
|
||||
|
||||
function sortPbiIds(byId: Record<string, BacklogPbi>, ids: string[]): string[] {
|
||||
return [...new Set(ids)]
|
||||
.filter((id) => byId[id] !== undefined)
|
||||
.sort((a, b) => comparePbi(byId[a], byId[b]))
|
||||
}
|
||||
|
||||
function sortStoryIds(byId: Record<string, BacklogStory>, ids: string[]): string[] {
|
||||
return [...new Set(ids)]
|
||||
.filter((id) => byId[id] !== undefined)
|
||||
.sort((a, b) => compareStory(byId[a], byId[b]))
|
||||
}
|
||||
|
||||
function sortTaskIds(
|
||||
byId: Record<string, BacklogTask | TaskDetail>,
|
||||
ids: string[],
|
||||
): string[] {
|
||||
return [...new Set(ids)]
|
||||
.filter((id) => byId[id] !== undefined)
|
||||
.sort((a, b) => compareTask(byId[a], byId[b]))
|
||||
}
|
||||
|
||||
function sanitizePbiPayload(p: Record<string, unknown>): Partial<BacklogPbi> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
void _e
|
||||
void _o
|
||||
return rest as Partial<BacklogPbi>
|
||||
}
|
||||
|
||||
function sanitizeStoryPayload(p: Record<string, unknown>): Partial<BacklogStory> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
void _e
|
||||
void _o
|
||||
return rest as Partial<BacklogStory>
|
||||
}
|
||||
|
||||
function sanitizeTaskPayload(p: Record<string, unknown>): Partial<BacklogTask> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
void _e
|
||||
void _o
|
||||
return rest as Partial<BacklogTask>
|
||||
}
|
||||
|
||||
function coercePbiPayload(id: string, p: Record<string, unknown>): BacklogPbi {
|
||||
return {
|
||||
id,
|
||||
code: (p.code as string | null) ?? null,
|
||||
title: String(p.title ?? ''),
|
||||
priority: Number(p.priority ?? 4),
|
||||
sort_order: Number(p.sort_order ?? 0),
|
||||
description: (p.description as string | null | undefined) ?? null,
|
||||
created_at:
|
||||
p.created_at instanceof Date
|
||||
? p.created_at
|
||||
: new Date(String(p.created_at ?? Date.now())),
|
||||
status: (p.status as BacklogPbi['status']) ?? 'ready',
|
||||
}
|
||||
}
|
||||
|
||||
function coerceStoryPayload(id: string, p: Record<string, unknown>): BacklogStory {
|
||||
return {
|
||||
id,
|
||||
code: (p.code as string | null) ?? null,
|
||||
title: String(p.title ?? ''),
|
||||
description: (p.description as string | null | undefined) ?? null,
|
||||
acceptance_criteria: (p.acceptance_criteria as string | null | undefined) ?? null,
|
||||
priority: Number(p.priority ?? 4),
|
||||
sort_order: Number(p.sort_order ?? 0),
|
||||
status: String(p.status ?? 'open'),
|
||||
pbi_id: String(p.pbi_id ?? ''),
|
||||
sprint_id: (p.sprint_id as string | null | undefined) ?? null,
|
||||
created_at:
|
||||
p.created_at instanceof Date
|
||||
? p.created_at
|
||||
: new Date(String(p.created_at ?? Date.now())),
|
||||
}
|
||||
}
|
||||
|
||||
function coerceTaskPayload(id: string, p: Record<string, unknown>): BacklogTask {
|
||||
return {
|
||||
id,
|
||||
title: String(p.title ?? ''),
|
||||
description: (p.description as string | null | undefined) ?? null,
|
||||
priority: Number(p.priority ?? 4),
|
||||
sort_order: Number(p.sort_order ?? 0),
|
||||
status: String(p.status ?? 'todo'),
|
||||
story_id: String(p.story_id ?? ''),
|
||||
created_at:
|
||||
p.created_at instanceof Date
|
||||
? p.created_at
|
||||
: new Date(String(p.created_at ?? Date.now())),
|
||||
}
|
||||
}
|
||||
140
stores/product-workspace/types.ts
Normal file
140
stores/product-workspace/types.ts
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import type { PbiStatusApi } from '@/lib/task-status'
|
||||
|
||||
export interface BacklogPbi {
|
||||
id: string
|
||||
code: string | null
|
||||
title: string
|
||||
priority: number
|
||||
sort_order: number
|
||||
description?: string | null
|
||||
created_at: Date
|
||||
status: PbiStatusApi
|
||||
}
|
||||
|
||||
export interface BacklogStory {
|
||||
id: string
|
||||
code: string | null
|
||||
title: string
|
||||
description: string | null
|
||||
acceptance_criteria: string | null
|
||||
priority: number
|
||||
sort_order: number
|
||||
status: string
|
||||
pbi_id: string
|
||||
sprint_id: string | null
|
||||
created_at: Date
|
||||
}
|
||||
|
||||
export interface BacklogTask {
|
||||
id: string
|
||||
title: string
|
||||
description: string | null
|
||||
priority: number
|
||||
status: string
|
||||
sort_order: number
|
||||
story_id: string
|
||||
created_at: Date
|
||||
}
|
||||
|
||||
export interface TaskDetail extends BacklogTask {
|
||||
_detail: true
|
||||
implementation_plan?: string | null
|
||||
acceptance_criteria?: string | null
|
||||
requires_opus?: boolean
|
||||
estimated_minutes?: number | null
|
||||
}
|
||||
|
||||
export function isDetail(task: BacklogTask | TaskDetail): task is TaskDetail {
|
||||
return (task as TaskDetail)._detail === true
|
||||
}
|
||||
|
||||
export interface ActiveProduct {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface ProductBacklogSnapshot {
|
||||
product?: ActiveProduct
|
||||
pbis: BacklogPbi[]
|
||||
storiesByPbi: Record<string, BacklogStory[]>
|
||||
tasksByStory: Record<string, BacklogTask[]>
|
||||
}
|
||||
|
||||
export type Op = 'I' | 'U' | 'D'
|
||||
|
||||
export interface PbiRealtimeEvent {
|
||||
entity: 'pbi'
|
||||
op: Op
|
||||
id: string
|
||||
product_id: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface StoryRealtimeEvent {
|
||||
entity: 'story'
|
||||
op: Op
|
||||
id: string
|
||||
product_id: string
|
||||
pbi_id?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface TaskRealtimeEvent {
|
||||
entity: 'task'
|
||||
op: Op
|
||||
id: string
|
||||
product_id: string
|
||||
story_id?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type ProductRealtimeEvent =
|
||||
| PbiRealtimeEvent
|
||||
| StoryRealtimeEvent
|
||||
| TaskRealtimeEvent
|
||||
|
||||
export type ResyncReason =
|
||||
| 'visible'
|
||||
| 'reconnect'
|
||||
| 'manual'
|
||||
| 'unknown-event'
|
||||
| 'stale-scope'
|
||||
| 'mutation-settled'
|
||||
|
||||
export type RealtimeStatus = 'connecting' | 'open' | 'disconnected'
|
||||
|
||||
export interface OptimisticPbiOrderMutation {
|
||||
kind: 'pbi-order'
|
||||
prevPbiIds: string[]
|
||||
}
|
||||
|
||||
export interface OptimisticStoryOrderMutation {
|
||||
kind: 'story-order'
|
||||
pbiId: string
|
||||
prevStoryIds: string[]
|
||||
}
|
||||
|
||||
export interface OptimisticTaskOrderMutation {
|
||||
kind: 'task-order'
|
||||
storyId: string
|
||||
prevTaskIds: string[]
|
||||
}
|
||||
|
||||
export interface OptimisticEntityPatchMutation {
|
||||
kind: 'entity-patch'
|
||||
entity: 'pbi' | 'story' | 'task'
|
||||
id: string
|
||||
prev: BacklogPbi | BacklogStory | BacklogTask | TaskDetail | undefined
|
||||
}
|
||||
|
||||
export type OptimisticMutation =
|
||||
| OptimisticPbiOrderMutation
|
||||
| OptimisticStoryOrderMutation
|
||||
| OptimisticTaskOrderMutation
|
||||
| OptimisticEntityPatchMutation
|
||||
|
||||
export interface PendingOptimisticMutation {
|
||||
id: string
|
||||
mutation: OptimisticMutation
|
||||
createdAt: number
|
||||
}
|
||||
84
tests/setup.ts
Normal file
84
tests/setup.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { beforeEach, vi } from 'vitest'
|
||||
|
||||
// G6: vitest 4 + jsdom 29 mist localStorage/sessionStorage op globalThis.
|
||||
// MemoryStorage-binding zodat tests zonder echte browser draaien.
|
||||
class MemoryStorage implements Storage {
|
||||
private store = new Map<string, string>()
|
||||
|
||||
get length(): number {
|
||||
return this.store.size
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear()
|
||||
}
|
||||
|
||||
getItem(key: string): string | null {
|
||||
return this.store.has(key) ? this.store.get(key)! : null
|
||||
}
|
||||
|
||||
key(index: number): string | null {
|
||||
return Array.from(this.store.keys())[index] ?? null
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
this.store.delete(key)
|
||||
}
|
||||
|
||||
setItem(key: string, value: string): void {
|
||||
this.store.set(key, String(value))
|
||||
}
|
||||
}
|
||||
|
||||
const localStorageMemory = new MemoryStorage()
|
||||
const sessionStorageMemory = new MemoryStorage()
|
||||
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: localStorageMemory,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
Object.defineProperty(globalThis, 'sessionStorage', {
|
||||
value: sessionStorageMemory,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
Object.defineProperty(window, 'localStorage', {
|
||||
value: localStorageMemory,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
Object.defineProperty(window, 'sessionStorage', {
|
||||
value: sessionStorageMemory,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// G7: maak globalThis.fetch herconfigureerbaar zodat vi.spyOn / vi.fn-stubs
|
||||
// de eigenschap kunnen redefineren. Default Node 24 / jsdom 29 binding is
|
||||
// vaak non-configurable, wat vi.spyOn(globalThis, 'fetch') laat falen.
|
||||
const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch
|
||||
Object.defineProperty(globalThis, 'fetch', {
|
||||
value: originalFetch,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
localStorageMemory.clear()
|
||||
sessionStorageMemory.clear()
|
||||
vi.restoreAllMocks()
|
||||
// Default fetch-stub voorkomt dat fire-and-forget ensure*Loaded calls
|
||||
// (b.v. via setActivePbi) lekken naar het echte network. Tests die
|
||||
// specifieke responses willen overrulen dit met vi.spyOn/vi.fn.
|
||||
// G8: mockImplementation (niet mockResolvedValue) zodat elke call een
|
||||
// verse Response krijgt — body wordt anders maar één keer leesbaar.
|
||||
;(globalThis as { fetch: typeof fetch }).fetch = vi
|
||||
.fn()
|
||||
.mockImplementation(() =>
|
||||
Promise.resolve(new Response('null', { status: 200 })),
|
||||
) as unknown as typeof fetch
|
||||
})
|
||||
1
tests/stubs/server-only.ts
Normal file
1
tests/stubs/server-only.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export {}
|
||||
|
|
@ -3,12 +3,14 @@ import path from 'path'
|
|||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
environment: 'jsdom',
|
||||
globals: true,
|
||||
setupFiles: ['tests/setup.ts'],
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, '.'),
|
||||
'server-only': path.resolve(__dirname, 'tests/stubs/server-only.ts'),
|
||||
},
|
||||
},
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue