Files
accounted/app/api/transactions/[id]/book/route.ts
T
MattssonandClaude Opus 4.8 9ed0b9515a Fix/invoice booking vat fixes (#778)
* feat(invoices): add Plusgiro input to bank details settings

Plusgiro was already persisted, validated by the API schema, rendered on
the invoice PDF and toggleable via "Visa plusgiro" — but the settings UI
had no field to enter the number, so plusgiro-only users could not fill
it in. Add the input next to Bankgiro with Luhn validation and hyphen
formatting, include it in the save payload (normalised on save so raw
digits still match the dashed schema format), and add sv/en strings.

Adds validatePlusgiroNumber/formatPlusgiroNumber helpers + tests.

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

* fix(invoices): respect non-VAT-registered seller in PDF preview + portal tooltips

Two user-reported bugs:

- PDF preview (/api/invoices/preview-pdf) ignored company.vat_registered and
  fell back to the customer-driven 25% rate, so a non-momsregistrerad seller
  saw VAT in the review step even though the created invoice books none. Mirror
  the server-side write gate (build-invoice-write.ts): force 0% when
  vat_registered is false (delivery notes excepted).

- InfoTooltip rendered TooltipContent without a Portal, so tooltips were
  clipped by the scrollable DialogContent (overflow-y-auto) in the send-invoice
  journal-entry review. Wrap in TooltipPrimitive.Portal.

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

* fix(transactions): book library mall from its literal lines, not a lossy fallback

Booking a bank transaction with a user-created booking-template (mall) via the
convertible "QuickReview" fast path reduced the template to a single category +
one account_override, silently discarding the chosen debit/credit. A
kundinbetalning mall (D 1930 / K 1510) booked as a generic cost (D 6991 / K 1930),
or with a VAT line as D 1930 / K 1930 / K 2611 — and the result flipped with the
direction inferred from the business/settlement line tags, so visually-identical
templates produced different verifikationer.

Route every library template through the journal-entry editor (applyTemplate ->
/book), which posts the literal lines, regardless of convertibility. Add
regression tests locking the contract.

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

* fix(bookkeeping): make the booking-time duplicate guard bypassable

TRANSACTION_BOOK_POSSIBLE_DUPLICATE told users they could "book anyway" but
the UI dead-ended on a toast with no way to do so. Add a shared
DuplicateBookingDialog that surfaces the already-booked sibling and lets the
user review it or book anyway (force bound to the reviewed candidate, which
the server re-detects so a stale id cannot wave the guard away).

- Wire the dialog into the /transactions categorize flow and the manual
  booking dialog (JournalEntryForm -> /api/transactions/[id]/book)
- Bind the override to expected_duplicate_transaction_id OR
  expected_duplicate_journal_entry_id so ledger-only vouchers (paid invoice,
  salary run) can be confirmed too
- Extend the guard to the pending-operations commit path and the MCP server
- Tests for book/categorize routes, detection, and the commit guard

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

* fix(bookkeeping): log duplicate-guard bypass to behandlingshistorik in the agent commit path

The web /book and /categorize routes append a durable
BankTransactionDuplicateDismissed event when a user books over a detected
possible double-booking. The agent commit path (commitCategorizeTransaction,
commitMarkInvoicePaid) skipped the guard silently on allow_duplicate=true,
leaving no behandlingshistorik — an auditor could not reconstruct why the
duplicate was allowed (BFNAR 2013:2 kap 8).

When allow_duplicate=true, re-detect the candidate and append the dismissal
event (BankTransactionDuplicateDismissed for the bank-line path,
InvoiceDuplicatePaymentDismissed for mark-paid). Best-effort — a logging
failure never blocks a legitimate booking. Payloads stay PII-safe (ids,
amounts, dates only — no customer or merchant name).

Also fix the misleading DuplicateBookingDialog JSDoc: the retry binds
expected_duplicate_journal_entry_id, not candidate.transaction_id, so the
systemdokumentation matches the actual control (BFL 7 kap).

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

* test(mcp-server): stub booking-duplicate guard in receipt-matcher categorize tests

The gnubok_categorize_transaction tool runs the booking-time duplicate guard
before staging; its detection queries consumed the queued supabase mock
results, so the staging assertions saw a thrown duplicate error instead of a
staged op. Mock detectBookingDuplicate to "no duplicate" since these tests
don't exercise that path.

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

* refactor(transactions): use roundOre for duplicate-guard öre rounding

Replace naive Math.round(x*100)/100 with roundOre() from @/lib/money in the
booking-time duplicate guard (detection lib, commit executor, MCP categorize
tool), satisfying the no-new-antipatterns ratchet guard.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 15:54:35 +02:00

202 lines
7.1 KiB
TypeScript

import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import { bookkeepingErrorResponse } from '@/lib/bookkeeping/errors'
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 { detectBookingDuplicate } 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()
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const { id } = await params
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
const validation = await validateBody(request, BookTransactionSchema)
if (!validation.success) return validation.response
const { fiscal_period_id, entry_date, description, lines, force, expected_duplicate_transaction_id, expected_duplicate_journal_entry_id } = validation.data
// Fetch transaction (validates ownership)
const { data: transaction, error: fetchError } = await supabase
.from('transactions')
.select('*')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (fetchError || !transaction) {
return NextResponse.json({ error: 'Transaction not found' }, { status: 404 })
}
// Reject if already booked
if (transaction.journal_entry_id) {
return NextResponse.json(
{ error: 'Transaction already has a journal entry' },
{ status: 409 }
)
}
// 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 detectBookingDuplicate(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 (
// force=true is bound to the reviewed candidate. A sibling-transaction
// candidate carries a transaction_id; a ledger-only voucher candidate does
// not, so both are bound by journal_entry_id. Either echoed id confirms.
// Re-detect and refuse the bypass unless it still matches, so a guessed id
// can't wave the guard.
!candidate ||
!(
(candidate.journal_entry_id && candidate.journal_entry_id === expected_duplicate_journal_entry_id) ||
(candidate.transaction_id && candidate.transaction_id === expected_duplicate_transaction_id)
)
) {
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', dupLog, {
details: {
expected_duplicate_transaction_id: expected_duplicate_transaction_id ?? null,
expected_duplicate_journal_entry_id: expected_duplicate_journal_entry_id ?? null,
detected_transaction_id: candidate?.transaction_id ?? null,
detected_journal_entry_id: candidate?.journal_entry_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 {
journalEntry = await createJournalEntry(supabase, companyId, user.id, {
fiscal_period_id,
entry_date,
description,
source_type: 'bank_transaction',
source_id: id,
lines,
})
} catch (err) {
const typed = bookkeepingErrorResponse(err)
if (typed) return typed
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to create journal entry' },
{ status: 400 }
)
}
// Link transaction to the journal entry
const { error: updateError } = await supabase
.from('transactions')
.update({
journal_entry_id: journalEntry.id,
is_business: true,
category: 'uncategorized',
})
.eq('id', id)
if (updateError) {
return NextResponse.json(
{ error: 'Failed to update transaction' },
{ status: 500 }
)
}
// Emit event (non-blocking)
try {
await eventBus.emit({
type: 'transaction.categorized',
payload: {
transaction: transaction as Transaction,
account: lines[0]?.account_number || '',
taxCode: '',
userId: user.id,
companyId,
},
})
} catch {
// Non-critical
}
return NextResponse.json({
data: journalEntry,
journal_entry_id: journalEntry.id,
success: true,
})
}