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
@@ -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')