docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,166 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/dimensions (create a custom dimension — PR10).
|
||||
*
|
||||
* Covers: auto-picking the next free SIE number >= 20 (proved both via the
|
||||
* insert result and via the self-parent guard, which names the picked
|
||||
* number), 409 on an explicitly taken number, 400 on an invalid parent, and
|
||||
* the 201 { data: { dimension } } contract for an explicit number.
|
||||
*
|
||||
* Queue order per request: ensure_company_dimensions RPC → existing-numbers
|
||||
* select → insert returning the row.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const noParams = { params: Promise.resolve({}) }
|
||||
const postRequest = (body: Record<string, unknown>) =>
|
||||
createMockRequest('/api/dimensions', { method: 'POST', body })
|
||||
|
||||
interface DimensionRow {
|
||||
id: string
|
||||
sie_dim_no: number
|
||||
name: string
|
||||
parent_sie_dim_no: number | null
|
||||
resets_annually: boolean
|
||||
is_system: boolean
|
||||
is_active: boolean
|
||||
sort_order: number
|
||||
}
|
||||
|
||||
type DimensionBody = { data: { dimension: DimensionRow } }
|
||||
type ErrorBody = { error: { code: string; message: string } }
|
||||
|
||||
function makeDimensionRow(overrides: Partial<DimensionRow> = {}): DimensionRow {
|
||||
return {
|
||||
id: 'dim-new',
|
||||
sie_dim_no: 21,
|
||||
name: 'Avdelning',
|
||||
parent_sie_dim_no: null,
|
||||
resets_annually: true,
|
||||
is_system: false,
|
||||
is_active: true,
|
||||
sort_order: 100,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** Enqueue the ensure RPC + the existing-numbers select. */
|
||||
function enqueuePreamble(existingNumbers: number[]) {
|
||||
enqueue({ data: null }) // ensure_company_dimensions
|
||||
enqueue({ data: existingNumbers.map((n) => ({ sie_dim_no: n })) })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
describe('POST /api/dimensions', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await POST(postRequest({ name: 'Avdelning' }), noParams)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('picks the next free number >= 20 when sie_dim_no is omitted ([1,6,20] → 21)', async () => {
|
||||
enqueuePreamble([1, 6, 20])
|
||||
enqueue({ data: makeDimensionRow({ sie_dim_no: 21 }) })
|
||||
|
||||
const response = await POST(postRequest({ name: 'Avdelning' }), noParams)
|
||||
const { status, body } = await parseJsonResponse<DimensionBody>(response)
|
||||
|
||||
expect(status).toBe(201)
|
||||
expect(body.data.dimension.sie_dim_no).toBe(21)
|
||||
expect(body.data.dimension.is_system).toBe(false)
|
||||
})
|
||||
|
||||
it('auto-picks exactly 21 — pinned via the self-parent guard message', async () => {
|
||||
// The queued mock cannot capture insert payloads, so pin the computed
|
||||
// number through an observable branch: parent 21 collides with the pick
|
||||
// ONLY if the route picked 21 (any other pick yields the "finns inte"
|
||||
// message instead, since 21 is not a registered number).
|
||||
enqueuePreamble([1, 6, 20])
|
||||
|
||||
const response = await POST(
|
||||
postRequest({ name: 'Avdelning', parent_sie_dim_no: 21 }),
|
||||
noParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<ErrorBody>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_PARENT_INVALID')
|
||||
expect(body.error.message).toBe(
|
||||
'En dimension kan inte vara sin egen överordnade dimension.',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 409 DIMENSION_NUMBER_TAKEN for an explicitly taken number', async () => {
|
||||
enqueuePreamble([1, 6])
|
||||
|
||||
const response = await POST(postRequest({ name: 'Projekt igen', sie_dim_no: 6 }), noParams)
|
||||
const { status, body } = await parseJsonResponse<ErrorBody>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('DIMENSION_NUMBER_TAKEN')
|
||||
})
|
||||
|
||||
it('returns 400 DIMENSION_PARENT_INVALID for an unknown parent', async () => {
|
||||
enqueuePreamble([1, 6])
|
||||
|
||||
const response = await POST(
|
||||
postRequest({ name: 'Avdelning', sie_dim_no: 30, parent_sie_dim_no: 99 }),
|
||||
noParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<ErrorBody>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_PARENT_INVALID')
|
||||
expect(body.error.message).toContain('99')
|
||||
})
|
||||
|
||||
it('creates an explicit-number dimension with the 201 { data: { dimension } } shape', async () => {
|
||||
enqueuePreamble([1, 6])
|
||||
const row = makeDimensionRow({
|
||||
sie_dim_no: 30,
|
||||
name: 'Maskin',
|
||||
parent_sie_dim_no: 6,
|
||||
resets_annually: false,
|
||||
})
|
||||
enqueue({ data: row })
|
||||
|
||||
const response = await POST(
|
||||
postRequest({ name: 'Maskin', sie_dim_no: 30, parent_sie_dim_no: 6, resets_annually: false }),
|
||||
noParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<DimensionBody>(response)
|
||||
|
||||
expect(status).toBe(201)
|
||||
expect(body.data.dimension).toEqual(row)
|
||||
})
|
||||
})
|
||||
@@ -1,197 +0,0 @@
|
||||
/**
|
||||
* Tests for PATCH /api/dimensions/[id] (update dimension) and
|
||||
* DELETE /api/dimensions/[id] (remove an unused custom dimension, #2219).
|
||||
*
|
||||
* Covers: 401, empty-body validation (400), 404, the is_system name-lock
|
||||
* ("Systemdimensioner kan inte döpas om", 400 DIMENSION_SYSTEM_RENAME),
|
||||
* archiving a system dimension (allowed), and the happy rename of a custom
|
||||
* dimension.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { PATCH, DELETE } from '../[id]/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'dim-1' })
|
||||
|
||||
describe('PATCH /api/dimensions/[id]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'Avdelning' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an empty body with 400', async () => {
|
||||
const request = createMockRequest('/api/dimensions/dim-1', { method: 'PATCH', body: {} })
|
||||
const response = await PATCH(request, params())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the dimension does not belong to the company', async () => {
|
||||
enqueue({ data: null }) // maybeSingle fetch
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'Avdelning' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('rejects renaming a system dimension with 400 DIMENSION_SYSTEM_RENAME', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Kostnadsställe', is_system: true } })
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'Avdelning' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_SYSTEM_RENAME')
|
||||
expect(body.error.message).toBe('Systemdimensioner kan inte döpas om.')
|
||||
})
|
||||
|
||||
it('allows archiving a system dimension (is_active only, no rename)', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Kostnadsställe', is_system: true } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'dim-1', sie_dim_no: 1, name: 'Kostnadsställe',
|
||||
resets_annually: true, is_system: true, is_active: false, sort_order: 10,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_active: false },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { is_active: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_active).toBe(false)
|
||||
})
|
||||
|
||||
it('renames a non-system dimension (happy path)', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Dimension 7', is_system: false } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'dim-1', sie_dim_no: 7, name: 'Avdelning',
|
||||
resets_annually: true, is_system: false, is_active: true, sort_order: 30,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'Avdelning', sort_order: 30 },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { name: string; sort_order: number } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.name).toBe('Avdelning')
|
||||
expect(body.data.sort_order).toBe(30)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/dimensions/[id]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
const del = () => DELETE(createMockRequest('/api/dimensions/dim-1', { method: 'DELETE' }), params())
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const response = await del()
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when the dimension does not belong to the company', async () => {
|
||||
enqueue({ data: null })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await del())
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('refuses a system dimension with 400 DIMENSION_SYSTEM_DELETE before touching the DB', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Kostnadsställe', is_system: true } })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(await del())
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_SYSTEM_DELETE')
|
||||
expect(body.error.message).toContain('avaktivera')
|
||||
})
|
||||
|
||||
it('surfaces the DB guard verbatim as 409 DIMENSION_REFERENCED when posted lines carry the number', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Avdelning', is_system: false } })
|
||||
enqueue({
|
||||
data: null,
|
||||
error: {
|
||||
code: 'P0001',
|
||||
message: 'Dimensionen 7 (Avdelning) används på bokförda verifikat och kan inte tas bort — avaktivera den istället.',
|
||||
},
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(await del())
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('DIMENSION_REFERENCED')
|
||||
expect(body.error.message).toContain('Avdelning')
|
||||
})
|
||||
|
||||
it('deletes an unused custom dimension (happy path)', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Avdelning', is_system: false } })
|
||||
enqueue({ data: [{ id: 'dim-1' }] })
|
||||
const { status, body } = await parseJsonResponse<{ success: boolean }>(await del())
|
||||
expect(status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,182 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/dimensions/import-existing (backfill scan).
|
||||
*
|
||||
* Covers: 401, the empty-company early exit, the happy path where codes
|
||||
* found on journal lines but missing from the registry are created as
|
||||
* inactive placeholder values ({ created: n }), code sanitization (PR1
|
||||
* backfill parity), and duplicate-tolerant upserts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { POST } from '../import-existing/route'
|
||||
|
||||
const request = () => createMockRequest('/api/dimensions/import-existing', { method: 'POST' })
|
||||
const noParams = { params: Promise.resolve({}) }
|
||||
|
||||
/**
|
||||
* Enqueue the two pages the scan reads through the two-step entry-lines fetch
|
||||
* (lib/bookkeeping/entry-lines.ts): the company's parent entries first, then
|
||||
* the lines keyed by journal_entry_id. The route never reads the parent, so a
|
||||
* single synthetic entry per line set is enough.
|
||||
*/
|
||||
function enqueueLines(rows: Array<{ id: string; dimensions: Record<string, string> }>) {
|
||||
enqueue({ data: rows.length > 0 ? [{ id: 'entry-1' }] : [] })
|
||||
// No entries means the helper never queries the lines at all.
|
||||
if (rows.length === 0) return
|
||||
enqueue({ data: rows.map((r) => ({ ...r, journal_entry_id: 'entry-1' })) })
|
||||
}
|
||||
|
||||
describe('POST /api/dimensions/import-existing', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns { created: 0 } when no line carries dimensions', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueueLines([]) // journal_entry_lines scan
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(0)
|
||||
})
|
||||
|
||||
it('creates inactive placeholder values for codes missing from the registry', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
// Lines: KS01 (dim 1) appears twice, P001 (dim 6) once, BUTIK already registered.
|
||||
enqueueLines([
|
||||
{ id: 'l1', dimensions: { '1': 'KS01' } },
|
||||
{ id: 'l2', dimensions: { '1': 'KS01', '6': 'P001' } },
|
||||
{ id: 'l3', dimensions: { '1': 'BUTIK' } },
|
||||
|
||||
])
|
||||
// Registry dims 1 & 6 exist (system dims).
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'dim-1', sie_dim_no: 1 },
|
||||
{ id: 'dim-6', sie_dim_no: 6 },
|
||||
],
|
||||
})
|
||||
// Existing values: BUTIK is already registered under dim 1.
|
||||
enqueue({ data: [{ dimension_id: 'dim-1', code: 'BUTIK' }] })
|
||||
// Upsert of the two missing values succeeds: created counts returned rows.
|
||||
enqueue({ data: [{ id: 'nv1' }, { id: 'nv2' }] })
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(2) // KS01 + P001; BUTIK skipped (already registered)
|
||||
})
|
||||
|
||||
it('sanitizes candidate codes like the PR1 backfill and de-duplicates after sanitization', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
// 'KS"01"' and 'KS{01}' both sanitize to KS01 (one candidate); a 50-char
|
||||
// code is capped at 40; '"{}"' sanitizes to empty and is dropped entirely.
|
||||
enqueueLines([
|
||||
{ id: 'l1', dimensions: { '1': 'KS"01"' } },
|
||||
{ id: 'l2', dimensions: { '1': 'KS{01}' } },
|
||||
{ id: 'l3', dimensions: { '1': 'X'.repeat(50) } },
|
||||
{ id: 'l4', dimensions: { '1': '"{}"' } },
|
||||
|
||||
])
|
||||
enqueue({ data: [{ id: 'dim-1', sie_dim_no: 1 }] }) // registry dims
|
||||
enqueue({ data: [] }) // no existing values
|
||||
// Upsert returns the two surviving sanitized codes (KS01 + the capped one).
|
||||
enqueue({ data: [{ id: 'nv1' }, { id: 'nv2' }] })
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(2)
|
||||
})
|
||||
|
||||
it('tolerates duplicates in the batch: created counts only the rows the upsert returned', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueueLines([
|
||||
{ id: 'l1', dimensions: { '1': 'KS01' } },
|
||||
{ id: 'l2', dimensions: { '1': 'KS02' } },
|
||||
|
||||
])
|
||||
enqueue({ data: [{ id: 'dim-1', sie_dim_no: 1 }] }) // registry dims
|
||||
enqueue({ data: [] }) // existing-values snapshot missed a raced KS02
|
||||
// ignoreDuplicates upsert skips the conflicting row instead of aborting
|
||||
// the batch: only KS01 comes back.
|
||||
enqueue({ data: [{ id: 'nv1' }] })
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(1)
|
||||
})
|
||||
|
||||
it('creates a registry dimension for an unregistered dim number found on lines', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueueLines([{ id: 'l1', dimensions: { '7': 'AVD-A' } }]) // lines
|
||||
// Registry only has the system dims: dim 7 is missing.
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'dim-1', sie_dim_no: 1 },
|
||||
{ id: 'dim-6', sie_dim_no: 6 },
|
||||
],
|
||||
})
|
||||
// Upsert of the missing dimension row returns its id.
|
||||
enqueue({ data: [{ id: 'dim-7', sie_dim_no: 7 }] })
|
||||
// No existing values.
|
||||
enqueue({ data: [] })
|
||||
// Value upsert succeeds.
|
||||
enqueue({ data: [{ id: 'nv1' }] })
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(1)
|
||||
})
|
||||
|
||||
it('returns 500 DIMENSION_IMPORT_FAILED when the scan blows up', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueue({ error: { message: 'relation missing' } }) // entry page throws
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error.code).toBe('DIMENSION_IMPORT_FAILED')
|
||||
})
|
||||
})
|
||||
@@ -1,136 +0,0 @@
|
||||
/**
|
||||
* Tests for GET /api/dimensions (dimension registry list).
|
||||
*
|
||||
* Exercises the route through the real withRouteContext wrapper, mocking only
|
||||
* its auth/company dependencies and injecting a queued Supabase mock via
|
||||
* requireAuth. Covers: 401, the ensure-RPC failure path, and the contract
|
||||
* shape ({ dimensions: [...] } with values nested per dimension).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
interface DimensionsBody {
|
||||
dimensions: Array<{
|
||||
id: string
|
||||
sie_dim_no: number
|
||||
name: string
|
||||
resets_annually: boolean
|
||||
is_system: boolean
|
||||
is_active: boolean
|
||||
sort_order: number
|
||||
values: Array<{
|
||||
id: string
|
||||
code: string
|
||||
name: string
|
||||
is_active: boolean
|
||||
start_date: string | null
|
||||
end_date: string | null
|
||||
}>
|
||||
}>
|
||||
}
|
||||
|
||||
describe('GET /api/dimensions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions'), { params: Promise.resolve({}) })
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('ensures system dims exist, then returns dimensions with nested values', async () => {
|
||||
// 1st DB hit: ensure_company_dimensions RPC.
|
||||
enqueue({ data: null })
|
||||
// 2nd: dimensions list (sorted by sort_order server-side).
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'dim-1', sie_dim_no: 1, name: 'Kostnadsställe', resets_annually: true, is_system: true, is_active: true, sort_order: 10 },
|
||||
{ id: 'dim-6', sie_dim_no: 6, name: 'Projekt', resets_annually: false, is_system: true, is_active: true, sort_order: 20 },
|
||||
],
|
||||
})
|
||||
// 3rd: dimension_values list (sorted by code server-side).
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'v1', dimension_id: 'dim-1', code: 'BUTIK', name: 'Butiken', is_active: true, start_date: null, end_date: null },
|
||||
{ id: 'v2', dimension_id: 'dim-6', code: 'P001', name: 'Projekt Björk', is_active: false, start_date: '2026-01-01', end_date: '2026-06-30' },
|
||||
],
|
||||
})
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<DimensionsBody>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('ensure_company_dimensions', {
|
||||
p_company_id: 'company-1',
|
||||
})
|
||||
expect(body.dimensions).toHaveLength(2)
|
||||
expect(body.dimensions[0]).toMatchObject({
|
||||
id: 'dim-1',
|
||||
sie_dim_no: 1,
|
||||
name: 'Kostnadsställe',
|
||||
resets_annually: true,
|
||||
is_system: true,
|
||||
values: [
|
||||
{ id: 'v1', code: 'BUTIK', name: 'Butiken', is_active: true, start_date: null, end_date: null },
|
||||
],
|
||||
})
|
||||
expect(body.dimensions[1].values).toEqual([
|
||||
{ id: 'v2', code: 'P001', name: 'Projekt Björk', is_active: false, start_date: '2026-01-01', end_date: '2026-06-30' },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns a dimension with an empty values array when it has no values', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'dim-1', sie_dim_no: 1, name: 'Kostnadsställe', resets_annually: true, is_system: true, is_active: true, sort_order: 10 },
|
||||
],
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<DimensionsBody>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.dimensions[0].values).toEqual([])
|
||||
})
|
||||
|
||||
it('returns 500 when the ensure RPC fails', async () => {
|
||||
enqueue({ error: { code: 'XX000', message: 'boom' } })
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error.code).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -1,292 +0,0 @@
|
||||
/**
|
||||
* Tests for /api/dimensions/rules (list + create) and
|
||||
* /api/dimensions/rules/[id] (update + delete) — dimensions PR10.
|
||||
*
|
||||
* Exercises the routes through the real withRouteContext wrapper, mocking
|
||||
* only its auth/company dependencies and injecting a queued Supabase mock via
|
||||
* requireAuth. Covers: 401, the DTO mapping contract, the account filter
|
||||
* validation, the schema's value-presence superRefine, referential 404s, the
|
||||
* 23505 → 409 duplicate mapping, PATCH's effective-type validation, and
|
||||
* DELETE's count-based 404.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { GET, POST } from '../rules/route'
|
||||
import { PATCH, DELETE } from '../rules/[id]/route'
|
||||
|
||||
const DIM_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const VALUE_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const RULE_ID = '33333333-3333-4333-8333-333333333333'
|
||||
|
||||
const noParams = { params: Promise.resolve({}) }
|
||||
const idParams = createMockRouteParams({ id: RULE_ID })
|
||||
|
||||
interface RuleDto {
|
||||
account_dimension_rule_id: string
|
||||
account_number: string
|
||||
dimension_id: string
|
||||
sie_dim_no: number
|
||||
dimension_name: string
|
||||
rule_type: string
|
||||
value_id: string | null
|
||||
value_code: string | null
|
||||
value_name: string | null
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
type RuleBody = { data: { rule: RuleDto } }
|
||||
type RulesBody = { data: { rules: RuleDto[] } }
|
||||
type ErrorBody = { error: { code: string; message: string } }
|
||||
|
||||
/** Raw row exactly as RULE_SELECT returns it (joined registry aliases). */
|
||||
function makeRawRule(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: RULE_ID,
|
||||
account_number: '4010',
|
||||
rule_type: 'default',
|
||||
value_id: VALUE_ID,
|
||||
is_active: true,
|
||||
dimension: { id: DIM_ID, sie_dim_no: 6, name: 'Projekt' },
|
||||
value: { code: 'P001', name: 'Projekt Alpha' },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
describe('GET /api/dimensions/rules', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions/rules'), noParams)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('maps rows through the DTO (account_dimension_rule_id + value fields)', async () => {
|
||||
enqueue({
|
||||
data: [
|
||||
makeRawRule(),
|
||||
makeRawRule({
|
||||
id: '44444444-4444-4444-8444-444444444444',
|
||||
account_number: '5010',
|
||||
rule_type: 'required',
|
||||
value_id: null,
|
||||
value: null,
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions/rules'), noParams)
|
||||
const { status, body } = await parseJsonResponse<RulesBody>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.rules).toHaveLength(2)
|
||||
expect(body.data.rules[0]).toEqual({
|
||||
account_dimension_rule_id: RULE_ID,
|
||||
account_number: '4010',
|
||||
dimension_id: DIM_ID,
|
||||
sie_dim_no: 6,
|
||||
dimension_name: 'Projekt',
|
||||
rule_type: 'default',
|
||||
value_id: VALUE_ID,
|
||||
value_code: 'P001',
|
||||
value_name: 'Projekt Alpha',
|
||||
is_active: true,
|
||||
})
|
||||
// A required rule has no value — the DTO carries explicit nulls.
|
||||
expect(body.data.rules[1]).toMatchObject({
|
||||
rule_type: 'required',
|
||||
value_id: null,
|
||||
value_code: null,
|
||||
value_name: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a malformed account_number filter with 400', async () => {
|
||||
const response = await GET(
|
||||
createMockRequest('/api/dimensions/rules', { searchParams: { account_number: '40' } }),
|
||||
noParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ type: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
// validateQuery's canonical envelope (review fix: inline regex → schema).
|
||||
expect(body.type).toBe('validation_error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/dimensions/rules', () => {
|
||||
const postRequest = (body: Record<string, unknown>) =>
|
||||
createMockRequest('/api/dimensions/rules', { method: 'POST', body })
|
||||
|
||||
const validDefaultBody = {
|
||||
account_number: '4010',
|
||||
dimension_id: DIM_ID,
|
||||
rule_type: 'default',
|
||||
value_id: VALUE_ID,
|
||||
}
|
||||
|
||||
it('creates a default rule (dimension → value → account → insert) with 201', async () => {
|
||||
enqueue({ data: { id: DIM_ID, is_active: true } }) // dimension lookup
|
||||
enqueue({ data: { id: VALUE_ID, is_active: true } }) // value lookup
|
||||
enqueue({ data: { account_number: '4010' } }) // chart lookup
|
||||
enqueue({ data: makeRawRule() }) // insert returning RULE_SELECT
|
||||
|
||||
const response = await POST(postRequest(validDefaultBody), noParams)
|
||||
const { status, body } = await parseJsonResponse<RuleBody>(response)
|
||||
|
||||
expect(status).toBe(201)
|
||||
expect(body.data.rule.account_dimension_rule_id).toBe(RULE_ID)
|
||||
expect(body.data.rule.rule_type).toBe('default')
|
||||
expect(body.data.rule.value_code).toBe('P001')
|
||||
})
|
||||
|
||||
it('rejects a required rule that carries a value (schema superRefine)', async () => {
|
||||
const response = await POST(
|
||||
postRequest({
|
||||
account_number: '4010',
|
||||
dimension_id: DIM_ID,
|
||||
rule_type: 'required',
|
||||
value_id: VALUE_ID,
|
||||
}),
|
||||
noParams,
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects a default rule without a value (schema superRefine)', async () => {
|
||||
const response = await POST(
|
||||
postRequest({ account_number: '4010', dimension_id: DIM_ID, rule_type: 'default' }),
|
||||
noParams,
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 for a dimension the company does not have', async () => {
|
||||
enqueue({ data: null }) // dimension lookup misses
|
||||
|
||||
const response = await POST(postRequest(validDefaultBody), noParams)
|
||||
const { status, body } = await parseJsonResponse<ErrorBody>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('maps the UNIQUE violation (23505) to 409 DIMENSION_RULE_EXISTS', async () => {
|
||||
enqueue({ data: { id: DIM_ID, is_active: true } })
|
||||
enqueue({ data: { id: VALUE_ID, is_active: true } })
|
||||
enqueue({ data: { account_number: '4010' } })
|
||||
enqueue({
|
||||
error: { code: '23505', message: 'duplicate key value violates unique constraint' },
|
||||
})
|
||||
|
||||
const response = await POST(postRequest(validDefaultBody), noParams)
|
||||
const { status, body } = await parseJsonResponse<ErrorBody>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('DIMENSION_RULE_EXISTS')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/dimensions/rules/[id]', () => {
|
||||
const patchRequest = (body: Record<string, unknown>) =>
|
||||
createMockRequest(`/api/dimensions/rules/${RULE_ID}`, { method: 'PATCH', body })
|
||||
|
||||
it('pauses a rule via is_active without touching the value', async () => {
|
||||
enqueue({
|
||||
data: { id: RULE_ID, rule_type: 'default', value_id: VALUE_ID, dimension_id: DIM_ID },
|
||||
}) // existing lookup
|
||||
enqueue({ data: makeRawRule({ is_active: false }) }) // update returning RULE_SELECT
|
||||
|
||||
const response = await PATCH(patchRequest({ is_active: false }), idParams)
|
||||
const { status, body } = await parseJsonResponse<RuleBody>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.rule.is_active).toBe(false)
|
||||
expect(body.data.rule.account_dimension_rule_id).toBe(RULE_ID)
|
||||
})
|
||||
|
||||
it('rejects switching to required while the stored value remains (effective type)', async () => {
|
||||
enqueue({
|
||||
data: { id: RULE_ID, rule_type: 'default', value_id: VALUE_ID, dimension_id: DIM_ID },
|
||||
})
|
||||
|
||||
const response = await PATCH(patchRequest({ rule_type: 'required' }), idParams)
|
||||
const { status, body } = await parseJsonResponse<ErrorBody>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('VALIDATION_FAILED')
|
||||
})
|
||||
|
||||
it('returns 404 for a rule outside the company', async () => {
|
||||
enqueue({ data: null })
|
||||
|
||||
const response = await PATCH(patchRequest({ is_active: false }), idParams)
|
||||
const { status, body } = await parseJsonResponse<ErrorBody>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_RULE_NOT_FOUND')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/dimensions/rules/[id]', () => {
|
||||
it('deletes the rule and confirms', async () => {
|
||||
enqueue({ count: 1 })
|
||||
|
||||
const response = await DELETE(
|
||||
createMockRequest(`/api/dimensions/rules/${RULE_ID}`, { method: 'DELETE' }),
|
||||
idParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { deleted: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.deleted).toBe(true)
|
||||
})
|
||||
|
||||
it('returns 404 when nothing was deleted (count 0)', async () => {
|
||||
enqueue({ count: 0 })
|
||||
|
||||
const response = await DELETE(
|
||||
createMockRequest(`/api/dimensions/rules/${RULE_ID}`, { method: 'DELETE' }),
|
||||
idParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<ErrorBody>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_RULE_NOT_FOUND')
|
||||
})
|
||||
})
|
||||
@@ -1,195 +0,0 @@
|
||||
/**
|
||||
* Tests for PATCH/DELETE /api/dimensions/[id]/values/[valueId].
|
||||
*
|
||||
* The DELETE suite pins the retention-trigger contract: a P0001 raise from
|
||||
* enforce_dimension_value_retention surfaces as 409 DIMENSION_VALUE_REFERENCED
|
||||
* with the trigger's own Swedish message ("…arkivera det istället") so the UI
|
||||
* can toast it verbatim.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { PATCH, DELETE } from '../[id]/values/[valueId]/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'dim-1', valueId: 'v1' })
|
||||
const URL_PATH = '/api/dimensions/dim-1/values/v1'
|
||||
|
||||
describe('PATCH /api/dimensions/[id]/values/[valueId]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'PATCH', body: { name: 'Nytt namn' } })
|
||||
const response = await PATCH(request, params())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an empty body with 400', async () => {
|
||||
const request = createMockRequest(URL_PATH, { method: 'PATCH', body: {} })
|
||||
const response = await PATCH(request, params())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the value does not exist in the company', async () => {
|
||||
enqueue({ error: { code: 'PGRST116', message: 'No rows found' } })
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'PATCH', body: { name: 'Nytt namn' } })
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('archives a value via is_active=false (happy path)', async () => {
|
||||
// The request carries end_date, so the route first checks the parent
|
||||
// dimension's resets_annually flag (accumulating → dates allowed).
|
||||
enqueue({ data: { id: 'dim-1', resets_annually: false } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'v1', dimension_id: 'dim-1', code: 'BUTIK', name: 'Butiken',
|
||||
is_active: false, start_date: null, end_date: '2026-06-30',
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest(URL_PATH, {
|
||||
method: 'PATCH',
|
||||
body: { is_active: false, end_date: '2026-06-30' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { is_active: boolean; code: string } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_active).toBe(false)
|
||||
// Code untouched: immutable in v1.
|
||||
expect(body.data.code).toBe('BUTIK')
|
||||
})
|
||||
|
||||
it('rejects start/end dates on a resets-annually dimension with 400', async () => {
|
||||
enqueue({ data: { id: 'dim-1', resets_annually: true } })
|
||||
|
||||
const request = createMockRequest(URL_PATH, {
|
||||
method: 'PATCH',
|
||||
body: { start_date: '2026-01-01' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_DATES_NOT_ALLOWED')
|
||||
expect(body.error.message).toBe(
|
||||
'Datum kan bara sättas på ackumulerande dimensioner (t.ex. projekt).',
|
||||
)
|
||||
})
|
||||
|
||||
it('allows clearing dates (explicit null) without checking the dimension', async () => {
|
||||
// start_date: null clears the field, a harmless no-op on any dimension,
|
||||
// so the route must not spend a dimension fetch on it. The single queued
|
||||
// result feeds the update itself.
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'v1', dimension_id: 'dim-1', code: 'BUTIK', name: 'Butiken',
|
||||
is_active: true, start_date: null, end_date: null,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest(URL_PATH, {
|
||||
method: 'PATCH',
|
||||
body: { start_date: null, end_date: null },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/dimensions/[id]/values/[valueId]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'DELETE' })
|
||||
const response = await DELETE(request, params())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('surfaces the retention trigger as 409 with the trigger\'s Swedish message', async () => {
|
||||
const triggerMessage =
|
||||
'Värdet "BUTIK" används på bokförda verifikat och kan inte tas bort: arkivera det istället.'
|
||||
enqueue({ error: { code: 'P0001', message: triggerMessage } })
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'DELETE' })
|
||||
const response = await DELETE(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_REFERENCED')
|
||||
// The trigger's message (naming the code) is surfaced verbatim for the toast.
|
||||
expect(body.error.message).toBe(triggerMessage)
|
||||
expect(body.error.message).toContain('arkivera det istället')
|
||||
})
|
||||
|
||||
it('returns 404 when nothing was deleted', async () => {
|
||||
enqueue({ data: [] })
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'DELETE' })
|
||||
const response = await DELETE(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('deletes an unreferenced value (happy path)', async () => {
|
||||
enqueue({ data: [{ id: 'v1' }] })
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'DELETE' })
|
||||
const response = await DELETE(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ success: boolean }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/dimensions/[id]/values (create dimension value).
|
||||
*
|
||||
* Covers: 401, the strict Fortnox code format (400), 404 on a foreign
|
||||
* dimension, the duplicate-code conflict (409 with Swedish message), the
|
||||
* dates-on-resets-annually rejection (400), atomic create-as-archived
|
||||
* (is_active=false), and the happy path.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { POST } from '../[id]/values/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'dim-1' })
|
||||
|
||||
describe('POST /api/dimensions/[id]/values', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'P001', name: 'Projekt Björk' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['space in code', 'P 001'],
|
||||
['too long (>20 chars)', 'A'.repeat(21)],
|
||||
['SIE-breaking char', 'P{1}'],
|
||||
])('rejects an invalid code (%s) with 400', async (_label, code) => {
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code, name: 'Projekt' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects end_date before start_date with 400', async () => {
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'P001', name: 'Projekt', start_date: '2026-06-01', end_date: '2026-01-01' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the dimension does not belong to the company', async () => {
|
||||
enqueue({ data: null }) // dimension maybeSingle
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'P001', name: 'Projekt Björk' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('rejects start/end dates on a resets-annually dimension with 400', async () => {
|
||||
// Kostnadsställe-style dims reset annually: value date ranges are only
|
||||
// meaningful on accumulating dims (projekt).
|
||||
enqueue({ data: { id: 'dim-1', resets_annually: true } })
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'KS01', name: 'Kontoret', start_date: '2026-01-01' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_DATES_NOT_ALLOWED')
|
||||
expect(body.error.message).toBe(
|
||||
'Datum kan bara sättas på ackumulerande dimensioner (t.ex. projekt).',
|
||||
)
|
||||
})
|
||||
|
||||
it('creates a value as archived when is_active=false (atomic, no follow-up PATCH)', async () => {
|
||||
enqueue({ data: { id: 'dim-1', resets_annually: false } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'v2', dimension_id: 'dim-1', code: 'NEDLAGD', name: 'Nedlagd avdelning',
|
||||
is_active: false, start_date: null, end_date: null,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'NEDLAGD', name: 'Nedlagd avdelning', is_active: false },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string; is_active: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('v2')
|
||||
expect(body.data.is_active).toBe(false)
|
||||
})
|
||||
|
||||
it('returns 409 with a Swedish message on a duplicate code', async () => {
|
||||
enqueue({ data: { id: 'dim-1' } })
|
||||
enqueue({ error: { code: '23505', message: 'duplicate key value' } })
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'P001', name: 'Projekt Björk' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_DUPLICATE_CODE')
|
||||
expect(body.error.message).toBe('Ett värde med samma kod finns redan i dimensionen.')
|
||||
})
|
||||
|
||||
it('creates a value (happy path, Swedish chars allowed in code)', async () => {
|
||||
enqueue({ data: { id: 'dim-1' } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'v1', dimension_id: 'dim-1', code: 'GÖTEBORG', name: 'Göteborgskontoret',
|
||||
is_active: true, start_date: null, end_date: null,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'GÖTEBORG', name: 'Göteborgskontoret' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string; code: string } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('v1')
|
||||
expect(body.data.code).toBe('GÖTEBORG')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user