fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,237 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
// mergeWithDefaults is exercised for real; it just fills defaults on the input.
import { GET, PUT } from '../route'
import { requireWritePermission } from '@/lib/auth/require-write'
const mockUser = { id: 'user-1', email: '[email protected]' }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
})
describe('GET /api/kpi/preferences', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/api/kpi/preferences'), { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns merged preferences', async () => {
enqueue({ data: { value: {} } })
const res = await GET(createMockRequest('/api/kpi/preferences'), { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
expect(status).toBe(200)
expect(body.data).toBeDefined()
})
})
describe('PUT /api/kpi/preferences', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/kpi/preferences', { method: 'PUT', body: {} })
const res = await PUT(req, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 403 when caller has read-only role', async () => {
vi.mocked(requireWritePermission).mockResolvedValue({
ok: false,
response: NextResponse.json(
{ error: 'Du har endast läsbehörighet i detta företag.' },
{ status: 403 },
),
})
const req = createMockRequest('/api/kpi/preferences', { method: 'PUT', body: {} })
const res = await PUT(req, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
})
it('rejects an account override that is not a 4-digit string', async () => {
const req = createMockRequest('/api/kpi/preferences', {
method: 'PUT',
body: { accountOverrides: { some_kpi: ['abc'] } },
})
const res = await PUT(req, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(400)
expect(body.error).toContain('4 digits')
})
it('upserts and returns the stored value on the happy path', async () => {
enqueue({ data: { value: {} } }) // existing row lookup
enqueue({ data: { value: { accountOverrides: { some_kpi: ['3001'] } } } }) // upsert
const req = createMockRequest('/api/kpi/preferences', {
method: 'PUT',
body: { accountOverrides: { some_kpi: ['3001'] } },
})
const res = await PUT(req, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: { accountOverrides: Record<string, string[]> } }>(res)
expect(status).toBe(200)
expect(body.data.accountOverrides.some_kpi).toEqual(['3001'])
})
it('rejects an accountOverrides value that is not an array of strings', async () => {
const req = createMockRequest('/api/kpi/preferences', {
method: 'PUT',
body: { accountOverrides: { some_kpi: 'not-an-array' } },
})
const res = await PUT(req, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
})
/**
* A partial save used to reset every unmentioned setting: mergeWithDefaults()
* fills absent keys with FACTORY defaults, and the merged document was what got
* stored, so saving an account override wiped the user's visible-KPI selection
* and ordering. The merge base is now the STORED row. Asserted on the payload
* handed to upsert(); the shared queued mock proxies every chain method, so the
* payload is captured with a purpose-built recorder.
*/
describe('PUT /api/kpi/preferences merge semantics', () => {
function createCapturingSupabase(results: { data?: unknown; error?: unknown }[]) {
const upsertPayloads: Record<string, unknown>[] = []
const upsertOptions: ({ onConflict?: string } | undefined)[] = []
let idx = 0
const makeBuilder = () => {
const result = results[idx++] ?? { data: null, error: null }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const b: any = {}
for (const m of ['select', 'eq', 'maybeSingle', 'single']) {
b[m] = () => b
}
b.upsert = (payload: Record<string, unknown>, options?: { onConflict?: string }) => {
upsertPayloads.push(payload)
upsertOptions.push(options)
return b
}
b.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null })
return b
}
return { supabase: { from: () => makeBuilder() }, upsertPayloads, upsertOptions }
}
const stored = {
visibleKpis: ['kpi_a'],
kpiOrder: ['kpi_a', 'kpi_b'],
accountOverrides: { kpi_a: ['3001'] },
}
async function put(body: unknown, existing: unknown) {
const { supabase, upsertPayloads, upsertOptions } = createCapturingSupabase([
{ data: existing === undefined ? null : { value: existing } },
{ data: { value: 'ok' } },
])
requireAuthMock.mockResolvedValue({ user: mockUser, supabase, error: null })
const res = await PUT(
createMockRequest('/api/kpi/preferences', { method: 'PUT', body }),
{ params: Promise.resolve({}) },
)
return {
res,
value: upsertPayloads[0]?.value as Record<string, unknown> | undefined,
payload: upsertPayloads[0],
options: upsertOptions[0],
}
}
it('keeps the stored visibleKpis and kpiOrder when only accountOverrides is sent', async () => {
const { res, value } = await put({ accountOverrides: { kpi_b: ['4010'] } }, stored)
expect(res.status).toBe(200)
expect(value).toEqual({
visibleKpis: ['kpi_a'],
kpiOrder: ['kpi_a', 'kpi_b'],
accountOverrides: { kpi_b: ['4010'] },
showMonthlyTable: true,
})
})
it('replaces every key when the dialog sends the complete object', async () => {
const full = {
visibleKpis: ['kpi_z'],
kpiOrder: ['kpi_z'],
accountOverrides: { kpi_z: ['3010'] },
showMonthlyTable: false,
}
const { value } = await put(full, stored)
expect(value).toEqual(full)
})
it('falls back to defaults for a row that has never been written', async () => {
const { res, value } = await put({ visibleKpis: ['kpi_new'] }, undefined)
expect(res.status).toBe(200)
expect(value?.visibleKpis).toEqual(['kpi_new'])
// The other two keys come from the defaults, not from undefined.
expect(value?.kpiOrder).toBeDefined()
expect(value?.accountOverrides).toBeDefined()
})
it('an empty body stores the stored value unchanged', async () => {
const { value } = await put({}, stored)
expect(value).toEqual({ ...stored, showMonthlyTable: true })
})
it('stores showMonthlyTable false and leaves the other keys alone', async () => {
const { res, value } = await put({ showMonthlyTable: false }, stored)
expect(res.status).toBe(200)
expect(value).toEqual({ ...stored, showMonthlyTable: false })
})
it('rejects a non-boolean showMonthlyTable', async () => {
const { res } = await put({ showMonthlyTable: 'yes' }, stored)
expect(res.status).toBe(400)
})
it('upserts against the company-scoped unique constraint', async () => {
// Migration 20260330130000 dropped UNIQUE (user_id, extension_id, key) in
// favor of UNIQUE (company_id, extension_id, key). Naming the old trio in
// onConflict makes Postgres reject every save with 42P10, because the
// surviving user_id index is non-unique and cannot arbitrate ON CONFLICT.
const { res, payload, options } = await put({ visibleKpis: ['kpi_a'] }, stored)
expect(res.status).toBe(200)
expect(options?.onConflict).toBe('company_id,extension_id,key')
// The row still carries company scoping + last-writer attribution.
expect(payload).toMatchObject({
company_id: 'company-1',
user_id: 'user-1',
extension_id: 'core/kpi',
key: 'preferences',
})
})
})
+111
View File
@@ -0,0 +1,111 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { sparsePatchBody } from '@/lib/api/sparse-patch'
import { mergeWithDefaults } from '@/lib/reports/kpi-definitions'
import type { KPIPreferences } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const EXTENSION_ID = 'core/kpi'
const KEY = 'preferences'
/**
* Deliberately carries no `.default()`: the defaults belong to
* mergeWithDefaults() on the read path, not to the parse of a write. A schema
* default here would resurrect on every save exactly the way a `.partial()`
* schema's defaults do. Keys are all optional so the route can tell "the
* caller set this" from "the caller said nothing about this".
*/
const UpdateKPIPreferencesSchema = z.object({
visibleKpis: z.array(z.string()).optional(),
kpiOrder: z.array(z.string()).optional(),
accountOverrides: z.record(z.string(), z.array(z.string())).optional(),
showMonthlyTable: z.boolean().optional(),
})
export const GET = withRouteContext('kpi.preferences.get', async (_request, { supabase, companyId }) => {
const { data } = await supabase
.from('extension_data')
.select('value')
.eq('company_id', companyId)
.eq('extension_id', EXTENSION_ID)
.eq('key', KEY)
.single()
const preferences = mergeWithDefaults((data?.value as Partial<KPIPreferences>) ?? {})
return NextResponse.json({ data: preferences })
})
export const PUT = withRouteContext(
'kpi.preferences.update',
async (request, { supabase, companyId, user }) => {
const validation = await validateBody(request, sparsePatchBody(UpdateKPIPreferencesSchema))
if (!validation.success) return validation.response
const prefs = validation.data
// Validate account overrides: must be 4-digit numeric strings
if (prefs.accountOverrides) {
for (const [kpiId, accounts] of Object.entries(prefs.accountOverrides)) {
for (const acc of accounts) {
if (!/^\d{4}$/.test(acc)) {
return NextResponse.json(
{ error: `Invalid account number "${acc}" in ${kpiId}: must be 4 digits` },
{ status: 400 }
)
}
}
}
}
// Merge over what is STORED, not over the defaults. mergeWithDefaults()
// fills every absent key with its default value, so saving one setting
// used to reset the other two: a PUT of `{ accountOverrides: … }` wiped
// visibleKpis and kpiOrder back to factory settings. Defaults still apply
// to a row that has never been written (and on the read path), but they no
// longer overwrite a stored choice the caller never mentioned. The
// settings dialog always sends the complete object (its reset button fills
// the draft with getDefaultPreferences() before saving), so its behaviour
// is unchanged; only sparse callers stop losing data.
const { data: existing } = await supabase
.from('extension_data')
.select('value')
.eq('company_id', companyId)
.eq('extension_id', EXTENSION_ID)
.eq('key', KEY)
.maybeSingle()
const stored = mergeWithDefaults((existing?.value as Partial<KPIPreferences>) ?? {})
const merged: KPIPreferences = { ...stored, ...prefs }
// KPI preferences are COMPANY-scoped, not per-user: the read paths (GET
// above and the KPI report route) filter on (company_id, extension_id,
// key) with no user filter, and the key carries no user id. user_id is
// stored purely as "who wrote this last" attribution. The upsert must
// therefore arbitrate on the company-scoped unique constraint: migration
// 20260330130000 dropped UNIQUE (user_id, extension_id, key) in favor of
// UNIQUE (company_id, extension_id, key), so naming the old column trio
// here makes Postgres fail every save with 42P10 (no matching constraint).
const { data, error } = await supabase
.from('extension_data')
.upsert(
{
user_id: user.id,
company_id: companyId,
extension_id: EXTENSION_ID,
key: KEY,
value: merged,
},
{ onConflict: 'company_id,extension_id,key' }
)
.select()
.single()
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data: data.value })
},
{ requireWrite: true }
)