* refactor: optimize page loading and data fetching * fix: resolve recurring production runtime errors * feat: add MCP company and customer updates * fix: handle year-end tax adjustments * feat: harden annual report compliance * fix: expand invoice logo and font support * fix: sanitize API route error responses * fix: sanitize user-facing error messages * feat: persist onboarding and tax assessment notices * fix: reduce cloud backup audit churn * feat: refine invoice editor layout * fix: show saved tax adjustments in INK2 * fix: complete annual report API mappings * docs: record operational safeguards and decisions * fix: harden annual report review findings * fix: adjust column span for description based on VAT registration * New css class name
48 lines
2.0 KiB
TypeScript
48 lines
2.0 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { lockPeriod } from '@/lib/core/bookkeeping/period-service'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
|
|
export const POST = withRouteContext(
|
|
'period.lock',
|
|
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
|
const { id } = await params
|
|
const { user, supabase, companyId, log, requestId } = ctx
|
|
const opLog = log.child({ periodId: id })
|
|
|
|
try {
|
|
const period = await lockPeriod(supabase, companyId!, user.id, id)
|
|
return NextResponse.json({ data: period })
|
|
} catch (err) {
|
|
opLog.error('failed to lock period', err as Error)
|
|
// The service throws plain Error with messages like "Period not found"
|
|
// or "Period contains drafts": translate to envelope codes.
|
|
const message = err instanceof Error ? err.message : ''
|
|
if (/not found/i.test(message)) {
|
|
return errorResponseFromCode('PERIOD_NOT_FOUND', opLog, { requestId })
|
|
}
|
|
if (/already locked|already closed/i.test(message)) {
|
|
return errorResponseFromCode('PERIOD_LOCK_ALREADY_LOCKED', opLog, { requestId })
|
|
}
|
|
if (/draft/i.test(message)) {
|
|
return errorResponseFromCode('PERIOD_LOCK_HAS_DRAFTS', opLog, {
|
|
requestId,
|
|
details: { reason: getErrorMessage(err) },
|
|
})
|
|
}
|
|
// lockPeriod() refuses to lock a period that still has uncategorized
|
|
// business transactions (the count is in the thrown message). Surface it
|
|
// as a clear 400 instead of letting it fall through to a generic 500.
|
|
if (/saknar bokföring|okategoriserade affärstransaktion/i.test(message)) {
|
|
return errorResponseFromCode('PERIOD_HAS_UNBOOKED_TRANSACTIONS', opLog, {
|
|
requestId,
|
|
details: { reason: getErrorMessage(err) },
|
|
})
|
|
}
|
|
return errorResponse(err, opLog, { requestId })
|
|
}
|
|
},
|
|
{ requireWrite: true },
|
|
)
|