feat(dimensions): show the value's name after picking, and let an unused custom dimension be deleted (#2219) (#2255)
* feat(dimensions): show the value's name after picking, and let an unused custom dimension be deleted (#2219) Two things from the same Discord report, both in bookkeeping from the transaction view: 1. After picking a kostnadsställe the field showed only the code ("1"). DimensionCombobox now writes the value's full name under the field once a code is committed, exactly as AccountCombobox does for the account name (looked up in the full registry so an archived code stays readable). The input text itself stays the code: the blur/revert logic keys on it. 2. A self-created dimension could not be removed at all: the DB already allowed it (enforce_dimension_registry_guards lets a non-system dimension go when no posted/reversed line carries its number, and the value retention trigger fires on the cascade), but no route or UI asked. New DELETE /api/dimensions/[id]: 400 DIMENSION_SYSTEM_DELETE for kostnadsställe/projekt, the guard's own Swedish P0001 verbatim as 409 DIMENSION_REFERENCED, 404, and a happy path; the register gets a quiet "Ta bort dimension" link for the active custom dimension behind a DestructiveConfirmDialog. Keys added to sv and en. Closes #2219 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VnConrmMCxJRQ5kfiPPWyy * test: satisfy the TypeScript ratchet for two test files main inherited from #2247 and #2242 accounts-route.test.ts built SyncResult literals without the requestedFromDate / historyNarrowed fields #2247 added (vitest does not typecheck, so it passed locally); fiscal-periods route.test.ts got two more one-argument POST(req) calls from #2242 in a file already at its ratchet baseline. Both files now typecheck; the ratchet runs clean. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VnConrmMCxJRQ5kfiPPWyy --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
2c3ffaf51c
commit
a48508e5b0
@@ -384,7 +384,7 @@ describe('POST /api/bookkeeping/fiscal-periods', () => {
|
||||
overlapping: [],
|
||||
})
|
||||
const req = createMockRequest({ name: '2022/2023', period_start: '2022-07-22', period_end: '2023-12-31' })
|
||||
const res = await POST(req)
|
||||
const res = await POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
@@ -393,7 +393,7 @@ describe('POST /api/bookkeeping/fiscal-periods', () => {
|
||||
allPeriods: [{ id: 'p2024', period_start: '2024-01-01', period_end: '2024-12-31', is_closed: false }],
|
||||
})
|
||||
const req = createMockRequest({ name: 'FY 2025', period_start: '2025-01-15', period_end: '2025-12-31' })
|
||||
const res = await POST(req)
|
||||
const res = await POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toMatch(/1st of a month/)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* PATCH /api/dimensions/[id]: update a dimension (name / is_active / sort_order).
|
||||
* DELETE /api/dimensions/[id]: remove a custom dimension nobody has booked on.
|
||||
*
|
||||
* Guard rails:
|
||||
* - Renaming an is_system dimension (1 = Kostnadsställe, 6 = Projekt) is
|
||||
@@ -7,6 +8,13 @@
|
||||
* döpas om"). Archiving (is_active=false) and reordering remain allowed.
|
||||
* - sie_dim_no / is_system are immutable at the DB level
|
||||
* (enforce_dimension_registry_guards) and not accepted here at all.
|
||||
* - DELETE (issue #2219): a system dimension answers 400
|
||||
* DIMENSION_SYSTEM_DELETE before the DB is asked. A custom dimension whose
|
||||
* number is tagged on any posted/reversed line is refused by the same DB
|
||||
* guard with a P0001 that names the dimension; that message rides the 409
|
||||
* DIMENSION_REFERENCED envelope verbatim. Values cascade (ON DELETE
|
||||
* CASCADE) and the value retention trigger fires on the cascade too, so
|
||||
* nothing booked can ever be pulled out from under a verifikat.
|
||||
*/
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
@@ -77,3 +85,61 @@ export const PATCH = withRouteContext(
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
export const DELETE = withRouteContext(
|
||||
'dimension.delete',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ dimensionId: id })
|
||||
|
||||
const { data: existing, error: fetchError } = await supabase
|
||||
.from('dimensions')
|
||||
.select('id, name, is_system')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (fetchError) {
|
||||
opLog.error('dimension fetch failed', fetchError)
|
||||
return errorResponse(fetchError, opLog, { requestId })
|
||||
}
|
||||
if (!existing) {
|
||||
return errorResponseFromCode('DIMENSION_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
if (existing.is_system) {
|
||||
return errorResponseFromCode('DIMENSION_SYSTEM_DELETE', opLog, { requestId })
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('dimensions')
|
||||
.delete()
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select('id')
|
||||
|
||||
if (error) {
|
||||
// P0001 = plpgsql RAISE EXCEPTION: the registry guard (or the value
|
||||
// retention trigger on the cascade) refusing the delete. Surface its
|
||||
// Swedish message verbatim: it names the dimension / code.
|
||||
if (error.code === 'P0001') {
|
||||
return errorResponseFromCode('DIMENSION_REFERENCED', opLog, {
|
||||
requestId,
|
||||
messageSv: error.message,
|
||||
})
|
||||
}
|
||||
opLog.error('dimension delete failed', error)
|
||||
return errorResponseFromCode('DIMENSION_DELETE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: getUserErrorMessage(error) },
|
||||
})
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return errorResponseFromCode('DIMENSION_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* Tests for PATCH /api/dimensions/[id] (update dimension).
|
||||
* 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),
|
||||
@@ -34,7 +35,7 @@ vi.mock('@/lib/auth/require-write', () => ({
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { PATCH } from '../[id]/route'
|
||||
import { PATCH, DELETE } from '../[id]/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'dim-1' })
|
||||
|
||||
@@ -137,3 +138,60 @@ describe('PATCH /api/dimensions/[id]', () => {
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user