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:
co-authored by
Claude Opus 4.8
parent
d95a0b6105
commit
8322830f46
@@ -22,6 +22,7 @@ import {
|
||||
// Invoice schemas
|
||||
CreateInvoiceItemSchema,
|
||||
CreateInvoiceSchema,
|
||||
UpdateInvoiceSchema,
|
||||
CreateCreditNoteSchema,
|
||||
MarkInvoicePaidSchema,
|
||||
// Customer schemas
|
||||
@@ -382,6 +383,33 @@ describe('CreateInvoiceSchema', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('UpdateInvoiceSchema', () => {
|
||||
it('accepts a valid update body', () => {
|
||||
const result = UpdateInvoiceSchema.safeParse(validInvoice())
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects an empty items array', () => {
|
||||
const result = UpdateInvoiceSchema.safeParse(validInvoice({ items: [] }))
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an invalid item shape', () => {
|
||||
const result = UpdateInvoiceSchema.safeParse(validInvoice({
|
||||
items: [validInvoiceItem({ description: '' })],
|
||||
}))
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('drops save_as_draft — editing a draft never re-creates it', () => {
|
||||
const result = UpdateInvoiceSchema.safeParse(validInvoice({ save_as_draft: true }))
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) {
|
||||
expect(result.data).not.toHaveProperty('save_as_draft')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('CreateInvoiceItemSchema', () => {
|
||||
it('accepts valid item with all fields', () => {
|
||||
const result = CreateInvoiceItemSchema.safeParse(validInvoiceItem({ vat_rate: 0.25 }))
|
||||
|
||||
+47
-17
@@ -353,9 +353,18 @@ export const CreateInvoiceSchema = z.object({
|
||||
// ("Granska och skapa"). An unnumbered draft is not yet an issued faktura
|
||||
// (ML 17 kap 24§), so it can be hard-deleted with no gap in the number series.
|
||||
save_as_draft: z.boolean().optional(),
|
||||
// Per-invoice öresavrundning toggle (display-only). Omitted → stored as null,
|
||||
// which inherits company_settings.ore_rounding when rendering totals.
|
||||
ore_rounding: z.boolean().optional(),
|
||||
items: z.array(CreateInvoiceItemSchema).min(1, 'At least one item is required'),
|
||||
})
|
||||
|
||||
// Update (edit) an existing DRAFT invoice in place. Same shape as create minus
|
||||
// `save_as_draft` — editing never (re)creates a draft or allocates a number, it
|
||||
// only rewrites the draft's header + line items. The PATCH route guards that the
|
||||
// target is still a draft (status='draft', no journal entry, not self-billed).
|
||||
export const UpdateInvoiceSchema = CreateInvoiceSchema.omit({ save_as_draft: true })
|
||||
|
||||
export const CreateCreditNoteSchema = z.object({
|
||||
credited_invoice_id: uuid,
|
||||
reason: z.string().optional(),
|
||||
@@ -623,6 +632,8 @@ export const CreateSupplierInvoiceSchema = z.object({
|
||||
reverse_charge: z.boolean().optional(),
|
||||
payment_reference: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
// Per-invoice öresavrundning toggle (display-only). Omitted → stored as null (off).
|
||||
ore_rounding: z.boolean().optional(),
|
||||
paid_with_private_funds: z.boolean().optional(),
|
||||
// For paid_with_private_funds: the date the owner paid out-of-pocket.
|
||||
// Defaults to invoice_date (common for kvitto where the two coincide).
|
||||
@@ -723,24 +734,43 @@ export const CreateTransactionSchema = z.object({
|
||||
notes: z.string().max(2000).optional(),
|
||||
})
|
||||
|
||||
export const CategorizeTransactionSchema = z.object({
|
||||
is_business: z.boolean(),
|
||||
category: TransactionCategorySchema.optional(),
|
||||
template_id: z.string().optional(),
|
||||
vat_treatment: VatTreatmentSchema.optional(),
|
||||
account_override: accountNumber.optional(),
|
||||
counterparty_template_id: z.string().uuid().optional(),
|
||||
user_description: z.string().max(500).optional(),
|
||||
inbox_item_id: z.string().uuid().optional(),
|
||||
confirm_no_match: z.boolean().optional(),
|
||||
})
|
||||
export const CategorizeTransactionSchema = z
|
||||
.object({
|
||||
is_business: z.boolean(),
|
||||
category: TransactionCategorySchema.optional(),
|
||||
template_id: z.string().optional(),
|
||||
vat_treatment: VatTreatmentSchema.optional(),
|
||||
account_override: accountNumber.optional(),
|
||||
counterparty_template_id: z.string().uuid().optional(),
|
||||
user_description: z.string().max(500).optional(),
|
||||
inbox_item_id: z.string().uuid().optional(),
|
||||
confirm_no_match: z.boolean().optional(),
|
||||
// Booking-time duplicate guard (TRANSACTION_BOOK_POSSIBLE_DUPLICATE). force
|
||||
// bypasses it after the user reviews the candidate; the bypass is bound to
|
||||
// the specific already-booked sibling via expected_duplicate_transaction_id
|
||||
// (re-detected server-side, so a guessed id can't wave the guard away).
|
||||
force: z.boolean().optional(),
|
||||
expected_duplicate_transaction_id: uuid.optional(),
|
||||
})
|
||||
.refine((v) => !v.force || !!v.expected_duplicate_transaction_id, {
|
||||
message: 'expected_duplicate_transaction_id is required when force=true',
|
||||
path: ['expected_duplicate_transaction_id'],
|
||||
})
|
||||
|
||||
export const BookTransactionSchema = z.object({
|
||||
fiscal_period_id: uuid,
|
||||
entry_date: isoDate,
|
||||
description: z.string().min(1, 'Description is required'),
|
||||
lines: z.array(CreateJournalEntryLineSchema).min(1, 'At least one line is required'),
|
||||
})
|
||||
export const BookTransactionSchema = z
|
||||
.object({
|
||||
fiscal_period_id: uuid,
|
||||
entry_date: isoDate,
|
||||
description: z.string().min(1, 'Description is required'),
|
||||
lines: z.array(CreateJournalEntryLineSchema).min(1, 'At least one line is required'),
|
||||
// Booking-time duplicate guard — see CategorizeTransactionSchema.
|
||||
force: z.boolean().optional(),
|
||||
expected_duplicate_transaction_id: uuid.optional(),
|
||||
})
|
||||
.refine((v) => !v.force || !!v.expected_duplicate_transaction_id, {
|
||||
message: 'expected_duplicate_transaction_id is required when force=true',
|
||||
path: ['expected_duplicate_transaction_id'],
|
||||
})
|
||||
|
||||
/**
|
||||
* Edit a bank transaction's title (description). Only the working label —
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { DEFAULT_ACCOUNTS_BY_CATEGORY, disposeAsset } from '../assets/asset-service'
|
||||
import {
|
||||
AssetCorrectionBlockedError,
|
||||
DEFAULT_ACCOUNTS_BY_CATEGORY,
|
||||
disposeAsset,
|
||||
updateAsset,
|
||||
} from '../assets/asset-service'
|
||||
import type { Asset } from '@/types'
|
||||
|
||||
vi.mock('@/lib/bookkeeping/engine', () => ({
|
||||
@@ -282,3 +287,183 @@ describe('disposeAsset — gain/loss account selection', () => {
|
||||
expect(lines.find((l) => l.account_number === '7973')?.debit_amount).toBe(20_000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('updateAsset — acquisition-basis correction guard', () => {
|
||||
function makeAssetRow(overrides: Partial<Asset> = {}): Asset {
|
||||
return {
|
||||
id: 'asset-1',
|
||||
user_id: 'u',
|
||||
company_id: 'co',
|
||||
name: 'reMarkable Paper Pro',
|
||||
category: 'computer',
|
||||
acquisition_date: '2025-04-19',
|
||||
acquisition_cost: 7999.2,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 36,
|
||||
depreciation_method: 'linear',
|
||||
bas_asset_account: '1250',
|
||||
bas_accumulated_account: '1259',
|
||||
bas_expense_account: '7833',
|
||||
restvarde_target: null,
|
||||
disposed_at: null,
|
||||
disposed_proceeds: null,
|
||||
disposed_proceeds_vat: 0,
|
||||
disposed_vat_treatment: null,
|
||||
jamkning_amount: 0,
|
||||
jamkning_remaining_months: null,
|
||||
jamkning_total_months: null,
|
||||
jamkning_original_input_vat: null,
|
||||
k3_components: null,
|
||||
notes: null,
|
||||
created_at: '2026-06-11T00:00:00Z',
|
||||
updated_at: '2026-06-11T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const asSupabase = (s: unknown) => s as Parameters<typeof updateAsset>[0]
|
||||
|
||||
/**
|
||||
* Minimal Supabase mock that captures the final UPDATE payload. updateAsset's
|
||||
* correction guard touches three tables:
|
||||
* - 'assets' → getAsset (.maybeSingle) and the update (.single)
|
||||
* - 'depreciation_schedules' → hasPostedDepreciation (1st call, head {count})
|
||||
* then hasManualDepreciationPosted (2nd call,
|
||||
* .select('journal_entry_id') → {data})
|
||||
* - 'journal_entry_lines' → hasManualDepreciationPosted ledger scan → {data}
|
||||
*/
|
||||
function mockForUpdate(
|
||||
asset: Asset,
|
||||
opts: {
|
||||
postedCount?: number
|
||||
otherAssetEntryIds?: string[]
|
||||
accumulatedCredits?: { journal_entry_id: string }[]
|
||||
} = {},
|
||||
) {
|
||||
const captured: { update: Record<string, unknown> | null } = { update: null }
|
||||
let schedCall = 0
|
||||
const supabase = {
|
||||
from: vi.fn((table: string) => {
|
||||
if (table === 'depreciation_schedules') {
|
||||
schedCall += 1
|
||||
const isCountQuery = schedCall === 1
|
||||
const chain: Record<string, unknown> = {}
|
||||
chain.select = vi.fn(() => chain)
|
||||
chain.eq = vi.fn(() => chain)
|
||||
chain.neq = vi.fn(() => chain)
|
||||
chain.not = vi.fn(() => chain)
|
||||
chain.then = (resolve: (v: unknown) => void) =>
|
||||
resolve(
|
||||
isCountQuery
|
||||
? { count: opts.postedCount ?? 0, error: null }
|
||||
: {
|
||||
data: (opts.otherAssetEntryIds ?? []).map((id) => ({
|
||||
journal_entry_id: id,
|
||||
})),
|
||||
error: null,
|
||||
},
|
||||
)
|
||||
return chain
|
||||
}
|
||||
if (table === 'journal_entry_lines') {
|
||||
const chain: Record<string, unknown> = {}
|
||||
chain.select = vi.fn(() => chain)
|
||||
chain.eq = vi.fn(() => chain)
|
||||
chain.gt = vi.fn(() => chain)
|
||||
chain.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: opts.accumulatedCredits ?? [], error: null })
|
||||
return chain
|
||||
}
|
||||
const chain: Record<string, unknown> = {}
|
||||
chain.select = vi.fn(() => chain)
|
||||
chain.eq = vi.fn(() => chain)
|
||||
chain.maybeSingle = vi.fn(async () => ({ data: asset, error: null }))
|
||||
chain.update = vi.fn((payload: Record<string, unknown>) => {
|
||||
captured.update = payload
|
||||
return chain
|
||||
})
|
||||
chain.single = vi.fn(async () => ({
|
||||
data: { ...asset, ...(captured.update ?? {}) },
|
||||
error: null,
|
||||
}))
|
||||
return chain
|
||||
}),
|
||||
}
|
||||
return { supabase, captured }
|
||||
}
|
||||
|
||||
it('corrects acquisition_date when not disposed and no depreciation is posted', async () => {
|
||||
const { supabase } = mockForUpdate(makeAssetRow(), { postedCount: 0 })
|
||||
const result = await updateAsset(asSupabase(supabase), 'co', 'asset-1', {
|
||||
acquisition_date: '2025-08-15',
|
||||
})
|
||||
expect(result.acquisition_date).toBe('2025-08-15')
|
||||
})
|
||||
|
||||
it('blocks an acquisition_date correction once depreciation is posted', async () => {
|
||||
const { supabase } = mockForUpdate(makeAssetRow(), { postedCount: 2 })
|
||||
await expect(
|
||||
updateAsset(asSupabase(supabase), 'co', 'asset-1', { acquisition_date: '2025-08-15' }),
|
||||
).rejects.toBeInstanceOf(AssetCorrectionBlockedError)
|
||||
})
|
||||
|
||||
it('blocks an acquisition_cost correction on a disposed asset', async () => {
|
||||
const { supabase } = mockForUpdate(
|
||||
makeAssetRow({ disposed_at: '2026-01-01', disposed_proceeds: 1000 }),
|
||||
)
|
||||
await expect(
|
||||
updateAsset(asSupabase(supabase), 'co', 'asset-1', { acquisition_cost: 5000 }),
|
||||
).rejects.toThrow(/disposed/i)
|
||||
})
|
||||
|
||||
it('allows a name-only edit even when depreciation is posted', async () => {
|
||||
// A name-only patch touches no acquisition-basis field, so the guard never
|
||||
// runs and the edit succeeds regardless of depreciation state.
|
||||
const { supabase } = mockForUpdate(makeAssetRow(), { postedCount: 5 })
|
||||
const result = await updateAsset(asSupabase(supabase), 'co', 'asset-1', {
|
||||
name: 'reMarkable Paper Pro 2',
|
||||
})
|
||||
expect(result.name).toBe('reMarkable Paper Pro 2')
|
||||
})
|
||||
|
||||
it('realigns the BAS triple to the new category defaults on a category correction', async () => {
|
||||
const { supabase, captured } = mockForUpdate(makeAssetRow(), { postedCount: 0 })
|
||||
await updateAsset(asSupabase(supabase), 'co', 'asset-1', { category: 'equipment' })
|
||||
// computer (1250/1259/7833) → equipment defaults (1220/1229/7832)
|
||||
expect(captured.update).toMatchObject({
|
||||
category: 'equipment',
|
||||
bas_asset_account: '1220',
|
||||
bas_accumulated_account: '1229',
|
||||
bas_expense_account: '7832',
|
||||
})
|
||||
})
|
||||
|
||||
it('blocks a correction when depreciation was hand-posted (no engine schedule)', async () => {
|
||||
// No depreciation_schedules row, but a manual credit to the asset's 1259
|
||||
// accumulated account exists in the ledger — must still block.
|
||||
const { supabase } = mockForUpdate(makeAssetRow(), {
|
||||
postedCount: 0,
|
||||
otherAssetEntryIds: [],
|
||||
accumulatedCredits: [{ journal_entry_id: 'manual-entry-1' }],
|
||||
})
|
||||
await expect(
|
||||
updateAsset(asSupabase(supabase), 'co', 'asset-1', { acquisition_date: '2025-08-15' }),
|
||||
).rejects.toBeInstanceOf(AssetCorrectionBlockedError)
|
||||
})
|
||||
|
||||
it('allows a correction when the only 1259 credit is a sibling asset’s engine entry', async () => {
|
||||
// Two computers share 1259. The sibling was depreciated via the engine, so
|
||||
// its journal entry is attributable to the OTHER asset and must NOT block a
|
||||
// correction of this still-undepreciated asset (no false positive).
|
||||
const { supabase, captured } = mockForUpdate(makeAssetRow(), {
|
||||
postedCount: 0,
|
||||
otherAssetEntryIds: ['sibling-engine-entry'],
|
||||
accumulatedCredits: [{ journal_entry_id: 'sibling-engine-entry' }],
|
||||
})
|
||||
const result = await updateAsset(asSupabase(supabase), 'co', 'asset-1', {
|
||||
acquisition_date: '2025-08-15',
|
||||
})
|
||||
expect(result.acquisition_date).toBe('2025-08-15')
|
||||
expect(captured.update).toMatchObject({ acquisition_date: '2025-08-15' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ vi.mock('@/lib/reports/income-statement', () => ({
|
||||
import {
|
||||
calculateBolagsskatt,
|
||||
BOLAGSSKATT_RATE,
|
||||
sumPostedYearEndDispositions,
|
||||
} from '../tax-provision/bolagsskatt-calculator'
|
||||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||||
|
||||
@@ -84,6 +85,55 @@ describe('calculateBolagsskatt', () => {
|
||||
expect(result!.amount).toBe(41_818)
|
||||
})
|
||||
|
||||
it('uses resultBeforeTaxOverride and does NOT read the income statement', async () => {
|
||||
// Preview mode: the dispositions builder passes the post-disposition base
|
||||
// directly. The income statement (pre-disposition) must not be consulted.
|
||||
const result = await calculateBolagsskatt(NOOP_CLIENT, 'co', 'fp', {
|
||||
resultBeforeTaxOverride: 750_000,
|
||||
})
|
||||
|
||||
expect(result!.amount).toBe(Math.round(750_000 * BOLAGSSKATT_RATE)) // 154_500
|
||||
expect(generateIncomeStatement).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('combines resultBeforeTaxOverride with manual adjustments', async () => {
|
||||
const result = await calculateBolagsskatt(NOOP_CLIENT, 'co', 'fp', {
|
||||
resultBeforeTaxOverride: 750_000,
|
||||
manualAdjustments: { schablonintaktPeriodiseringsfond: 3_000 },
|
||||
})
|
||||
|
||||
// (750_000 + 3_000) × 0.206 = 155_118
|
||||
expect(result!.amount).toBe(155_118)
|
||||
expect(generateIncomeStatement).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sumPostedYearEndDispositions adds back periodiseringsfond + överavskrivning (class-88) + SLP, ignores tax/liability', async () => {
|
||||
// Commit path: bolagsskatt is computed after the other dispositions are
|
||||
// posted. They carry source_type='year_end' (excluded from the income
|
||||
// statement), so the tax base must add their P&L effect back.
|
||||
const rows = [
|
||||
{ account_number: '8811', debit_amount: 150_000, credit_amount: 0 }, // avsättning −150k
|
||||
{ account_number: '8819', debit_amount: 0, credit_amount: 20_000 }, // återföring +20k
|
||||
{ account_number: '8853', debit_amount: 39_000, credit_amount: 0 }, // överavskrivning −39k
|
||||
{ account_number: '7533', debit_amount: 5_000, credit_amount: 0 }, // SLP −5k
|
||||
{ account_number: '8910', debit_amount: 123_600, credit_amount: 0 }, // skatt — ignored
|
||||
{ account_number: '2124', debit_amount: 0, credit_amount: 150_000 }, // skuld — ignored
|
||||
]
|
||||
const result = { data: rows, error: null }
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') return (resolve: (v: unknown) => void) => resolve(result)
|
||||
return () => new Proxy({}, handler)
|
||||
},
|
||||
}
|
||||
const client = { from: () => new Proxy({}, handler) } as unknown as Parameters<
|
||||
typeof sumPostedYearEndDispositions
|
||||
>[0]
|
||||
|
||||
const effect = await sumPostedYearEndDispositions(client, 'co', 'fp')
|
||||
expect(effect).toBe(-174_000) // -150k + 20k - 39k - 5k
|
||||
})
|
||||
|
||||
it('truncates taxable result to whole krona before applying tax', async () => {
|
||||
vi.mocked(generateIncomeStatement).mockResolvedValue({
|
||||
net_result: 100_999.99,
|
||||
|
||||
@@ -180,6 +180,31 @@ describe('buildDispositionsProposal — K3 framework', () => {
|
||||
expect(credit.credit_amount).toBe(20_600)
|
||||
})
|
||||
|
||||
it('computes bolagsskatt on the result AFTER the periodiseringsfond avsättning', async () => {
|
||||
// Regression (customer report): the preview computed bolagsskatt on the
|
||||
// pre-disposition net result, ignoring the avsättning it proposes in the
|
||||
// same snapshot — so the previewed/agent-facing tax was too high and
|
||||
// diverged from ÅR/INK2. With a 1,000,000 result and no existing fonder:
|
||||
// avsättning = 25 % × 1,000,000 = 250,000
|
||||
// skattem. res = 1,000,000 − 250,000 = 750,000
|
||||
// bolagsskatt = 20.6 % × 750,000 = 154,500 (NOT 206,000)
|
||||
vi.mocked(generateIncomeStatement).mockResolvedValue({
|
||||
net_result: 1_000_000,
|
||||
} as Awaited<ReturnType<typeof generateIncomeStatement>>)
|
||||
|
||||
const supabase = makeSupabase({ entityType: 'aktiebolag', accountingFramework: 'k2' })
|
||||
const result = await buildDispositionsProposal(
|
||||
supabase as unknown as Parameters<typeof buildDispositionsProposal>[0],
|
||||
'co',
|
||||
'fp1',
|
||||
)
|
||||
|
||||
const avsattning = result.proposals.find((p) => p.kind === 'periodiseringsfond_avsattning')
|
||||
const bolagsskatt = result.proposals.find((p) => p.kind === 'bolagsskatt')
|
||||
expect(avsattning?.amount).toBe(250_000)
|
||||
expect(bolagsskatt?.amount).toBe(154_500)
|
||||
})
|
||||
|
||||
it('does NOT add an uppskjuten_skatt proposal for K2 aktiebolag', async () => {
|
||||
const supabase = makeSupabase({ entityType: 'aktiebolag', accountingFramework: 'k2' })
|
||||
const result = await buildDispositionsProposal(
|
||||
|
||||
@@ -138,11 +138,42 @@ export async function getAsset(
|
||||
return (data as Asset | null) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when the caller tries to correct an asset's acquisition basis
|
||||
* (date / cost / category) after that basis has already driven postings —
|
||||
* i.e. the asset is disposed, or planenliga avskrivningar have been booked.
|
||||
* Allowing the edit would silently desync the posted vouchers from the
|
||||
* register, so the caller must reverse/storno first. The `code` field is
|
||||
* read by errorResponse() (see lib/errors/structured-errors.ts) to map this
|
||||
* to a 409.
|
||||
*/
|
||||
export class AssetCorrectionBlockedError extends Error {
|
||||
readonly code = 'ASSET_CORRECTION_BLOCKED'
|
||||
constructor(readonly reason: 'disposed' | 'depreciation_posted') {
|
||||
super(
|
||||
reason === 'disposed'
|
||||
? 'Cannot correct acquisition date/cost/category of a disposed asset — reverse the disposal first.'
|
||||
: 'Cannot correct acquisition date/cost/category after depreciation has been posted — reverse the depreciation (storno) first.',
|
||||
)
|
||||
this.name = 'AssetCorrectionBlockedError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface UpdateAssetInput {
|
||||
name?: string
|
||||
notes?: string | null
|
||||
/** "Correction" fields — they redefine the depreciation basis, so changing
|
||||
* them implies the original entry was wrong. Only permitted while the asset
|
||||
* is neither disposed nor depreciated (updateAsset() enforces; throws
|
||||
* AssetCorrectionBlockedError otherwise). Use the disposal/storno flow for a
|
||||
* real change to an already-depreciated asset. */
|
||||
category?: AssetCategory
|
||||
acquisition_date?: string
|
||||
acquisition_cost?: number
|
||||
/** Salvage value, useful life, method, accounts — editable as long as the
|
||||
* asset isn't disposed yet (DB trigger enforces this beyond the API). */
|
||||
* asset isn't disposed yet (DB trigger enforces this beyond the API).
|
||||
* Unlike the correction fields above, revising useful life or method is a
|
||||
* legitimate *prospective* change and stays allowed after depreciation. */
|
||||
salvage_value?: number
|
||||
useful_life_months?: number
|
||||
depreciation_method?: DepreciationMethod
|
||||
@@ -158,6 +189,85 @@ export interface UpdateAssetInput {
|
||||
k3_components?: K3Component[] | null
|
||||
}
|
||||
|
||||
/**
|
||||
* True when at least one depreciation_schedules row for this asset is linked
|
||||
* to a posted journal entry. A `head` count keeps it cheap — we only need
|
||||
* existence, not the rows. Used to gate acquisition-basis corrections.
|
||||
*/
|
||||
async function hasPostedDepreciation(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
assetId: string,
|
||||
): Promise<boolean> {
|
||||
const { count, error } = await supabase
|
||||
.from('depreciation_schedules')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.eq('asset_id', assetId)
|
||||
.not('journal_entry_id', 'is', null)
|
||||
if (error) {
|
||||
throw new Error(
|
||||
`Failed to check posted depreciation for asset ${assetId}: ${error.message}`,
|
||||
)
|
||||
}
|
||||
return (count ?? 0) > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Catch depreciation that was posted by hand (a manual avskrivningsverifikat),
|
||||
* which leaves no depreciation_schedules row and so slips past
|
||||
* hasPostedDepreciation. We look at the ledger instead: any posted CREDIT to
|
||||
* the asset's ackumulerade-avskrivningar account (12x9) is depreciation.
|
||||
*
|
||||
* The wrinkle is shared accounts — siblings in the same category default to
|
||||
* the same 12x9, so a sibling's *engine* avskrivning would otherwise look like
|
||||
* depreciation of this asset. We exclude entries that depreciation_schedules
|
||||
* attributes to a *different* asset, so engine siblings don't cause a false
|
||||
* block. What remains is depreciation tied to this asset (engine or manual)
|
||||
* plus the rare case of a manual sibling entry on a shared account — there we
|
||||
* err toward blocking, which is the safe direction for a basis correction.
|
||||
*/
|
||||
async function hasManualDepreciationPosted(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
asset: Asset,
|
||||
): Promise<boolean> {
|
||||
// Engine-posted depreciation entries that belong to OTHER assets — these are
|
||||
// safely attributable and must not block a correction of this asset.
|
||||
const { data: otherSched, error: schedError } = await supabase
|
||||
.from('depreciation_schedules')
|
||||
.select('journal_entry_id')
|
||||
.eq('company_id', companyId)
|
||||
.neq('asset_id', asset.id)
|
||||
.not('journal_entry_id', 'is', null)
|
||||
if (schedError) {
|
||||
throw new Error(
|
||||
`Failed to load sibling depreciation entries for asset ${asset.id}: ${schedError.message}`,
|
||||
)
|
||||
}
|
||||
const siblingEngineEntries = new Set(
|
||||
((otherSched ?? []) as { journal_entry_id: string | null }[])
|
||||
.map((r) => r.journal_entry_id)
|
||||
.filter((id): id is string => id !== null),
|
||||
)
|
||||
|
||||
const { data: lines, error } = await supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('journal_entry_id, journal_entries!inner(company_id, status)')
|
||||
.eq('account_number', asset.bas_accumulated_account)
|
||||
.eq('journal_entries.company_id', companyId)
|
||||
.eq('journal_entries.status', 'posted')
|
||||
.gt('credit_amount', 0)
|
||||
if (error) {
|
||||
throw new Error(
|
||||
`Failed to scan ledger depreciation for asset ${asset.id}: ${error.message}`,
|
||||
)
|
||||
}
|
||||
return ((lines ?? []) as { journal_entry_id: string }[]).some(
|
||||
(line) => !siblingEngineEntries.has(line.journal_entry_id),
|
||||
)
|
||||
}
|
||||
|
||||
export async function updateAsset(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
@@ -166,21 +276,85 @@ export async function updateAsset(
|
||||
): Promise<Asset> {
|
||||
// Copy so we can adjust restvarde_target without mutating the caller's object.
|
||||
let input: UpdateAssetInput = { ...inputParam }
|
||||
// Defense-in-depth: when callers remap BAS accounts, refuse anything
|
||||
// outside the legitimate range for the existing asset's category — keeps
|
||||
// INK2R mappings + the depreciation engine's category-driven defaults in
|
||||
// sync with what users actually pick.
|
||||
|
||||
// Almost every meaningful patch needs the current row (range checks, the
|
||||
// method/target biconditional, the correction guard). Load it once.
|
||||
const needsExisting =
|
||||
input.category !== undefined ||
|
||||
input.acquisition_date !== undefined ||
|
||||
input.acquisition_cost !== undefined ||
|
||||
input.depreciation_method !== undefined ||
|
||||
input.restvarde_target !== undefined ||
|
||||
input.bas_asset_account !== undefined ||
|
||||
input.bas_accumulated_account !== undefined ||
|
||||
input.bas_expense_account !== undefined
|
||||
let existing: Asset | null = null
|
||||
if (needsExisting) {
|
||||
existing = await getAsset(supabase, companyId, assetId)
|
||||
if (!existing) throw new Error('Asset not found')
|
||||
}
|
||||
|
||||
// ── Correction guard ──────────────────────────────────────────────
|
||||
// acquisition_date / acquisition_cost / category redefine the depreciation
|
||||
// basis. Correcting a fresh data-entry mistake is safe, but once the basis
|
||||
// has driven postings (disposal voucher or booked avskrivningar) the edit
|
||||
// would silently desync those vouchers from the register. Force those cases
|
||||
// through reverse/storno instead.
|
||||
const isCorrection =
|
||||
input.category !== undefined ||
|
||||
input.acquisition_date !== undefined ||
|
||||
input.acquisition_cost !== undefined
|
||||
if (isCorrection && existing) {
|
||||
if (existing.disposed_at) {
|
||||
throw new AssetCorrectionBlockedError('disposed')
|
||||
}
|
||||
// Engine-driven (depreciation_schedules) OR hand-posted (ledger) — either
|
||||
// means the basis has driven postings and a correction must go via storno.
|
||||
if (
|
||||
(await hasPostedDepreciation(supabase, companyId, assetId)) ||
|
||||
(await hasManualDepreciationPosted(supabase, companyId, existing))
|
||||
) {
|
||||
throw new AssetCorrectionBlockedError('depreciation_posted')
|
||||
}
|
||||
}
|
||||
|
||||
// ── Category change → realign BAS accounts ────────────────────────
|
||||
// The BAS triple is category-scoped (INK2R mapping + engine defaults depend
|
||||
// on it). When the category changes and the caller didn't supply explicit
|
||||
// accounts, reset the triple to the new category's defaults so the chart
|
||||
// stays aligned — mirrors createAsset()'s defaulting.
|
||||
if (
|
||||
input.category !== undefined &&
|
||||
existing &&
|
||||
input.category !== existing.category &&
|
||||
input.bas_asset_account === undefined &&
|
||||
input.bas_accumulated_account === undefined &&
|
||||
input.bas_expense_account === undefined
|
||||
) {
|
||||
const defaults = DEFAULT_ACCOUNTS_BY_CATEGORY[input.category]
|
||||
input = {
|
||||
...input,
|
||||
bas_asset_account: defaults.asset,
|
||||
bas_accumulated_account: defaults.accumulated,
|
||||
bas_expense_account: defaults.expense,
|
||||
}
|
||||
}
|
||||
|
||||
// ── BAS account range validation ──────────────────────────────────
|
||||
// Defense-in-depth: refuse anything outside the legitimate range for the
|
||||
// asset's (possibly newly-changed) category. Validates against the final
|
||||
// category so a category+account change is checked as a unit.
|
||||
if (
|
||||
input.bas_asset_account ||
|
||||
input.bas_accumulated_account ||
|
||||
input.bas_expense_account
|
||||
) {
|
||||
const existing = await getAsset(supabase, companyId, assetId)
|
||||
if (!existing) throw new Error('Asset not found')
|
||||
const ranges = BAS_RANGES_BY_CATEGORY[existing.category]
|
||||
const finalCategory = input.category ?? existing.category
|
||||
const ranges = BAS_RANGES_BY_CATEGORY[finalCategory]
|
||||
if (input.bas_asset_account && !inBasRange(input.bas_asset_account, ranges.asset)) {
|
||||
throw new Error(
|
||||
`bas_asset_account ${input.bas_asset_account} is outside ${ranges.asset[0]}–${ranges.asset[1]} for ${existing.category}`,
|
||||
`bas_asset_account ${input.bas_asset_account} is outside ${ranges.asset[0]}–${ranges.asset[1]} for ${finalCategory}`,
|
||||
)
|
||||
}
|
||||
if (
|
||||
@@ -188,7 +362,7 @@ export async function updateAsset(
|
||||
!inBasRange(input.bas_accumulated_account, ranges.accumulated)
|
||||
) {
|
||||
throw new Error(
|
||||
`bas_accumulated_account ${input.bas_accumulated_account} is outside ${ranges.accumulated[0]}–${ranges.accumulated[1]} for ${existing.category}`,
|
||||
`bas_accumulated_account ${input.bas_accumulated_account} is outside ${ranges.accumulated[0]}–${ranges.accumulated[1]} for ${finalCategory}`,
|
||||
)
|
||||
}
|
||||
if (
|
||||
@@ -196,7 +370,7 @@ export async function updateAsset(
|
||||
!inBasRange(input.bas_expense_account, ranges.expense)
|
||||
) {
|
||||
throw new Error(
|
||||
`bas_expense_account ${input.bas_expense_account} is outside ${ranges.expense[0]}–${ranges.expense[1]} for ${existing.category}`,
|
||||
`bas_expense_account ${input.bas_expense_account} is outside ${ranges.expense[0]}–${ranges.expense[1]} for ${finalCategory}`,
|
||||
)
|
||||
}
|
||||
// Anskaffning and ackumulerade-avskrivningar must be different accounts —
|
||||
@@ -210,15 +384,22 @@ export async function updateAsset(
|
||||
}
|
||||
}
|
||||
|
||||
// Method / restvärde-target biconditional: required iff restvärdeavskrivning.
|
||||
// Resolve final method+target across the merged row (existing + patch) so we
|
||||
// can null the target when switching away and require it when switching in.
|
||||
if (input.depreciation_method !== undefined || input.restvarde_target !== undefined) {
|
||||
const existing = await getAsset(supabase, companyId, assetId)
|
||||
// ── Method / restvärde-target biconditional ───────────────────────
|
||||
// Required iff restvärdeavskrivning. Resolve final method+target+cost across
|
||||
// the merged row (existing + patch) so we can null the target when switching
|
||||
// away, require it when switching in, and re-check the floor when the cost
|
||||
// itself is being corrected.
|
||||
if (
|
||||
input.depreciation_method !== undefined ||
|
||||
input.restvarde_target !== undefined ||
|
||||
input.acquisition_cost !== undefined
|
||||
) {
|
||||
if (!existing) throw new Error('Asset not found')
|
||||
const finalMethod = input.depreciation_method ?? existing.depreciation_method
|
||||
const finalTarget =
|
||||
input.restvarde_target !== undefined ? input.restvarde_target : existing.restvarde_target
|
||||
const finalCost =
|
||||
input.acquisition_cost !== undefined ? input.acquisition_cost : Number(existing.acquisition_cost)
|
||||
if (finalMethod === 'restvardesavskrivning_25' && (finalTarget === null || finalTarget === undefined)) {
|
||||
throw new Error(
|
||||
'restvarde_target krävs när avskrivningsmetoden är restvärdeavskrivning (25 %).',
|
||||
@@ -233,7 +414,7 @@ export async function updateAsset(
|
||||
finalMethod === 'restvardesavskrivning_25' &&
|
||||
finalTarget !== null &&
|
||||
finalTarget !== undefined &&
|
||||
Number(finalTarget) >= Number(existing.acquisition_cost)
|
||||
Number(finalTarget) >= Number(finalCost)
|
||||
) {
|
||||
throw new Error(
|
||||
'restvarde_target måste vara lägre än anskaffningsvärdet — annars finns inget kvar att skriva av.',
|
||||
|
||||
@@ -103,7 +103,21 @@ export async function buildDispositionsProposal(
|
||||
const slp = await calculateSarskildLoneskatt(supabase, companyId, fiscalPeriodId)
|
||||
if (slp) proposals.push(slp)
|
||||
|
||||
// Bolagsskatt must be computed on the result AFTER the dispositions above.
|
||||
// In preview mode nothing is posted yet, so the income statement still shows
|
||||
// the pre-disposition result — we mirror each proposal's effect on resultat
|
||||
// före skatt and hand the post-disposition base to the calculator:
|
||||
// + återföring (8819, intäkt)
|
||||
// − avsättning (8811, kostnad)
|
||||
// − SLP (7533, kostnad)
|
||||
// Without this, the previewed tax ignores the avsättning (tax too high) and
|
||||
// diverges from what the sequential commit books and from ÅR/INK2.
|
||||
const ateforingTotal = ateforing.proposals.reduce((sum, p) => sum + p.amount, 0)
|
||||
const resultAfterDispositions =
|
||||
resultBeforeTax + ateforingTotal - (avsattning?.amount ?? 0) - (slp?.amount ?? 0)
|
||||
|
||||
const bolagsskatt = await calculateBolagsskatt(supabase, companyId, fiscalPeriodId, {
|
||||
resultBeforeTaxOverride: resultAfterDispositions,
|
||||
manualAdjustments: {
|
||||
schablonintaktPeriodiseringsfond: ateforing.schablonintaktAmount,
|
||||
},
|
||||
|
||||
@@ -6,6 +6,16 @@ import type { ProposedDisposition } from '../types'
|
||||
export const BOLAGSSKATT_RATE = 0.206
|
||||
|
||||
export interface BolagsskattInput {
|
||||
/** Result before tax to use as the base, OVERRIDING the income-statement
|
||||
* net_result. The dispositions builder passes this in *preview* mode: there,
|
||||
* the proposed bokslutsdispositioner (periodiseringsfond avsättning/
|
||||
* återföring, SLP) are not posted yet, so the income statement still shows
|
||||
* the *pre-disposition* result. The builder computes the post-disposition
|
||||
* result itself and passes it here so the previewed tax matches what the
|
||||
* sequential commit will actually book. When omitted, the calculator reads
|
||||
* incomeStatement.net_result — correct only once the dispositions are already
|
||||
* posted (the POST commit path, where bolagsskatt is computed last). */
|
||||
resultBeforeTaxOverride?: number
|
||||
/** Manual adjustments to taxable result that the calculator can't derive.
|
||||
* Each is a SEK amount that ADDS to taxable result (so e.g. non-deductible
|
||||
* representation costs are positive; non-taxable dividend income is negative). */
|
||||
@@ -38,6 +48,51 @@ export interface BolagsskattComputation {
|
||||
taxAmount: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Sum the P&L effect of bokslutsdispositioner already posted in this period.
|
||||
*
|
||||
* Dispositioner (periodiseringsfond avsättning/återföring, SLP, över-
|
||||
* avskrivningar) are booked with source_type='year_end', which
|
||||
* generateIncomeStatement EXCLUDES — so net_result alone overstates resultat
|
||||
* före skatt. The tax base must add them back. We sum class 88
|
||||
* (bokslutsdispositioner) plus 7533 (SLP); tax (89xx) and the closing entry
|
||||
* (8999/2099) are intentionally left out.
|
||||
*
|
||||
* Returns a signed SEK amount: avsättning (8811 debit) lowers it, återföring
|
||||
* (8819 credit) raises it. Used by the commit path, where bolagsskatt is
|
||||
* computed AFTER the other dispositions are posted.
|
||||
*/
|
||||
export async function sumPostedYearEndDispositions(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
fiscalPeriodId: string,
|
||||
): Promise<number> {
|
||||
const { data, error } = await supabase
|
||||
.from('journal_entry_lines')
|
||||
.select(
|
||||
'account_number, debit_amount, credit_amount, journal_entries!inner(company_id, fiscal_period_id, status, source_type)',
|
||||
)
|
||||
.eq('journal_entries.company_id', companyId)
|
||||
.eq('journal_entries.fiscal_period_id', fiscalPeriodId)
|
||||
.eq('journal_entries.status', 'posted')
|
||||
.eq('journal_entries.source_type', 'year_end')
|
||||
if (error) {
|
||||
throw new Error(`Failed to read posted dispositions: ${error.message}`)
|
||||
}
|
||||
type Row = {
|
||||
account_number: string
|
||||
debit_amount: number | string | null
|
||||
credit_amount: number | string | null
|
||||
}
|
||||
let effect = 0
|
||||
for (const row of (data ?? []) as Row[]) {
|
||||
const acc = row.account_number
|
||||
if (!(acc.startsWith('88') || acc === '7533')) continue
|
||||
effect += (Number(row.credit_amount) || 0) - (Number(row.debit_amount) || 0)
|
||||
}
|
||||
return Math.round(effect * 100) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute bolagsskatt 20.6 % on the company's taxable result.
|
||||
*
|
||||
@@ -56,8 +111,12 @@ export async function calculateBolagsskatt(
|
||||
fiscalPeriodId: string,
|
||||
input: BolagsskattInput = {},
|
||||
): Promise<ProposedDisposition | null> {
|
||||
const incomeStatement = await generateIncomeStatement(supabase, companyId, fiscalPeriodId)
|
||||
const resultBeforeTax = incomeStatement.net_result
|
||||
// Prefer an explicit base when the caller already knows the post-disposition
|
||||
// result (preview mode). Only hit the income statement when no override is
|
||||
// given — that path is correct once the dispositions are posted (commit).
|
||||
const resultBeforeTax =
|
||||
input.resultBeforeTaxOverride ??
|
||||
(await generateIncomeStatement(supabase, companyId, fiscalPeriodId)).net_result
|
||||
|
||||
const adjustments = input.manualAdjustments ?? {}
|
||||
const nonDeductibleExpenses = adjustments.nonDeductibleExpenses ?? 0
|
||||
|
||||
@@ -285,6 +285,20 @@ const BOOKKEEPING: Record<string, StructuredErrorEntry> = {
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const TRANSACTIONS: Record<string, StructuredErrorEntry> = {
|
||||
TRANSACTION_BOOK_POSSIBLE_DUPLICATE: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'En annan transaktion på samma datum och belopp är redan bokförd. Det här ser ut som en dubblett — bokför inte samma affärshändelse två gånger. Granska den befintliga verifikationen, eller bokför ändå om transaktionerna inte hör ihop.',
|
||||
message_en:
|
||||
'Another transaction with the same date and amount is already booked. This looks like a duplicate — do not book the same business event twice. Review the existing voucher, or pass force=true to book it anyway if they are genuinely unrelated.',
|
||||
},
|
||||
TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Den möjliga dubbletten som visades matchar inte längre. Ladda om och försök igen så att rätt transaktion visas.',
|
||||
message_en:
|
||||
'The duplicate transaction echoed in expected_duplicate_transaction_id no longer matches the one detected at request time. Re-run the booking pre-flight to obtain the current candidate, then retry.',
|
||||
},
|
||||
TX_CATEGORIZE_TX_NOT_FOUND: {
|
||||
httpStatus: 404,
|
||||
message_sv: 'Transaktionen kunde inte hittas.',
|
||||
@@ -2391,6 +2405,16 @@ const BOLAGSVERKET: Record<string, StructuredErrorEntry> = {
|
||||
},
|
||||
}
|
||||
|
||||
const ASSETS: Record<string, StructuredErrorEntry> = {
|
||||
ASSET_CORRECTION_BLOCKED: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Anskaffningsdatum, anskaffningsvärde och kategori kan inte ändras efter att tillgången avyttrats eller avskrivningar bokförts. Återför (storno) först, eller använd avyttringsflödet.',
|
||||
message_en:
|
||||
'Acquisition date, cost and category cannot be changed once the asset has been disposed or depreciation has been posted. Reverse (storno) first, or use the disposal flow.',
|
||||
},
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
// Combined registry
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
@@ -2433,6 +2457,7 @@ const REGISTRY: Record<string, StructuredErrorEntry> = {
|
||||
...PROVIDER,
|
||||
...SKATTEVERKET,
|
||||
...BOLAGSVERKET,
|
||||
...ASSETS,
|
||||
}
|
||||
|
||||
export function getErrorEntry(code: string): StructuredErrorEntry | undefined {
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase, makeCustomer } from '@/tests/helpers'
|
||||
import { buildInvoiceWriteData, type InvoiceWriteInput } from '@/lib/invoices/build-invoice-write'
|
||||
import type { Customer, InvoiceDocumentType } from '@/types'
|
||||
|
||||
// Uses the REAL getVatRules / rot-rut-rules / personnummer helpers (only the
|
||||
// supabase lookups are mocked) so the test exercises the same computation the
|
||||
// POST and PATCH routes rely on.
|
||||
function call(
|
||||
enqueue: ReturnType<typeof createQueuedMockSupabase>['enqueue'],
|
||||
supabase: SupabaseClient,
|
||||
customer: Customer,
|
||||
input: InvoiceWriteInput,
|
||||
documentType: InvoiceDocumentType = 'invoice',
|
||||
) {
|
||||
return buildInvoiceWriteData({ supabase, companyId: 'company-1', customer, documentType, input })
|
||||
}
|
||||
|
||||
const baseHeader = {
|
||||
customer_id: 'customer-1',
|
||||
invoice_date: '2026-06-15',
|
||||
due_date: '2026-07-15',
|
||||
currency: 'SEK' as const,
|
||||
}
|
||||
|
||||
describe('buildInvoiceWriteData', () => {
|
||||
it('computes totals + item rows for a domestic 25% invoice and omits number/status', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { vat_registered: true }, error: null }) // company_settings.vat_registered
|
||||
|
||||
const customer = makeCustomer({ customer_type: 'swedish_business' })
|
||||
const result = await call(enqueue, supabase as unknown as SupabaseClient, customer, {
|
||||
...baseHeader,
|
||||
items: [{ description: 'Konsult', quantity: 10, unit: 'tim', unit_price: 1000, vat_rate: 25 }],
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.invoiceFields.subtotal).toBe(10000)
|
||||
expect(result.invoiceFields.vat_amount).toBe(2500)
|
||||
expect(result.invoiceFields.total).toBe(12500)
|
||||
expect(result.invoiceFields.remaining_amount).toBe(12500)
|
||||
expect(result.invoiceFields.vat_rate).toBe(25)
|
||||
// The route owns these — the builder must never set them.
|
||||
expect(result.invoiceFields).not.toHaveProperty('invoice_number')
|
||||
expect(result.invoiceFields).not.toHaveProperty('status')
|
||||
expect(result.invoiceFields).not.toHaveProperty('user_id')
|
||||
// Item row carries no invoice_id — the route adds it.
|
||||
expect(result.items).toHaveLength(1)
|
||||
expect(result.items[0]).not.toHaveProperty('invoice_id')
|
||||
expect(result.items[0]).toMatchObject({
|
||||
sort_order: 0,
|
||||
line_type: 'product',
|
||||
line_total: 10000,
|
||||
vat_rate: 25,
|
||||
vat_amount: 2500,
|
||||
})
|
||||
})
|
||||
|
||||
it('handles a mixed-rate invoice (vat_rate becomes null on the header)', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { vat_registered: true }, error: null })
|
||||
|
||||
const customer = makeCustomer({ customer_type: 'swedish_business' })
|
||||
const result = await call(enqueue, supabase as unknown as SupabaseClient, customer, {
|
||||
...baseHeader,
|
||||
items: [
|
||||
{ description: 'Tjänst', quantity: 1, unit: 'st', unit_price: 1000, vat_rate: 25 },
|
||||
{ description: 'Bok', quantity: 1, unit: 'st', unit_price: 1000, vat_rate: 6 },
|
||||
],
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.invoiceFields.vat_rate).toBeNull()
|
||||
expect(result.invoiceFields.vat_amount).toBe(250 + 60)
|
||||
})
|
||||
|
||||
it('zeroes VAT when the company is not VAT-registered', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { vat_registered: false }, error: null })
|
||||
|
||||
const customer = makeCustomer({ customer_type: 'swedish_business' })
|
||||
const result = await call(enqueue, supabase as unknown as SupabaseClient, customer, {
|
||||
...baseHeader,
|
||||
items: [{ description: 'Konsult', quantity: 1, unit: 'tim', unit_price: 1000, vat_rate: 25 }],
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.invoiceFields.vat_amount).toBe(0)
|
||||
expect(result.invoiceFields.total).toBe(1000)
|
||||
expect(result.invoiceFields.vat_treatment).toBe('exempt')
|
||||
expect(result.items[0].vat_rate).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a VAT rate not allowed for the customer type', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { vat_registered: true }, error: null })
|
||||
|
||||
// EU business with a validated VAT number → reverse charge, only 0% allowed.
|
||||
const customer = makeCustomer({ customer_type: 'eu_business', vat_number_validated: true })
|
||||
const result = await call(enqueue, supabase as unknown as SupabaseClient, customer, {
|
||||
...baseHeader,
|
||||
items: [{ description: 'Konsult', quantity: 1, unit: 'tim', unit_price: 1000, vat_rate: 25 }],
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) return
|
||||
expect('code' in result && result.code).toBe('INVOICE_CREATE_VAT_RULE_VIOLATION')
|
||||
})
|
||||
|
||||
it('excludes free-text rows from totals', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { vat_registered: true }, error: null })
|
||||
|
||||
const customer = makeCustomer({ customer_type: 'swedish_business' })
|
||||
const result = await call(enqueue, supabase as unknown as SupabaseClient, customer, {
|
||||
...baseHeader,
|
||||
items: [
|
||||
{ description: 'Rubrik', quantity: 0, unit: '', unit_price: 0, vat_rate: 0, line_type: 'text' },
|
||||
{ description: 'Konsult', quantity: 2, unit: 'tim', unit_price: 500, vat_rate: 25 },
|
||||
],
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.invoiceFields.subtotal).toBe(1000)
|
||||
expect(result.invoiceFields.vat_amount).toBe(250)
|
||||
expect(result.items[0]).toMatchObject({ line_type: 'text', line_total: 0, vat_amount: 0 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
|
||||
|
||||
describe('isEditableInvoiceDraft', () => {
|
||||
it('allows a plain draft with no committed verifikat', () => {
|
||||
expect(
|
||||
isEditableInvoiceDraft({ status: 'draft', journal_entry_id: null, is_self_billed: false }),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('allows a draft when the optional fields are absent', () => {
|
||||
expect(isEditableInvoiceDraft({ status: 'draft' })).toBe(true)
|
||||
})
|
||||
|
||||
it('blocks any non-draft status', () => {
|
||||
for (const status of ['sent', 'paid', 'cancelled', 'credited', 'overdue']) {
|
||||
expect(isEditableInvoiceDraft({ status })).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('blocks a draft that somehow already carries a committed verifikat', () => {
|
||||
expect(
|
||||
isEditableInvoiceDraft({ status: 'draft', journal_entry_id: 'je-1', is_self_billed: false }),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('blocks a received self-billed document', () => {
|
||||
expect(
|
||||
isEditableInvoiceDraft({ status: 'draft', journal_entry_id: null, is_self_billed: true }),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -44,4 +44,28 @@ describe('getDisplayTotal', () => {
|
||||
expect(r.applies).toBe(true)
|
||||
expect(r.displayed).toBe(100)
|
||||
})
|
||||
|
||||
it('per-invoice flag (true) wins over a disabled company setting', () => {
|
||||
const r = getDisplayTotal({ total: 99.99, currency: 'SEK', ore_rounding: true }, co(false))
|
||||
expect(r.applies).toBe(true)
|
||||
expect(r.displayed).toBe(100)
|
||||
})
|
||||
|
||||
it('per-invoice flag (false) wins over an enabled company setting', () => {
|
||||
const r = getDisplayTotal({ total: 99.99, currency: 'SEK', ore_rounding: false }, co(true))
|
||||
expect(r.applies).toBe(false)
|
||||
expect(r.displayed).toBe(99.99)
|
||||
})
|
||||
|
||||
it('null per-invoice flag falls back to the company setting', () => {
|
||||
const r = getDisplayTotal({ total: 99.99, currency: 'SEK', ore_rounding: null }, co(true))
|
||||
expect(r.applies).toBe(true)
|
||||
expect(r.displayed).toBe(100)
|
||||
})
|
||||
|
||||
it('null per-invoice flag with company-off resolves to off (supplier-invoice convention)', () => {
|
||||
const r = getDisplayTotal({ total: 99.99, currency: 'SEK', ore_rounding: null }, co(false))
|
||||
expect(r.applies).toBe(false)
|
||||
expect(r.displayed).toBe(99.99)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { Currency, Customer, InvoiceDocumentType } from '@/types'
|
||||
import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
|
||||
import { DEFAULT_DEFERRED_REVENUE_ACCOUNT } from '@/lib/bookkeeping/accruals/account-suggestions'
|
||||
import {
|
||||
computeDeduction,
|
||||
computeInvoiceDeductionTotal,
|
||||
validateInvoice as validateRotRut,
|
||||
} from '@/lib/invoices/rot-rut-rules'
|
||||
import {
|
||||
encryptPersonnummer,
|
||||
extractLast4,
|
||||
validatePersonnummer,
|
||||
} from '@/lib/salary/personnummer'
|
||||
|
||||
/**
|
||||
* Shared invoice write-builder.
|
||||
*
|
||||
* Encapsulates the validation + computation that is IDENTICAL whether an
|
||||
* invoice (or proforma / delivery note) is being created (POST /api/invoices)
|
||||
* or a draft is being edited in place (PATCH /api/invoices/[id]):
|
||||
*
|
||||
* - per-customer VAT rule gating (allowed rates) + not-VAT-registered zeroing
|
||||
* - periodisering (accrual) guards
|
||||
* - subtotal / per-rate VAT / total
|
||||
* - per-line revenue-account override validation against chart_of_accounts
|
||||
* - server-side ROT/RUT compute + personnummer encryption (never trust client)
|
||||
* - mixed-rate detection, currency → SEK conversion
|
||||
* - the invoice_items row mapping
|
||||
*
|
||||
* It intentionally does NOT allocate an invoice number or emit events — those
|
||||
* differ between create and update and stay in the route handlers. The returned
|
||||
* `invoiceFields` exclude `user_id`, `company_id`, `invoice_number` and `status`;
|
||||
* the caller merges those. Returned `items` carry no `invoice_id` — the caller
|
||||
* adds it once the invoice row id is known.
|
||||
*/
|
||||
|
||||
// The validated line shape (a superset of what create/update schemas produce).
|
||||
export interface InvoiceWriteItemInput {
|
||||
line_type?: 'product' | 'text'
|
||||
description: string
|
||||
quantity: number
|
||||
unit: string
|
||||
unit_price: number
|
||||
vat_rate?: number
|
||||
article_id?: string | null
|
||||
revenue_account?: string | null
|
||||
deduction_type?: 'rot' | 'rut' | null
|
||||
labor_hours?: number | null
|
||||
work_type?: string | null
|
||||
housing_designation?: string | null
|
||||
apartment_number?: string | null
|
||||
accrual_period_start?: string | null
|
||||
accrual_period_end?: string | null
|
||||
accrual_balance_account?: string | null
|
||||
}
|
||||
|
||||
export interface InvoiceWriteInput {
|
||||
customer_id: string
|
||||
invoice_date: string
|
||||
due_date: string
|
||||
delivery_date?: string | null
|
||||
currency: Currency
|
||||
your_reference?: string
|
||||
our_reference?: string
|
||||
notes?: string
|
||||
/** Per-invoice öresavrundning override (display-only). Omitted → null (inherit company setting). */
|
||||
ore_rounding?: boolean
|
||||
deduction_personnummer?: string
|
||||
deduction_housing_designation?: string
|
||||
items: InvoiceWriteItemInput[]
|
||||
}
|
||||
|
||||
// The computed invoice-row fields shared by create and update. Deliberately
|
||||
// untyped-strict (Record) so it slots straight into a Supabase insert/update;
|
||||
// every value is computed here from validated input.
|
||||
export type InvoiceWriteFields = {
|
||||
customer_id: string
|
||||
invoice_date: string
|
||||
due_date: string
|
||||
delivery_date: string | null
|
||||
currency: Currency
|
||||
exchange_rate: number | null
|
||||
exchange_rate_date: string | null
|
||||
subtotal: number
|
||||
subtotal_sek: number | null
|
||||
vat_amount: number
|
||||
vat_amount_sek: number | null
|
||||
total: number
|
||||
total_sek: number | null
|
||||
remaining_amount: number
|
||||
vat_treatment: string
|
||||
vat_rate: number | null
|
||||
moms_ruta: string | null
|
||||
reverse_charge_text: string | null
|
||||
your_reference: string | null | undefined
|
||||
our_reference: string | null | undefined
|
||||
notes: string | null | undefined
|
||||
ore_rounding: boolean | null
|
||||
document_type: InvoiceDocumentType
|
||||
deduction_total: number
|
||||
deduction_personnummer_encrypted: string | null
|
||||
deduction_personnummer_last4: string | null
|
||||
}
|
||||
|
||||
export type InvoiceWriteItemRow = {
|
||||
sort_order: number
|
||||
line_type: 'product' | 'text'
|
||||
description: string
|
||||
quantity: number
|
||||
unit: string
|
||||
unit_price: number
|
||||
line_total: number
|
||||
vat_rate: number
|
||||
vat_amount: number
|
||||
article_id: string | null
|
||||
revenue_account: string | null
|
||||
deduction_type: 'rot' | 'rut' | null
|
||||
deduction_amount: number
|
||||
labor_hours: number | null
|
||||
work_type: string | null
|
||||
housing_designation: string | null
|
||||
apartment_number: string | null
|
||||
accrual_period_start: string | null
|
||||
accrual_period_end: string | null
|
||||
accrual_balance_account: string | null
|
||||
}
|
||||
|
||||
export type BuildInvoiceWriteResult =
|
||||
| { ok: true; invoiceFields: InvoiceWriteFields; items: InvoiceWriteItemRow[] }
|
||||
// Domain validation failure — map via errorResponseFromCode(code, { details }).
|
||||
| { ok: false; code: string; details?: Record<string, unknown> }
|
||||
// Unexpected DB error from an internal lookup — map via errorResponse(dbError).
|
||||
| { ok: false; dbError: unknown }
|
||||
|
||||
export async function buildInvoiceWriteData(params: {
|
||||
supabase: SupabaseClient
|
||||
companyId: string
|
||||
customer: Customer
|
||||
documentType: InvoiceDocumentType
|
||||
input: InvoiceWriteInput
|
||||
}): Promise<BuildInvoiceWriteResult> {
|
||||
const { supabase, companyId, customer, documentType, input } = params
|
||||
const items = input.items
|
||||
|
||||
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.
|
||||
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 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 = items.some(
|
||||
(item) => item.accrual_period_start && item.accrual_period_end,
|
||||
)
|
||||
if (hasAccrualItems) {
|
||||
if (documentType !== 'invoice') {
|
||||
return { ok: false, code: 'INVOICE_CREATE_ACCRUAL_INVALID', details: { reason: 'document_type', documentType } }
|
||||
}
|
||||
if (vatRules.treatment === 'reverse_charge' || vatRules.treatment === 'export') {
|
||||
return { ok: false, code: 'INVOICE_CREATE_ACCRUAL_INVALID', 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 { ok: false, code: 'INVOICE_CREATE_ACCRUAL_INVALID', details: { reason: 'accounting_method' } }
|
||||
}
|
||||
}
|
||||
|
||||
// Free-text rows carry no amounts and are excluded from totals + VAT.
|
||||
const subtotal = 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 items) {
|
||||
if (item.line_type === 'text') continue
|
||||
const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate
|
||||
if (!allowedRates.has(itemRate)) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'INVOICE_CREATE_VAT_RULE_VIOLATION',
|
||||
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.
|
||||
const overrideAccounts = Array.from(
|
||||
new Set(
|
||||
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) {
|
||||
return { ok: false, dbError: accountsError }
|
||||
}
|
||||
const validSet = new Set((validAccounts ?? []).map((a) => a.account_number))
|
||||
const invalid = overrideAccounts.filter((a) => !validSet.has(a))
|
||||
if (invalid.length > 0) {
|
||||
return { ok: false, code: 'INVOICE_CREATE_REVENUE_ACCOUNT_INVALID', 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 = !!input.deduction_housing_designation?.trim()
|
||||
const personnummerRaw = input.deduction_personnummer?.trim() || ''
|
||||
const personnummerProvided = personnummerRaw.length > 0
|
||||
|
||||
const validateInput = 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 {
|
||||
ok: false,
|
||||
code: 'INVOICE_CREATE_ROT_RUT_VALIDATION',
|
||||
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 { ok: false, code: 'INVOICE_CREATE_ROT_RUT_PERSONNUMMER_INVALID', details: { error: pnValid.error } }
|
||||
}
|
||||
deductionPersonnummerEncrypted = encryptPersonnummer(personnummerRaw)
|
||||
deductionPersonnummerLast4 = extractLast4(personnummerRaw)
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueRates = new Set(
|
||||
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 (input.currency !== 'SEK') {
|
||||
const rateData = await fetchExchangeRate(input.currency)
|
||||
if (rateData) {
|
||||
exchangeRate = rateData.rate
|
||||
exchangeRateDate = rateData.date
|
||||
subtotalSek = convertToSEK(subtotal, exchangeRate)
|
||||
vatAmountSek = convertToSEK(vatAmount, exchangeRate)
|
||||
totalSek = convertToSEK(total, exchangeRate)
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceFields: InvoiceWriteFields = {
|
||||
customer_id: input.customer_id,
|
||||
invoice_date: input.invoice_date,
|
||||
due_date: input.due_date,
|
||||
delivery_date: input.delivery_date ?? null,
|
||||
currency: input.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,
|
||||
// remaining_amount = total - deduction for real invoices so open-invoice
|
||||
// queries treat them as fully unpaid for the CUSTOMER's share — the
|
||||
// Skatteverket portion is on 1513 and clears when the agency pays out.
|
||||
// Proformas / delivery notes have no payment obligation → keep 0.
|
||||
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: input.your_reference,
|
||||
our_reference: input.our_reference,
|
||||
notes: input.notes,
|
||||
// Display-only öresavrundning override; null inherits company_settings.ore_rounding.
|
||||
ore_rounding: input.ore_rounding ?? null,
|
||||
document_type: documentType,
|
||||
deduction_total: deductionTotal,
|
||||
deduction_personnummer_encrypted: deductionPersonnummerEncrypted,
|
||||
deduction_personnummer_last4: deductionPersonnummerLast4,
|
||||
}
|
||||
|
||||
const itemRows: InvoiceWriteItemRow[] = items.map((item, index) => {
|
||||
// Free-text / blank rows carry no amounts and never book — store the
|
||||
// description only and zero everything else. Keys must match the product
|
||||
// branch exactly so a bulk insert isn't rejected for differing key sets.
|
||||
if (item.line_type === 'text') {
|
||||
return {
|
||||
sort_order: index,
|
||||
line_type: 'text',
|
||||
description: item.description ?? '',
|
||||
quantity: 0,
|
||||
unit: '',
|
||||
unit_price: 0,
|
||||
line_total: 0,
|
||||
vat_rate: 0,
|
||||
vat_amount: 0,
|
||||
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.
|
||||
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 {
|
||||
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 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,
|
||||
}
|
||||
})
|
||||
|
||||
return { ok: true, invoiceFields, items: itemRows }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* A draft invoice (or proforma / delivery note) is editable in place — header
|
||||
* fields AND line items — only while it has no committed verifikat. A journal
|
||||
* entry is created when the invoice is sent (mark-sent / send) or, for
|
||||
* kontantmetoden, at payment; once one exists, BFL immutability applies and the
|
||||
* invoice must be corrected with a credit note instead. A self-billed invoice we
|
||||
* received is the counterparty's document — never editable here.
|
||||
*
|
||||
* This is the single source of truth for that predicate. The PATCH route
|
||||
* (app/api/invoices/[id]/route.ts) enforces it server-side; the detail and edit
|
||||
* pages call it only to avoid opening a dead form — they are UX hints, not the
|
||||
* trust boundary. Keeping all three on one function stops the rule from drifting.
|
||||
*/
|
||||
export function isEditableInvoiceDraft(invoice: {
|
||||
status: string
|
||||
journal_entry_id?: string | null
|
||||
is_self_billed?: boolean | null
|
||||
}): boolean {
|
||||
return invoice.status === 'draft' && !invoice.journal_entry_id && !invoice.is_self_billed
|
||||
}
|
||||
@@ -1,6 +1,16 @@
|
||||
import type { Invoice, CompanySettings } from '@/types'
|
||||
|
||||
type InvoiceTotalShape = Pick<Invoice, 'total' | 'currency'>
|
||||
/**
|
||||
* Shape accepted by getDisplayTotal. `currency` is widened to `string` so the
|
||||
* helper works for both customer (`Invoice`) and supplier (`SupplierInvoice`)
|
||||
* rows. `ore_rounding` is the optional per-invoice override (see below).
|
||||
*/
|
||||
type InvoiceTotalShape = {
|
||||
total: Invoice['total']
|
||||
currency: string
|
||||
/** Per-invoice öresavrundning override. Wins over the company setting when set. */
|
||||
ore_rounding?: boolean | null
|
||||
}
|
||||
type CompanyRoundingShape = Pick<CompanySettings, 'ore_rounding'>
|
||||
|
||||
export interface DisplayTotal {
|
||||
@@ -8,22 +18,30 @@ export interface DisplayTotal {
|
||||
displayed: number
|
||||
/** displayed - raw total. Zero when rounding does not apply or the total is already an integer. */
|
||||
roundingDelta: number
|
||||
/** True when both the company setting is on, currency is SEK, and there are öre to round. */
|
||||
/** True when rounding is enabled, currency is SEK, and there are öre to round. */
|
||||
applies: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Single source of truth for öresavrundning display logic. Mirrors the rule
|
||||
* baked into the PDF template since day one: only SEK invoices, only when
|
||||
* the company has the setting enabled, and only when there's actually a
|
||||
* non-integer total to round. The helper centralizes the rule so the list,
|
||||
* detail page, and PDF cannot drift apart.
|
||||
* rounding is enabled, and only when there's actually a non-integer total to
|
||||
* round. The helper centralizes the rule so the list, detail page, and PDF
|
||||
* cannot drift apart.
|
||||
*
|
||||
* Resolution order for "is rounding enabled":
|
||||
* 1. the per-invoice override (`invoice.ore_rounding`) when not null,
|
||||
* 2. else the company-wide setting (`company.ore_rounding`),
|
||||
* 3. else default-on.
|
||||
* Callers that want a different null-fallback (e.g. supplier invoices, where
|
||||
* rounding never existed historically) pass `{ ore_rounding: false }` as the
|
||||
* company arg so a null per-invoice flag resolves to off.
|
||||
*/
|
||||
export function getDisplayTotal(
|
||||
invoice: InvoiceTotalShape,
|
||||
company: CompanyRoundingShape | null | undefined,
|
||||
): DisplayTotal {
|
||||
const enabled = company?.ore_rounding ?? true
|
||||
const enabled = invoice.ore_rounding ?? company?.ore_rounding ?? true
|
||||
if (!enabled || invoice.currency !== 'SEK') {
|
||||
return { displayed: invoice.total, roundingDelta: 0, applies: false }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Tests for the booking-time duplicate guard.
|
||||
*
|
||||
* Detection queries `transactions` for same-date already-booked siblings, then
|
||||
* filters by öre + cash-account compatibility in JS, then resolves the voucher
|
||||
* label from `journal_entries`. The mock returns the rows each query yields.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { detectBookedDuplicateTransaction } from '../booking-duplicate-detection'
|
||||
|
||||
type TxRow = {
|
||||
id: string
|
||||
date: string
|
||||
amount: number | string
|
||||
description: string | null
|
||||
cash_account_id: string | null
|
||||
journal_entry_id: string
|
||||
}
|
||||
type JeRow = { voucher_series: string | null; voucher_number: number | null; entry_date: string | null }
|
||||
|
||||
function txChain(data: TxRow[]) {
|
||||
const c: Record<string, unknown> = {}
|
||||
c.select = () => c
|
||||
c.eq = () => c
|
||||
c.not = () => c
|
||||
c.neq = () => c
|
||||
c.limit = () => Promise.resolve({ data, error: null })
|
||||
return c
|
||||
}
|
||||
function jeChain(data: JeRow | null) {
|
||||
const c: Record<string, unknown> = {}
|
||||
c.select = () => c
|
||||
c.eq = () => c
|
||||
c.maybeSingle = () => Promise.resolve({ data, error: null })
|
||||
return c
|
||||
}
|
||||
function makeSupabase(txData: TxRow[], jeData: JeRow | null = { voucher_series: 'A', voucher_number: 142, entry_date: '2025-12-19' }) {
|
||||
return {
|
||||
from: (table: string) => (table === 'transactions' ? txChain(txData) : jeChain(jeData)),
|
||||
} as never
|
||||
}
|
||||
|
||||
const COMPANY = 'co-1'
|
||||
const sibling = (over: Partial<TxRow> = {}): TxRow => ({
|
||||
id: 'sib-1',
|
||||
date: '2025-12-19',
|
||||
amount: -1616,
|
||||
description: 'TELENOR SVERIGE AB',
|
||||
cash_account_id: null,
|
||||
journal_entry_id: 'je-1',
|
||||
...over,
|
||||
})
|
||||
|
||||
describe('detectBookedDuplicateTransaction', () => {
|
||||
it('returns null when no same-date booked sibling exists', async () => {
|
||||
const supabase = makeSupabase([])
|
||||
const result = await detectBookedDuplicateTransaction(supabase, COMPANY, {
|
||||
id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: null,
|
||||
})
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('flags a same date+amount+account booked sibling with its voucher label', async () => {
|
||||
const supabase = makeSupabase([sibling()])
|
||||
const result = await detectBookedDuplicateTransaction(supabase, COMPANY, {
|
||||
id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: null,
|
||||
})
|
||||
expect(result).toEqual({
|
||||
transaction_id: 'sib-1',
|
||||
journal_entry_id: 'je-1',
|
||||
voucher_label: 'A142',
|
||||
entry_date: '2025-12-19',
|
||||
description: 'TELENOR SVERIGE AB',
|
||||
amount: -1616,
|
||||
})
|
||||
})
|
||||
|
||||
it('does NOT flag a sibling on a different known cash account', async () => {
|
||||
const supabase = makeSupabase([sibling({ cash_account_id: 'acct-A' })])
|
||||
const result = await detectBookedDuplicateTransaction(supabase, COMPANY, {
|
||||
id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: 'acct-B',
|
||||
})
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('flags when accounts are compatible via a null on either side', async () => {
|
||||
const supabase = makeSupabase([sibling({ cash_account_id: 'acct-A' })])
|
||||
const result = await detectBookedDuplicateTransaction(supabase, COMPANY, {
|
||||
id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: null,
|
||||
})
|
||||
expect(result?.transaction_id).toBe('sib-1')
|
||||
})
|
||||
|
||||
it('does NOT flag a sibling with a different amount', async () => {
|
||||
const supabase = makeSupabase([sibling({ amount: -1000 })])
|
||||
const result = await detectBookedDuplicateTransaction(supabase, COMPANY, {
|
||||
id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: null,
|
||||
})
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('matches a numeric-string amount from PostgREST against a JS number (öre)', async () => {
|
||||
const supabase = makeSupabase([sibling({ amount: '-1616.00' })])
|
||||
const result = await detectBookedDuplicateTransaction(supabase, COMPANY, {
|
||||
id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: null,
|
||||
})
|
||||
expect(result?.transaction_id).toBe('sib-1')
|
||||
})
|
||||
|
||||
it('returns null for a zero-amount target without querying', async () => {
|
||||
const supabase = makeSupabase([sibling({ amount: 0 })])
|
||||
const result = await detectBookedDuplicateTransaction(supabase, COMPANY, {
|
||||
id: 'self', date: '2025-12-19', amount: 0, cash_account_id: null,
|
||||
})
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('picks the lowest-id sibling deterministically (stable under force re-detect)', async () => {
|
||||
const supabase = makeSupabase([
|
||||
sibling({ id: 'sib-9' }),
|
||||
sibling({ id: 'sib-2' }),
|
||||
])
|
||||
const result = await detectBookedDuplicateTransaction(supabase, COMPANY, {
|
||||
id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: null,
|
||||
})
|
||||
expect(result?.transaction_id).toBe('sib-2')
|
||||
})
|
||||
})
|
||||
@@ -356,17 +356,19 @@ describe('ingestTransactions', () => {
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 2c. No false positive: same date+amount but different description does
|
||||
// NOT trigger content dedup — guards against the historical concern
|
||||
// about unrelated transfers colliding on (date, amount) alone.
|
||||
// 2c. No false positive within ONE channel: same date+amount but a different
|
||||
// description does NOT dedupe when the stored row is from the SAME feed
|
||||
// (a re-import that legitimately holds two distinct same-(date,amount)
|
||||
// transactions). Only a cross-channel mirror (2c-bis) drops the
|
||||
// description requirement.
|
||||
// -----------------------------------------------------------------------
|
||||
it('does not dedupe when date+amount match but description differs', async () => {
|
||||
it('does not dedupe a same-channel row when the description differs', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
const raw = makeRaw({
|
||||
date: '2024-06-15',
|
||||
amount: -250.0,
|
||||
description: 'Coop Stockholm',
|
||||
external_id: 'lunar_csvhash456',
|
||||
external_id: 'csv_lunar_456',
|
||||
import_source: 'csv_lunar',
|
||||
})
|
||||
const inserted = makeTransaction({
|
||||
@@ -377,9 +379,10 @@ describe('ingestTransactions', () => {
|
||||
|
||||
// Booked transaction map query — none
|
||||
enqueue({ data: [], error: null })
|
||||
// Unbooked bank-synced transaction map query — a PSD2 row with same date/amount but DIFFERENT description
|
||||
// Unbooked row from the SAME feed (csv_lunar), same date/amount, DIFFERENT
|
||||
// description → not a cross-channel mirror → must NOT dedupe.
|
||||
enqueue({
|
||||
data: [{ date: '2024-06-15', amount: -250.0, description: 'ICA Maxi Solna' }],
|
||||
data: [{ date: '2024-06-15', amount: -250.0, original_description: 'ICA Maxi Solna', description: 'ICA Maxi Solna', import_source: 'csv_lunar' }],
|
||||
error: null,
|
||||
})
|
||||
// Supplier invoices fetch
|
||||
@@ -398,6 +401,250 @@ describe('ingestTransactions', () => {
|
||||
expect(result.transaction_ids).toEqual(['tx-no-collision'])
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 2c-bis. Cross-channel mirror: the SAME bank account imported via two feeds
|
||||
// (Nordea CSV payee text vs PSD2 OCR/message) — same date+amount, one row
|
||||
// per channel, descriptions that do NOT bridge — IS deduped on
|
||||
// (date, öre). This is the AXMD/Axel case: a CSV import landing on top of
|
||||
// existing Enable Banking rows whose descriptions share no text.
|
||||
// -----------------------------------------------------------------------
|
||||
it('dedupes a cross-channel mirror (CSV vs PSD2) even when descriptions do not bridge', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
const raw = makeRaw({
|
||||
date: '2025-10-23',
|
||||
amount: -941,
|
||||
description: 'Fortnox Finans AB', // Nordea CSV payee
|
||||
external_id: 'nordea_business_abc123',
|
||||
import_source: 'csv_nordea_business',
|
||||
})
|
||||
|
||||
// Booked transaction map query — none
|
||||
enqueue({ data: [], error: null })
|
||||
// Stored unbooked PSD2 row: same date+amount, DIFFERENT text (the OCR), from
|
||||
// a DIFFERENT feed (enable_banking).
|
||||
enqueue({
|
||||
data: [{ date: '2025-10-23', amount: -941, original_description: '506401841738056', description: '506401841738056', import_source: 'enable_banking' }],
|
||||
error: null,
|
||||
})
|
||||
// Supplier invoices fetch
|
||||
enqueue({ data: [], error: null })
|
||||
// Batch external_id dedup query — different namespace, no match
|
||||
enqueue({ data: [], error: null })
|
||||
// No insert — deduped by the cross-channel mirror.
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, [raw])
|
||||
|
||||
expect(result.duplicates).toBe(1)
|
||||
expect(result.imported).toBe(0)
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 2c-ter. Cross-channel but NOT a mirror (counts differ) → ambiguous, so the
|
||||
// description requirement stands and nothing is dropped. Two incoming CSV
|
||||
// rows + one stored PSD2 row with no bridging text → both incoming kept.
|
||||
// Guards the rare case where the two feeds disagree on how many
|
||||
// transactions a (date, öre) bucket holds: prefer a visible (deletable)
|
||||
// duplicate over silently collapsing a genuinely-new row.
|
||||
// -----------------------------------------------------------------------
|
||||
it('does not text-independently dedupe an asymmetric cross-channel bucket', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
const rows = [
|
||||
makeRaw({ date: '2025-10-23', amount: -500, description: 'Betalning A', external_id: 'nordea_business_a', import_source: 'csv_nordea_business' }),
|
||||
makeRaw({ date: '2025-10-23', amount: -500, description: 'Betalning B', external_id: 'nordea_business_b', import_source: 'csv_nordea_business' }),
|
||||
]
|
||||
|
||||
// Booked transaction map query — none
|
||||
enqueue({ data: [], error: null })
|
||||
// Only ONE stored PSD2 row (different text) → incoming 2 vs cross 1 = asymmetric.
|
||||
enqueue({
|
||||
data: [{ date: '2025-10-23', amount: -500, original_description: 'A107 RAMBER', description: 'A107 RAMBER', import_source: 'enable_banking' }],
|
||||
error: null,
|
||||
})
|
||||
// Supplier invoices fetch
|
||||
enqueue({ data: [], error: null })
|
||||
// Batch external_id dedup query — no match
|
||||
enqueue({ data: [], error: null })
|
||||
enqueue({ data: makeTransaction({ id: 'tx-a', amount: -500 }), error: null })
|
||||
enqueue({ data: makeTransaction({ id: 'tx-b', amount: -500 }), error: null })
|
||||
|
||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, rows)
|
||||
|
||||
expect(result.imported).toBe(2)
|
||||
expect(result.duplicates).toBe(0)
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 2c-quater. The cross-channel mirror is still subject to the account guard:
|
||||
// a mirror match on a DIFFERENT known cash account is rejected, so a
|
||||
// multi-account company never collapses a transaction across accounts.
|
||||
// -----------------------------------------------------------------------
|
||||
it('respects the cash-account guard on the cross-channel mirror path', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
const raw = makeRaw({
|
||||
date: '2025-10-23',
|
||||
amount: -941,
|
||||
description: 'Fortnox Finans AB',
|
||||
external_id: 'nordea_business_xyz',
|
||||
import_source: 'csv_nordea_business',
|
||||
})
|
||||
const inserted = makeTransaction({ id: 'tx-acctB', amount: -941 })
|
||||
|
||||
// Booked transaction map query — none
|
||||
enqueue({ data: [], error: null })
|
||||
// Stored cross-feed twin, but it settled on a DIFFERENT account (A).
|
||||
enqueue({
|
||||
data: [{ date: '2025-10-23', amount: -941, original_description: '506401841738056', description: '506401841738056', import_source: 'enable_banking', cash_account_id: 'acct-A' }],
|
||||
error: null,
|
||||
})
|
||||
// Supplier invoices fetch
|
||||
enqueue({ data: [], error: null })
|
||||
// Batch external_id dedup query — no match
|
||||
enqueue({ data: [], error: null })
|
||||
// cash_accounts lookup → batch settled on account B
|
||||
enqueue({ data: { id: 'acct-B' }, error: null })
|
||||
// Insert — different account, not a duplicate
|
||||
enqueue({ data: inserted, error: null })
|
||||
|
||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, [raw], {
|
||||
settlementAccount: '1931',
|
||||
})
|
||||
|
||||
expect(result.imported).toBe(1)
|
||||
expect(result.duplicates).toBe(0)
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 2c-shadow. Same-feed scope-drift (Hole A) — SHADOW MODE. Enable Banking
|
||||
// returns the same account under a drifted IBAN, so the IBAN-embedded
|
||||
// external_id is new (Layer-1 misses) and, because both rows are the SAME
|
||||
// feed, the cross-channel mirror does not fire. The shadow detector
|
||||
// MEASURES how often an enforcing rule would treat this as a re-import —
|
||||
// it logs/counts but NEVER changes what is inserted. These tests pin both
|
||||
// that it detects the real case and, crucially, that it never flags a
|
||||
// genuine row (the only failure mode that would matter).
|
||||
// -----------------------------------------------------------------------
|
||||
it('shadow-flags a same-feed scope-drift re-import but still imports it (no behavior change)', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
// Same account re-fetched under a drifted IBAN → new external_id, and a
|
||||
// description that shares no prefix with the stored row (so the text bridge
|
||||
// cannot catch it either — this is purely the scope-drift signal).
|
||||
const raw = makeRaw({
|
||||
date: '2024-06-15',
|
||||
amount: -250,
|
||||
description: 'TELENOR SVERIGE',
|
||||
external_id: 'eb_SE_NEW_2024-06-15_-25000_0',
|
||||
import_source: 'enable_banking',
|
||||
bank_connection_id: 'conn-1',
|
||||
})
|
||||
const inserted = makeTransaction({ id: 'tx-new', external_id: raw.external_id })
|
||||
|
||||
enqueue({ data: [], error: null }) // booked map — none
|
||||
// Unbooked map — the stored twin from the SAME feed under the OLD id scope.
|
||||
enqueue({
|
||||
data: [{
|
||||
date: '2024-06-15', amount: -250,
|
||||
original_description: 'LAN AXMD 19', description: 'LAN AXMD 19',
|
||||
import_source: 'enable_banking', bank_connection_id: 'conn-1',
|
||||
cash_account_id: 'ca-1930', external_id: 'eb_SE_OLD_2024-06-15_-25000_0',
|
||||
}],
|
||||
error: null,
|
||||
})
|
||||
enqueue({ data: [], error: null }) // supplier invoices — none
|
||||
enqueue({ data: [], error: null }) // external_id dedup — OLD id not among incoming NEW ids
|
||||
enqueue({ data: { id: 'ca-1930' }, error: null }) // cash_accounts — same account as the stored row
|
||||
enqueue({ data: inserted, error: null }) // insert — STILL imported (shadow only logs)
|
||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, [raw], {
|
||||
settlementAccount: '1930',
|
||||
})
|
||||
|
||||
// Detected, but NOT acted on: imports exactly as before.
|
||||
expect(result.imported).toBe(1)
|
||||
expect(result.duplicates).toBe(0)
|
||||
expect(result.shadow_scope_drift_candidates).toBe(1)
|
||||
})
|
||||
|
||||
it('does not shadow-flag an asymmetric same-feed bucket (counts differ)', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
// TWO incoming rows share (date, amount) but only ONE stored twin exists →
|
||||
// the channels disagree on how many transactions the bucket holds, so the
|
||||
// signal is ambiguous and we stay silent.
|
||||
const rows = [
|
||||
makeRaw({ date: '2024-06-15', amount: -250, description: 'BETALNING A', external_id: 'eb_NEW_a', import_source: 'enable_banking' }),
|
||||
makeRaw({ date: '2024-06-15', amount: -250, description: 'BETALNING B', external_id: 'eb_NEW_b', import_source: 'enable_banking' }),
|
||||
]
|
||||
enqueue({ data: [], error: null }) // booked
|
||||
enqueue({
|
||||
data: [{ date: '2024-06-15', amount: -250, original_description: 'OCR 9988', description: 'OCR 9988', import_source: 'enable_banking', cash_account_id: null, external_id: 'eb_OLD_x' }],
|
||||
error: null,
|
||||
}) // unbooked — ONE stored twin
|
||||
enqueue({ data: [], error: null }) // supplier
|
||||
enqueue({ data: [], error: null }) // external_id dedup
|
||||
enqueue({ data: makeTransaction({ id: 'tx-a' }), error: null }) // insert a
|
||||
enqueue({ data: makeTransaction({ id: 'tx-b' }), error: null }) // insert b
|
||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, rows)
|
||||
|
||||
expect(result.imported).toBe(2)
|
||||
expect(result.duplicates).toBe(0)
|
||||
expect(result.shadow_scope_drift_candidates).toBe(0)
|
||||
})
|
||||
|
||||
it('does not shadow-flag when the stored twin is on a different known cash account', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
const raw = makeRaw({ date: '2024-06-15', amount: -250, description: 'TELENOR', external_id: 'eb_NEW_acctB', import_source: 'enable_banking' })
|
||||
const inserted = makeTransaction({ id: 'tx-b', external_id: raw.external_id })
|
||||
enqueue({ data: [], error: null }) // booked
|
||||
enqueue({
|
||||
data: [{ date: '2024-06-15', amount: -250, original_description: 'OCR', description: 'OCR', import_source: 'enable_banking', cash_account_id: 'acct-A', external_id: 'eb_OLD_acctA' }],
|
||||
error: null,
|
||||
}) // unbooked twin on account A
|
||||
enqueue({ data: [], error: null }) // supplier
|
||||
enqueue({ data: [], error: null }) // external_id dedup
|
||||
enqueue({ data: { id: 'acct-B' }, error: null }) // cash_accounts → batch settled on account B
|
||||
enqueue({ data: inserted, error: null }) // insert
|
||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, [raw], { settlementAccount: '1931' })
|
||||
|
||||
expect(result.imported).toBe(1)
|
||||
expect(result.shadow_scope_drift_candidates).toBe(0)
|
||||
})
|
||||
|
||||
it('does not shadow-flag a genuinely new row when the stored sibling id re-arrives (not drift)', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
// The stored row's id IS present in this batch (normal re-sync, no drift) →
|
||||
// Layer-1 dedupes it. The SECOND incoming row is a genuinely new same-day /
|
||||
// same-amount transaction with a non-bridging description: it must import
|
||||
// AND must NOT be shadow-flagged, because the stored sibling is not
|
||||
// "orphaned" by a drifted id. This is the data-loss guard.
|
||||
const rows = [
|
||||
makeRaw({ date: '2024-06-15', amount: -250, description: 'COFFEE STARBUCKS', external_id: 'eb_X_0', import_source: 'enable_banking' }),
|
||||
makeRaw({ date: '2024-06-15', amount: -250, description: 'LUNCH RESTAURANG', external_id: 'eb_X_1', import_source: 'enable_banking' }),
|
||||
]
|
||||
enqueue({ data: [], error: null }) // booked
|
||||
enqueue({
|
||||
data: [{ date: '2024-06-15', amount: -250, original_description: 'COFFEE STARBUCKS', description: 'COFFEE STARBUCKS', import_source: 'enable_banking', cash_account_id: null, external_id: 'eb_X_0' }],
|
||||
error: null,
|
||||
}) // stored = the _0 sibling
|
||||
enqueue({ data: [], error: null }) // supplier
|
||||
enqueue({ data: [{ external_id: 'eb_X_0' }], error: null }) // external_id dedup → eb_X_0 matches stored
|
||||
enqueue({ data: makeTransaction({ id: 'tx-x1' }), error: null }) // insert eb_X_1 only
|
||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, rows)
|
||||
|
||||
expect(result.duplicates).toBe(1) // eb_X_0 deduped by Layer-1
|
||||
expect(result.imported).toBe(1) // eb_X_1 (genuine new) imported
|
||||
expect(result.shadow_scope_drift_candidates).toBe(0) // and NOT shadow-flagged
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 2d. Description drift: PSD2 enrichment is prefix-preserving, so an
|
||||
// enriched re-import ("TIC" → "TIC BG … via internet") still bridges
|
||||
@@ -957,6 +1204,7 @@ describe('ingestTransactions', () => {
|
||||
auto_matched_invoices: 0,
|
||||
errors: 0,
|
||||
transaction_ids: [],
|
||||
shadow_scope_drift_candidates: 0,
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Booking-time duplicate guard for bank transactions.
|
||||
*
|
||||
* Why this exists
|
||||
* ---------------
|
||||
* A bank account's transactions can land in the `transactions` table twice — a
|
||||
* CSV import on top of a PSD2 sync, or a re-sync whose external_id drifted (see
|
||||
* the import dedup in lib/transactions/ingest.ts). Import-time dedup is
|
||||
* best-effort and can miss. The cosmetic cost of a missed duplicate is a second
|
||||
* row in the "Att bokföra" list. The REAL cost is booking BOTH copies: that
|
||||
* creates two verifikationer for one affärshändelse, double-counts the
|
||||
* cost/income, and is felaktig bokföring under BFL (the second verifikat has no
|
||||
* underlying event). Rättelse would then require storno, not deletion.
|
||||
*
|
||||
* This guard runs at booking time. Before a transaction becomes a verifikat it
|
||||
* looks for ANOTHER transaction in the same company that is already booked and
|
||||
* shares this one's (date, amount, cash account). If found, the caller surfaces
|
||||
* it as a WARNING — never a hard block, because genuinely repeated
|
||||
* same-(date,amount) payments do occur (e.g. several identical Swish transfers
|
||||
* in one day). The user confirms with force=true after reviewing the candidate.
|
||||
*
|
||||
* Mirrors the invoice-side `detectDuplicatePaymentVoucher`
|
||||
* (lib/invoices/duplicate-payment-detection.ts), but keyed on an already-booked
|
||||
* sibling TRANSACTION rather than a manually-posted journal entry.
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/** Integer öre — representation-agnostic amount key (mirrors the ingest dedup). */
|
||||
function toOre(amount: number | string): number {
|
||||
return Math.round(Number(amount) * 100)
|
||||
}
|
||||
|
||||
/** An already-booked transaction that looks like the same real movement. */
|
||||
export interface BookedDuplicateCandidate {
|
||||
/** The sibling transaction that is already booked. */
|
||||
transaction_id: string
|
||||
/** Its verifikat. */
|
||||
journal_entry_id: string
|
||||
/** Human label, e.g. "A142" (voucher_series + voucher_number). */
|
||||
voucher_label: string
|
||||
entry_date: string
|
||||
description: string | null
|
||||
amount: number
|
||||
}
|
||||
|
||||
/** Minimal shape of the transaction about to be booked. */
|
||||
export interface BookingTarget {
|
||||
id: string
|
||||
date: string
|
||||
amount: number | string
|
||||
cash_account_id?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an already-booked sibling transaction sharing (date, amount, account).
|
||||
* Returns the single best candidate, or null.
|
||||
*
|
||||
* Account guard mirrors the import dedup bridge: when BOTH sides know their
|
||||
* cash_account_id they must match; a null on either side is treated as
|
||||
* compatible (single-account companies and un-backfilled rows behave as before).
|
||||
*
|
||||
* Fail-open: a query error returns null rather than throwing — a detection
|
||||
* failure must never block a legitimate booking. The pick is deterministic
|
||||
* (lowest id) so a re-detection under force=true returns the same candidate the
|
||||
* user reviewed.
|
||||
*/
|
||||
export async function detectBookedDuplicateTransaction(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
target: BookingTarget,
|
||||
): Promise<BookedDuplicateCandidate | null> {
|
||||
const targetOre = toOre(target.amount)
|
||||
if (targetOre === 0 || Number.isNaN(targetOre)) return null
|
||||
|
||||
// Same company, same date, already booked, not the target row itself. The
|
||||
// amount and account match is applied in JS so a numeric-string amount from
|
||||
// PostgREST ("-1616.00") collapses to the same öre as the number (-1616).
|
||||
const { data, error } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, date, amount, description, cash_account_id, journal_entry_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('date', target.date)
|
||||
.not('journal_entry_id', 'is', null)
|
||||
.neq('id', target.id)
|
||||
.limit(100)
|
||||
|
||||
if (error || !data || data.length === 0) return null
|
||||
|
||||
type Row = {
|
||||
id: string
|
||||
date: string
|
||||
amount: number | string
|
||||
description: string | null
|
||||
cash_account_id: string | null
|
||||
journal_entry_id: string
|
||||
}
|
||||
const targetAccount = target.cash_account_id ?? null
|
||||
const matches = (data as unknown as Row[]).filter((r) => {
|
||||
if (toOre(r.amount) !== targetOre) return false
|
||||
// Account guard: both-known must match; a null on either side is compatible.
|
||||
if (targetAccount !== null && r.cash_account_id !== null && r.cash_account_id !== targetAccount) {
|
||||
return false
|
||||
}
|
||||
return r.journal_entry_id != null
|
||||
})
|
||||
if (matches.length === 0) return null
|
||||
|
||||
matches.sort((a, b) => a.id.localeCompare(b.id))
|
||||
const best = matches[0]
|
||||
|
||||
// Resolve the voucher label for the warning (best-effort — a missing label
|
||||
// still yields a usable candidate the UI can render by date/amount).
|
||||
let voucherLabel = ''
|
||||
let entryDate = best.date
|
||||
const { data: je } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('voucher_series, voucher_number, entry_date')
|
||||
.eq('id', best.journal_entry_id)
|
||||
.maybeSingle()
|
||||
if (je) {
|
||||
const j = je as { voucher_series: string | null; voucher_number: number | null; entry_date: string | null }
|
||||
voucherLabel = `${j.voucher_series ?? 'A'}${j.voucher_number ?? ''}`
|
||||
entryDate = j.entry_date ?? best.date
|
||||
}
|
||||
|
||||
return {
|
||||
transaction_id: best.id,
|
||||
journal_entry_id: best.journal_entry_id,
|
||||
voucher_label: voucherLabel,
|
||||
entry_date: entryDate,
|
||||
description: best.description,
|
||||
amount: Math.round(Number(best.amount) * 100) / 100,
|
||||
}
|
||||
}
|
||||
+245
-47
@@ -8,6 +8,8 @@ import { fetchExchangeRate } from '@/lib/currency/riksbanken'
|
||||
import { logMatchEvent } from '@/lib/invoices/match-log'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { contentBucketKey, descriptionsBridge, normalizeImportedDescription } from '@/lib/transactions/external-id'
|
||||
import { isImportedTransaction } from '@/lib/transactions/origin'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { Transaction, RawTransaction, IngestResult, IngestOptions, SupplierInvoice, Currency, ExchangeRate } from '@/types'
|
||||
|
||||
// Re-export types for backward compatibility
|
||||
@@ -15,11 +17,26 @@ export type { RawTransaction, IngestResult } from '@/types'
|
||||
|
||||
/**
|
||||
* One existing row in a content-dedup bucket: its normalized/lowercased
|
||||
* description plus the cash account it settled on (null for legacy rows that
|
||||
* predate the cash_account_id backfill). `cashAccountId` is the cross-account
|
||||
* guard — see `consumeBridgingTwin`.
|
||||
* description, the cash account it settled on (null for legacy rows that
|
||||
* predate the cash_account_id backfill), the import channel it came from, and
|
||||
* whether that channel is an external feed (vs a hand-entered row). `source` +
|
||||
* `isImportFeed` drive the cross-channel mirror bridge (see
|
||||
* `consumeBridgingTwin`); `cashAccountId` is the cross-account guard.
|
||||
*/
|
||||
type BucketEntry = { desc: string; cashAccountId: string | null }
|
||||
type BucketEntry = {
|
||||
desc: string
|
||||
cashAccountId: string | null
|
||||
source: string | null
|
||||
isImportFeed: boolean
|
||||
/**
|
||||
* The stored row's `external_id`. Used ONLY by the shadow-mode same-feed
|
||||
* scope-drift instrumentation (see ingestTransactions): a stored row is a
|
||||
* "drift candidate" when its id is NOT among the incoming batch's ids, which
|
||||
* is what distinguishes an IBAN-scope re-import from a normal sibling whose id
|
||||
* Layer-1 already reconciles. Null for rows predating the column.
|
||||
*/
|
||||
externalId: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Content-dedup bucket: a `{date}|{öre}` key mapped to the multiset of existing
|
||||
@@ -34,13 +51,16 @@ interface ExistingTransactionMaps {
|
||||
/** Booked transactions (any source) — consumed by any incoming raw transaction. */
|
||||
booked: DescBucket
|
||||
/**
|
||||
* Unbooked enable_banking transactions — consumed by any incoming raw
|
||||
* transaction regardless of source. Catches two cases: PSD2 reconnect
|
||||
* duplicates (external_id regenerated, same tx already pending) AND
|
||||
* CSV imports overlapping an active PSD2 sync (same Lunar/etc tx arriving
|
||||
* twice, once via PSD2 and once via file upload).
|
||||
* Unbooked rows from ANY external import feed (Enable Banking PSD2 sync,
|
||||
* bank-file CSV/CAMT import) — consumed by any incoming raw transaction
|
||||
* regardless of source. Catches the cross-channel re-import: the same bank
|
||||
* account pulled once via PSD2 and once via a CSV/CAMT file upload (in either
|
||||
* order), plus PSD2 reconnect duplicates whose external_id regenerated.
|
||||
* Hand-entered rows (import_source manual/mcp/null) are deliberately
|
||||
* excluded — only real feeds mirror one another, and a manual row must never
|
||||
* be silently consumed by an import.
|
||||
*/
|
||||
unbookedEnableBanking: DescBucket
|
||||
unbookedImported: DescBucket
|
||||
}
|
||||
|
||||
/** Push a row into its (date, öre) bucket, normalizing the description. */
|
||||
@@ -50,9 +70,18 @@ function addToBucket(
|
||||
amount: number | string,
|
||||
description: string,
|
||||
cashAccountId: string | null,
|
||||
source: string | null,
|
||||
isImportFeed: boolean,
|
||||
externalId: string | null,
|
||||
): void {
|
||||
const key = contentBucketKey(date, amount)
|
||||
const entry: BucketEntry = { desc: description.toLowerCase().trim(), cashAccountId }
|
||||
const entry: BucketEntry = {
|
||||
desc: description.toLowerCase().trim(),
|
||||
cashAccountId,
|
||||
source,
|
||||
isImportFeed,
|
||||
externalId,
|
||||
}
|
||||
const entries = bucket.get(key)
|
||||
if (entries) entries.push(entry)
|
||||
else bucket.set(key, [entry])
|
||||
@@ -64,8 +93,8 @@ async function buildExistingTransactionMaps(
|
||||
rawTransactions: RawTransaction[]
|
||||
): Promise<ExistingTransactionMaps> {
|
||||
const booked: DescBucket = new Map()
|
||||
const unbookedEnableBanking: DescBucket = new Map()
|
||||
if (rawTransactions.length === 0) return { booked, unbookedEnableBanking }
|
||||
const unbookedImported: DescBucket = new Map()
|
||||
if (rawTransactions.length === 0) return { booked, unbookedImported }
|
||||
|
||||
const dates = rawTransactions.map((t) => t.date).sort()
|
||||
const dateFrom = dates[0]
|
||||
@@ -74,7 +103,7 @@ async function buildExistingTransactionMaps(
|
||||
try {
|
||||
const { data: bookedRows } = await supabase
|
||||
.from('transactions')
|
||||
.select('date, amount, original_description, description, cash_account_id')
|
||||
.select('date, amount, original_description, description, cash_account_id, import_source, bank_connection_id, external_id')
|
||||
.eq('company_id', companyId)
|
||||
.not('journal_entry_id', 'is', null)
|
||||
.gte('date', dateFrom)
|
||||
@@ -92,6 +121,9 @@ async function buildExistingTransactionMaps(
|
||||
tx.amount,
|
||||
normalizeImportedDescription(tx.original_description ?? tx.description),
|
||||
tx.cash_account_id ?? null,
|
||||
tx.import_source ?? null,
|
||||
isImportedTransaction({ import_source: tx.import_source, bank_connection_id: tx.bank_connection_id }),
|
||||
tx.external_id ?? null,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -100,25 +132,35 @@ async function buildExistingTransactionMaps(
|
||||
}
|
||||
|
||||
try {
|
||||
const { data: unbookedBank } = await supabase
|
||||
// ALL unbooked import-feed rows — not just enable_banking. An unbooked CSV
|
||||
// row must dedup an incoming PSD2 sync of the same account, and an unbooked
|
||||
// PSD2 row must dedup an incoming CSV import. Feeds always set a non-null
|
||||
// import_source outside the user-created allowlist (manual/mcp); null /
|
||||
// manual / mcp are hand-entered and intentionally excluded.
|
||||
const { data: unbookedRows } = await supabase
|
||||
.from('transactions')
|
||||
.select('date, amount, original_description, description, cash_account_id')
|
||||
.select('date, amount, original_description, description, cash_account_id, import_source, bank_connection_id, external_id')
|
||||
.eq('company_id', companyId)
|
||||
.is('journal_entry_id', null)
|
||||
.eq('import_source', 'enable_banking')
|
||||
.not('import_source', 'is', null)
|
||||
.neq('import_source', 'manual')
|
||||
.neq('import_source', 'mcp')
|
||||
.gte('date', dateFrom)
|
||||
.lte('date', dateTo)
|
||||
|
||||
if (unbookedBank) {
|
||||
for (const tx of unbookedBank) {
|
||||
if (unbookedRows) {
|
||||
for (const tx of unbookedRows) {
|
||||
// See booked-map note: dedup on the immutable bank original so a
|
||||
// user title edit cannot reopen the duplicate-import window.
|
||||
addToBucket(
|
||||
unbookedEnableBanking,
|
||||
unbookedImported,
|
||||
tx.date,
|
||||
tx.amount,
|
||||
normalizeImportedDescription(tx.original_description ?? tx.description),
|
||||
tx.cash_account_id ?? null,
|
||||
tx.import_source ?? null,
|
||||
isImportedTransaction({ import_source: tx.import_source, bank_connection_id: tx.bank_connection_id }),
|
||||
tx.external_id ?? null,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -126,7 +168,7 @@ async function buildExistingTransactionMaps(
|
||||
// Non-critical — reconnect dedup will be skipped
|
||||
}
|
||||
|
||||
return { booked, unbookedEnableBanking }
|
||||
return { booked, unbookedImported }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,15 +205,60 @@ export async function ingestTransactions(
|
||||
auto_matched_invoices: 0,
|
||||
errors: 0,
|
||||
transaction_ids: [],
|
||||
shadow_scope_drift_candidates: 0,
|
||||
}
|
||||
|
||||
// Pre-fetch existing transactions for content-based dedup
|
||||
// (date+amount+description prefix). Booked rows catch cross-source
|
||||
// duplicates after they've been booked; unbooked enable_banking rows
|
||||
// catch the more common case where a PSD2 row is still pending in the
|
||||
// inbox when the user re-imports the same period via CSV.
|
||||
const log = createLogger('transactions.ingest', { companyId })
|
||||
// SHADOW-ONLY instrumentation for the same-feed scope-drift bridge (Hole A:
|
||||
// Enable Banking returns the same account under a drifted IBAN, the
|
||||
// IBAN-embedded external_id changes, Layer-1 dedup misses the re-import, and
|
||||
// because both rows are the SAME feed the cross-channel mirror does not fire).
|
||||
// When on, we LOG which rows an enforcing rule WOULD treat as re-imports and
|
||||
// count them — but never change what gets inserted. Default on; set
|
||||
// DEDUP_SCOPE_DRIFT_MODE=off to silence. There is deliberately NO 'enforce'
|
||||
// branch yet: we validate on real fleet data first (see the plan).
|
||||
const scopeDriftShadow = process.env.DEDUP_SCOPE_DRIFT_MODE !== 'off'
|
||||
|
||||
// Pre-fetch existing transactions for content-based dedup (date+amount+
|
||||
// description prefix, plus the cross-channel mirror below). Booked rows catch
|
||||
// cross-source duplicates after they've been booked; unbooked import-feed rows
|
||||
// catch the common case where a PSD2 row is still unbooked when the user
|
||||
// re-imports the same period via CSV — or the reverse, a CSV import that
|
||||
// predates the first PSD2 sync of the same account.
|
||||
const existingMaps = await buildExistingTransactionMaps(supabase, companyId, rawTransactions)
|
||||
|
||||
// Every row in one ingest call shares an import_source — EB sync passes
|
||||
// 'enable_banking', bank-file import passes 'csv_<format>'/'camt053' — so the
|
||||
// first row's source identifies this batch's channel. We use it to find
|
||||
// "cross-channel mirror" buckets: a (date, öre) bucket where the number of
|
||||
// incoming rows EQUALS the number of stored rows from a DIFFERENT feed. That
|
||||
// equality is the signal that the same set of real transactions is arriving
|
||||
// once per channel (e.g. Nordea's CSV export and its PSD2 feed), where the
|
||||
// per-row description is known-unreliable — CSV shows the payee, PSD2 the
|
||||
// OCR/message, or vice versa. Only in those buckets do we dedup on
|
||||
// (date, öre, account) without a description match (see consumeBridgingTwin).
|
||||
// An asymmetric bucket keeps the description requirement, so a genuinely-new
|
||||
// row is never collapsed into a different one.
|
||||
const batchSource = rawTransactions[0]?.import_source ?? null
|
||||
const batchIsImportFeed = isImportedTransaction({ import_source: batchSource })
|
||||
const incomingByBucket = new Map<string, number>()
|
||||
const crossSourceStoredByBucket = new Map<string, number>()
|
||||
if (batchIsImportFeed) {
|
||||
for (const raw of rawTransactions) {
|
||||
const k = contentBucketKey(raw.date, raw.amount)
|
||||
incomingByBucket.set(k, (incomingByBucket.get(k) ?? 0) + 1)
|
||||
}
|
||||
for (const bucket of [existingMaps.booked, existingMaps.unbookedImported]) {
|
||||
for (const [k, entries] of bucket) {
|
||||
for (const entry of entries) {
|
||||
if (entry.isImportFeed && entry.source !== batchSource) {
|
||||
crossSourceStoredByBucket.set(k, (crossSourceStoredByBucket.get(k) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// When rawInsertOnly is set (viewer imports), skip pre-fetching supplier
|
||||
// invoices and exchange rates — they are not used.
|
||||
let unpaidSupplierInvoices: SupplierInvoice[] = []
|
||||
@@ -266,6 +353,50 @@ export async function ingestTransactions(
|
||||
cashAccountId = (ca?.id as string | undefined) ?? null
|
||||
}
|
||||
|
||||
// ── Shadow-mode same-feed scope-drift precompute (measure only) ──────────
|
||||
// Two per-(date, öre) bucket counts that, when EQUAL and non-zero, mark a
|
||||
// bucket as a probable scope-drift mirror:
|
||||
// - unmatchedIncomingByBucket: incoming rows whose external_id is NOT
|
||||
// already stored (i.e. Layer-1 will not reconcile them — the ones that
|
||||
// would otherwise insert as fresh rows).
|
||||
// - driftCandidateStoredByBucket: stored rows from THIS SAME feed whose id
|
||||
// the incoming batch does NOT carry (so they are "orphaned" by a drifted
|
||||
// id), restricted to account-compatible rows. Account compatibility uses
|
||||
// the batch settlement account (cash_account_id), which is keyed on the
|
||||
// provider's STABLE account uid — not the drifting IBAN that broke the
|
||||
// external_id (see lib/cash-accounts/service.ts upsertFromPsd2). So a
|
||||
// genuinely different account on the same company is never a candidate.
|
||||
// Equality is the safety signal (same as the cross-channel mirror): it means
|
||||
// the same set of transactions re-arrived once, under new ids. An asymmetric
|
||||
// bucket is left alone. Counts are pre-loop snapshots; the gate is evaluated
|
||||
// per incoming row inside the loop.
|
||||
const incomingIdSet = new Set(externalIds)
|
||||
const unmatchedIncomingByBucket = new Map<string, number>()
|
||||
const driftCandidateStoredByBucket = new Map<string, number>()
|
||||
if (batchIsImportFeed && scopeDriftShadow) {
|
||||
for (const raw of rawTransactions) {
|
||||
if (!existingExternalIds.has(raw.external_id)) {
|
||||
const k = contentBucketKey(raw.date, raw.amount)
|
||||
unmatchedIncomingByBucket.set(k, (unmatchedIncomingByBucket.get(k) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
for (const bucket of [existingMaps.booked, existingMaps.unbookedImported]) {
|
||||
for (const [k, entries] of bucket) {
|
||||
for (const entry of entries) {
|
||||
const sameFeed = entry.isImportFeed && entry.source === batchSource
|
||||
const accountCompatible =
|
||||
cashAccountId === null ||
|
||||
entry.cashAccountId === null ||
|
||||
entry.cashAccountId === cashAccountId
|
||||
const idOrphaned = entry.externalId !== null && !incomingIdSet.has(entry.externalId)
|
||||
if (sameFeed && accountCompatible && idOrphaned) {
|
||||
driftCandidateStoredByBucket.set(k, (driftCandidateStoredByBucket.get(k) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Track already-matched invoice IDs within this ingestion batch
|
||||
// to prevent suggesting the same invoice for multiple transactions
|
||||
const matchedInvoiceIds = new Set<string>()
|
||||
@@ -287,60 +418,127 @@ export async function ingestTransactions(
|
||||
}
|
||||
|
||||
// 1b/1c. Content-dedup bridge: skip if an existing booked row (any source)
|
||||
// OR an unbooked enable_banking row shares this (date, öre) bucket and a
|
||||
// *bridging* description (prefix-containment, see descriptionsBridge). This
|
||||
// is the net that catches re-imports the external_id check misses — chiefly
|
||||
// old-format ids re-synced after the id scheme changed, and PSD2 description
|
||||
// enrichment between syncs ("TIC" → "TIC BG … via internet"). Booked first,
|
||||
// then unbooked, preserving the historical 1b-before-1c order.
|
||||
// OR an unbooked import-feed row shares this (date, öre) bucket and EITHER
|
||||
// (a) a *bridging* description (prefix-containment, see descriptionsBridge),
|
||||
// OR (b) the bucket is a cross-channel mirror (crossSourceMirror below).
|
||||
// (a) catches re-imports the external_id check misses — old-format ids
|
||||
// re-synced after the id scheme changed, and PSD2 description enrichment
|
||||
// between syncs ("TIC" → "TIC BG … via internet"). (b) catches the same
|
||||
// bank account imported via two channels whose descriptions don't bridge at
|
||||
// all (Nordea CSV payee "TELENOR"/"Nordea" vs PSD2 OCR/message), which (a)
|
||||
// alone cannot. Booked first, then unbooked.
|
||||
//
|
||||
// Consumed with COUNTING semantics: each match splices one stored entry out
|
||||
// of its bucket, so N stored twins dedup exactly N incoming and two
|
||||
// genuinely-distinct same-(date,amount) transactions are kept apart. We
|
||||
// consume the LONGEST bridging stored description first so a more-specific
|
||||
// twin is matched before a generic one, leaving generic entries for shorter
|
||||
// incoming rows.
|
||||
// genuinely-distinct same-(date,amount) transactions are kept apart. The
|
||||
// text bridge is tried first (LONGEST bridging description wins, so a
|
||||
// more-specific twin is matched before a generic one); the cross-channel
|
||||
// mirror is the text-independent fallback.
|
||||
//
|
||||
// Account guard: when BOTH the incoming batch and a stored entry have a known
|
||||
// cash_account_id, they must match — so a transaction on one bank account
|
||||
// never deduplicates a genuinely-different one on another account of the same
|
||||
// company (the content bucket is company-wide; only external_id embeds the
|
||||
// account). A null on either side falls back to bridge-allowed, leaving
|
||||
// single-account and legacy (un-backfilled) rows exactly as before.
|
||||
// single-account and legacy (un-backfilled) rows exactly as before. The guard
|
||||
// applies to BOTH the text and the cross-channel-mirror path.
|
||||
//
|
||||
// Residual trade-off: within one account, a genuinely-new row whose
|
||||
// description is a prefix-extension of an existing same-(date,öre) row can be
|
||||
// mis-deduped; it is rare, bounded to the ~90-day PSD2 window where old-format
|
||||
// ids still overlap, and the frozen external_id (Layer 1) is the exact dedup
|
||||
// going forward — accepted to stop the re-import flood (the inverse, a visible
|
||||
// duplicate, was the reported pain).
|
||||
// crossSourceMirror: this (date, öre) bucket holds the same number of
|
||||
// incoming rows as stored rows from a different feed → the same real
|
||||
// transactions arriving once per channel. Only then is the description
|
||||
// requirement dropped; an asymmetric bucket keeps it, so when the channels
|
||||
// disagree on how many transactions a bucket holds we keep a visible
|
||||
// (deletable) duplicate rather than risk collapsing a genuinely-new row.
|
||||
const bucketKey = contentBucketKey(raw.date, raw.amount)
|
||||
const crossSourceMirror =
|
||||
batchIsImportFeed &&
|
||||
(crossSourceStoredByBucket.get(bucketKey) ?? 0) > 0 &&
|
||||
incomingByBucket.get(bucketKey) === crossSourceStoredByBucket.get(bucketKey)
|
||||
const consumeBridgingTwin = (bucket: DescBucket): boolean => {
|
||||
const entries = bucket.get(bucketKey)
|
||||
if (!entries || entries.length === 0) return false
|
||||
let bestIdx = -1
|
||||
let bestLen = -1
|
||||
let crossIdx = -1
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i]
|
||||
const sameAccount =
|
||||
cashAccountId === null || entry.cashAccountId === null || entry.cashAccountId === cashAccountId
|
||||
if (sameAccount && descriptionsBridge(description, entry.desc) && entry.desc.length > bestLen) {
|
||||
if (!sameAccount) continue
|
||||
if (descriptionsBridge(description, entry.desc) && entry.desc.length > bestLen) {
|
||||
bestIdx = i
|
||||
bestLen = entry.desc.length
|
||||
}
|
||||
// Text-independent fallback: in a cross-channel mirror bucket a stored
|
||||
// entry from a different feed is the same transaction even when the
|
||||
// descriptions don't bridge. Remember the first eligible one.
|
||||
if (crossIdx === -1 && crossSourceMirror && entry.isImportFeed && entry.source !== batchSource) {
|
||||
crossIdx = i
|
||||
}
|
||||
}
|
||||
if (bestIdx === -1) return false
|
||||
entries.splice(bestIdx, 1)
|
||||
const idx = bestIdx !== -1 ? bestIdx : crossIdx
|
||||
if (idx === -1) return false
|
||||
entries.splice(idx, 1)
|
||||
return true
|
||||
}
|
||||
if (
|
||||
consumeBridgingTwin(existingMaps.booked) ||
|
||||
consumeBridgingTwin(existingMaps.unbookedEnableBanking)
|
||||
consumeBridgingTwin(existingMaps.unbookedImported)
|
||||
) {
|
||||
result.duplicates++
|
||||
continue
|
||||
}
|
||||
|
||||
// SHADOW-ONLY: this row survived Layer-1 and Layer-2, so today it WILL
|
||||
// insert. If its bucket is a symmetric same-feed scope-drift mirror (equal
|
||||
// non-zero counts of unreconciled incoming rows and account-compatible
|
||||
// same-feed drift candidates), an enforcing rule WOULD treat it as a
|
||||
// re-import. We only record it — full content on both sides so every
|
||||
// decision can be human-verified against real fleet data before any
|
||||
// enforcement is switched on — then fall through and insert exactly as
|
||||
// before. This block has NO effect on result.imported/duplicates.
|
||||
if (scopeDriftShadow && batchIsImportFeed) {
|
||||
const driftCount = driftCandidateStoredByBucket.get(bucketKey) ?? 0
|
||||
const unmatchedCount = unmatchedIncomingByBucket.get(bucketKey) ?? 0
|
||||
if (driftCount > 0 && unmatchedCount === driftCount) {
|
||||
let matched: BucketEntry | undefined
|
||||
for (const bucket of [existingMaps.booked, existingMaps.unbookedImported]) {
|
||||
const entries = bucket.get(bucketKey)
|
||||
if (!entries) continue
|
||||
matched = entries.find(
|
||||
(e) =>
|
||||
e.isImportFeed &&
|
||||
e.source === batchSource &&
|
||||
e.externalId !== null &&
|
||||
!incomingIdSet.has(e.externalId) &&
|
||||
(cashAccountId === null ||
|
||||
e.cashAccountId === null ||
|
||||
e.cashAccountId === cashAccountId)
|
||||
)
|
||||
if (matched) break
|
||||
}
|
||||
if (matched) {
|
||||
result.shadow_scope_drift_candidates =
|
||||
(result.shadow_scope_drift_candidates ?? 0) + 1
|
||||
log.info('import dedup shadow: same-feed scope-drift candidate', {
|
||||
decision: 'same-feed-scope-drift',
|
||||
mode: 'shadow',
|
||||
bucket: bucketKey,
|
||||
unmatchedIncoming: unmatchedCount,
|
||||
driftCandidates: driftCount,
|
||||
incomingExternalId: raw.external_id,
|
||||
incomingDescription: description,
|
||||
incomingAmount: raw.amount,
|
||||
incomingSource: raw.import_source ?? null,
|
||||
cashAccountId,
|
||||
matchedStoredExternalId: matched.externalId,
|
||||
matchedStoredDescription: matched.desc,
|
||||
matchedStoredCashAccountId: matched.cashAccountId,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Insert new transaction (with SEK conversion for foreign currencies)
|
||||
const rateInfo = raw.currency && raw.currency !== 'SEK'
|
||||
? exchangeRatesByDate.get(`${raw.currency}|${raw.date}`)
|
||||
|
||||
Reference in New Issue
Block a user