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>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
bc09cea07e
commit
9ed0b9515a
@@ -98,19 +98,24 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Företagsinställningar saknas' }, { status: 404 })
|
||||
}
|
||||
|
||||
// VAT rules are customer-type-driven; the seller's registration status no
|
||||
// longer constrains the preview. A non-momsregistrerad seller who chose a
|
||||
// non-zero rate sees the rate they picked rendered — the form surfaces the
|
||||
// ML 16 kap. 23 § warning at submit time.
|
||||
// VAT rules are customer-type-driven and only know the customer side.
|
||||
const vatRules = getVatRules(customer.customer_type, customer.vat_number_validated)
|
||||
|
||||
const docType: InvoiceDocumentType = document_type || 'invoice'
|
||||
const isDeliveryNote = docType === 'delivery_note'
|
||||
|
||||
// VAT registration gate — mirror the server-side write gate
|
||||
// (lib/invoices/build-invoice-write.ts) so the preview never shows output VAT
|
||||
// for a non-momsregistrerad seller. Without this the per-item fallback below
|
||||
// (`?? vatRules.rate`) would render 25% for a Swedish customer even though the
|
||||
// created invoice books no VAT, misleading the user at the review step.
|
||||
const notVatRegistered = (company as { vat_registered?: boolean }).vat_registered === false
|
||||
const zeroVat = notVatRegistered && !isDeliveryNote
|
||||
|
||||
// Build items with line totals and per-item VAT
|
||||
const invoiceItems: InvoiceItem[] = items.map((item: { description: string; quantity: number; unit: string; unit_price: number; vat_rate?: number }, index: number) => {
|
||||
const lineTotal = Math.round(item.quantity * item.unit_price * 100) / 100
|
||||
const rate = item.vat_rate ?? vatRules.rate
|
||||
const rate = zeroVat ? 0 : (item.vat_rate ?? vatRules.rate)
|
||||
return {
|
||||
id: `preview-${index}`,
|
||||
invoice_id: 'preview',
|
||||
|
||||
@@ -37,7 +37,7 @@ vi.mock('@/lib/bookkeeping/engine', () => ({
|
||||
// lib/transactions/__tests__/booking-duplicate-detection.test.ts.
|
||||
const mockDetectDup = vi.fn()
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookedDuplicateTransaction: (...args: unknown[]) => mockDetectDup(...args),
|
||||
detectBookingDuplicate: (...args: unknown[]) => mockDetectDup(...args),
|
||||
}))
|
||||
|
||||
// Behandlingshistorik append — mocked so we can assert the dismissal is
|
||||
@@ -52,6 +52,7 @@ 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'
|
||||
const VOUCHER_JE_UUID = '880e8400-e29b-41d4-a716-446655440333'
|
||||
|
||||
describe('POST /api/transactions/[id]/book', () => {
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
@@ -289,6 +290,68 @@ describe('POST /api/transactions/[id]/book', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 409 when a ledger-only voucher (no sibling transaction) already books this movement', async () => {
|
||||
const tx = makeTransaction({ id: 'tx-1', amount: 98565, journal_entry_id: null })
|
||||
enqueue({ data: tx, error: null }) // fetch
|
||||
// A voucher-keyed candidate has no transaction_id — it's bound by je id.
|
||||
mockDetectDup.mockResolvedValue({
|
||||
transaction_id: null,
|
||||
journal_entry_id: VOUCHER_JE_UUID,
|
||||
voucher_label: 'A2',
|
||||
entry_date: '2026-03-30',
|
||||
description: 'Inbetalning kundfaktura 2026001',
|
||||
amount: 98565,
|
||||
})
|
||||
|
||||
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 | null; journal_entry_id: string } } }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('TRANSACTION_BOOK_POSSIBLE_DUPLICATE')
|
||||
expect(body.error.details.candidate.transaction_id).toBeNull()
|
||||
expect(body.error.details.candidate.journal_entry_id).toBe(VOUCHER_JE_UUID)
|
||||
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('books a voucher-keyed duplicate when force=true binds the expected journal_entry_id', async () => {
|
||||
const tx = makeTransaction({ id: 'tx-1', amount: 98565, 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: null,
|
||||
journal_entry_id: VOUCHER_JE_UUID,
|
||||
voucher_label: 'A2',
|
||||
entry_date: '2026-03-30',
|
||||
description: null,
|
||||
amount: 98565,
|
||||
})
|
||||
mockCreateJournalEntry.mockResolvedValue(je)
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-1/book', {
|
||||
method: 'POST',
|
||||
body: { ...validBody, force: true, expected_duplicate_journal_entry_id: VOUCHER_JE_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(mockCreateJournalEntry).toHaveBeenCalledTimes(1)
|
||||
expect(mockAppendProcessingHistory).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
eventType: 'BankTransactionDuplicateDismissed',
|
||||
payload: expect.objectContaining({
|
||||
dismissed_transaction_id: null,
|
||||
dismissed_journal_entry_id: VOUCHER_JE_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
|
||||
|
||||
@@ -8,7 +8,7 @@ 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 { 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'
|
||||
@@ -36,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, force, expected_duplicate_transaction_id } = validation.data
|
||||
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
|
||||
@@ -65,7 +65,7 @@ export async function POST(
|
||||
// match-invoice soft-duplicate guard.
|
||||
const dupLog = createLogger('transactions.book', { companyId, userId: user.id })
|
||||
try {
|
||||
const candidate = await detectBookedDuplicateTransaction(supabase, companyId, {
|
||||
const candidate = await detectBookingDuplicate(supabase, companyId, {
|
||||
id,
|
||||
date: transaction.date,
|
||||
amount: transaction.amount,
|
||||
@@ -77,13 +77,24 @@ export async function POST(
|
||||
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.
|
||||
} 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 {
|
||||
|
||||
@@ -43,7 +43,7 @@ vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
// 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),
|
||||
detectBookingDuplicate: (...args: unknown[]) => mockDetectDup(...args),
|
||||
}))
|
||||
|
||||
// Behandlingshistorik append — mocked so we can assert the dismissal is
|
||||
|
||||
@@ -5,7 +5,7 @@ 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 { detectBookingDuplicate } 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'
|
||||
@@ -153,7 +153,7 @@ export const POST = withRouteContext(
|
||||
// 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, {
|
||||
const candidate = await detectBookingDuplicate(supabase, companyId, {
|
||||
id,
|
||||
date: transaction.date,
|
||||
amount: transaction.amount,
|
||||
@@ -166,12 +166,24 @@ export const POST = withRouteContext(
|
||||
details: { candidate },
|
||||
})
|
||||
}
|
||||
} else if (!candidate || candidate.transaction_id !== body.expected_duplicate_transaction_id) {
|
||||
} 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. Re-detect and refuse
|
||||
// the bypass unless it still matches, so a guessed id can't wave it away.
|
||||
!candidate ||
|
||||
!(
|
||||
(candidate.journal_entry_id && candidate.journal_entry_id === body.expected_duplicate_journal_entry_id) ||
|
||||
(candidate.transaction_id && 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,
|
||||
expected_duplicate_journal_entry_id: body.expected_duplicate_journal_entry_id ?? null,
|
||||
detected_transaction_id: candidate?.transaction_id ?? null,
|
||||
detected_journal_entry_id: candidate?.journal_entry_id ?? null,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user