* fix(git): pin LF on generated extension registry and vitest snapshots setup:extensions and vitest write these files with LF; with core.autocrlf=true git expects CRLF and flags them as phantom modifications on every dev/build run. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(security): enforce MFA on mcp-oauth consent and gate viewer storno route mcp-oauth/authorize renders an HTML consent page and issues 303 redirects that withRouteContext cannot express, so it kept raw getUser() and thereby skipped the AAL2 gate: a password-only (AAL1) session could approve consent that mints a long-lived, MFA-bypassing API key. Add a route-local requireAal2() step-up on GET and POST; AAL1 sessions redirect to /mfa/verify, BankID users are exempt. Separately, POST /api/reports/vat-declaration/rc-basis-gaps/fix calls correctEntry() (storno of a posted entry) but lacked requireWrite, so viewer-role members could trigger it. Add { requireWrite: true }. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route transactions endpoints through withRouteContext Migrate the transactions routes off hand-rolled supabase.auth.getUser() onto the MFA-enforcing withRouteContext wrapper; add requireWrite on mutating handlers (book, uncategorize, attach-document, ignore, batch-match, create-from-document). Behavior and response shapes preserved; tests updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route SIE import and bank reconciliation through withRouteContext Migrate import/sie and reconciliation/bank routes onto the MFA-enforcing wrapper; requireWrite on mutations (import execute, create-accounts, mappings write verbs, link/unlink/run/mark-opening-balance). Reads (status, unmatched-entries) stay ungated. Response shapes preserved; tests added/updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route salary endpoints through withRouteContext Migrate salary employees and runs routes (plus ku, payroll-config, tax-tables) onto the MFA-enforcing wrapper; requireWrite on mutations. Personnummer masking/encryption untouched; file downloads (AGI XML, payslip PDF, payment files) keep their headers. Two payment-file GETs retain requireWrite because they stamp *_file_generated_at and previously gated viewers. Tests added/updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route report endpoints through withRouteContext Migrate the read-only report routes (trial balance, balansrapport, resultatrapport, income statement, ledgers, KPI, VAT declaration, salary journal, monthly breakdown, journal register, continuity check, full archive, etc.) onto the MFA-enforcing wrapper. All read-only, no requireWrite. JSON/XLSX/PDF/ZIP response bodies and headers preserved byte-for-byte; tests updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route invoices, skatteverket, agent and extension endpoints through withRouteContext Migrate invoices, supplier-invoices, skatteverket tax-payments, and dynamic extension routes onto the MFA-enforcing wrapper with requireWrite on mutations. The two NDJSON streaming agent routes (invoke, onboarding/stream) use requireAuth() directly (the wrapper can't wrap a streaming response) so MFA is still enforced. skatteverket payment-file GET keeps requireWrite (stamps a generated-at field). Response shapes and file headers preserved; tests added/updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route documents, events, team and account endpoints through withRouteContext Migrate documents, events, kpi/preferences, vat/validate, support/contact onto the MFA-enforcing wrapper with requireWrite on mutations. account/password, team/accept and team/members use requireAuth() directly (user-level or pre-membership flows with no active company context) so MFA is still enforced. events keeps its dual API-key-or-session auth. Document retention guard untouched; tests added/updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route settings and pending-operations endpoints through withRouteContext Migrate settings (api-keys, oauth-clients, booking-templates, counterparty-templates, logo, company settings) and pending-operations (commit, bulk-commit, reject, edit-before-approve) onto the MFA-enforcing wrapper with requireWrite on mutations. Credential-guarding routes keep their per-user ownership filters. Response shapes preserved; tests added/updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(guards): ratchet raw-route-auth baseline 119->1 after A1 migration Lock in the withRouteContext migration so the count cannot regress. The single remaining entry, mcp-oauth/authorize, is a documented exception (HTML consent + redirects, MFA enforced via route-local step-up). Record the campaign and requireWrite decisions in DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(vat): add eSKD momsdeklaration file export for "Deklarera via fil" Generate the Skatteverket eSKDUpload v6.0 XML file so users can file VAT by upload instead of typing every ruta into the form. Extract buildFiledAmounts() as the shared whole-krona source of truth (öre truncated per SFL 22 kap 1 §) so the XML file and the manual-filing PDF can never disagree. Adds the /eskd API route, an XML option in the report export menu, and the upload button on the manual-filing card. Strings in sv + en. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(vat): add 'vat_settlement' source type and update related components * fix(booking): adjust search input layout and enable autofocus * fix(vat): support 12-digit org numbers and adjust emission order for eSKD file * fix(migration): add 'vat_settlement' to journal_entries.source_type CHECK --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
188 lines
6.9 KiB
TypeScript
188 lines
6.9 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { eventBus } from '@/lib/events'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
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 { detectBookingDuplicate } from '@/lib/transactions/booking-duplicate-detection'
|
|
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
|
import type { Transaction } from '@/types'
|
|
|
|
ensureInitialized()
|
|
|
|
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
|
'transaction.book',
|
|
async (request, { supabase, user, companyId, log }, { params }) => {
|
|
const { id } = await params
|
|
|
|
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 = log
|
|
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,
|
|
})
|
|
},
|
|
{ requireWrite: true },
|
|
)
|