feat(PBI-76): migrate cookie-based prefs to user-settings (Phase 2) (#189)

* feat(PBI-76): extend UserSettings schema with layout

Adds layout.splitPanePositions and layout.activeSprints. These will
hold values currently kept in client-side and server-side cookies
(Phase 2). Two new tests cover the shape.

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

* feat(PBI-76): migrate SplitPane positions to user-settings store

Outside of a drag the store is the source of truth (cross-tab
updates flow in for free). During a drag we keep splits in local
state so mousemove does not round-trip through the store. On
mouseup we persist the final splits via setPref. Removes
document.cookie reads/writes — cookieKey is reused as the
store-key for backwards compat.

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

* feat(PBI-76): resolveActiveSprint reads from User.settings

lib/active-sprint:
- New helpers: getActiveSprintIdFromSettings, setActiveSprintInSettings,
  clearActiveSprintInSettings — all read/write user.settings.layout.activeSprints.
- resolveActiveSprint(productId, userId) — userId now required, falls back
  to first OPEN, then most recent CLOSED sprint.
- Cookie helpers (getActiveSprintIdFromCookie/setActiveSprintCookie/
  clearActiveSprintCookie) removed.

Callers updated to pass session.userId. The cookie-based fallback path
is gone — `actions/active-sprint.ts` and `actions/sprints.ts` will be
updated in the next commit (T-917).

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

* feat(PBI-76): rewrite setActiveSprint callers to use settings

setActiveSprintAction, syncActiveSprintCookieAction, and the two
sprint-creation paths in actions/sprints.ts now write through
setActiveSprintInSettings (which also emits pg_notify for cross-tab
sync) instead of dropping a cookie. The action names keep the
'cookie' suffix in the user-visible API for now — clean rename can
come later.

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

* feat(PBI-76): migration helper v2 — handle legacy cookies

Bumps marker version to 'v2'. buildMigrationPatch now also scans
document.cookie for `sp:*` (split-pane positions) and
`active_sprint_*` (active sprint per product) and lifts them into
layout.splitPanePositions / layout.activeSprints. clearLegacyStorage
replaces clearLegacyLocalStorage and clears both keys and cookies.
clearLegacyLocalStorage stays as a deprecated alias so the bridge
upgrade is a single rename.

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

* test(PBI-76): align tests with new SplitPane and active-sprint flow

- split-pane.test.tsx: seed positions via Zustand store instead of
  document.cookie; mock @/actions/user-settings so the prisma client
  is not transitively initialised in jsdom.
- backlog-split-pane.test.tsx: same action mock.
- sprint-dates.test.ts: add user.findUnique/update + $executeRaw
  mocks because createSprintAction now writes to user-settings.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Janpeter Visser 2026-05-10 21:20:29 +02:00 committed by GitHub
parent 852945efa3
commit bf7162a5fc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 298 additions and 116 deletions

View file

@ -1,6 +1,10 @@
import { cookies } from 'next/headers'
import type { SprintStatus } from '@prisma/client'
import type { Prisma, SprintStatus } from '@prisma/client'
import { prisma } from '@/lib/prisma'
import {
mergeSettings,
parseUserSettings,
type UserSettings,
} from '@/lib/user-settings'
export type ActiveSprint = {
id: string
@ -8,43 +12,87 @@ export type ActiveSprint = {
status: SprintStatus
}
function cookieName(productId: string): string {
return `active_sprint_${productId}`
async function readSettings(userId: string): Promise<UserSettings> {
const user = await prisma.user.findUnique({
where: { id: userId },
select: { settings: true },
})
return parseUserSettings(user?.settings)
}
export async function getActiveSprintIdFromCookie(
productId: string,
): Promise<string | null> {
const store = await cookies()
return store.get(cookieName(productId))?.value ?? null
}
export async function setActiveSprintCookie(
productId: string,
sprintId: string,
): Promise<void> {
const store = await cookies()
store.set(cookieName(productId), sprintId, {
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 365,
async function writeSettings(userId: string, next: UserSettings): Promise<void> {
await prisma.user.update({
where: { id: userId },
data: { settings: next as unknown as Prisma.InputJsonValue },
})
}
export async function clearActiveSprintCookie(productId: string): Promise<void> {
const store = await cookies()
store.delete(cookieName(productId))
async function notifyUserSettings(
userId: string,
patch: Partial<UserSettings>,
): Promise<void> {
await prisma.$executeRaw`
SELECT pg_notify('scrum4me_changes', ${JSON.stringify({
kind: 'user_settings',
userId,
patch,
})}::text)
`
}
export async function getActiveSprintIdFromSettings(
userId: string,
productId: string,
): Promise<string | null> {
const settings = await readSettings(userId)
return settings.layout?.activeSprints?.[productId] ?? null
}
export async function setActiveSprintInSettings(
userId: string,
productId: string,
sprintId: string,
): Promise<void> {
const current = await readSettings(userId)
const patch: Partial<UserSettings> = {
layout: {
activeSprints: {
...(current.layout?.activeSprints ?? {}),
[productId]: sprintId,
},
},
}
await writeSettings(userId, mergeSettings(current, patch))
await notifyUserSettings(userId, patch)
}
export async function clearActiveSprintInSettings(
userId: string,
productId: string,
): Promise<void> {
const current = await readSettings(userId)
const existing = current.layout?.activeSprints
if (!existing || !(productId in existing)) return
const nextActiveSprints = { ...existing }
delete nextActiveSprints[productId]
const next: UserSettings = {
...current,
layout: { ...current.layout, activeSprints: nextActiveSprints },
}
await writeSettings(userId, next)
await notifyUserSettings(userId, {
layout: { activeSprints: nextActiveSprints },
})
}
export async function resolveActiveSprint(
productId: string,
userId: string,
): Promise<ActiveSprint | null> {
const cookieId = await getActiveSprintIdFromCookie(productId)
if (cookieId) {
const stored = await getActiveSprintIdFromSettings(userId, productId)
if (stored) {
const sprint = await prisma.sprint.findFirst({
where: { id: cookieId, product_id: productId },
where: { id: stored, product_id: productId },
select: { id: true, code: true, status: true },
})
if (sprint) return sprint

View file

@ -17,7 +17,7 @@ export async function getSoloWorkspaceSnapshot(
const product = await getAccessibleProduct(productId, userId)
if (!product) return null
const active = sprintId ? { id: sprintId } : await resolveActiveSprint(productId)
const active = sprintId ? { id: sprintId } : await resolveActiveSprint(productId, userId)
const sprint = active
? await prisma.sprint.findFirst({ where: { id: active.id, product_id: productId } })
: null

View file

@ -19,7 +19,7 @@ export interface SprintSwitcherData {
export async function getSprintSwitcherData(
productId: string,
opts?: { activeSprintId?: string | null },
opts?: { activeSprintId?: string | null; userId?: string },
): Promise<SprintSwitcherData> {
const allSprints = await prisma.sprint.findMany({
where: { product_id: productId },
@ -51,8 +51,8 @@ export async function getSprintSwitcherData(
activeSprintItem = opts.activeSprintId
? sprintItems.find(s => s.id === opts.activeSprintId) ?? null
: null
} else {
const resolved = await resolveActiveSprint(productId)
} else if (opts?.userId) {
const resolved = await resolveActiveSprint(productId, opts.userId)
activeSprintItem = resolved
? sprintItems.find(s => s.id === resolved.id) ?? null
: null

View file

@ -8,14 +8,28 @@
import type { UserSettings } from './user-settings'
const MIGRATION_MARKER = 'scrum4me:settings_migrated'
const CURRENT_VERSION = 'v1'
const CURRENT_VERSION = 'v2'
export interface MigrationResult {
patch: Partial<UserSettings>
legacyKeys: string[]
legacyCookies: string[]
hasData: boolean
}
function readCookies(): Record<string, string> {
if (typeof document === 'undefined') return {}
const out: Record<string, string> = {}
for (const part of document.cookie.split(';')) {
const eq = part.indexOf('=')
if (eq < 0) continue
const key = part.slice(0, eq).trim()
const val = part.slice(eq + 1).trim()
if (key) out[key] = val
}
return out
}
function readJsonArray(key: string): string[] | null {
const raw = localStorage.getItem(key)
if (!raw) return null
@ -54,13 +68,20 @@ function setIfNotNull<T>(target: Record<string, unknown>, key: string, value: T
}
export function buildMigrationPatch(): MigrationResult {
const empty: MigrationResult = { patch: {}, legacyKeys: [], hasData: false }
const empty: MigrationResult = {
patch: {},
legacyKeys: [],
legacyCookies: [],
hasData: false,
}
if (typeof window === 'undefined') return empty
if (localStorage.getItem(MIGRATION_MARKER) === CURRENT_VERSION) return empty
const patch: Partial<UserSettings> = {}
const views: NonNullable<UserSettings['views']> = {}
const layout: NonNullable<UserSettings['layout']> = {}
const legacyKeys: string[] = []
const legacyCookies: string[] = []
let hasData = false
// sprint_pb_*
@ -206,10 +227,48 @@ export function buildMigrationPatch(): MigrationResult {
hasData = true
}
return { patch, legacyKeys, hasData }
// layout from cookies (Phase 2)
const cookies = readCookies()
const splitPanePositions: Record<string, number[]> = {}
const activeSprints: Record<string, string> = {}
for (const [name, rawValue] of Object.entries(cookies)) {
if (name.startsWith('sp:')) {
const key = name.slice(3)
try {
const arr = JSON.parse(decodeURIComponent(rawValue))
if (
Array.isArray(arr) &&
arr.every((n) => typeof n === 'number') &&
Math.abs(arr.reduce((a, b) => a + b, 0) - 100) <= 1
) {
splitPanePositions[key] = arr as number[]
legacyCookies.push(name)
}
} catch {
// ignore malformed cookie
}
} else if (name.startsWith('active_sprint_') && rawValue) {
const productId = name.slice('active_sprint_'.length)
activeSprints[productId] = decodeURIComponent(rawValue)
legacyCookies.push(name)
}
}
if (Object.keys(splitPanePositions).length > 0) {
layout.splitPanePositions = splitPanePositions
hasData = true
}
if (Object.keys(activeSprints).length > 0) {
layout.activeSprints = activeSprints
hasData = true
}
if (Object.keys(layout).length > 0) {
patch.layout = layout
}
return { patch, legacyKeys, legacyCookies, hasData }
}
export function clearLegacyLocalStorage(keys: string[]): void {
export function clearLegacyStorage(keys: string[], cookies: string[] = []): void {
if (typeof window === 'undefined') return
for (const k of keys) {
try {
@ -218,9 +277,20 @@ export function clearLegacyLocalStorage(keys: string[]): void {
// storage quota exceeded or disabled — ignore
}
}
for (const c of cookies) {
try {
document.cookie = `${c}=; max-age=0; path=/; samesite=lax`
} catch {
// ignore
}
}
try {
localStorage.setItem(MIGRATION_MARKER, CURRENT_VERSION)
} catch {
// ignore
}
}
/** @deprecated use clearLegacyStorage */
export const clearLegacyLocalStorage = (keys: string[]) =>
clearLegacyStorage(keys, [])

View file

@ -43,9 +43,15 @@ const DevToolsPrefs = z.object({
debugMode: z.boolean().optional(),
}).strict()
const LayoutPrefs = z.object({
splitPanePositions: z.record(z.string(), z.array(z.number())).optional(),
activeSprints: z.record(z.string(), z.string()).optional(),
}).strict()
export const UserSettingsSchema = z.object({
views: ViewsPrefs.optional(),
devTools: DevToolsPrefs.optional(),
layout: LayoutPrefs.optional(),
}).strict()
export type UserSettings = z.infer<typeof UserSettingsSchema>