feat(PBI-74): sprint-workspace-store skelet (Story 9 / T-879)
- stores/sprint-workspace/{types,store,selectors,restore}.ts conform
product-workspace blueprint
- ContextSlice: activeProduct, activeSprintId, activeStoryId, activeTaskId
- EntitiesSlice: sprintsById, storiesById, tasksById
- RelationsSlice: sprintIdsByProduct, storyIdsBySprint, taskIdsByStory
- LoadingSlice met activeRequestId voor race-safe ensure*Loaded
- SyncSlice: realtimeStatus, lastResyncAt, resyncReason
- Realtime applyRealtimeEvent voor sprint/story/task entities + unknown-event
fallback, parent-move handling, child-cleanup bij D op sprint/story
- Optimistic mutations: sprint-story-order, sprint-task-order, entity-patch
- LocalStorage hints (storage key sprint-workspace-hints) per product/sprint
- 45 unit-tests groen — verplicht 13 cases uit workspace-store.md §Tests
This commit is contained in:
parent
5df04feb11
commit
fdd83005a8
6 changed files with 2348 additions and 0 deletions
119
__tests__/stores/sprint-workspace/restore.test.ts
Normal file
119
__tests__/stores/sprint-workspace/restore.test.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
clearHints,
|
||||
readHints,
|
||||
writeProductHint,
|
||||
writeSprintHint,
|
||||
writeStoryHint,
|
||||
writeTaskHint,
|
||||
} from '@/stores/sprint-workspace/restore'
|
||||
|
||||
describe('readHints', () => {
|
||||
it('retourneert lege defaults wanneer localStorage leeg is', () => {
|
||||
const hints = readHints()
|
||||
expect(hints.lastActiveProductId).toBeNull()
|
||||
expect(hints.perProduct).toEqual({})
|
||||
expect(hints.perSprint).toEqual({})
|
||||
})
|
||||
|
||||
it('herstelt hints uit localStorage', () => {
|
||||
localStorage.setItem(
|
||||
'sprint-workspace-hints',
|
||||
JSON.stringify({
|
||||
lastActiveProductId: 'p1',
|
||||
perProduct: { p1: { lastActiveSprintId: 'sp-1' } },
|
||||
perSprint: { 'sp-1': { lastActiveStoryId: 's-1' } },
|
||||
}),
|
||||
)
|
||||
const hints = readHints()
|
||||
expect(hints.lastActiveProductId).toBe('p1')
|
||||
expect(hints.perProduct.p1.lastActiveSprintId).toBe('sp-1')
|
||||
expect(hints.perSprint['sp-1'].lastActiveStoryId).toBe('s-1')
|
||||
})
|
||||
|
||||
it('valt terug op defaults bij ongeldige JSON', () => {
|
||||
localStorage.setItem('sprint-workspace-hints', '{not-json')
|
||||
const hints = readHints()
|
||||
expect(hints.lastActiveProductId).toBeNull()
|
||||
expect(hints.perProduct).toEqual({})
|
||||
expect(hints.perSprint).toEqual({})
|
||||
})
|
||||
|
||||
it('valt terug op defaults bij verkeerde shape', () => {
|
||||
localStorage.setItem('sprint-workspace-hints', '"just a string"')
|
||||
const hints = readHints()
|
||||
expect(hints.perProduct).toEqual({})
|
||||
expect(hints.perSprint).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('writeSprintHint', () => {
|
||||
it('schrijft lastActiveSprintId per productId', () => {
|
||||
writeSprintHint('prod-1', 'sp-a')
|
||||
writeSprintHint('prod-2', 'sp-b')
|
||||
const hints = readHints()
|
||||
expect(hints.perProduct['prod-1'].lastActiveSprintId).toBe('sp-a')
|
||||
expect(hints.perProduct['prod-2'].lastActiveSprintId).toBe('sp-b')
|
||||
})
|
||||
|
||||
it('accepteert null om sprint-hint te wissen', () => {
|
||||
writeSprintHint('prod-1', 'sp-a')
|
||||
writeSprintHint('prod-1', null)
|
||||
expect(readHints().perProduct['prod-1'].lastActiveSprintId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeStoryHint', () => {
|
||||
it('schrijft lastActiveStoryId per sprintId', () => {
|
||||
writeStoryHint('sp-1', 's-1')
|
||||
expect(readHints().perSprint['sp-1'].lastActiveStoryId).toBe('s-1')
|
||||
})
|
||||
|
||||
it('null wist child task-hint', () => {
|
||||
writeStoryHint('sp-1', 's-1')
|
||||
writeTaskHint('sp-1', 't-1')
|
||||
writeStoryHint('sp-1', null)
|
||||
expect(readHints().perSprint['sp-1'].lastActiveStoryId).toBeNull()
|
||||
expect(readHints().perSprint['sp-1'].lastActiveTaskId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeTaskHint', () => {
|
||||
it('schrijft lastActiveTaskId per sprintId', () => {
|
||||
writeTaskHint('sp-1', 't-1')
|
||||
expect(readHints().perSprint['sp-1'].lastActiveTaskId).toBe('t-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('clearHints', () => {
|
||||
it('verwijdert alle hints', () => {
|
||||
writeProductHint('p1')
|
||||
writeSprintHint('p1', 'sp-1')
|
||||
writeStoryHint('sp-1', 's-1')
|
||||
clearHints()
|
||||
const hints = readHints()
|
||||
expect(hints.lastActiveProductId).toBeNull()
|
||||
expect(hints.perProduct).toEqual({})
|
||||
expect(hints.perSprint).toEqual({})
|
||||
})
|
||||
})
|
||||
910
__tests__/stores/sprint-workspace/store.test.ts
Normal file
910
__tests__/stores/sprint-workspace/store.test.ts
Normal file
|
|
@ -0,0 +1,910 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { useSprintWorkspaceStore } from '@/stores/sprint-workspace/store'
|
||||
import type {
|
||||
SprintWorkspaceSnapshot,
|
||||
SprintWorkspaceSprint,
|
||||
SprintWorkspaceStory,
|
||||
SprintWorkspaceTask,
|
||||
SprintWorkspaceTaskDetail,
|
||||
} from '@/stores/sprint-workspace/types'
|
||||
|
||||
// G5: snapshot original actions on module-load; restore in beforeEach.
|
||||
const originalActions = (() => {
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
return {
|
||||
hydrateSnapshot: s.hydrateSnapshot,
|
||||
hydrateProductSprints: s.hydrateProductSprints,
|
||||
setActiveProduct: s.setActiveProduct,
|
||||
setActiveSprint: s.setActiveSprint,
|
||||
setActiveStory: s.setActiveStory,
|
||||
setActiveTask: s.setActiveTask,
|
||||
ensureProductSprintsLoaded: s.ensureProductSprintsLoaded,
|
||||
ensureSprintLoaded: s.ensureSprintLoaded,
|
||||
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() {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = null
|
||||
s.context.activeSprintId = null
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
s.entities.sprintsById = {}
|
||||
s.entities.storiesById = {}
|
||||
s.entities.tasksById = {}
|
||||
s.relations.sprintIdsByProduct = {}
|
||||
s.relations.storyIdsBySprint = {}
|
||||
s.relations.taskIdsByStory = {}
|
||||
s.loading.loadedProductSprintsIds = {}
|
||||
s.loading.loadingProductId = null
|
||||
s.loading.loadedSprintIds = {}
|
||||
s.loading.loadingSprintId = null
|
||||
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 makeSprint(
|
||||
overrides: Partial<SprintWorkspaceSprint> & { id: string; product_id: string },
|
||||
): SprintWorkspaceSprint {
|
||||
return {
|
||||
id: overrides.id,
|
||||
product_id: overrides.product_id,
|
||||
code: overrides.code ?? `S-${overrides.id}`,
|
||||
sprint_goal: overrides.sprint_goal ?? `Goal ${overrides.id}`,
|
||||
status: overrides.status ?? 'OPEN',
|
||||
start_date: overrides.start_date ?? '2026-04-01',
|
||||
end_date: overrides.end_date ?? '2026-04-14',
|
||||
created_at: overrides.created_at ?? new Date('2026-03-15'),
|
||||
completed_at: overrides.completed_at ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
function makeStory(
|
||||
overrides: Partial<SprintWorkspaceStory> & { id: string; pbi_id: string },
|
||||
): SprintWorkspaceStory {
|
||||
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<SprintWorkspaceTask> & { id: string; story_id: string },
|
||||
): SprintWorkspaceTask {
|
||||
return {
|
||||
id: overrides.id,
|
||||
code: overrides.code ?? null,
|
||||
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,
|
||||
sprint_id: overrides.sprint_id ?? null,
|
||||
created_at: overrides.created_at ?? new Date('2026-01-01'),
|
||||
}
|
||||
}
|
||||
|
||||
function snapshotWith(
|
||||
sprint: SprintWorkspaceSprint | undefined,
|
||||
stories: SprintWorkspaceStory[] = [],
|
||||
tasksByStory: Record<string, SprintWorkspaceTask[]> = {},
|
||||
product?: { id: string; name: string },
|
||||
): SprintWorkspaceSnapshot {
|
||||
return { product, sprint, stories, tasksByStory }
|
||||
}
|
||||
|
||||
// G7/G8: mock fetch via mockImplementation (vers Response per call)
|
||||
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, relations en loaded-marker', () => {
|
||||
const sprint = makeSprint({ id: 'sp-1', product_id: 'prod-1' })
|
||||
const storyA = makeStory({ id: 's-a', pbi_id: 'pbi-1', sprint_id: 'sp-1', sort_order: 2 })
|
||||
const storyB = makeStory({ id: 's-b', pbi_id: 'pbi-1', sprint_id: 'sp-1', sort_order: 1 })
|
||||
const taskA = makeTask({ id: 't-a', story_id: 's-a', sort_order: 2 })
|
||||
const taskB = makeTask({ id: 't-b', story_id: 's-a', sort_order: 1 })
|
||||
|
||||
useSprintWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
sprint,
|
||||
[storyA, storyB],
|
||||
{ 's-a': [taskA, taskB] },
|
||||
{ id: 'prod-1', name: 'Product 1' },
|
||||
),
|
||||
)
|
||||
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.entities.sprintsById['sp-1']).toEqual(sprint)
|
||||
expect(s.entities.storiesById['s-a']).toEqual(storyA)
|
||||
expect(s.entities.storiesById['s-b']).toEqual(storyB)
|
||||
// sort_order: storyB (1) before storyA (2)
|
||||
expect(s.relations.storyIdsBySprint['sp-1']).toEqual(['s-b', 's-a'])
|
||||
// sort_order: taskB (1) before taskA (2)
|
||||
expect(s.relations.taskIdsByStory['s-a']).toEqual(['t-b', 't-a'])
|
||||
expect(s.context.activeProduct).toEqual({ id: 'prod-1', name: 'Product 1' })
|
||||
expect(s.loading.loadedSprintIds['sp-1']).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hydrateProductSprints', () => {
|
||||
it('sorteert OPEN voor CLOSED, dan op start_date desc', () => {
|
||||
const closedOld = makeSprint({
|
||||
id: 'sp-closed-old',
|
||||
product_id: 'prod-1',
|
||||
status: 'CLOSED',
|
||||
start_date: '2026-01-01',
|
||||
})
|
||||
const openNew = makeSprint({
|
||||
id: 'sp-open-new',
|
||||
product_id: 'prod-1',
|
||||
status: 'OPEN',
|
||||
start_date: '2026-04-01',
|
||||
})
|
||||
const openOld = makeSprint({
|
||||
id: 'sp-open-old',
|
||||
product_id: 'prod-1',
|
||||
status: 'OPEN',
|
||||
start_date: '2026-02-01',
|
||||
})
|
||||
|
||||
useSprintWorkspaceStore
|
||||
.getState()
|
||||
.hydrateProductSprints('prod-1', [closedOld, openOld, openNew])
|
||||
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.relations.sprintIdsByProduct['prod-1']).toEqual([
|
||||
'sp-open-new',
|
||||
'sp-open-old',
|
||||
'sp-closed-old',
|
||||
])
|
||||
expect(s.loading.loadedProductSprintsIds['prod-1']).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// Selection cascade
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('selection cascade', () => {
|
||||
it('setActiveSprint reset story+task; setActiveStory reset task', () => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeSprintId = 'sp-old'
|
||||
s.context.activeStoryId = 's-old'
|
||||
s.context.activeTaskId = 't-old'
|
||||
})
|
||||
|
||||
useSprintWorkspaceStore.getState().setActiveSprint('sp-new')
|
||||
let s = useSprintWorkspaceStore.getState()
|
||||
expect(s.context.activeSprintId).toBe('sp-new')
|
||||
expect(s.context.activeStoryId).toBeNull()
|
||||
expect(s.context.activeTaskId).toBeNull()
|
||||
|
||||
useSprintWorkspaceStore.setState((draft) => {
|
||||
draft.context.activeStoryId = 's-old'
|
||||
draft.context.activeTaskId = 't-old'
|
||||
})
|
||||
useSprintWorkspaceStore.getState().setActiveStory('s-new')
|
||||
s = useSprintWorkspaceStore.getState()
|
||||
expect(s.context.activeStoryId).toBe('s-new')
|
||||
expect(s.context.activeTaskId).toBeNull()
|
||||
})
|
||||
|
||||
it('setActiveProduct(null) ruimt entities en relations op', () => {
|
||||
useSprintWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
makeSprint({ id: 'sp-1', product_id: 'prod-1' }),
|
||||
[makeStory({ id: 's-1', pbi_id: 'pbi-1', sprint_id: 'sp-1' })],
|
||||
{ 's-1': [makeTask({ id: 't-1', story_id: 's-1' })] },
|
||||
{ id: 'prod-1', name: 'Product 1' },
|
||||
),
|
||||
)
|
||||
|
||||
useSprintWorkspaceStore.getState().setActiveProduct(null)
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.context.activeProduct).toBeNull()
|
||||
expect(s.context.activeSprintId).toBeNull()
|
||||
expect(s.entities.sprintsById).toEqual({})
|
||||
expect(s.entities.storiesById).toEqual({})
|
||||
expect(s.entities.tasksById).toEqual({})
|
||||
expect(s.relations.sprintIdsByProduct).toEqual({})
|
||||
expect(s.relations.storyIdsBySprint).toEqual({})
|
||||
expect(s.relations.taskIdsByStory).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// applyRealtimeEvent
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('applyRealtimeEvent — sprint', () => {
|
||||
beforeEach(() => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
})
|
||||
|
||||
it('I — voegt sprint toe aan product-lijst', () => {
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'sprint',
|
||||
op: 'I',
|
||||
id: 'sp-new',
|
||||
product_id: 'prod-1',
|
||||
code: 'S-1',
|
||||
sprint_goal: 'New Sprint',
|
||||
status: 'OPEN',
|
||||
start_date: '2026-05-01',
|
||||
end_date: '2026-05-14',
|
||||
created_at: new Date('2026-04-15').toISOString(),
|
||||
})
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.entities.sprintsById['sp-new']).toBeDefined()
|
||||
expect(s.relations.sprintIdsByProduct['prod-1']).toContain('sp-new')
|
||||
})
|
||||
|
||||
it('I — idempotent voor bestaande id', () => {
|
||||
useSprintWorkspaceStore
|
||||
.getState()
|
||||
.hydrateProductSprints('prod-1', [
|
||||
makeSprint({ id: 'sp-1', product_id: 'prod-1', sprint_goal: 'Origineel' }),
|
||||
])
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'sprint',
|
||||
op: 'I',
|
||||
id: 'sp-1',
|
||||
product_id: 'prod-1',
|
||||
sprint_goal: 'echo',
|
||||
})
|
||||
expect(useSprintWorkspaceStore.getState().entities.sprintsById['sp-1'].sprint_goal).toBe(
|
||||
'Origineel',
|
||||
)
|
||||
})
|
||||
|
||||
it('U — patch + her-sorteert', () => {
|
||||
useSprintWorkspaceStore
|
||||
.getState()
|
||||
.hydrateProductSprints('prod-1', [
|
||||
makeSprint({
|
||||
id: 'sp-a',
|
||||
product_id: 'prod-1',
|
||||
status: 'OPEN',
|
||||
start_date: '2026-04-01',
|
||||
}),
|
||||
makeSprint({
|
||||
id: 'sp-b',
|
||||
product_id: 'prod-1',
|
||||
status: 'OPEN',
|
||||
start_date: '2026-03-01',
|
||||
}),
|
||||
])
|
||||
// sp-a (newer) komt eerst
|
||||
expect(
|
||||
useSprintWorkspaceStore.getState().relations.sprintIdsByProduct['prod-1'],
|
||||
).toEqual(['sp-a', 'sp-b'])
|
||||
|
||||
// Sluit sp-a → moet naar achteren
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'sprint',
|
||||
op: 'U',
|
||||
id: 'sp-a',
|
||||
product_id: 'prod-1',
|
||||
status: 'CLOSED',
|
||||
})
|
||||
expect(
|
||||
useSprintWorkspaceStore.getState().relations.sprintIdsByProduct['prod-1'],
|
||||
).toEqual(['sp-b', 'sp-a'])
|
||||
})
|
||||
|
||||
it('D — verwijdert sprint inclusief child stories en tasks', () => {
|
||||
useSprintWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
makeSprint({ id: 'sp-1', product_id: 'prod-1' }),
|
||||
[makeStory({ id: 's-1', pbi_id: 'pbi-1', sprint_id: 'sp-1' })],
|
||||
{ 's-1': [makeTask({ id: 't-1', story_id: 's-1' })] },
|
||||
{ id: 'prod-1', name: 'Product 1' },
|
||||
),
|
||||
)
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'sprint',
|
||||
op: 'D',
|
||||
id: 'sp-1',
|
||||
product_id: 'prod-1',
|
||||
})
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.entities.sprintsById['sp-1']).toBeUndefined()
|
||||
expect(s.entities.storiesById['s-1']).toBeUndefined()
|
||||
expect(s.entities.tasksById['t-1']).toBeUndefined()
|
||||
expect(s.relations.storyIdsBySprint['sp-1']).toBeUndefined()
|
||||
expect(s.relations.taskIdsByStory['s-1']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('D — clear actieve sprint selectie als die de verwijderde sprint was', () => {
|
||||
useSprintWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(makeSprint({ id: 'sp-1', product_id: 'prod-1' }), []),
|
||||
)
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeSprintId = 'sp-1'
|
||||
s.context.activeStoryId = 's-x'
|
||||
s.context.activeTaskId = 't-x'
|
||||
})
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'sprint',
|
||||
op: 'D',
|
||||
id: 'sp-1',
|
||||
product_id: 'prod-1',
|
||||
})
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.context.activeSprintId).toBeNull()
|
||||
expect(s.context.activeStoryId).toBeNull()
|
||||
expect(s.context.activeTaskId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRealtimeEvent — story sprint-move', () => {
|
||||
beforeEach(() => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
useSprintWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
makeSprint({ id: 'sp-1', product_id: 'prod-1' }),
|
||||
[makeStory({ id: 's-1', pbi_id: 'pbi-1', sprint_id: 'sp-1' })],
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('U met andere sprint_id verplaatst story uit sprint-relatie', () => {
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'story',
|
||||
op: 'U',
|
||||
id: 's-1',
|
||||
product_id: 'prod-1',
|
||||
pbi_id: 'pbi-1',
|
||||
sprint_id: 'sp-other',
|
||||
})
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.relations.storyIdsBySprint['sp-1']).toEqual([])
|
||||
expect(s.relations.storyIdsBySprint['sp-other']).toEqual(['s-1'])
|
||||
expect(s.entities.storiesById['s-1'].sprint_id).toBe('sp-other')
|
||||
})
|
||||
|
||||
it('U met sprint_id=null haalt story uit sprint-relatie', () => {
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'story',
|
||||
op: 'U',
|
||||
id: 's-1',
|
||||
product_id: 'prod-1',
|
||||
pbi_id: 'pbi-1',
|
||||
sprint_id: null,
|
||||
})
|
||||
expect(useSprintWorkspaceStore.getState().relations.storyIdsBySprint['sp-1']).toEqual([])
|
||||
expect(useSprintWorkspaceStore.getState().entities.storiesById['s-1'].sprint_id).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRealtimeEvent — task parent-move', () => {
|
||||
beforeEach(() => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
useSprintWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
makeSprint({ id: 'sp-1', product_id: 'prod-1' }),
|
||||
[
|
||||
makeStory({ id: 's-1', pbi_id: 'pbi-1', sprint_id: 'sp-1' }),
|
||||
makeStory({ id: 's-2', pbi_id: 'pbi-1', sprint_id: 'sp-1' }),
|
||||
],
|
||||
{
|
||||
's-1': [makeTask({ id: 't-1', story_id: 's-1' })],
|
||||
's-2': [],
|
||||
},
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('U met andere story_id verplaatst task naar nieuwe parent', () => {
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'task',
|
||||
op: 'U',
|
||||
id: 't-1',
|
||||
product_id: 'prod-1',
|
||||
story_id: 's-2',
|
||||
})
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.relations.taskIdsByStory['s-1']).toEqual([])
|
||||
expect(s.relations.taskIdsByStory['s-2']).toEqual(['t-1'])
|
||||
expect(s.entities.tasksById['t-1'].story_id).toBe('s-2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRealtimeEvent — andere product genegeerd', () => {
|
||||
it('event met ander product_id raakt de store niet', () => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
useSprintWorkspaceStore
|
||||
.getState()
|
||||
.hydrateProductSprints('prod-1', [makeSprint({ id: 'sp-1', product_id: 'prod-1' })])
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'sprint',
|
||||
op: 'I',
|
||||
id: 'sp-other',
|
||||
product_id: 'prod-2',
|
||||
code: 'X',
|
||||
})
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.entities.sprintsById['sp-other']).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyRealtimeEvent — unknown entity → resync trigger', () => {
|
||||
function withSpy(): ReturnType<typeof vi.fn> {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
})
|
||||
const spy = vi.fn().mockResolvedValue(undefined)
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.resyncActiveScopes = spy as unknown as typeof s.resyncActiveScopes
|
||||
})
|
||||
return spy
|
||||
}
|
||||
|
||||
it('unknown entity met matching product triggert resync', () => {
|
||||
const spy = withSpy()
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'comment',
|
||||
op: 'I',
|
||||
id: 'cm-1',
|
||||
product_id: 'prod-1',
|
||||
})
|
||||
expect(spy).toHaveBeenCalledWith('unknown-event')
|
||||
})
|
||||
|
||||
it('unknown entity met ander product_id triggert geen resync', () => {
|
||||
const spy = withSpy()
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'comment',
|
||||
op: 'I',
|
||||
id: 'cm-1',
|
||||
product_id: 'prod-2',
|
||||
})
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('claude_job_status (type-veld) triggert geen resync', () => {
|
||||
const spy = withSpy()
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
type: 'claude_job_status',
|
||||
job_id: 'job-1',
|
||||
product_id: 'prod-1',
|
||||
status: 'queued',
|
||||
})
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('worker_heartbeat (type-veld) triggert geen resync', () => {
|
||||
const spy = withSpy()
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
type: 'worker_heartbeat',
|
||||
worker_id: 'w-1',
|
||||
product_id: 'prod-1',
|
||||
})
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('payload zonder entity en zonder type wordt genegeerd', () => {
|
||||
const spy = withSpy()
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
product_id: 'prod-1',
|
||||
something: 'else',
|
||||
})
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// ensure*Loaded
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('ensureProductSprintsLoaded', () => {
|
||||
it('fetcht sprint-list en hydreert met sortering', async () => {
|
||||
const sprints = [
|
||||
makeSprint({
|
||||
id: 'sp-old',
|
||||
product_id: 'prod-1',
|
||||
status: 'CLOSED',
|
||||
start_date: '2026-01-01',
|
||||
}),
|
||||
makeSprint({
|
||||
id: 'sp-new',
|
||||
product_id: 'prod-1',
|
||||
status: 'OPEN',
|
||||
start_date: '2026-04-01',
|
||||
}),
|
||||
]
|
||||
const fetchSpy = mockFetchSequence([sprints])
|
||||
|
||||
await useSprintWorkspaceStore.getState().ensureProductSprintsLoaded('prod-1')
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'/api/products/prod-1/sprints',
|
||||
expect.objectContaining({ cache: 'no-store' }),
|
||||
)
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.relations.sprintIdsByProduct['prod-1']).toEqual(['sp-new', 'sp-old'])
|
||||
expect(s.loading.loadedProductSprintsIds['prod-1']).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureSprintLoaded', () => {
|
||||
it('fetcht sprint-snapshot en hydreert', async () => {
|
||||
const sprint = makeSprint({ id: 'sp-1', product_id: 'prod-1' })
|
||||
const snapshot: SprintWorkspaceSnapshot = {
|
||||
product: { id: 'prod-1', name: 'P1' },
|
||||
sprint,
|
||||
stories: [makeStory({ id: 's-1', pbi_id: 'pbi-1', sprint_id: 'sp-1' })],
|
||||
tasksByStory: {
|
||||
's-1': [makeTask({ id: 't-1', story_id: 's-1' })],
|
||||
},
|
||||
}
|
||||
const fetchSpy = mockFetchSequence([snapshot])
|
||||
|
||||
await useSprintWorkspaceStore.getState().ensureSprintLoaded('sp-1')
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'/api/sprints/sp-1/workspace',
|
||||
expect.objectContaining({ cache: 'no-store' }),
|
||||
)
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.entities.sprintsById['sp-1']).toBeDefined()
|
||||
expect(s.relations.storyIdsBySprint['sp-1']).toEqual(['s-1'])
|
||||
expect(s.relations.taskIdsByStory['s-1']).toEqual(['t-1'])
|
||||
expect(s.loading.loadedSprintIds['sp-1']).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('race-safe ensure*Loaded — activeRequestId guard', () => {
|
||||
it('oudere in-flight ensureSprintLoaded mag nieuwere selectie niet overschrijven', async () => {
|
||||
let resolveOld: ((snap: SprintWorkspaceSnapshot) => void) | null = null
|
||||
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation((async (url: string) => {
|
||||
if (url === '/api/sprints/sp-old/workspace') {
|
||||
const snap = await new Promise<SprintWorkspaceSnapshot>((resolve) => {
|
||||
resolveOld = resolve
|
||||
})
|
||||
return new Response(JSON.stringify(snap), { status: 200 })
|
||||
}
|
||||
if (url === '/api/sprints/sp-new/workspace') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
sprint: makeSprint({ id: 'sp-new', product_id: 'prod-1' }),
|
||||
stories: [makeStory({ id: 'new-st', pbi_id: 'p', sprint_id: 'sp-new' })],
|
||||
tasksByStory: {},
|
||||
}),
|
||||
{ status: 200 },
|
||||
)
|
||||
}
|
||||
return new Response('null', { status: 200 })
|
||||
}) as unknown as typeof fetch)
|
||||
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
|
||||
s.context.activeSprintId = 'sp-old'
|
||||
s.loading.activeRequestId = 'req-old'
|
||||
})
|
||||
const oldPromise = useSprintWorkspaceStore
|
||||
.getState()
|
||||
.ensureSprintLoaded('sp-old', 'req-old')
|
||||
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeSprintId = 'sp-new'
|
||||
s.loading.activeRequestId = 'req-new'
|
||||
})
|
||||
await useSprintWorkspaceStore
|
||||
.getState()
|
||||
.ensureSprintLoaded('sp-new', 'req-new')
|
||||
|
||||
expect(useSprintWorkspaceStore.getState().entities.storiesById['new-st']).toBeDefined()
|
||||
|
||||
resolveOld!({
|
||||
sprint: makeSprint({ id: 'sp-old', product_id: 'prod-1' }),
|
||||
stories: [makeStory({ id: 'old-st', pbi_id: 'p', sprint_id: 'sp-old' })],
|
||||
tasksByStory: {},
|
||||
})
|
||||
await oldPromise
|
||||
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.context.activeSprintId).toBe('sp-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',
|
||||
code: 'C1',
|
||||
title: 'Task 1',
|
||||
description: 'desc',
|
||||
priority: 1,
|
||||
sort_order: 1,
|
||||
status: 'todo',
|
||||
story_id: 's-1',
|
||||
sprint_id: 'sp-1',
|
||||
created_at: new Date('2026-02-01').toISOString(),
|
||||
implementation_plan: 'detailed plan here',
|
||||
},
|
||||
])
|
||||
|
||||
await useSprintWorkspaceStore.getState().ensureTaskLoaded('t-1')
|
||||
const task = useSprintWorkspaceStore.getState().entities.tasksById[
|
||||
't-1'
|
||||
] as SprintWorkspaceTaskDetail
|
||||
expect(task._detail).toBe(true)
|
||||
expect(task.implementation_plan).toBe('detailed plan here')
|
||||
expect(useSprintWorkspaceStore.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([
|
||||
// ensureProductSprintsLoaded
|
||||
[],
|
||||
// ensureSprintLoaded
|
||||
{
|
||||
sprint: makeSprint({ id: 'sp-1', product_id: 'prod-1' }),
|
||||
stories: [],
|
||||
tasksByStory: {},
|
||||
},
|
||||
// ensureStoryLoaded
|
||||
[],
|
||||
// ensureTaskLoaded
|
||||
{
|
||||
id: 't-1',
|
||||
title: 'T',
|
||||
description: null,
|
||||
priority: 1,
|
||||
sort_order: 1,
|
||||
status: 'todo',
|
||||
story_id: 's-1',
|
||||
sprint_id: 'sp-1',
|
||||
created_at: '2026-02-01',
|
||||
},
|
||||
])
|
||||
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'P' }
|
||||
s.context.activeSprintId = 'sp-1'
|
||||
s.context.activeStoryId = 's-1'
|
||||
s.context.activeTaskId = 't-1'
|
||||
})
|
||||
|
||||
await useSprintWorkspaceStore.getState().resyncActiveScopes('manual')
|
||||
|
||||
const calls = fetchSpy.mock.calls.map(([url]) => url)
|
||||
expect(calls).toContain('/api/products/prod-1/sprints')
|
||||
expect(calls).toContain('/api/sprints/sp-1/workspace')
|
||||
expect(calls).toContain('/api/stories/s-1/tasks')
|
||||
expect(calls).toContain('/api/tasks/t-1')
|
||||
|
||||
const s = useSprintWorkspaceStore.getState()
|
||||
expect(s.sync.lastResyncAt).toBeTypeOf('number')
|
||||
expect(s.sync.resyncReason).toBe('manual')
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// Restore-hint flow
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('restore-hint flow — setters persisteren hints', () => {
|
||||
it('setActiveProduct schrijft lastActiveProductId', () => {
|
||||
useSprintWorkspaceStore.getState().setActiveProduct({ id: 'prod-1', name: 'P1' })
|
||||
const raw = localStorage.getItem('sprint-workspace-hints')
|
||||
expect(raw).not.toBeNull()
|
||||
const hints = JSON.parse(raw!)
|
||||
expect(hints.lastActiveProductId).toBe('prod-1')
|
||||
})
|
||||
|
||||
it('setActiveSprint schrijft lastActiveSprintId per product', () => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'P1' }
|
||||
})
|
||||
useSprintWorkspaceStore.getState().setActiveSprint('sp-a')
|
||||
const hints = JSON.parse(localStorage.getItem('sprint-workspace-hints')!)
|
||||
expect(hints.perProduct['prod-1'].lastActiveSprintId).toBe('sp-a')
|
||||
})
|
||||
|
||||
it('setActiveStory schrijft lastActiveStoryId per sprint', () => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeSprintId = 'sp-1'
|
||||
})
|
||||
useSprintWorkspaceStore.getState().setActiveStory('s-a')
|
||||
const hints = JSON.parse(localStorage.getItem('sprint-workspace-hints')!)
|
||||
expect(hints.perSprint['sp-1'].lastActiveStoryId).toBe('s-a')
|
||||
})
|
||||
|
||||
it('setActiveTask schrijft lastActiveTaskId per sprint', () => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeSprintId = 'sp-1'
|
||||
})
|
||||
useSprintWorkspaceStore.getState().setActiveTask('t-a')
|
||||
const hints = JSON.parse(localStorage.getItem('sprint-workspace-hints')!)
|
||||
expect(hints.perSprint['sp-1'].lastActiveTaskId).toBe('t-a')
|
||||
})
|
||||
})
|
||||
|
||||
describe('restore-hint flow — chain triggert na ensure*Loaded', () => {
|
||||
it('hint die NIET in entities zit wordt genegeerd', async () => {
|
||||
localStorage.setItem(
|
||||
'sprint-workspace-hints',
|
||||
JSON.stringify({
|
||||
lastActiveProductId: 'prod-1',
|
||||
perProduct: { 'prod-1': { lastActiveSprintId: 'ghost-sprint' } },
|
||||
perSprint: {},
|
||||
}),
|
||||
)
|
||||
mockFetchSequence([[]])
|
||||
|
||||
useSprintWorkspaceStore.getState().setActiveProduct({ id: 'prod-1', name: 'P1' })
|
||||
await new Promise((r) => setTimeout(r, 20))
|
||||
|
||||
expect(useSprintWorkspaceStore.getState().context.activeSprintId).toBeNull()
|
||||
})
|
||||
|
||||
it('hint die wel in entities zit wordt toegepast', async () => {
|
||||
const validSprint = makeSprint({ id: 'sp-known', product_id: 'prod-1' })
|
||||
localStorage.setItem(
|
||||
'sprint-workspace-hints',
|
||||
JSON.stringify({
|
||||
lastActiveProductId: 'prod-1',
|
||||
perProduct: { 'prod-1': { lastActiveSprintId: 'sp-known' } },
|
||||
perSprint: {},
|
||||
}),
|
||||
)
|
||||
mockFetchSequence([
|
||||
// ensureProductSprintsLoaded — levert sp-known
|
||||
[validSprint],
|
||||
// ensureSprintLoaded triggered door setActiveSprint(hint)
|
||||
{ sprint: validSprint, stories: [], tasksByStory: {} },
|
||||
])
|
||||
|
||||
useSprintWorkspaceStore.getState().setActiveProduct({ id: 'prod-1', name: 'P1' })
|
||||
await new Promise((r) => setTimeout(r, 30))
|
||||
|
||||
expect(useSprintWorkspaceStore.getState().context.activeSprintId).toBe('sp-known')
|
||||
})
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// Optimistic mutations
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('optimistic mutations', () => {
|
||||
it('rollback herstelt vorige sprint-story-order', () => {
|
||||
useSprintWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(
|
||||
makeSprint({ id: 'sp-1', product_id: 'prod-1' }),
|
||||
[
|
||||
makeStory({ id: 'a', pbi_id: 'p', sprint_id: 'sp-1', sort_order: 1 }),
|
||||
makeStory({ id: 'b', pbi_id: 'p', sprint_id: 'sp-1', sort_order: 2 }),
|
||||
],
|
||||
),
|
||||
)
|
||||
const prevOrder = [
|
||||
...useSprintWorkspaceStore.getState().relations.storyIdsBySprint['sp-1'],
|
||||
]
|
||||
|
||||
const id = useSprintWorkspaceStore.getState().applyOptimisticMutation({
|
||||
kind: 'sprint-story-order',
|
||||
sprintId: 'sp-1',
|
||||
prevStoryIds: prevOrder,
|
||||
})
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.relations.storyIdsBySprint['sp-1'] = ['b', 'a']
|
||||
})
|
||||
|
||||
useSprintWorkspaceStore.getState().rollbackMutation(id)
|
||||
expect(useSprintWorkspaceStore.getState().relations.storyIdsBySprint['sp-1']).toEqual(
|
||||
prevOrder,
|
||||
)
|
||||
expect(useSprintWorkspaceStore.getState().pendingMutations[id]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('settle ruimt pending op zonder state te wijzigen', () => {
|
||||
useSprintWorkspaceStore.getState().hydrateSnapshot(
|
||||
snapshotWith(makeSprint({ id: 'sp-1', product_id: 'prod-1' }), [
|
||||
makeStory({ id: 'a', pbi_id: 'p', sprint_id: 'sp-1' }),
|
||||
]),
|
||||
)
|
||||
const id = useSprintWorkspaceStore.getState().applyOptimisticMutation({
|
||||
kind: 'sprint-story-order',
|
||||
sprintId: 'sp-1',
|
||||
prevStoryIds: ['a'],
|
||||
})
|
||||
expect(useSprintWorkspaceStore.getState().pendingMutations[id]).toBeDefined()
|
||||
|
||||
useSprintWorkspaceStore.getState().settleMutation(id)
|
||||
expect(useSprintWorkspaceStore.getState().pendingMutations[id]).toBeUndefined()
|
||||
expect(useSprintWorkspaceStore.getState().relations.storyIdsBySprint['sp-1']).toEqual([
|
||||
'a',
|
||||
])
|
||||
})
|
||||
|
||||
it('SSE-echo van een al-bestaande sprint is idempotent', () => {
|
||||
useSprintWorkspaceStore.setState((s) => {
|
||||
s.context.activeProduct = { id: 'prod-1', name: 'P' }
|
||||
})
|
||||
useSprintWorkspaceStore
|
||||
.getState()
|
||||
.hydrateProductSprints('prod-1', [
|
||||
makeSprint({ id: 'sp-1', product_id: 'prod-1', sprint_goal: 'Origineel' }),
|
||||
])
|
||||
useSprintWorkspaceStore.getState().applyRealtimeEvent({
|
||||
entity: 'sprint',
|
||||
op: 'I',
|
||||
id: 'sp-1',
|
||||
product_id: 'prod-1',
|
||||
sprint_goal: 'echo',
|
||||
})
|
||||
expect(
|
||||
useSprintWorkspaceStore.getState().entities.sprintsById['sp-1'].sprint_goal,
|
||||
).toBe('Origineel')
|
||||
})
|
||||
})
|
||||
128
stores/sprint-workspace/restore.ts
Normal file
128
stores/sprint-workspace/restore.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
const STORAGE_KEY = 'sprint-workspace-hints'
|
||||
|
||||
interface PerProductHint {
|
||||
lastActiveSprintId?: string | null
|
||||
}
|
||||
|
||||
interface PerSprintHint {
|
||||
lastActiveStoryId?: string | null
|
||||
lastActiveTaskId?: string | null
|
||||
}
|
||||
|
||||
export interface SprintWorkspaceHints {
|
||||
lastActiveProductId: string | null
|
||||
perProduct: Record<string, PerProductHint>
|
||||
perSprint: Record<string, PerSprintHint>
|
||||
}
|
||||
|
||||
const EMPTY_HINTS: SprintWorkspaceHints = {
|
||||
lastActiveProductId: null,
|
||||
perProduct: {},
|
||||
perSprint: {},
|
||||
}
|
||||
|
||||
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(): SprintWorkspaceHints {
|
||||
const storage = safeStorage()
|
||||
if (!storage) return { ...EMPTY_HINTS, perProduct: {}, perSprint: {} }
|
||||
try {
|
||||
const raw = storage.getItem(STORAGE_KEY)
|
||||
if (!raw) return { ...EMPTY_HINTS, perProduct: {}, perSprint: {} }
|
||||
const parsed = JSON.parse(raw) as Partial<SprintWorkspaceHints> | null
|
||||
if (!parsed || typeof parsed !== 'object') {
|
||||
return { ...EMPTY_HINTS, perProduct: {}, perSprint: {} }
|
||||
}
|
||||
return {
|
||||
lastActiveProductId: parsed.lastActiveProductId ?? null,
|
||||
perProduct:
|
||||
parsed.perProduct && typeof parsed.perProduct === 'object'
|
||||
? parsed.perProduct
|
||||
: {},
|
||||
perSprint:
|
||||
parsed.perSprint && typeof parsed.perSprint === 'object'
|
||||
? parsed.perSprint
|
||||
: {},
|
||||
}
|
||||
} catch {
|
||||
return { ...EMPTY_HINTS, perProduct: {}, perSprint: {} }
|
||||
}
|
||||
}
|
||||
|
||||
function writeHints(hints: SprintWorkspaceHints): 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: SprintWorkspaceHints,
|
||||
productId: string,
|
||||
): PerProductHint {
|
||||
if (!hints.perProduct[productId]) {
|
||||
hints.perProduct[productId] = {}
|
||||
}
|
||||
return hints.perProduct[productId]
|
||||
}
|
||||
|
||||
function ensurePerSprint(
|
||||
hints: SprintWorkspaceHints,
|
||||
sprintId: string,
|
||||
): PerSprintHint {
|
||||
if (!hints.perSprint[sprintId]) {
|
||||
hints.perSprint[sprintId] = {}
|
||||
}
|
||||
return hints.perSprint[sprintId]
|
||||
}
|
||||
|
||||
export function writeSprintHint(productId: string, sprintId: string | null): void {
|
||||
const hints = readHints()
|
||||
const entry = ensurePerProduct(hints, productId)
|
||||
entry.lastActiveSprintId = sprintId
|
||||
writeHints(hints)
|
||||
}
|
||||
|
||||
export function writeStoryHint(sprintId: string, storyId: string | null): void {
|
||||
const hints = readHints()
|
||||
const entry = ensurePerSprint(hints, sprintId)
|
||||
entry.lastActiveStoryId = storyId
|
||||
if (storyId === null) {
|
||||
entry.lastActiveTaskId = null
|
||||
}
|
||||
writeHints(hints)
|
||||
}
|
||||
|
||||
export function writeTaskHint(sprintId: string, taskId: string | null): void {
|
||||
const hints = readHints()
|
||||
const entry = ensurePerSprint(hints, sprintId)
|
||||
entry.lastActiveTaskId = taskId
|
||||
writeHints(hints)
|
||||
}
|
||||
|
||||
export function clearHints(): void {
|
||||
const storage = safeStorage()
|
||||
if (!storage) return
|
||||
try {
|
||||
storage.removeItem(STORAGE_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
115
stores/sprint-workspace/selectors.ts
Normal file
115
stores/sprint-workspace/selectors.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import type { SprintWorkspaceStore } from './store'
|
||||
import type {
|
||||
SprintWorkspaceSprint,
|
||||
SprintWorkspaceStory,
|
||||
SprintWorkspaceTask,
|
||||
SprintWorkspaceTaskDetail,
|
||||
} from './types'
|
||||
|
||||
// G1: stable EMPTY-references zodat selectors geen nieuwe array per call retourneren.
|
||||
const EMPTY_SPRINTS: SprintWorkspaceSprint[] = []
|
||||
const EMPTY_STORIES: SprintWorkspaceStory[] = []
|
||||
const EMPTY_TASKS: (SprintWorkspaceTask | SprintWorkspaceTaskDetail)[] = []
|
||||
|
||||
/**
|
||||
* Lijst-selector. Vereist `useShallow` in componenten (G2).
|
||||
*/
|
||||
export function selectVisibleSprints(s: SprintWorkspaceStore): SprintWorkspaceSprint[] {
|
||||
const productId = s.context.activeProduct?.id
|
||||
if (!productId) return EMPTY_SPRINTS
|
||||
const ids = s.relations.sprintIdsByProduct[productId]
|
||||
if (!ids || ids.length === 0) return EMPTY_SPRINTS
|
||||
const out: SprintWorkspaceSprint[] = []
|
||||
for (const id of ids) {
|
||||
const sprint = s.entities.sprintsById[id]
|
||||
if (sprint) out.push(sprint)
|
||||
}
|
||||
return out.length === 0 ? EMPTY_SPRINTS : out
|
||||
}
|
||||
|
||||
/**
|
||||
* Lijst-selector. Vereist `useShallow` in componenten (G2).
|
||||
*/
|
||||
export function selectStoriesForActiveSprint(
|
||||
s: SprintWorkspaceStore,
|
||||
): SprintWorkspaceStory[] {
|
||||
const sprintId = s.context.activeSprintId
|
||||
if (!sprintId) return EMPTY_STORIES
|
||||
const ids = s.relations.storyIdsBySprint[sprintId]
|
||||
if (!ids || ids.length === 0) return EMPTY_STORIES
|
||||
const out: SprintWorkspaceStory[] = []
|
||||
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: SprintWorkspaceStore,
|
||||
): (SprintWorkspaceTask | SprintWorkspaceTaskDetail)[] {
|
||||
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: (SprintWorkspaceTask | SprintWorkspaceTaskDetail)[] = []
|
||||
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.
|
||||
*/
|
||||
export function selectActiveSprint(
|
||||
s: SprintWorkspaceStore,
|
||||
): SprintWorkspaceSprint | null {
|
||||
const id = s.context.activeSprintId
|
||||
if (!id) return null
|
||||
return s.entities.sprintsById[id] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-value selector. `useShallow` niet vereist.
|
||||
*/
|
||||
export function selectActiveStory(
|
||||
s: SprintWorkspaceStore,
|
||||
): SprintWorkspaceStory | 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: SprintWorkspaceStore,
|
||||
): SprintWorkspaceTask | SprintWorkspaceTaskDetail | null {
|
||||
const id = s.context.activeTaskId
|
||||
if (!id) return null
|
||||
return s.entities.tasksById[id] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Lijst-selector voor tasks binnen een specifieke story (niet per se actief).
|
||||
* Vereist `useShallow` in componenten (G2).
|
||||
*/
|
||||
export function selectTasksForStory(
|
||||
s: SprintWorkspaceStore,
|
||||
storyId: string,
|
||||
): (SprintWorkspaceTask | SprintWorkspaceTaskDetail)[] {
|
||||
const ids = s.relations.taskIdsByStory[storyId]
|
||||
if (!ids || ids.length === 0) return EMPTY_TASKS
|
||||
const out: (SprintWorkspaceTask | SprintWorkspaceTaskDetail)[] = []
|
||||
for (const id of ids) {
|
||||
const task = s.entities.tasksById[id]
|
||||
if (task) out.push(task)
|
||||
}
|
||||
return out.length === 0 ? EMPTY_TASKS : out
|
||||
}
|
||||
918
stores/sprint-workspace/store.ts
Normal file
918
stores/sprint-workspace/store.ts
Normal file
|
|
@ -0,0 +1,918 @@
|
|||
import { create } from 'zustand'
|
||||
import { immer } from 'zustand/middleware/immer'
|
||||
|
||||
import {
|
||||
isDetail,
|
||||
type ActiveProductRef,
|
||||
type OptimisticMutation,
|
||||
type PendingOptimisticMutation,
|
||||
type RealtimeStatus,
|
||||
type ResyncReason,
|
||||
type SprintWorkspaceSnapshot,
|
||||
type SprintWorkspaceSprint,
|
||||
type SprintWorkspaceStory,
|
||||
type SprintWorkspaceTask,
|
||||
type SprintWorkspaceTaskDetail,
|
||||
} from './types'
|
||||
import {
|
||||
readHints,
|
||||
writeProductHint,
|
||||
writeSprintHint,
|
||||
writeStoryHint,
|
||||
writeTaskHint,
|
||||
} from './restore'
|
||||
|
||||
interface ContextSlice {
|
||||
activeProduct: ActiveProductRef | null
|
||||
activeSprintId: string | null
|
||||
activeStoryId: string | null
|
||||
activeTaskId: string | null
|
||||
}
|
||||
|
||||
interface EntitiesSlice {
|
||||
sprintsById: Record<string, SprintWorkspaceSprint>
|
||||
storiesById: Record<string, SprintWorkspaceStory>
|
||||
tasksById: Record<string, SprintWorkspaceTask | SprintWorkspaceTaskDetail>
|
||||
}
|
||||
|
||||
interface RelationsSlice {
|
||||
sprintIdsByProduct: Record<string, string[]>
|
||||
storyIdsBySprint: Record<string, string[]>
|
||||
taskIdsByStory: Record<string, string[]>
|
||||
}
|
||||
|
||||
interface LoadingSlice {
|
||||
loadedProductSprintsIds: Record<string, true>
|
||||
loadingProductId: string | null
|
||||
loadedSprintIds: Record<string, true>
|
||||
loadingSprintId: string | null
|
||||
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: SprintWorkspaceSnapshot): void
|
||||
hydrateProductSprints(productId: string, sprints: SprintWorkspaceSprint[]): void
|
||||
|
||||
setActiveProduct(product: ActiveProductRef | null): void
|
||||
setActiveSprint(sprintId: string | null): void
|
||||
setActiveStory(storyId: string | null): void
|
||||
setActiveTask(taskId: string | null): void
|
||||
|
||||
ensureProductSprintsLoaded(productId: string, requestId?: string): Promise<void>
|
||||
ensureSprintLoaded(sprintId: string, requestId?: string): Promise<void>
|
||||
ensureStoryLoaded(storyId: string, requestId?: string): Promise<void>
|
||||
ensureTaskLoaded(taskId: string, requestId?: string): Promise<void>
|
||||
|
||||
applyRealtimeEvent(event: 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 SprintWorkspaceStore = State & Actions
|
||||
|
||||
const initialState: State = {
|
||||
context: {
|
||||
activeProduct: null,
|
||||
activeSprintId: null,
|
||||
activeStoryId: null,
|
||||
activeTaskId: null,
|
||||
},
|
||||
entities: {
|
||||
sprintsById: {},
|
||||
storiesById: {},
|
||||
tasksById: {},
|
||||
},
|
||||
relations: {
|
||||
sprintIdsByProduct: {},
|
||||
storyIdsBySprint: {},
|
||||
taskIdsByStory: {},
|
||||
},
|
||||
loading: {
|
||||
loadedProductSprintsIds: {},
|
||||
loadingProductId: null,
|
||||
loadedSprintIds: {},
|
||||
loadingSprintId: null,
|
||||
loadedStoryIds: {},
|
||||
loadedTaskIds: {},
|
||||
activeRequestId: null,
|
||||
},
|
||||
sync: {
|
||||
realtimeStatus: 'connecting',
|
||||
lastEventAt: null,
|
||||
lastResyncAt: null,
|
||||
resyncReason: null,
|
||||
},
|
||||
pendingMutations: {},
|
||||
}
|
||||
|
||||
function compareSprint(a: SprintWorkspaceSprint, b: SprintWorkspaceSprint): number {
|
||||
// OPEN sprints first, then CLOSED
|
||||
if (a.status !== b.status) return a.status === 'OPEN' ? -1 : 1
|
||||
// Newest start_date first within same status
|
||||
const aStart = a.start_date ? new Date(a.start_date).getTime() : 0
|
||||
const bStart = b.start_date ? new Date(b.start_date).getTime() : 0
|
||||
if (aStart !== bStart) return bStart - aStart
|
||||
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
|
||||
}
|
||||
|
||||
function compareStory(a: SprintWorkspaceStory, b: SprintWorkspaceStory): 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: SprintWorkspaceTask, b: SprintWorkspaceTask): 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 'sprint' | 'story' | 'task' {
|
||||
return entity === 'sprint' || 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 useSprintWorkspaceStore = create<SprintWorkspaceStore>()(
|
||||
immer((set, get) => ({
|
||||
...initialState,
|
||||
|
||||
hydrateSnapshot(snapshot) {
|
||||
set((s) => {
|
||||
if (snapshot.product) s.context.activeProduct = snapshot.product
|
||||
|
||||
const sprintId = snapshot.sprint?.id ?? null
|
||||
const productId = snapshot.product?.id ?? snapshot.sprint?.product_id ?? null
|
||||
|
||||
if (snapshot.sprint) {
|
||||
s.entities.sprintsById[snapshot.sprint.id] = snapshot.sprint
|
||||
if (productId) {
|
||||
const list = s.relations.sprintIdsByProduct[productId] ?? []
|
||||
if (!list.includes(snapshot.sprint.id)) {
|
||||
list.push(snapshot.sprint.id)
|
||||
s.relations.sprintIdsByProduct[productId] = sortSprintIds(
|
||||
s.entities.sprintsById,
|
||||
list,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const story of snapshot.stories) {
|
||||
s.entities.storiesById[story.id] = story
|
||||
}
|
||||
if (sprintId) {
|
||||
s.relations.storyIdsBySprint[sprintId] = [...snapshot.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 (sprintId) {
|
||||
s.loading.loadedSprintIds[sprintId] = true
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
hydrateProductSprints(productId, sprints) {
|
||||
set((s) => {
|
||||
for (const sprint of sprints) {
|
||||
s.entities.sprintsById[sprint.id] = sprint
|
||||
}
|
||||
s.relations.sprintIdsByProduct[productId] = [...sprints]
|
||||
.sort(compareSprint)
|
||||
.map((sp) => sp.id)
|
||||
s.loading.loadedProductSprintsIds[productId] = true
|
||||
})
|
||||
},
|
||||
|
||||
setActiveProduct(product) {
|
||||
const requestId = newRequestId()
|
||||
const productChanged = get().context.activeProduct?.id !== product?.id
|
||||
|
||||
set((s) => {
|
||||
s.context.activeProduct = product
|
||||
s.context.activeSprintId = null
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
s.loading.activeRequestId = requestId
|
||||
|
||||
if (productChanged) {
|
||||
s.entities.sprintsById = {}
|
||||
s.entities.storiesById = {}
|
||||
s.entities.tasksById = {}
|
||||
s.relations.sprintIdsByProduct = {}
|
||||
s.relations.storyIdsBySprint = {}
|
||||
s.relations.taskIdsByStory = {}
|
||||
s.loading.loadedProductSprintsIds = {}
|
||||
s.loading.loadedSprintIds = {}
|
||||
s.loading.loadedStoryIds = {}
|
||||
s.loading.loadedTaskIds = {}
|
||||
}
|
||||
})
|
||||
|
||||
writeProductHint(product?.id ?? null)
|
||||
|
||||
if (product) {
|
||||
const productId = product.id
|
||||
void (async () => {
|
||||
await get().ensureProductSprintsLoaded(productId, requestId)
|
||||
if (get().loading.activeRequestId !== requestId) return
|
||||
const hint = readHints().perProduct[productId]?.lastActiveSprintId
|
||||
if (hint && get().entities.sprintsById[hint]) {
|
||||
get().setActiveSprint(hint)
|
||||
}
|
||||
})()
|
||||
}
|
||||
},
|
||||
|
||||
setActiveSprint(sprintId) {
|
||||
const requestId = newRequestId()
|
||||
const productId = get().context.activeProduct?.id ?? null
|
||||
|
||||
set((s) => {
|
||||
s.context.activeSprintId = sprintId
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
s.loading.activeRequestId = requestId
|
||||
})
|
||||
|
||||
if (productId) writeSprintHint(productId, sprintId)
|
||||
|
||||
if (sprintId) {
|
||||
void (async () => {
|
||||
await get().ensureSprintLoaded(sprintId, requestId)
|
||||
if (get().loading.activeRequestId !== requestId) return
|
||||
const hint = readHints().perSprint[sprintId]?.lastActiveStoryId
|
||||
if (hint && get().entities.storiesById[hint]) {
|
||||
get().setActiveStory(hint)
|
||||
}
|
||||
})()
|
||||
}
|
||||
},
|
||||
|
||||
setActiveStory(storyId) {
|
||||
const requestId = newRequestId()
|
||||
const sprintId = get().context.activeSprintId
|
||||
|
||||
set((s) => {
|
||||
s.context.activeStoryId = storyId
|
||||
s.context.activeTaskId = null
|
||||
s.loading.activeRequestId = requestId
|
||||
})
|
||||
|
||||
if (sprintId) writeStoryHint(sprintId, storyId)
|
||||
|
||||
if (storyId) {
|
||||
void (async () => {
|
||||
await get().ensureStoryLoaded(storyId, requestId)
|
||||
if (get().loading.activeRequestId !== requestId) return
|
||||
if (!sprintId) return
|
||||
const hint = readHints().perSprint[sprintId]?.lastActiveTaskId
|
||||
if (hint && get().entities.tasksById[hint]) {
|
||||
get().setActiveTask(hint)
|
||||
}
|
||||
})()
|
||||
}
|
||||
},
|
||||
|
||||
setActiveTask(taskId) {
|
||||
const sprintId = get().context.activeSprintId
|
||||
|
||||
set((s) => {
|
||||
s.context.activeTaskId = taskId
|
||||
})
|
||||
|
||||
if (sprintId) writeTaskHint(sprintId, taskId)
|
||||
|
||||
if (taskId) {
|
||||
void get().ensureTaskLoaded(taskId)
|
||||
}
|
||||
},
|
||||
|
||||
async ensureProductSprintsLoaded(productId, requestId) {
|
||||
set((s) => {
|
||||
s.loading.loadingProductId = productId
|
||||
})
|
||||
try {
|
||||
const sprints = await fetchJson<SprintWorkspaceSprint[] | null>(
|
||||
`/api/products/${encodeURIComponent(productId)}/sprints`,
|
||||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!Array.isArray(sprints)) return
|
||||
get().hydrateProductSprints(productId, sprints)
|
||||
} finally {
|
||||
set((s) => {
|
||||
if (s.loading.loadingProductId === productId) {
|
||||
s.loading.loadingProductId = null
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
async ensureSprintLoaded(sprintId, requestId) {
|
||||
set((s) => {
|
||||
s.loading.loadingSprintId = sprintId
|
||||
})
|
||||
try {
|
||||
const snapshot = await fetchJson<SprintWorkspaceSnapshot | null>(
|
||||
`/api/sprints/${encodeURIComponent(sprintId)}/workspace`,
|
||||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!snapshot || !Array.isArray(snapshot.stories)) return
|
||||
get().hydrateSnapshot(snapshot)
|
||||
} finally {
|
||||
set((s) => {
|
||||
if (s.loading.loadingSprintId === sprintId) {
|
||||
s.loading.loadingSprintId = null
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
async ensureStoryLoaded(storyId, requestId) {
|
||||
const tasks = await fetchJson<SprintWorkspaceTask[] | 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<SprintWorkspaceTaskDetail | 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 === 'sprint') {
|
||||
applySprintEvent(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().ensureProductSprintsLoaded(ctx.activeProduct.id))
|
||||
}
|
||||
if (ctx.activeSprintId) tasks.push(get().ensureSprintLoaded(ctx.activeSprintId))
|
||||
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>[] = []
|
||||
for (const productId of Object.keys(loading.loadedProductSprintsIds)) {
|
||||
tasks.push(get().ensureProductSprintsLoaded(productId))
|
||||
}
|
||||
for (const sprintId of Object.keys(loading.loadedSprintIds)) {
|
||||
tasks.push(get().ensureSprintLoaded(sprintId))
|
||||
}
|
||||
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(),
|
||||
}
|
||||
})
|
||||
return id
|
||||
},
|
||||
|
||||
rollbackMutation(mutationId) {
|
||||
const pending = get().pendingMutations[mutationId]
|
||||
if (!pending) return
|
||||
const { mutation } = pending
|
||||
set((s) => {
|
||||
switch (mutation.kind) {
|
||||
case 'sprint-story-order':
|
||||
s.relations.storyIdsBySprint[mutation.sprintId] = [...mutation.prevStoryIds]
|
||||
break
|
||||
case 'sprint-task-order':
|
||||
s.relations.taskIdsByStory[mutation.storyId] = [...mutation.prevTaskIds]
|
||||
break
|
||||
case 'entity-patch': {
|
||||
const { entity, id, prev } = mutation
|
||||
if (prev) {
|
||||
if (entity === 'sprint')
|
||||
s.entities.sprintsById[id] = prev as SprintWorkspaceSprint
|
||||
else if (entity === 'story')
|
||||
s.entities.storiesById[id] = prev as SprintWorkspaceStory
|
||||
else
|
||||
s.entities.tasksById[id] = prev as
|
||||
| SprintWorkspaceTask
|
||||
| SprintWorkspaceTaskDetail
|
||||
} else {
|
||||
if (entity === 'sprint') delete s.entities.sprintsById[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<SprintWorkspaceStore>>[0]>[0]
|
||||
type ImmerGet = () => SprintWorkspaceStore
|
||||
|
||||
function applySprintEvent(
|
||||
id: string,
|
||||
op: 'I' | 'U' | 'D',
|
||||
payload: Record<string, unknown>,
|
||||
set: ImmerSet,
|
||||
get: ImmerGet,
|
||||
) {
|
||||
if (op === 'D') {
|
||||
set((s) => {
|
||||
const sprint = s.entities.sprintsById[id]
|
||||
const productId = sprint?.product_id
|
||||
// Cascade: stories binnen deze sprint, tasks binnen die stories
|
||||
const childStoryIds = s.relations.storyIdsBySprint[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.storyIdsBySprint[id]
|
||||
delete s.entities.sprintsById[id]
|
||||
if (productId) {
|
||||
const list = s.relations.sprintIdsByProduct[productId]
|
||||
if (list) {
|
||||
s.relations.sprintIdsByProduct[productId] = list.filter((sid) => sid !== id)
|
||||
}
|
||||
} else {
|
||||
for (const pid of Object.keys(s.relations.sprintIdsByProduct)) {
|
||||
s.relations.sprintIdsByProduct[pid] = s.relations.sprintIdsByProduct[pid].filter(
|
||||
(sid) => sid !== id,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (s.context.activeSprintId === id) {
|
||||
s.context.activeSprintId = null
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (op === 'U') {
|
||||
if (!get().entities.sprintsById[id]) return
|
||||
set((s) => {
|
||||
const existing = s.entities.sprintsById[id]
|
||||
if (!existing) return
|
||||
Object.assign(existing, sanitizeSprintPayload(payload))
|
||||
const productId = existing.product_id
|
||||
if (productId && s.relations.sprintIdsByProduct[productId]) {
|
||||
s.relations.sprintIdsByProduct[productId] = sortSprintIds(
|
||||
s.entities.sprintsById,
|
||||
s.relations.sprintIdsByProduct[productId],
|
||||
)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// I
|
||||
if (get().entities.sprintsById[id]) return
|
||||
set((s) => {
|
||||
const sprint = coerceSprintPayload(id, payload)
|
||||
s.entities.sprintsById[id] = sprint
|
||||
const productId = sprint.product_id
|
||||
const list = s.relations.sprintIdsByProduct[productId] ?? []
|
||||
list.push(id)
|
||||
s.relations.sprintIdsByProduct[productId] = sortSprintIds(s.entities.sprintsById, list)
|
||||
})
|
||||
}
|
||||
|
||||
function applyStoryEvent(
|
||||
id: string,
|
||||
op: 'I' | 'U' | 'D',
|
||||
payload: Record<string, unknown>,
|
||||
set: ImmerSet,
|
||||
get: ImmerGet,
|
||||
) {
|
||||
const activeSprintId = get().context.activeSprintId
|
||||
|
||||
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?.sprint_id) {
|
||||
const ids = s.relations.storyIdsBySprint[story.sprint_id]
|
||||
if (ids) {
|
||||
s.relations.storyIdsBySprint[story.sprint_id] = ids.filter((sid) => sid !== id)
|
||||
}
|
||||
} else {
|
||||
for (const sprintId of Object.keys(s.relations.storyIdsBySprint)) {
|
||||
s.relations.storyIdsBySprint[sprintId] = s.relations.storyIdsBySprint[sprintId].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) {
|
||||
// Story moved into our active sprint? If sprint_id matches active, treat as I
|
||||
if (
|
||||
activeSprintId &&
|
||||
payload.sprint_id === activeSprintId &&
|
||||
get().context.activeProduct?.id === payload.product_id
|
||||
) {
|
||||
set((s) => {
|
||||
const story = coerceStoryPayload(id, payload)
|
||||
s.entities.storiesById[id] = story
|
||||
if (story.sprint_id) {
|
||||
const list = s.relations.storyIdsBySprint[story.sprint_id] ?? []
|
||||
if (!list.includes(id)) list.push(id)
|
||||
s.relations.storyIdsBySprint[story.sprint_id] = sortStoryIds(
|
||||
s.entities.storiesById,
|
||||
list,
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
set((s) => {
|
||||
const story = s.entities.storiesById[id]
|
||||
if (!story) return
|
||||
const oldSprintId = story.sprint_id
|
||||
Object.assign(story, sanitizeStoryPayload(payload))
|
||||
const newSprintId = story.sprint_id
|
||||
if (oldSprintId !== newSprintId) {
|
||||
if (oldSprintId) {
|
||||
const oldList = s.relations.storyIdsBySprint[oldSprintId]
|
||||
if (oldList) {
|
||||
s.relations.storyIdsBySprint[oldSprintId] = oldList.filter((sid) => sid !== id)
|
||||
}
|
||||
}
|
||||
if (newSprintId) {
|
||||
const targetList = s.relations.storyIdsBySprint[newSprintId] ?? []
|
||||
if (!targetList.includes(id)) targetList.push(id)
|
||||
s.relations.storyIdsBySprint[newSprintId] = sortStoryIds(
|
||||
s.entities.storiesById,
|
||||
targetList,
|
||||
)
|
||||
}
|
||||
} else if (oldSprintId && s.relations.storyIdsBySprint[oldSprintId]) {
|
||||
s.relations.storyIdsBySprint[oldSprintId] = sortStoryIds(
|
||||
s.entities.storiesById,
|
||||
s.relations.storyIdsBySprint[oldSprintId],
|
||||
)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// I
|
||||
if (get().entities.storiesById[id]) return
|
||||
set((s) => {
|
||||
const story = coerceStoryPayload(id, payload)
|
||||
s.entities.storiesById[id] = story
|
||||
if (story.sprint_id) {
|
||||
const list = s.relations.storyIdsBySprint[story.sprint_id] ?? []
|
||||
list.push(id)
|
||||
s.relations.storyIdsBySprint[story.sprint_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 sortSprintIds(
|
||||
byId: Record<string, SprintWorkspaceSprint>,
|
||||
ids: string[],
|
||||
): string[] {
|
||||
return [...new Set(ids)]
|
||||
.filter((id) => byId[id] !== undefined)
|
||||
.sort((a, b) => compareSprint(byId[a], byId[b]))
|
||||
}
|
||||
|
||||
function sortStoryIds(
|
||||
byId: Record<string, SprintWorkspaceStory>,
|
||||
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, SprintWorkspaceTask | SprintWorkspaceTaskDetail>,
|
||||
ids: string[],
|
||||
): string[] {
|
||||
return [...new Set(ids)]
|
||||
.filter((id) => byId[id] !== undefined)
|
||||
.sort((a, b) => compareTask(byId[a], byId[b]))
|
||||
}
|
||||
|
||||
function sanitizeSprintPayload(p: Record<string, unknown>): Partial<SprintWorkspaceSprint> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
void _e
|
||||
void _o
|
||||
return rest as Partial<SprintWorkspaceSprint>
|
||||
}
|
||||
|
||||
function sanitizeStoryPayload(p: Record<string, unknown>): Partial<SprintWorkspaceStory> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
void _e
|
||||
void _o
|
||||
return rest as Partial<SprintWorkspaceStory>
|
||||
}
|
||||
|
||||
function sanitizeTaskPayload(p: Record<string, unknown>): Partial<SprintWorkspaceTask> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
void _e
|
||||
void _o
|
||||
return rest as Partial<SprintWorkspaceTask>
|
||||
}
|
||||
|
||||
function coerceSprintPayload(
|
||||
id: string,
|
||||
p: Record<string, unknown>,
|
||||
): SprintWorkspaceSprint {
|
||||
return {
|
||||
id,
|
||||
product_id: String(p.product_id ?? ''),
|
||||
code: String(p.code ?? ''),
|
||||
sprint_goal: String(p.sprint_goal ?? ''),
|
||||
status: (p.status as SprintWorkspaceSprint['status']) ?? 'OPEN',
|
||||
start_date: (p.start_date as string | null | undefined) ?? null,
|
||||
end_date: (p.end_date as string | null | undefined) ?? null,
|
||||
created_at:
|
||||
p.created_at instanceof Date
|
||||
? p.created_at
|
||||
: new Date(String(p.created_at ?? Date.now())),
|
||||
completed_at:
|
||||
p.completed_at instanceof Date
|
||||
? p.completed_at
|
||||
: p.completed_at
|
||||
? new Date(String(p.completed_at))
|
||||
: null,
|
||||
}
|
||||
}
|
||||
|
||||
function coerceStoryPayload(
|
||||
id: string,
|
||||
p: Record<string, unknown>,
|
||||
): SprintWorkspaceStory {
|
||||
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>): SprintWorkspaceTask {
|
||||
return {
|
||||
id,
|
||||
code: (p.code as string | null) ?? null,
|
||||
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 ?? ''),
|
||||
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())),
|
||||
}
|
||||
}
|
||||
158
stores/sprint-workspace/types.ts
Normal file
158
stores/sprint-workspace/types.ts
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import type { TaskStatusApi } from '@/lib/task-status'
|
||||
|
||||
export type SprintStatus = 'OPEN' | 'CLOSED'
|
||||
|
||||
export interface SprintWorkspaceSprint {
|
||||
id: string
|
||||
product_id: string
|
||||
code: string
|
||||
sprint_goal: string
|
||||
status: SprintStatus
|
||||
start_date: string | null
|
||||
end_date: string | null
|
||||
created_at: Date
|
||||
completed_at: Date | null
|
||||
}
|
||||
|
||||
export interface SprintWorkspaceStory {
|
||||
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
|
||||
taskCount?: number
|
||||
doneCount?: number
|
||||
assignee_id?: string | null
|
||||
assignee_username?: string | null
|
||||
}
|
||||
|
||||
export interface SprintWorkspaceTask {
|
||||
id: string
|
||||
code: string | null
|
||||
title: string
|
||||
description: string | null
|
||||
priority: number
|
||||
sort_order: number
|
||||
status: TaskStatusApi | string
|
||||
story_id: string
|
||||
sprint_id: string | null
|
||||
created_at: Date
|
||||
}
|
||||
|
||||
export interface SprintWorkspaceTaskDetail extends SprintWorkspaceTask {
|
||||
_detail: true
|
||||
implementation_plan?: string | null
|
||||
acceptance_criteria?: string | null
|
||||
requires_opus?: boolean
|
||||
verify_only?: boolean
|
||||
estimated_minutes?: number | null
|
||||
}
|
||||
|
||||
export function isDetail(
|
||||
task: SprintWorkspaceTask | SprintWorkspaceTaskDetail,
|
||||
): task is SprintWorkspaceTaskDetail {
|
||||
return (task as SprintWorkspaceTaskDetail)._detail === true
|
||||
}
|
||||
|
||||
export interface ActiveProductRef {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface SprintWorkspaceSnapshot {
|
||||
product?: ActiveProductRef
|
||||
sprint?: SprintWorkspaceSprint
|
||||
stories: SprintWorkspaceStory[]
|
||||
tasksByStory: Record<string, SprintWorkspaceTask[]>
|
||||
}
|
||||
|
||||
export interface ProductSprintsList {
|
||||
productId: string
|
||||
sprints: SprintWorkspaceSprint[]
|
||||
}
|
||||
|
||||
export type Op = 'I' | 'U' | 'D'
|
||||
|
||||
export interface SprintEntityRealtimeEvent {
|
||||
entity: 'sprint'
|
||||
op: Op
|
||||
id: string
|
||||
product_id: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface SprintStoryRealtimeEvent {
|
||||
entity: 'story'
|
||||
op: Op
|
||||
id: string
|
||||
product_id: string
|
||||
pbi_id?: string
|
||||
sprint_id?: string | null
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface SprintTaskRealtimeEvent {
|
||||
entity: 'task'
|
||||
op: Op
|
||||
id: string
|
||||
product_id: string
|
||||
story_id?: string
|
||||
sprint_id?: string | null
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type SprintRealtimeEvent =
|
||||
| SprintEntityRealtimeEvent
|
||||
| SprintStoryRealtimeEvent
|
||||
| SprintTaskRealtimeEvent
|
||||
|
||||
export type ResyncReason =
|
||||
| 'visible'
|
||||
| 'reconnect'
|
||||
| 'manual'
|
||||
| 'unknown-event'
|
||||
| 'stale-scope'
|
||||
| 'mutation-settled'
|
||||
|
||||
export type RealtimeStatus = 'connecting' | 'open' | 'disconnected'
|
||||
|
||||
export interface OptimisticSprintStoryOrderMutation {
|
||||
kind: 'sprint-story-order'
|
||||
sprintId: string
|
||||
prevStoryIds: string[]
|
||||
}
|
||||
|
||||
export interface OptimisticSprintTaskOrderMutation {
|
||||
kind: 'sprint-task-order'
|
||||
storyId: string
|
||||
prevTaskIds: string[]
|
||||
}
|
||||
|
||||
export interface OptimisticEntityPatchMutation {
|
||||
kind: 'entity-patch'
|
||||
entity: 'sprint' | 'story' | 'task'
|
||||
id: string
|
||||
prev:
|
||||
| SprintWorkspaceSprint
|
||||
| SprintWorkspaceStory
|
||||
| SprintWorkspaceTask
|
||||
| SprintWorkspaceTaskDetail
|
||||
| undefined
|
||||
}
|
||||
|
||||
export type OptimisticMutation =
|
||||
| OptimisticSprintStoryOrderMutation
|
||||
| OptimisticSprintTaskOrderMutation
|
||||
| OptimisticEntityPatchMutation
|
||||
|
||||
export interface PendingOptimisticMutation {
|
||||
id: string
|
||||
mutation: OptimisticMutation
|
||||
createdAt: number
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue