Add/issue in absurdum (#739)

* feat(assets): allow editing fixed asset fields before depreciation

The fixed asset register only offered a "Dispose" action, so correcting a
mis-entered acquisition date/cost/category meant running the disposal flow —
which posts a real divestment voucher plus a Ch. 8a VAT adjustment.
Disproportionate and wrong for a data-entry fix.

Add an Edit action that allows correcting those fields directly, gated for
correctness:

- service: extend updateAsset() with category/acquisition_date/
  acquisition_cost; block the change once the asset is disposed or has posted
  depreciation (AssetCorrectionBlockedError) where it would desync posted
  vouchers from the register; realign the BAS triple on category change.
  Name, useful life, and method stay editable.
- api: extend the PATCH schema; annotate GET /api/assets with
  has_posted_depreciation so the UI can lock basis fields proactively.
- ui: EditAssetDialog + pencil action; disables date/cost/category when
  depreciation has been booked, with an inline explanation.
- errors: register ASSET_CORRECTION_BLOCKED (409).
- tests: unit tests for the guard; pg test for pre-disposal editability.

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

* feat(assets): also block basis edits when depreciation was hand-posted

The correction guard only consulted depreciation_schedules, so an
avskrivning booked as a manual journal entry (no schedule row) slipped
through and a basis correction was wrongly allowed.

Add a ledger scan: any posted credit to the asset's ackumulerade-
avskrivningar account (12x9) counts as depreciation. Entries that
depreciation_schedules attributes to a *different* asset are excluded, so
a sibling's engine avskrivning on a shared 12x9 account doesn't produce a
false block. What remains is depreciation tied to this asset (engine or
manual); a basis correction is blocked there and must go through storno.

Adds two unit tests: blocks on a hand-posted credit, allows when the only
12x9 credit belongs to a sibling's engine entry.

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

* fix(invoices): allow negative unit prices for discount lines

The invoice creation form rejected negative unit prices via a frontend
superRefine check, blocking valid discount lines (e.g. "Rabatt -100").
The unit_price error was never rendered inline, so submission failed
silently. The backend schema already allows negative unit prices (see
CreateInvoiceItemSchema test), so the form was simply out of sync.

Remove the non-negative constraint; empty/NaN prices are still rejected
by the base z.number() type. Drop the now-unused validation_price_positive
translation key from both locale files.

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

* feat(invoices): allow editing draft invoices

Drafts could be saved but not edited — the only way to change a draft's
lines, customer, dates or amounts was to delete and recreate it. Add a
"Redigera" action on draft invoices that opens the invoice editor
pre-filled with the draft and saves changes in place.

A verifikat is only created when an invoice is sent (or paid, under
kontantmetoden), so every status=draft invoice is uncommitted and safe to
edit; sent/paid invoices stay immutable and still require a credit note.

- Extract buildInvoiceWriteData() with the shared validation + computation
  (VAT rules, ROT/RUT, accruals, totals, currency, item rows); POST now
  uses it too, behaviour unchanged.
- Add UpdateInvoiceSchema and PATCH /api/invoices/[id], guarded to drafts
  (status=draft, no journal entry, not self-billed); number and status are
  preserved and no invoice.created is emitted.
- Extract the invoice creator into a shared InvoiceEditor with create /
  edit modes; /invoices/new is now a thin wrapper and /invoices/[id]/edit
  is the new edit page.
- Add a "Redigera" button on draft invoice detail pages + sv/en strings.
- Tests for the builder, UpdateInvoiceSchema and the PATCH route.

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

* feat(reports): make Huvudbok findable via account/saldo search terms

Searching the command palette for natural phrases like 'saldo per konto', 'kontoutdrag', 'kontoanalys' or 'transaktioner per konto' returned nothing, so users couldn't find the general ledger. Enrich the Huvudbok entry's keywords with those synonyms, and let Saldobalans and Balansrapport match 'saldo per konto' too since they are genuinely per-account balance views.

Companion change — the clearer Huvudbok report description ('Saldo och alla transaktioner per konto') — already landed in d5f474cb.

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

* feat(settings): let users edit their personal name

Add an editable Namn field to /settings/account that updates profiles.full_name and best-effort syncs auth user_metadata. Previously the personal name was only ever set from BankID's legal name at signup with no way to correct it, so users whose tilltalsnamn isn't their first given name were greeted by the wrong name (and email/password users had no name at all).

New POST /api/user/profile route (requireAuth, RLS-scoped update) mirrors /api/user/locale. sv/en strings added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(invoices): per-invoice öresavrundning override

Add a display-only öresavrundning flag per invoice that wins over the
company-wide setting. Resolution order in getDisplayTotal: per-invoice
override -> company setting -> default-on. The stored total and the booked
verifikat keep the exact öre; only the rendered total changes.

Supplier invoices gain the same flag but resolve a null to off (they never
had rounding historically), exposed via a toggle on the new-invoice form
and a rounding row on the detail page.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(transactions): warn on possible duplicate before booking

Before committing a transaction (via book or categorize), detect an
already-booked sibling with the same date and amount and return a 409
TRANSACTION_BOOK_POSSIBLE_DUPLICATE instead of silently double-booking.

The user can override with force=true, which must be bound to the reviewed
sibling via expected_duplicate_transaction_id; the candidate is re-detected
server-side, so a stale or guessed id is rejected with
TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH. Detection is fail-open on the
non-force path and fail-closed under force.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(transactions): shadow-mode scope-drift dedup counter in bank ingest

Count rows that an enforcing same-feed scope-drift rule WOULD treat as
re-imports (the IBAN-drift re-imports the external_id check misses) and
surface it as IngestResult.shadow_scope_drift_candidates. Nothing is
blocked yet -- the counter only measures how often the rule would fire so
it can be validated against real data before enforcement.

Also gitignore scripts/delete-duplicate-transactions.ts: a destructive,
hand-run cleanup tool kept out of the repo so it can't run in CI/cron or be
mistaken for a supported feature.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(bokslut): base bolagsskatt on post-disposition result

Bokslutsdispositioner are booked as source_type='year_end', which the
income statement excludes, so net_result alone overstates resultat före
skatt and the booked tax ignored the periodiseringsfond avsättning (too-high
tax, ÅR/INK2 mismatch).

calculateBolagsskatt now accepts resultBeforeTaxOverride. The preview builder
mirrors each proposal's P&L effect (+återföring, -avsättning, -SLP) onto the
pre-disposition result; the commit path sums the already-posted dispositions
via the new sumPostedYearEndDispositions (class 88 + 7533) since bolagsskatt
is committed last.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(settings): fiscal years manager

Add a FiscalYearsManager to the bookkeeping settings that lists fiscal
periods with their status (closed > locked > open) and creates the next
year via CreatePeriodDialog, seeded to chain forward from the latest
period end.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(api): return 400 when locking a period with unbooked transactions

lockPeriod() refuses to lock a period that still has uncategorized business
transactions. Detect that message in the lock route and surface it as a
clear PERIOD_HAS_UNBOOKED_TRANSACTIONS (400) instead of a generic 500.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(invoices): implement isEditableInvoiceDraft utility and apply it across invoice edit routes
feat(transactions): log duplicate dismissal events in behandlingshistorik
test(invoices): add tests for isEditableInvoiceDraft function
test(transactions): enhance tests to verify behandlingshistorik logging
refactor(bokslut): update tax calculation test descriptions for clarity

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-06-16 10:42:37 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent d95a0b6105
commit 8322830f46
55 changed files with 6049 additions and 2376 deletions
+21 -1
View File
@@ -6,7 +6,18 @@ import { validateBody } from '@/lib/api/validate'
import { K3ComponentSchema } from '@/lib/api/schemas'
import { getAsset, updateAsset } from '@/lib/bokslut/assets/asset-service'
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
import type { DepreciationMethod } from '@/types'
import type { AssetCategory, DepreciationMethod } from '@/types'
const ASSET_CATEGORIES: readonly AssetCategory[] = [
'immaterial',
'building',
'land_improvement',
'machinery',
'equipment',
'vehicle',
'computer',
'other_tangible',
] as const
const DEPRECIATION_METHODS: readonly DepreciationMethod[] = [
'linear',
@@ -19,6 +30,15 @@ const UpdateAssetSchema = z
.object({
name: z.string().min(1).optional(),
notes: z.string().nullable().optional(),
// Acquisition-basis corrections. The service (updateAsset) only permits
// these while the asset is neither disposed nor depreciated, returning
// ASSET_CORRECTION_BLOCKED (409) otherwise — they redefine the
// depreciation basis, so a post-posting change must go through storno.
category: z
.enum(ASSET_CATEGORIES as unknown as [AssetCategory, ...AssetCategory[]])
.optional(),
acquisition_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
acquisition_cost: z.number().positive().optional(),
salvage_value: z.number().nonnegative().optional(),
useful_life_months: z.number().int().positive().optional(),
depreciation_method: z
+27 -1
View File
@@ -204,7 +204,33 @@ export const GET = withRouteContext('assets.list', async (request, ctx) => {
const activeOnly = url.searchParams.get('active') === 'true'
try {
const data = await listAssets(supabase, companyId, { activeOnly })
return NextResponse.json({ data })
// Annotate each asset with whether any depreciation has been posted
// against it. The UI uses this to lock the acquisition-basis fields
// (date/cost/category) — once avskrivningar are booked a correction must
// go through storno (the service enforces the same rule server-side).
const postedAssetIds = new Set<string>()
if (data.length > 0) {
const { data: posted, error } = await supabase
.from('depreciation_schedules')
.select('asset_id')
.eq('company_id', companyId)
.in(
'asset_id',
data.map((a) => a.id),
)
.not('journal_entry_id', 'is', null)
if (error) throw new Error(`Failed to load depreciation status: ${error.message}`)
for (const row of (posted ?? []) as { asset_id: string }[]) {
postedAssetIds.add(row.asset_id)
}
}
const annotated = data.map((asset) => ({
...asset,
has_posted_depreciation: postedAssetIds.has(asset.id),
}))
return NextResponse.json({ data: annotated })
} catch (err) {
return errorResponse(err, log, { requestId })
}
@@ -4,7 +4,10 @@ import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { validateBody } from '@/lib/api/validate'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import { calculateBolagsskatt } from '@/lib/bokslut/tax-provision/bolagsskatt-calculator'
import {
calculateBolagsskatt,
sumPostedYearEndDispositions,
} from '@/lib/bokslut/tax-provision/bolagsskatt-calculator'
import { calculateSarskildLoneskatt } from '@/lib/bokslut/tax-provision/sarskild-loneskatt-calculator'
import {
listExistingPeriodiseringsfonder,
@@ -205,10 +208,24 @@ async function computeProposal(
fiscalYear: number,
): Promise<ProposedDisposition | null> {
switch (item.kind) {
case 'bolagsskatt':
case 'bolagsskatt': {
// Dispositioner are booked as source_type='year_end', which the income
// statement excludes — so net_result alone overstates resultat före skatt.
// Add the already-posted dispositions back (avsättning −, återföring +,
// SLP −, överavskrivningar −); bolagsskatt is sorted LAST so they are
// committed by now. Without this the booked tax ignores the avsättning
// (the original customer bug — too-high tax, ÅR/INK2 mismatch).
const incomeStatement = await generateIncomeStatement(supabase, companyId, fiscalPeriodId)
const dispositionsEffect = await sumPostedYearEndDispositions(
supabase,
companyId,
fiscalPeriodId,
)
return calculateBolagsskatt(supabase, companyId, fiscalPeriodId, {
resultBeforeTaxOverride: incomeStatement.net_result + dispositionsEffect,
manualAdjustments: item.manualAdjustments,
})
}
case 'sarskild_loneskatt':
return calculateSarskildLoneskatt(supabase, companyId, fiscalPeriodId, {
manualAdjustment: item.manualAdjustment,
@@ -0,0 +1,78 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: vi.fn(),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/core/bookkeeping/period-service', () => ({
lockPeriod: vi.fn(),
}))
import { requireAuth } from '@/lib/auth/require-auth'
import { lockPeriod } from '@/lib/core/bookkeeping/period-service'
import { POST } from '../route'
function lockRequest(): Request {
return createMockRequest('/api/bookkeeping/fiscal-periods/p1/lock', { method: 'POST' })
}
function mockAuth() {
;(requireAuth as ReturnType<typeof vi.fn>).mockResolvedValue({
user: { id: 'user-1' },
supabase: {},
error: null,
})
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('POST /api/bookkeeping/fiscal-periods/[id]/lock', () => {
it('locks the period and returns it on success', async () => {
mockAuth()
;(lockPeriod as ReturnType<typeof vi.fn>).mockResolvedValue({ id: 'p1', locked_at: '2026-06-15T00:00:00Z' })
const res = await POST(lockRequest(), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.id).toBe('p1')
})
// Regression: an unbooked-transactions failure must surface as a clear 400,
// not a generic 500. lockPeriod throws a plain Error (no code) with the
// Swedish count message; the route maps it to PERIOD_HAS_UNBOOKED_TRANSACTIONS.
it('maps the unbooked-transactions error to a 400, not a 500', async () => {
mockAuth()
;(lockPeriod as ReturnType<typeof vi.fn>).mockRejectedValue(
new Error('Kan inte låsa period: 3 affärstransaktion(er) saknar bokföring. Bokför alla transaktioner innan perioden låses.'),
)
const res = await POST(lockRequest(), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error.code).toBe('PERIOD_HAS_UNBOOKED_TRANSACTIONS')
})
it('maps an already-locked period to a 409', async () => {
mockAuth()
;(lockPeriod as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('Period is already locked'))
const res = await POST(lockRequest(), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(409)
const body = await res.json()
expect(body.error.code).toBe('PERIOD_LOCK_ALREADY_LOCKED')
})
it('maps a missing period to a 404', async () => {
mockAuth()
;(lockPeriod as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('Fiscal period not found'))
const res = await POST(lockRequest(), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(404)
const body = await res.json()
expect(body.error.code).toBe('PERIOD_NOT_FOUND')
})
})
@@ -30,6 +30,15 @@ export const POST = withRouteContext(
details: { reason: message },
})
}
// 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: message },
})
}
return errorResponse(err, opLog, { requestId })
}
},
@@ -0,0 +1,201 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
createMockRouteParams,
parseJsonResponse,
createQueuedMockSupabase,
makeInvoice,
makeCustomer,
} from '@/tests/helpers'
import { eventBus } from '@/lib/events'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
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 }),
}))
const mockGetVatRules = vi.fn()
const mockGetAvailableVatRates = vi.fn()
vi.mock('@/lib/invoices/vat-rules', () => ({
getVatRules: (...args: unknown[]) => mockGetVatRules(...args),
getAvailableVatRates: (...args: unknown[]) => mockGetAvailableVatRates(...args),
}))
vi.mock('@/lib/currency/riksbanken', () => ({
fetchExchangeRate: vi.fn().mockResolvedValue(null),
convertToSEK: vi.fn(),
}))
import { PATCH } from '../route'
const VALID_BODY = {
customer_id: '11111111-1111-4111-8111-111111111111',
invoice_date: '2026-06-15',
due_date: '2026-07-15',
currency: 'SEK',
items: [{ description: 'Konsult', quantity: 10, unit: 'tim', unit_price: 1000, vat_rate: 25 }],
}
function patch(id: string, body: unknown = VALID_BODY) {
return PATCH(
createMockRequest(`/api/invoices/${id}`, { method: 'PATCH', body }),
createMockRouteParams({ id }),
)
}
describe('PATCH /api/invoices/[id]', () => {
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
mockGetVatRules.mockReturnValue({
treatment: 'standard_25',
rate: 25,
momsRuta: '05',
reverseChargeText: undefined,
})
mockGetAvailableVatRates.mockReturnValue([
{ rate: 25, label: '25%', treatment: 'standard_25' },
{ rate: 0, label: '0%', treatment: 'exempt' },
])
})
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const { status } = await parseJsonResponse(await patch('inv-1'))
expect(status).toBe(401)
})
it('returns 400 on an invalid body', async () => {
const { status } = await parseJsonResponse(await patch('inv-1', { currency: 'SEK' }))
expect(status).toBe(400)
})
it('returns 404 INVOICE_NOT_FOUND when the invoice does not exist', async () => {
enqueue({ data: null, error: { message: 'not found' } })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(404)
expect(body.error.code).toBe('INVOICE_NOT_FOUND')
})
it('returns 409 INVOICE_UPDATE_NOT_DRAFT for a sent invoice', async () => {
enqueue({
data: { id: 'inv-1', status: 'sent', invoice_number: 'F-1', journal_entry_id: null, is_self_billed: false },
error: null,
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_NOT_DRAFT')
})
it('refuses to edit a draft that already carries a journal entry', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: 'F-1', journal_entry_id: 'je-1', is_self_billed: false },
error: null,
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_NOT_DRAFT')
})
it('refuses to edit a received self-billing invoice', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: true },
error: null,
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_NOT_DRAFT')
})
it('returns 404 INVOICE_CUSTOMER_NOT_FOUND when the customer is missing', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: false },
error: null,
})
enqueue({ data: null, error: { message: 'no customer' } }) // customer lookup
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(404)
expect(body.error.code).toBe('INVOICE_CUSTOMER_NOT_FOUND')
})
it('updates a draft (header + items) and returns the refreshed invoice without emitting invoice.created', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit')
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: 'F-1', journal_entry_id: null, is_self_billed: false },
error: null,
}) // existing
enqueue({ data: makeCustomer({ id: 'customer-1', customer_type: 'swedish_business' }), error: null }) // customer
enqueue({ data: { vat_registered: true }, error: null }) // company_settings.vat_registered
enqueue({ data: [{ id: 'inv-1' }], error: null }) // update ... select('id')
enqueue({ data: [], error: null }) // delete invoice_items
enqueue({ data: null, error: null }) // insert invoice_items
enqueue({
data: makeInvoice({ id: 'inv-1', status: 'draft', invoice_number: 'F-1', total: 12500 }),
error: null,
}) // re-select complete invoice
const { status, body } = await parseJsonResponse<{ data: { id: string; status: string; invoice_number: string } }>(
await patch('inv-1'),
)
expect(status).toBe(200)
expect(body.data.id).toBe('inv-1')
// Editing a draft never re-issues it — status + number are unchanged and no
// invoice.created event is emitted.
expect(body.data.status).toBe('draft')
expect(body.data.invoice_number).toBe('F-1')
expect(emitSpy).not.toHaveBeenCalled()
})
it('returns 409 when the draft is sent/finalized concurrently (0-row update)', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: false },
error: null,
}) // existing
enqueue({ data: makeCustomer({ id: 'customer-1', customer_type: 'swedish_business' }), error: null }) // customer
enqueue({ data: { vat_registered: true }, error: null }) // settings
enqueue({ data: [], error: null }) // update matched 0 rows (status flipped)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_NOT_DRAFT')
})
it('passes through a VAT-rule violation from the shared builder', async () => {
mockGetAvailableVatRates.mockReturnValue([{ rate: 0, label: '0%', treatment: 'reverse_charge' }])
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: false },
error: null,
}) // existing
enqueue({ data: makeCustomer({ id: 'customer-1', customer_type: 'eu_business', vat_number_validated: true }), error: null }) // customer
enqueue({ data: { vat_registered: true }, error: null }) // settings
const { body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(body.error.code).toBe('INVOICE_CREATE_VAT_RULE_VIOLATION')
})
})
+158 -1
View File
@@ -4,8 +4,14 @@ import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { createLogger } from '@/lib/logger'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { UpdateInvoiceSchema } from '@/lib/api/schemas'
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
import type { InvoiceDocumentType } from '@/types'
ensureInitialized() // Module-level — wires the audit-log handler for invoice.draft_deleted.
@@ -121,3 +127,154 @@ export async function DELETE(
return NextResponse.json({ data: { cancelled: true, invoice_number: invoice.invoice_number } })
}
/**
* PATCH /api/invoices/[id]
*
* Edit a DRAFT invoice (or proforma / delivery note) in place — header fields
* AND line items. Only drafts are editable: a journal entry (verifikat) is
* created when an invoice is sent (mark-sent / send) or, for kontantmetoden, at
* payment, so a draft has no committed entry and BFL immutability (guard rail #1)
* does not yet apply. Sent / paid / cancelled / credited invoices are immutable
* and must be reversed via a credit note instead.
*
* The invoice's number and status are preserved — editing never (re)allocates a
* number nor changes lifecycle state, and never emits invoice.created (numbered
* drafts already emitted it at create; unnumbered ones emit on finalize). The
* validation + computation is shared with POST /api/invoices via
* buildInvoiceWriteData so VAT rules, ROT/RUT, accruals and totals stay identical.
*/
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
'invoice.update',
async (request, { supabase, companyId, log: ctxLog, requestId }, { params }) => {
const { id } = await params
const validation = await validateBody(request, UpdateInvoiceSchema, {
log: ctxLog,
operation: 'invoice.update',
})
if (!validation.success) return validation.response
const input = validation.data
const documentType: InvoiceDocumentType = input.document_type || 'invoice'
// Fetch the target. Only drafts (not sent, no committed verifikat, not a
// received self-billing document) may be edited.
const { data: existing, error: fetchError } = await supabase
.from('invoices')
.select('id, status, invoice_number, journal_entry_id, is_self_billed')
.eq('id', id)
.eq('company_id', companyId!)
.single()
if (fetchError || !existing) {
return errorResponseFromCode('INVOICE_NOT_FOUND', ctxLog, { requestId })
}
// journal_entry_id is belt-and-suspenders — a draft shouldn't carry one,
// but if some flow ever booked it, refuse the edit (the entry is immutable).
// Shared predicate (lib/invoices/is-editable-draft) — the single source of
// truth the detail and edit pages also gate on, so the rule can't drift.
if (!isEditableInvoiceDraft(existing)) {
return errorResponseFromCode('INVOICE_UPDATE_NOT_DRAFT', ctxLog, { requestId })
}
// Resolve the (possibly changed) customer.
const { data: customer, error: customerError } = await supabase
.from('customers')
.select('*')
.eq('id', input.customer_id)
.eq('company_id', companyId!)
.single()
if (customerError || !customer) {
return errorResponseFromCode('INVOICE_CUSTOMER_NOT_FOUND', ctxLog, {
requestId,
details: { customerId: input.customer_id },
})
}
const build = await buildInvoiceWriteData({
supabase,
companyId: companyId!,
customer,
documentType,
input,
})
if (!build.ok) {
if ('dbError' in build) {
ctxLog.error('invoice write build failed on a DB lookup', build.dbError as Error)
return errorResponse(build.dbError, ctxLog, { requestId })
}
return errorResponseFromCode(build.code, ctxLog, { requestId, details: build.details })
}
// Update the draft row. invoice_number + status are intentionally NOT in
// build.invoiceFields, so they are preserved. The .eq('status','draft')
// guard turns a concurrent send/finalize into a 0-row update (race), rather
// than silently rewriting a now-issued invoice.
// Öresavrundning is display-only and optional in the update body. Persist
// it when the editor sent a value; otherwise strip it so a partial update
// can't reset a draft's stored flag (build defaults an absent flag to null).
const updateFields =
input.ore_rounding === undefined
? (() => {
const { ore_rounding: _oreRounding, ...rest } = build.invoiceFields
return rest
})()
: build.invoiceFields
const { data: updated, error: updateError } = await supabase
.from('invoices')
.update({ ...updateFields, updated_at: new Date().toISOString() })
.eq('id', id)
.eq('company_id', companyId!)
.eq('status', 'draft')
.select('id')
if (updateError) {
ctxLog.error('invoice update failed', updateError, { invoiceId: id })
return errorResponseFromCode('INVOICE_CREATE_INSERT_FAILED', ctxLog, {
requestId,
details: { pgCode: updateError.code, pgMessage: updateError.message },
})
}
if (!updated || updated.length === 0) {
return errorResponseFromCode('INVOICE_UPDATE_NOT_DRAFT', ctxLog, { requestId })
}
// Replace line items wholesale. A draft has no journal entry or linked docs,
// so delete + reinsert is safe and lets the user add / remove / reorder rows
// freely. invoice_items cascade nothing else.
const { error: deleteItemsError } = await supabase
.from('invoice_items')
.delete()
.eq('invoice_id', id)
if (deleteItemsError) {
ctxLog.error('invoice items delete failed on update', deleteItemsError, { invoiceId: id })
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', ctxLog, {
requestId,
details: { pgCode: deleteItemsError.code, pgMessage: deleteItemsError.message },
})
}
const itemsToInsert = build.items.map((item) => ({ ...item, invoice_id: id }))
const { error: itemsError } = await supabase.from('invoice_items').insert(itemsToInsert)
if (itemsError) {
ctxLog.error('invoice items insert failed on update', itemsError, { invoiceId: id })
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', ctxLog, {
requestId,
details: { pgCode: itemsError.code, pgMessage: itemsError.message },
})
}
const { data: completeInvoice } = await supabase
.from('invoices')
.select('*, customer:customers(*), items:invoice_items(*)')
.eq('id', id)
.single()
return NextResponse.json({ data: completeInvoice })
},
{ requireWrite: true },
)
+21 -312
View File
@@ -4,22 +4,10 @@ import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { CreateInvoiceSchema, CreateCreditNoteSchema } from '@/lib/api/schemas'
import type { EntityType, AccountingMethod, Invoice, CreditNote, InvoiceDocumentType } from '@/types'
import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
import { createCreditNoteJournalEntry } from '@/lib/bookkeeping/invoice-entries'
import { cancelSchedulesForSource } from '@/lib/bookkeeping/accruals/service'
import { DEFAULT_DEFERRED_REVENUE_ACCOUNT } from '@/lib/bookkeeping/accruals/account-suggestions'
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
import {
computeDeduction,
computeInvoiceDeductionTotal,
validateInvoice as validateRotRut,
} from '@/lib/invoices/rot-rut-rules'
import {
encryptPersonnummer,
extractLast4,
validatePersonnummer,
} from '@/lib/salary/personnummer'
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { Logger } from '@/lib/logger'
@@ -121,190 +109,26 @@ export const POST = withRouteContext(
})
}
const vatRules = getVatRules(customer.customer_type, customer.vat_number_validated)
const availableRates = getAvailableVatRates(customer.customer_type, customer.vat_number_validated)
const allowedRates = new Set(availableRates.map((r) => r.rate))
// VAT registration gate (defense in depth — the invoice form already hides
// the Moms column when vat_registered is false). A non-momsregistrerad
// company books no output VAT: zero every line rate so the sale lands as
// momsfri (treatment 'exempt' → revenue 3004/3100, no 2611). 0% is a valid
// rate for every customer type, so the allowedRates guard below still
// passes. Mirrors lib/pending-operations/commit.ts commitCreateInvoice.
const { data: vatSettings } = await supabase
.from('company_settings')
.select('vat_registered')
.eq('company_id', companyId!)
.maybeSingle()
const notVatRegistered = vatSettings?.vat_registered === false
if (notVatRegistered && documentType !== 'delivery_note') {
for (const item of invoiceInput.items) item.vat_rate = 0
}
// Periodisering guards. The line schema already validates the period
// shape; here we gate the flows where deferral has no meaning: cash
// method (recognition at payment), reverse charge/export (3308/3305 must
// reflect the full sale for ruta 39/40), and non-invoice document types.
const hasAccrualItems = invoiceInput.items.some(
(item) => item.accrual_period_start && item.accrual_period_end,
)
if (hasAccrualItems) {
if (documentType !== 'invoice') {
return errorResponseFromCode('INVOICE_CREATE_ACCRUAL_INVALID', log, {
requestId,
details: { reason: 'document_type', documentType },
})
}
if (vatRules.treatment === 'reverse_charge' || vatRules.treatment === 'export') {
return errorResponseFromCode('INVOICE_CREATE_ACCRUAL_INVALID', log, {
requestId,
details: { reason: 'vat_treatment', vatTreatment: vatRules.treatment },
})
}
const { data: methodSettings } = await supabase
.from('company_settings')
.select('accounting_method')
.eq('company_id', companyId!)
.maybeSingle()
if ((methodSettings?.accounting_method || 'accrual') !== 'accrual') {
return errorResponseFromCode('INVOICE_CREATE_ACCRUAL_INVALID', log, {
requestId,
details: { reason: 'accounting_method' },
})
}
}
// Free-text rows carry no amounts and are excluded from totals + VAT.
const subtotal = invoiceInput.items.reduce(
(sum, item) => (item.line_type === 'text' ? sum : sum + item.quantity * item.unit_price),
0,
)
let vatAmount = 0
if (documentType !== 'delivery_note') {
for (const item of invoiceInput.items) {
if (item.line_type === 'text') continue
const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate
if (!allowedRates.has(itemRate)) {
return errorResponseFromCode('INVOICE_CREATE_VAT_RULE_VIOLATION', log, {
requestId,
details: {
attemptedRate: itemRate,
allowedRates: Array.from(allowedRates),
customerType: customer.customer_type,
},
})
}
const lineTotal = item.quantity * item.unit_price
vatAmount += Math.round(lineTotal * itemRate / 100 * 100) / 100
}
}
const total = documentType === 'delivery_note' ? 0 : subtotal + vatAmount
// Validate any per-line revenue-account override against the company's chart
// of accounts. Zod already constrains the shape to a 3xxx string; here we
// confirm each is a real, active class-3 account so a typo or a non-revenue
// account can never be booked. Never trust the client — same posture as the
// server-recomputed ROT/RUT amounts.
const overrideAccounts = Array.from(
new Set(
invoiceInput.items
.map((item) => item.revenue_account)
.filter((a): a is string => !!a),
),
)
if (overrideAccounts.length > 0) {
const { data: validAccounts, error: accountsError } = await supabase
.from('chart_of_accounts')
.select('account_number')
.eq('company_id', companyId!)
.eq('account_class', 3)
.eq('is_active', true)
.in('account_number', overrideAccounts)
if (accountsError) {
log.error('revenue account validation query failed', accountsError)
return errorResponse(accountsError, log, { requestId })
}
const validSet = new Set((validAccounts ?? []).map((a) => a.account_number))
const invalid = overrideAccounts.filter((a) => !validSet.has(a))
if (invalid.length > 0) {
return errorResponseFromCode('INVOICE_CREATE_REVENUE_ACCOUNT_INVALID', log, {
requestId,
details: { invalidAccounts: invalid },
})
}
}
// ROT/RUT-avdrag: validate prerequisites and compute the per-item +
// invoice-level deduction. Computed server-side (never trusted from
// the client) so a tampered request can't expand the 1513 receivable.
// Skipped entirely for proformas, delivery notes, and quotes — those
// documents don't post journal entries and have no deduction model.
let deductionTotal = 0
let deductionPersonnummerEncrypted: string | null = null
let deductionPersonnummerLast4: string | null = null
if (documentType === 'invoice') {
const housingProvided = !!invoiceInput.deduction_housing_designation?.trim()
const personnummerRaw = invoiceInput.deduction_personnummer?.trim() || ''
const personnummerProvided = personnummerRaw.length > 0
const validateInput = invoiceInput.items.map((item) => ({
unit_price: item.unit_price,
quantity: item.quantity,
deduction_type: item.deduction_type ?? null,
labor_hours: item.labor_hours ?? null,
housing_designation: item.housing_designation ?? null,
}))
const validation = validateRotRut(validateInput, personnummerProvided, housingProvided)
if (validation.errors.length > 0) {
return errorResponseFromCode('INVOICE_CREATE_ROT_RUT_VALIDATION', log, {
requestId,
details: { errors: validation.errors, warnings: validation.warnings },
})
}
// Compute and (when present) encrypt the personnummer. The plaintext
// value never touches the DB — only the AES-256-GCM ciphertext + the
// last four digits go into invoices columns.
deductionTotal = computeInvoiceDeductionTotal(validateInput)
if (personnummerProvided) {
const pnValid = validatePersonnummer(personnummerRaw)
if (!pnValid.valid) {
return errorResponseFromCode('INVOICE_CREATE_ROT_RUT_PERSONNUMMER_INVALID', log, {
requestId,
details: { error: pnValid.error },
})
}
deductionPersonnummerEncrypted = encryptPersonnummer(personnummerRaw)
deductionPersonnummerLast4 = extractLast4(personnummerRaw)
}
}
const uniqueRates = new Set(
invoiceInput.items
.filter((item) => item.line_type !== 'text')
.map((item) => item.vat_rate ?? vatRules.rate),
)
const isMixedRate = uniqueRates.size > 1
let exchangeRate: number | null = null
let exchangeRateDate: string | null = null
let subtotalSek: number | null = null
let vatAmountSek: number | null = null
let totalSek: number | null = null
if (invoiceInput.currency !== 'SEK') {
const rateData = await fetchExchangeRate(invoiceInput.currency)
if (rateData) {
exchangeRate = rateData.rate
exchangeRateDate = rateData.date
subtotalSek = convertToSEK(subtotal, exchangeRate)
vatAmountSek = convertToSEK(vatAmount, exchangeRate)
totalSek = convertToSEK(total, exchangeRate)
}
// Shared validation + computation (VAT rules, accrual guards, totals,
// revenue-account override checks, server-side ROT/RUT, currency, item
// rows). Identical to the PATCH (draft edit) path — see build-invoice-write.
const build = await buildInvoiceWriteData({
supabase,
companyId: companyId!,
customer,
documentType,
input: invoiceInput,
})
if (!build.ok) {
if ('dbError' in build) {
log.error('invoice write build failed on a DB lookup', build.dbError as Error)
return errorResponse(build.dbError, log, { requestId })
}
return errorResponseFromCode(build.code, log, { requestId, details: build.details })
}
// Delivery notes are always numbered at insert (ignores save_as_draft);
// invoices/proformas get their F-number below or at finalize.
let invoiceNumber: string | null = null
if (documentType === 'delivery_note') {
const { data: dnNumber } = await supabase.rpc('generate_delivery_note_number', {
@@ -318,39 +142,8 @@ export const POST = withRouteContext(
.insert({
user_id: user.id,
company_id: companyId,
customer_id: invoiceInput.customer_id,
invoice_number: invoiceNumber,
invoice_date: invoiceInput.invoice_date,
due_date: invoiceInput.due_date,
delivery_date: invoiceInput.delivery_date ?? null,
currency: invoiceInput.currency,
exchange_rate: exchangeRate,
exchange_rate_date: exchangeRateDate,
subtotal: documentType === 'delivery_note' ? 0 : subtotal,
subtotal_sek: documentType === 'delivery_note' ? null : subtotalSek,
vat_amount: vatAmount,
vat_amount_sek: documentType === 'delivery_note' ? null : vatAmountSek,
total,
total_sek: documentType === 'delivery_note' ? null : totalSek,
// Initialize remaining_amount to total - deduction for real invoices
// so the open-invoice queries (InvoicePicker, AR ledger, supplier
// matching) treat newly-created invoices as fully unpaid for the
// CUSTOMER's share — the Skatteverket portion is on 1513 and will be
// cleared when the agency pays out, not by the customer payment.
// Proformas, delivery notes and quotes have no payment obligation,
// so they keep the 0 default.
remaining_amount: documentType === 'invoice' ? total - deductionTotal : 0,
vat_treatment: notVatRegistered ? 'exempt' : vatRules.treatment,
vat_rate: documentType === 'delivery_note' ? 0 : (isMixedRate ? null : (uniqueRates.values().next().value ?? vatRules.rate)),
moms_ruta: notVatRegistered ? null : vatRules.momsRuta,
reverse_charge_text: notVatRegistered ? null : (vatRules.reverseChargeText || null),
your_reference: invoiceInput.your_reference,
our_reference: invoiceInput.our_reference,
notes: invoiceInput.notes,
document_type: documentType,
deduction_total: deductionTotal,
deduction_personnummer_encrypted: deductionPersonnummerEncrypted,
deduction_personnummer_last4: deductionPersonnummerLast4,
...build.invoiceFields,
})
.select()
.single()
@@ -363,91 +156,7 @@ export const POST = withRouteContext(
})
}
const items = invoiceInput.items.map((item, index) => {
// Free-text / blank rows carry no amounts and never book — store the
// description only and zero everything else.
if (item.line_type === 'text') {
return {
invoice_id: invoice.id,
sort_order: index,
line_type: 'text',
description: item.description ?? '',
quantity: 0,
unit: '',
unit_price: 0,
line_total: 0,
vat_rate: 0,
vat_amount: 0,
// Keys must match the product branch exactly — PostgREST rejects a
// bulk insert whose objects have differing key sets.
article_id: null,
revenue_account: null,
deduction_type: null,
deduction_amount: 0,
labor_hours: null,
work_type: null,
housing_designation: null,
apartment_number: null,
accrual_period_start: null,
accrual_period_end: null,
accrual_balance_account: null,
}
}
const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate
const lineTotal = item.quantity * item.unit_price
const itemVat = documentType === 'delivery_note' ? 0 : Math.round(lineTotal * itemRate / 100 * 100) / 100
// ROT/RUT deduction is recomputed server-side so a tampered client
// can't expand the 1513 receivable beyond the rules. Non-invoice
// document types never carry deduction_type (rules above strip them
// implicitly because validateRotRut isn't invoked).
const deductionType = documentType === 'invoice' ? (item.deduction_type ?? null) : null
const deductionAmount = deductionType
? computeDeduction({
unit_price: item.unit_price,
quantity: item.quantity,
deduction_type: deductionType,
})
: 0
return {
invoice_id: invoice.id,
sort_order: index,
line_type: 'product',
description: item.description,
quantity: item.quantity,
unit: item.unit,
unit_price: item.unit_price,
line_total: lineTotal,
vat_rate: itemRate,
vat_amount: itemVat,
// Article linkage. revenue_account is frozen-copied here so a later
// article edit never re-books this line; null falls through to the
// VAT-treatment-derived account in generatePerRateLines().
article_id: item.article_id ?? null,
revenue_account: item.revenue_account ?? null,
deduction_type: deductionType,
deduction_amount: deductionAmount,
labor_hours: documentType === 'invoice' ? (item.labor_hours ?? null) : null,
work_type: documentType === 'invoice' ? (item.work_type ?? null) : null,
housing_designation: documentType === 'invoice' ? (item.housing_designation ?? null) : null,
apartment_number: documentType === 'invoice' ? (item.apartment_number ?? null) : null,
// Periodisering (förutbetald intäkt): frozen onto the line. The
// schedule itself is created when the invoice is sent/booked. ROT/RUT
// lines never defer (schema-enforced); the guard above already
// restricted this to real invoices under faktureringsmetoden.
accrual_period_start:
documentType === 'invoice' && !deductionType
? (item.accrual_period_start ?? null)
: null,
accrual_period_end:
documentType === 'invoice' && !deductionType
? (item.accrual_period_end ?? null)
: null,
accrual_balance_account:
documentType === 'invoice' && !deductionType && item.accrual_period_start && item.accrual_period_end
? (item.accrual_balance_account ?? DEFAULT_DEFERRED_REVENUE_ACCOUNT)
: null,
}
})
const items = build.items.map((item) => ({ ...item, invoice_id: invoice.id }))
const { error: itemsError } = await supabase.from('invoice_items').insert(items)
+2
View File
@@ -248,6 +248,8 @@ export const POST = withRouteContext(
remaining_amount: paidPrivately ? 0 : totalRounded,
paid_at: paidPrivately ? new Date().toISOString() : null,
notes: body.notes || null,
// Display-only öresavrundning override; null = off (no retroactive rounding).
ore_rounding: body.ore_rounding ?? null,
})
.select()
.single()
@@ -32,9 +32,26 @@ vi.mock('@/lib/bookkeeping/engine', () => ({
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
}))
// Booking-time duplicate guard — mocked so route tests exercise the WIRING
// (warn / force / mismatch); the detection query itself is unit-tested in
// lib/transactions/__tests__/booking-duplicate-detection.test.ts.
const mockDetectDup = vi.fn()
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
detectBookedDuplicateTransaction: (...args: unknown[]) => mockDetectDup(...args),
}))
// Behandlingshistorik append — mocked so we can assert the dismissal is
// persisted without reaching the service-role client.
const mockAppendProcessingHistory = vi.fn()
vi.mock('@/lib/processing-history/append', () => ({
appendProcessingHistory: (...args: unknown[]) => mockAppendProcessingHistory(...args),
}))
import { POST } from '../route'
const VALID_UUID = '550e8400-e29b-41d4-a716-446655440000'
const SIBLING_UUID = '660e8400-e29b-41d4-a716-446655440111'
const OTHER_UUID = '770e8400-e29b-41d4-a716-446655440222'
describe('POST /api/transactions/[id]/book', () => {
const mockUser = { id: 'user-1', email: 'test@test.se' }
@@ -53,6 +70,9 @@ describe('POST /api/transactions/[id]/book', () => {
reset()
eventBus.clear()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
// No booking-duplicate by default; guard tests override per-case.
mockDetectDup.mockResolvedValue(null)
mockAppendProcessingHistory.mockResolvedValue('evt-1')
})
it('returns 401 when not authenticated', async () => {
@@ -197,4 +217,110 @@ describe('POST /api/transactions/[id]/book', () => {
expect(status).toBe(500)
expect(body.error).toBe('Failed to update transaction')
})
// ── Booking-time duplicate guard ──────────────────────────────────────
it('returns 409 duplicate warning when a booked sibling shares date+amount', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
enqueue({ data: tx, error: null }) // fetch
mockDetectDup.mockResolvedValue({
transaction_id: SIBLING_UUID,
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: 'redan bokförd',
amount: -500,
})
const request = createMockRequest('/api/transactions/tx-1/book', { method: 'POST', body: validBody })
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { candidate: { transaction_id: string; voucher_label: string } } }
}>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_BOOK_POSSIBLE_DUPLICATE')
expect(body.error.details.candidate.transaction_id).toBe(SIBLING_UUID)
expect(body.error.details.candidate.voucher_label).toBe('A142')
// Critically: no verifikat is created when a duplicate is flagged.
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
// Blocking a duplicate is not a dismissal — nothing is logged.
expect(mockAppendProcessingHistory).not.toHaveBeenCalled()
})
it('books when force=true and the expected sibling still matches', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
const je = makeJournalEntry({ id: 'je-new' })
enqueue({ data: tx, error: null }) // fetch
enqueue({ data: null, error: null }) // update
mockDetectDup.mockResolvedValue({
transaction_id: SIBLING_UUID,
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: null,
amount: -500,
})
mockCreateJournalEntry.mockResolvedValue(je)
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: { ...validBody, force: true, expected_duplicate_transaction_id: SIBLING_UUID },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ success: boolean; journal_entry_id: string }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.journal_entry_id).toBe('je-new')
expect(mockCreateJournalEntry).toHaveBeenCalledTimes(1)
// The dismissal is recorded to behandlingshistorik (BFNAR 2013:2 kap 8).
expect(mockAppendProcessingHistory).toHaveBeenCalledWith(
expect.objectContaining({
eventType: 'BankTransactionDuplicateDismissed',
aggregateType: 'BankTransaction',
aggregateId: 'tx-1',
actor: { type: 'user', id: 'user-1' },
payload: expect.objectContaining({
transaction_id: 'tx-1',
dismissed_transaction_id: SIBLING_UUID,
}),
}),
)
})
it('rejects force=true when the expected sibling no longer matches the detected one', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
enqueue({ data: tx, error: null }) // fetch
mockDetectDup.mockResolvedValue({
transaction_id: SIBLING_UUID, // server detects this one…
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: null,
amount: -500,
})
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: { ...validBody, force: true, expected_duplicate_transaction_id: OTHER_UUID }, // …caller claims another
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH')
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
})
it('returns 400 when force=true is sent without expected_duplicate_transaction_id', async () => {
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: { ...validBody, force: true },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse<{ error: string }>(response)
expect(status).toBe(400)
})
})
+76 -1
View File
@@ -8,6 +8,10 @@ import { validateBody } from '@/lib/api/validate'
import { BookTransactionSchema } from '@/lib/api/schemas'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { detectBookedDuplicateTransaction } from '@/lib/transactions/booking-duplicate-detection'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { createLogger } from '@/lib/logger'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import type { Transaction } from '@/types'
ensureInitialized()
@@ -32,7 +36,7 @@ export async function POST(
const validation = await validateBody(request, BookTransactionSchema)
if (!validation.success) return validation.response
const { fiscal_period_id, entry_date, description, lines } = validation.data
const { fiscal_period_id, entry_date, description, lines, force, expected_duplicate_transaction_id } = validation.data
// Fetch transaction (validates ownership)
const { data: transaction, error: fetchError } = await supabase
@@ -54,6 +58,77 @@ export async function POST(
)
}
// Booking-time duplicate guard: if another transaction with the same
// date+amount+account is already booked, booking this one would double-count
// one real event (two verifikationer — felaktig bokföring per BFL). Warn; the
// user confirms with force=true bound to the reviewed sibling. Mirrors the
// match-invoice soft-duplicate guard.
const dupLog = createLogger('transactions.book', { companyId, userId: user.id })
try {
const candidate = await detectBookedDuplicateTransaction(supabase, companyId, {
id,
date: transaction.date,
amount: transaction.amount,
cash_account_id: transaction.cash_account_id ?? null,
})
if (!force) {
if (candidate) {
return errorResponseFromCode('TRANSACTION_BOOK_POSSIBLE_DUPLICATE', dupLog, {
details: { candidate },
})
}
} else if (!candidate || candidate.transaction_id !== expected_duplicate_transaction_id) {
// force=true is bound to a specific candidate. Re-detect and refuse the
// bypass unless it still matches, so a guessed id can't wave the guard.
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', dupLog, {
details: {
expected_duplicate_transaction_id: expected_duplicate_transaction_id ?? null,
detected_transaction_id: candidate?.transaction_id ?? null,
},
})
} else {
dupLog.warn('booking-time duplicate guard bypassed', {
reason: 'force=true',
transactionId: id,
dismissedTransactionId: candidate.transaction_id,
})
// Persist the dismissal to behandlingshistorik (BFNAR 2013:2 kap 8): the
// decision to book over a DETECTED possible double-booking is a
// bookkeeping act that must leave a durable, queryable record — a warn in
// the application log is ephemeral and does not satisfy the requirement.
// Best-effort — a logging failure must never block a legitimate booking.
try {
await appendProcessingHistory({
companyId,
correlationId: id,
aggregateType: 'BankTransaction',
aggregateId: id,
eventType: 'BankTransactionDuplicateDismissed',
payload: {
transaction_id: id,
dismissed_transaction_id: candidate.transaction_id,
dismissed_journal_entry_id: candidate.journal_entry_id,
amount_ore: Math.round(candidate.amount * 100),
entry_date: candidate.entry_date,
},
actor: { type: 'user', id: user.id },
occurredAt: new Date(),
})
} catch (logErr) {
dupLog.error('failed to append duplicate-dismissal behandlingshistorik', logErr as Error)
}
}
} catch (err) {
// Detection is fail-open for the non-force path; force requires a confirmed
// candidate, so a detection failure under force is rejected as a mismatch.
if (force) {
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', dupLog, {
details: { detection_failed: true },
})
}
dupLog.warn('booking-time duplicate detection failed (continuing)', err as Error)
}
// Create journal entry via the engine
let journalEntry
try {
@@ -38,6 +38,21 @@ vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
mockCreateTransactionJournalEntry(...args),
}))
// Booking-time duplicate guard — mocked to "no duplicate" by default so these
// tests exercise categorization, not the guard. The detection query is
// unit-tested in lib/transactions/__tests__/booking-duplicate-detection.test.ts.
const mockDetectDup = vi.fn()
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
detectBookedDuplicateTransaction: (...args: unknown[]) => mockDetectDup(...args),
}))
// Behandlingshistorik append — mocked so we can assert the dismissal is
// persisted without reaching the service-role client.
const mockAppendProcessingHistory = vi.fn()
vi.mock('@/lib/processing-history/append', () => ({
appendProcessingHistory: (...args: unknown[]) => mockAppendProcessingHistory(...args),
}))
const mockSaveUserMappingRule = vi.fn()
vi.mock('@/lib/bookkeeping/mapping-engine', () => ({
saveUserMappingRule: (...args: unknown[]) => mockSaveUserMappingRule(...args),
@@ -96,6 +111,9 @@ describe('POST /api/transactions/[id]/categorize', () => {
// Default: every mapped account exists and is active. Tests covering the
// missing-account path override this per-case.
mockFindMissingActiveAccounts.mockResolvedValue([])
// Default: no booking-time duplicate. The dedicated guard test overrides this.
mockDetectDup.mockResolvedValue(null)
mockAppendProcessingHistory.mockResolvedValue('evt-1')
})
it('returns 401 when not authenticated', async () => {
@@ -586,6 +604,84 @@ describe('POST /api/transactions/[id]/categorize', () => {
expect(body.journal_entry_id).toBe('je-1')
})
it('warns (409) and books nothing when a booked sibling shares date+amount', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
enqueue({ data: tx, error: null }) // fetch — guard runs right after, before any booking work
mockDetectDup.mockResolvedValue({
transaction_id: '660e8400-e29b-41d4-a716-446655440111',
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: 'redan bokförd',
amount: -500,
})
const request = createMockRequest('/api/transactions/tx-1/categorize', {
method: 'POST',
body: { is_business: true, category: 'income_services', confirm_no_match: true },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { candidate: { voucher_label: string } } }
}>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_BOOK_POSSIBLE_DUPLICATE')
expect(body.error.details.candidate.voucher_label).toBe('A142')
// The duplicate guard fires before any verifikat is created.
expect(mockCreateTransactionJournalEntry).not.toHaveBeenCalled()
// Blocking a duplicate is not a dismissal — nothing is logged.
expect(mockAppendProcessingHistory).not.toHaveBeenCalled()
})
it('persists a behandlingshistorik event when force=true dismisses a duplicate', async () => {
const SIBLING_UUID = '660e8400-e29b-41d4-a716-446655440111'
const tx = makeTransaction({ id: 'tx-1', amount: -500, merchant_name: 'GitHub', journal_entry_id: null })
enqueue({ data: tx, error: null }) // fetch
enqueue({ data: { entity_type: 'enskild_firma', fiscal_year_start_month: 1 }, error: null }) // settings
enqueue({ data: [{ id: 'period-1' }], error: null }) // ensureFiscalPeriod existing check
mockCreateTransactionJournalEntry.mockResolvedValue({ id: 'je-1' })
mockSaveUserMappingRule.mockResolvedValue(undefined)
enqueue({ data: [{ id: 'tx-1' }], error: null }) // tx update (CAS matched)
mockDetectDup.mockResolvedValue({
transaction_id: SIBLING_UUID,
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: null,
amount: -500,
})
const request = createMockRequest('/api/transactions/tx-1/categorize', {
method: 'POST',
body: {
is_business: true,
category: 'expense_software',
force: true,
expected_duplicate_transaction_id: SIBLING_UUID,
},
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ success: boolean; journal_entry_created: boolean }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.journal_entry_created).toBe(true)
// The dismissal is recorded to behandlingshistorik (BFNAR 2013:2 kap 8).
expect(mockAppendProcessingHistory).toHaveBeenCalledWith(
expect.objectContaining({
eventType: 'BankTransactionDuplicateDismissed',
aggregateType: 'BankTransaction',
aggregateId: 'tx-1',
actor: { type: 'user', id: 'user-1' },
payload: expect.objectContaining({ dismissed_transaction_id: SIBLING_UUID }),
}),
)
})
it('categorizes as private when is_business is false', async () => {
const tx = makeTransaction({
id: 'tx-1',
@@ -5,6 +5,8 @@ import { ensureInitialized } from '@/lib/init'
import { buildMappingResultFromCategory } from '@/lib/bookkeeping/category-mapping'
import { getTemplateById, buildMappingResultFromTemplate, validateTemplateForEntity } from '@/lib/bookkeeping/booking-templates'
import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
import { detectBookedDuplicateTransaction } from '@/lib/transactions/booking-duplicate-detection'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import { saveUserMappingRule, applySettlementAccount } from '@/lib/bookkeeping/mapping-engine'
import { upsertCounterpartyTemplate, buildMappingResultFromCounterpartyTemplate } from '@/lib/bookkeeping/counterparty-templates'
import { withRouteContext } from '@/lib/api/with-route-context'
@@ -144,6 +146,75 @@ export const POST = withRouteContext(
})
}
// Booking-time duplicate guard: this transaction is about to become a NEW
// verifikat. If another transaction on the same date+amount+account is
// already booked, booking this one double-counts one real affärshändelse
// (felaktig bokföring per BFL). Warn; the user confirms with force=true
// bound to the reviewed sibling. Mirrors the match-invoice soft-duplicate
// guard. Runs before any categorization work so the user resolves it first.
try {
const candidate = await detectBookedDuplicateTransaction(supabase, companyId, {
id,
date: transaction.date,
amount: transaction.amount,
cash_account_id: transaction.cash_account_id ?? null,
})
if (!body.force) {
if (candidate) {
return errorResponseFromCode('TRANSACTION_BOOK_POSSIBLE_DUPLICATE', txLog, {
requestId,
details: { candidate },
})
}
} else if (!candidate || candidate.transaction_id !== body.expected_duplicate_transaction_id) {
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', txLog, {
requestId,
details: {
expected_duplicate_transaction_id: body.expected_duplicate_transaction_id ?? null,
detected_transaction_id: candidate?.transaction_id ?? null,
},
})
} else {
txLog.warn('booking-time duplicate guard bypassed', {
reason: 'force=true',
requestId,
dismissedTransactionId: candidate.transaction_id,
})
// Persist the dismissal to behandlingshistorik (BFNAR 2013:2 kap 8) —
// booking over a DETECTED possible double-booking is a bookkeeping
// decision that needs a durable record. Best-effort; never blocks the
// booking.
try {
await appendProcessingHistory({
companyId,
correlationId: id,
aggregateType: 'BankTransaction',
aggregateId: id,
eventType: 'BankTransactionDuplicateDismissed',
payload: {
transaction_id: id,
dismissed_transaction_id: candidate.transaction_id,
dismissed_journal_entry_id: candidate.journal_entry_id,
amount_ore: Math.round(candidate.amount * 100),
entry_date: candidate.entry_date,
},
actor: { type: 'user', id: user.id },
occurredAt: new Date(),
})
} catch (logErr) {
txLog.error('failed to append duplicate-dismissal behandlingshistorik', logErr as Error)
}
}
} catch (err) {
if (body.force) {
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', txLog, {
requestId,
details: { detection_failed: true },
})
}
txLog.warn('booking-time duplicate detection failed (continuing)', err as Error)
}
const { data: settings } = await supabase
.from('company_settings')
.select('entity_type, fiscal_year_start_month')
+66
View File
@@ -0,0 +1,66 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { createLogger } from '@/lib/logger'
const log = createLogger('user/profile')
// User-scoped (not company-scoped) — same shape as /api/user/locale, so it
// opts out of withRouteContext and calls requireAuth() directly (MFA still
// enforced on hosted).
const BodySchema = z.object({
full_name: z.string().min(1).max(100),
})
export async function POST(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const parsed = BodySchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid name' }, { status: 400 })
}
const fullName = parsed.data.full_name.trim()
if (!fullName) {
return NextResponse.json({ error: 'Invalid name' }, { status: 400 })
}
// Source of truth: profiles.full_name. Read by the account menu
// (app/(dashboard)/layout.tsx), the first-name greetings, the agent context,
// and the AGI/KU contact-person field. RLS scopes the update to the caller's
// own row (profiles_update policy: auth.uid() = id).
const { error: updateError } = await supabase
.from('profiles')
.update({ full_name: fullName })
.eq('id', user.id)
if (updateError) {
return NextResponse.json({ error: 'Could not save name' }, { status: 500 })
}
// Best-effort: keep auth user_metadata.full_name in sync so the two stores
// don't drift. It seeds profiles via the handle_new_user trigger at signup
// and is wiped on account deletion as a display-name store. updateUserById
// REPLACES user_metadata wholesale, so read-merge-write to keep other keys.
try {
const admin = createServiceClient()
const { data: current } = await admin.auth.admin.getUserById(user.id)
const priorMeta = current?.user?.user_metadata ?? {}
await admin.auth.admin.updateUserById(user.id, {
user_metadata: { ...priorMeta, full_name: fullName },
})
} catch (syncError) {
log.warn('user_metadata full_name sync failed (non-blocking)', syncError)
}
return NextResponse.json({ data: { full_name: fullName } })
}