Add/issue in absurdum (#739)

* feat(assets): allow editing fixed asset fields before depreciation

The fixed asset register only offered a "Dispose" action, so correcting a
mis-entered acquisition date/cost/category meant running the disposal flow —
which posts a real divestment voucher plus a Ch. 8a VAT adjustment.
Disproportionate and wrong for a data-entry fix.

Add an Edit action that allows correcting those fields directly, gated for
correctness:

- service: extend updateAsset() with category/acquisition_date/
  acquisition_cost; block the change once the asset is disposed or has posted
  depreciation (AssetCorrectionBlockedError) where it would desync posted
  vouchers from the register; realign the BAS triple on category change.
  Name, useful life, and method stay editable.
- api: extend the PATCH schema; annotate GET /api/assets with
  has_posted_depreciation so the UI can lock basis fields proactively.
- ui: EditAssetDialog + pencil action; disables date/cost/category when
  depreciation has been booked, with an inline explanation.
- errors: register ASSET_CORRECTION_BLOCKED (409).
- tests: unit tests for the guard; pg test for pre-disposal editability.

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

* feat(assets): also block basis edits when depreciation was hand-posted

The correction guard only consulted depreciation_schedules, so an
avskrivning booked as a manual journal entry (no schedule row) slipped
through and a basis correction was wrongly allowed.

Add a ledger scan: any posted credit to the asset's ackumulerade-
avskrivningar account (12x9) counts as depreciation. Entries that
depreciation_schedules attributes to a *different* asset are excluded, so
a sibling's engine avskrivning on a shared 12x9 account doesn't produce a
false block. What remains is depreciation tied to this asset (engine or
manual); a basis correction is blocked there and must go through storno.

Adds two unit tests: blocks on a hand-posted credit, allows when the only
12x9 credit belongs to a sibling's engine entry.

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

* fix(invoices): allow negative unit prices for discount lines

The invoice creation form rejected negative unit prices via a frontend
superRefine check, blocking valid discount lines (e.g. "Rabatt -100").
The unit_price error was never rendered inline, so submission failed
silently. The backend schema already allows negative unit prices (see
CreateInvoiceItemSchema test), so the form was simply out of sync.

Remove the non-negative constraint; empty/NaN prices are still rejected
by the base z.number() type. Drop the now-unused validation_price_positive
translation key from both locale files.

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

* feat(invoices): allow editing draft invoices

Drafts could be saved but not edited — the only way to change a draft's
lines, customer, dates or amounts was to delete and recreate it. Add a
"Redigera" action on draft invoices that opens the invoice editor
pre-filled with the draft and saves changes in place.

A verifikat is only created when an invoice is sent (or paid, under
kontantmetoden), so every status=draft invoice is uncommitted and safe to
edit; sent/paid invoices stay immutable and still require a credit note.

- Extract buildInvoiceWriteData() with the shared validation + computation
  (VAT rules, ROT/RUT, accruals, totals, currency, item rows); POST now
  uses it too, behaviour unchanged.
- Add UpdateInvoiceSchema and PATCH /api/invoices/[id], guarded to drafts
  (status=draft, no journal entry, not self-billed); number and status are
  preserved and no invoice.created is emitted.
- Extract the invoice creator into a shared InvoiceEditor with create /
  edit modes; /invoices/new is now a thin wrapper and /invoices/[id]/edit
  is the new edit page.
- Add a "Redigera" button on draft invoice detail pages + sv/en strings.
- Tests for the builder, UpdateInvoiceSchema and the PATCH route.

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

* feat(reports): make Huvudbok findable via account/saldo search terms

Searching the command palette for natural phrases like 'saldo per konto', 'kontoutdrag', 'kontoanalys' or 'transaktioner per konto' returned nothing, so users couldn't find the general ledger. Enrich the Huvudbok entry's keywords with those synonyms, and let Saldobalans and Balansrapport match 'saldo per konto' too since they are genuinely per-account balance views.

Companion change — the clearer Huvudbok report description ('Saldo och alla transaktioner per konto') — already landed in d5f474cb.

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

* feat(settings): let users edit their personal name

Add an editable Namn field to /settings/account that updates profiles.full_name and best-effort syncs auth user_metadata. Previously the personal name was only ever set from BankID's legal name at signup with no way to correct it, so users whose tilltalsnamn isn't their first given name were greeted by the wrong name (and email/password users had no name at all).

New POST /api/user/profile route (requireAuth, RLS-scoped update) mirrors /api/user/locale. sv/en strings added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(invoices): per-invoice öresavrundning override

Add a display-only öresavrundning flag per invoice that wins over the
company-wide setting. Resolution order in getDisplayTotal: per-invoice
override -> company setting -> default-on. The stored total and the booked
verifikat keep the exact öre; only the rendered total changes.

Supplier invoices gain the same flag but resolve a null to off (they never
had rounding historically), exposed via a toggle on the new-invoice form
and a rounding row on the detail page.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(transactions): warn on possible duplicate before booking

Before committing a transaction (via book or categorize), detect an
already-booked sibling with the same date and amount and return a 409
TRANSACTION_BOOK_POSSIBLE_DUPLICATE instead of silently double-booking.

The user can override with force=true, which must be bound to the reviewed
sibling via expected_duplicate_transaction_id; the candidate is re-detected
server-side, so a stale or guessed id is rejected with
TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH. Detection is fail-open on the
non-force path and fail-closed under force.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(transactions): shadow-mode scope-drift dedup counter in bank ingest

Count rows that an enforcing same-feed scope-drift rule WOULD treat as
re-imports (the IBAN-drift re-imports the external_id check misses) and
surface it as IngestResult.shadow_scope_drift_candidates. Nothing is
blocked yet -- the counter only measures how often the rule would fire so
it can be validated against real data before enforcement.

Also gitignore scripts/delete-duplicate-transactions.ts: a destructive,
hand-run cleanup tool kept out of the repo so it can't run in CI/cron or be
mistaken for a supported feature.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(bokslut): base bolagsskatt on post-disposition result

Bokslutsdispositioner are booked as source_type='year_end', which the
income statement excludes, so net_result alone overstates resultat före
skatt and the booked tax ignored the periodiseringsfond avsättning (too-high
tax, ÅR/INK2 mismatch).

calculateBolagsskatt now accepts resultBeforeTaxOverride. The preview builder
mirrors each proposal's P&L effect (+återföring, -avsättning, -SLP) onto the
pre-disposition result; the commit path sums the already-posted dispositions
via the new sumPostedYearEndDispositions (class 88 + 7533) since bolagsskatt
is committed last.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(settings): fiscal years manager

Add a FiscalYearsManager to the bookkeeping settings that lists fiscal
periods with their status (closed > locked > open) and creates the next
year via CreatePeriodDialog, seeded to chain forward from the latest
period end.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(api): return 400 when locking a period with unbooked transactions

lockPeriod() refuses to lock a period that still has uncategorized business
transactions. Detect that message in the lock route and surface it as a
clear PERIOD_HAS_UNBOOKED_TRANSACTIONS (400) instead of a generic 500.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(invoices): implement isEditableInvoiceDraft utility and apply it across invoice edit routes
feat(transactions): log duplicate dismissal events in behandlingshistorik
test(invoices): add tests for isEditableInvoiceDraft function
test(transactions): enhance tests to verify behandlingshistorik logging
refactor(bokslut): update tax calculation test descriptions for clarity

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-06-16 10:42:37 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent d95a0b6105
commit 8322830f46
55 changed files with 6049 additions and 2376 deletions
+5
View File
@@ -90,6 +90,11 @@ supabase/.branches/
# Local-only SIE test fixtures — may contain real/scrubbed company data, never commit
tests/fixtures/sie/
# Local-only DESTRUCTIVE duplicate-cleanup tooling — one-off, run by hand against
# real räkenskapsinformation. Deliberately NOT committed so it can never run in
# CI/cron and so its logic isn't mistaken for a supported product feature.
scripts/delete-duplicate-transactions.ts
# Diagnostic/cleanup tooling under /scripts is tracked, but the DATA those
# scripts read or emit (ledger dumps, reconciliation exports) is real customer
# räkenskapsinformation — never commit it. Keep the .ts/.sql tooling, ignore the data.
+39 -7
View File
@@ -10,7 +10,7 @@ import { Badge } from '@/components/ui/badge'
import { PageHeader } from '@/components/ui/page-header'
import { EmptyState } from '@/components/ui/empty-state'
import { Skeleton } from '@/components/ui/skeleton'
import { Package, Plus } from 'lucide-react'
import { Package, Pencil, Plus } from 'lucide-react'
import {
Table,
TableBody,
@@ -22,6 +22,10 @@ import {
import { formatCurrency, formatDate } from '@/lib/utils'
import type { Asset, AssetCategory } from '@/types'
import { CreateAssetDialog } from '@/components/bookkeeping/assets/CreateAssetDialog'
import { EditAssetDialog } from '@/components/bookkeeping/assets/EditAssetDialog'
/** GET /api/assets annotates each row with whether depreciation has posted. */
type AssetRow = Asset & { has_posted_depreciation?: boolean }
const CATEGORY_LABEL_KEYS: Record<AssetCategory, string> = {
immaterial: 'category_immaterial',
@@ -36,9 +40,10 @@ const CATEGORY_LABEL_KEYS: Record<AssetCategory, string> = {
export default function AssetsPage() {
const t = useTranslations('assets')
const [assets, setAssets] = useState<Asset[] | null>(null)
const [assets, setAssets] = useState<AssetRow[] | null>(null)
const [error, setError] = useState<string | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [editing, setEditing] = useState<AssetRow | null>(null)
const [reloadKey, setReloadKey] = useState(0)
@@ -51,7 +56,7 @@ export default function AssetsPage() {
setError(t('load_failed'))
return
}
const { data } = (await res.json()) as { data: Asset[] }
const { data } = (await res.json()) as { data: AssetRow[] }
if (cancelled) return
setError(null)
setAssets(data)
@@ -69,6 +74,11 @@ export default function AssetsPage() {
setReloadKey((k) => k + 1)
}, [])
const handleSaved = useCallback(() => {
setEditing(null)
setReloadKey((k) => k + 1)
}, [])
return (
<div className="space-y-8">
<PageHeader
@@ -150,11 +160,21 @@ export default function AssetsPage() {
</TableCell>
<TableCell className="text-right">
{!asset.disposed_at && (
<Link href={`/assets/${asset.id}/dispose`}>
<Button variant="ghost" size="sm">
{t('action_dispose')}
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => setEditing(asset)}
>
<Pencil className="mr-1 h-4 w-4" />
{t('action_edit')}
</Button>
</Link>
<Link href={`/assets/${asset.id}/dispose`}>
<Button variant="ghost" size="sm">
{t('action_dispose')}
</Button>
</Link>
</div>
)}
</TableCell>
</TableRow>
@@ -167,6 +187,18 @@ export default function AssetsPage() {
)}
<CreateAssetDialog open={dialogOpen} onOpenChange={setDialogOpen} onCreated={handleCreated} />
{editing && (
<EditAssetDialog
key={editing.id}
asset={editing}
open={editing !== null}
onOpenChange={(open) => {
if (!open) setEditing(null)
}}
onSaved={handleSaved}
/>
)}
</div>
)
}
@@ -0,0 +1,87 @@
'use client'
import { useEffect, useState, use } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { createClient } from '@/lib/supabase/client'
import { useToast } from '@/components/ui/use-toast'
import { Loader2 } from 'lucide-react'
import InvoiceEditor, { type InvoiceForEdit } from '@/components/invoices/InvoiceEditor'
import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
import type { InvoiceItem } from '@/types'
/**
* Edit an existing DRAFT invoice. Loads the invoice + items, guards that it is
* still an editable draft (no committed verifikat, not sent, not self-billed),
* then hands it to the shared <InvoiceEditor> in edit mode. The PATCH route
* enforces the same guard server-side; this just avoids opening a dead form.
*/
export default function EditInvoicePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
const router = useRouter()
const { toast } = useToast()
const supabase = createClient()
const t = useTranslations('invoice_detail')
const [invoice, setInvoice] = useState<InvoiceForEdit | null>(null)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
let cancelled = false
;(async () => {
const { data, error } = await supabase
.from('invoices')
.select('*, customer:customers(*), items:invoice_items(*)')
.eq('id', id)
.single()
if (cancelled) return
if (error || !data) {
toast({
title: t('load_failed_title'),
description: t('load_failed_description'),
variant: 'destructive',
})
router.replace('/invoices')
return
}
// Only drafts (no committed verifikat, not sent, not a received
// self-billing document) may be edited — shared predicate, the same one
// the PATCH route enforces server-side.
const editable = isEditableInvoiceDraft(data)
if (!editable) {
toast({
title: t('edit_not_allowed_title'),
description: t('edit_not_allowed_description'),
variant: 'destructive',
})
router.replace(`/invoices/${id}`)
return
}
// The editor's field array expects items in display order.
if (Array.isArray(data.items)) {
data.items.sort((a: InvoiceItem, b: InvoiceItem) => a.sort_order - b.sort_order)
}
setInvoice(data as InvoiceForEdit)
setIsLoading(false)
})()
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id])
if (isLoading || !invoice) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
)
}
return <InvoiceEditor mode="edit" initial={invoice} />
}
+14
View File
@@ -14,6 +14,7 @@ import { formatCurrency, formatDate, cn } from '@/lib/utils'
import { getVatTreatmentLabel } from '@/lib/invoices/vat-rules'
import { invoiceDisplayNumber } from '@/lib/invoices/display'
import { getDisplayTotal } from '@/lib/invoices/rounding'
import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
import {
Loader2,
ArrowLeft,
@@ -31,6 +32,7 @@ import {
Trash2,
Lock,
CalendarClock,
Pencil,
} from 'lucide-react'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import PaymentBookingDialog from '@/components/invoices/PaymentBookingDialog'
@@ -519,6 +521,10 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
// Self-billing invoices we received: the document is the counterparty's, so
// there is no own PDF to render and no send step — it arrives already booked.
const isSelfBilled = !!invoice.is_self_billed
// A draft (no committed verifikat, not sent, not self-billed) can be edited
// in place — header + lines — via /invoices/{id}/edit. Sent/paid invoices are
// immutable (BFL); they are corrected with a credit note instead.
const isEditableDraft = isEditableInvoiceDraft(invoice)
const hasAccruedItems = invoice.items.some(itemHasAccrual)
return (
<div className="space-y-8">
@@ -559,6 +565,14 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
{/* Actions */}
<div className="flex flex-wrap items-center gap-2">
{isEditableDraft && canWrite && (
<Link href={`/invoices/${invoice.id}/edit`}>
<Button variant="outline">
<Pencil className="mr-2 h-4 w-4" />
{t('edit_draft')}
</Button>
</Link>
)}
{isProforma && invoice.status !== 'cancelled' && (
<Button
onClick={convertToInvoice}
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -139,7 +139,7 @@ export default function InvoicesPage() {
.filter(isOutstandingReceivable)
.reduce((sum, i) => {
if (i.currency === 'SEK') {
return sum + getDisplayTotal({ total: Number(i.total), currency: 'SEK' }, { ore_rounding: oreRounding }).displayed
return sum + getDisplayTotal({ total: Number(i.total), currency: 'SEK', ore_rounding: i.ore_rounding }, { ore_rounding: oreRounding }).displayed
}
return sum + Number(i.total_sek || i.total)
}, 0),
@@ -289,7 +289,7 @@ export default function InvoicesPage() {
const statusVariant: InvoiceStatusVariant | 'outline' = isUnsentInvoice ? 'outline' : status.variant
const relativeTime = invoice.due_date ? getRelativeTimeLabel(invoice.due_date, invoice.status) : null
const displayedTotal = getDisplayTotal(
{ total: Number(invoice.total), currency: invoice.currency },
{ total: Number(invoice.total), currency: invoice.currency, ore_rounding: invoice.ore_rounding },
{ ore_rounding: oreRounding },
).displayed
return (
+2 -2
View File
@@ -81,7 +81,7 @@ export default async function DashboardPage() {
.eq('journal_entry.status', 'posted')
.eq('journal_entry.company_id', companyId)
.gte('journal_entry.entry_date', startOfYearStr),
supabase.from('invoices').select('total, total_sek, vat_amount, vat_amount_sek, status').eq('company_id', companyId).in('status', ['sent', 'overdue']).is('credited_invoice_id', null),
supabase.from('invoices').select('total, total_sek, vat_amount, vat_amount_sek, status, ore_rounding').eq('company_id', companyId).in('status', ['sent', 'overdue']).is('credited_invoice_id', null),
supabase.from('bank_connections').select('id, accounts_data, status, consent_expires, bank_name').eq('company_id', companyId).eq('status', 'active'),
supabase.from('deadlines').select('*, customer:customers(id, name)').eq('company_id', companyId).eq('is_completed', false)
.or(`due_date.lt.${today},due_date.lte.${nextWeek}`).order('due_date', { ascending: true }),
@@ -191,7 +191,7 @@ export default async function DashboardPage() {
// total matches what the user sees on the invoice list when the setting is on.
const unpaidTotal = (unpaidInvoices || []).reduce(
(sum, inv) => sum + getDisplayTotal(
{ total: Number(inv.total_sek || inv.total), currency: 'SEK' },
{ total: Number(inv.total_sek || inv.total), currency: 'SEK', ore_rounding: inv.ore_rounding },
settings,
).displayed,
0
@@ -23,6 +23,7 @@ import { AccountNumber } from '@/components/ui/account-number'
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import { formatCurrency } from '@/lib/utils'
import { getDisplayTotal } from '@/lib/invoices/rounding'
import type { SupplierInvoice, SupplierInvoiceItem, SupplierInvoicePayment, BASAccount } from '@/types'
interface EditableLine {
@@ -422,6 +423,15 @@ export default function SupplierInvoiceDetailPage() {
const items = (invoice.items || []) as SupplierInvoiceItem[]
const payments = (invoice.payments || []) as SupplierInvoicePayment[]
// Display-only öresavrundning. The stored total/booked verifikat keep the
// exact öre; this only adjusts the rendered total. Supplier invoices never
// had rounding historically, so a null flag resolves to off (company arg
// false) — only an explicit per-invoice `true` rounds the display.
const rounding = getDisplayTotal(
{ total: invoice.total, currency: invoice.currency, ore_rounding: invoice.ore_rounding },
{ ore_rounding: false },
)
return (
<div className="space-y-6 max-w-4xl">
{/* Header */}
@@ -601,9 +611,15 @@ export default function SupplierInvoiceDetailPage() {
<span className="text-muted-foreground">{t('vat_label')}</span>
<span className="font-mono">{formatAmount(invoice.vat_amount)} {invoice.currency}</span>
</div>
{rounding.applies && (
<div className="flex justify-between">
<span className="text-muted-foreground">{t('ore_rounding')}</span>
<span className="font-mono">{formatAmount(rounding.roundingDelta)} {invoice.currency}</span>
</div>
)}
<div className="flex justify-between font-bold text-base pt-2 border-t">
<span>{t('total_label')}</span>
<span className="font-mono">{formatAmount(invoice.total)} {invoice.currency}</span>
<span className="font-mono">{formatAmount(rounding.displayed)} {invoice.currency}</span>
</div>
<div className="flex justify-between pt-2">
<span className="text-muted-foreground">{t('paid_label')}</span>
@@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import AiFilledIndicator from '@/components/ui/ai-filled-indicator'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
@@ -274,6 +275,9 @@ export default function NewSupplierInvoicePage() {
const [accounts, setAccounts] = useState<BASAccount[]>([])
const [entityType, setEntityType] = useState<EntityType>('enskild_firma')
const [accountingMethod, setAccountingMethod] = useState<'accrual' | 'cash'>('accrual')
// Öresavrundning is display-only; defaults to the company-wide setting and is
// overridable per invoice via the toggle in the totals section.
const [oreRounding, setOreRounding] = useState<boolean>(true)
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
const [periodsLoaded, setPeriodsLoaded] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
@@ -625,6 +629,7 @@ export default function NewSupplierInvoicePage() {
if (data?.accounting_method === 'cash' || data?.accounting_method === 'accrual') {
setAccountingMethod(data.accounting_method)
}
if (typeof data?.ore_rounding === 'boolean') setOreRounding(data.ore_rounding)
} catch {
// Default to enskild_firma / accrual
}
@@ -824,6 +829,7 @@ export default function NewSupplierInvoicePage() {
payment_reference: data.payment_reference || undefined,
notes: data.notes || undefined,
paid_with_private_funds: data.paid_with_private_funds,
ore_rounding: oreRounding,
items: data.items.map((item) => ({
description: item.description,
amount: item.amount,
@@ -1772,6 +1778,23 @@ export default function NewSupplierInvoicePage() {
<span>{t('total_label')}</span>
<span className="font-mono sm:w-32 text-right">{formatCurrency(total, watchedCurrency)}</span>
</div>
{/* Öresavrundning — display-only rounding of the displayed total to
whole kronor (SEK only). The registered amount and the booked
verifikat keep the exact öre; this only changes what's shown. */}
{(watchedCurrency || 'SEK') === 'SEK' && (
<div className="flex items-center justify-between gap-4 pt-3 mt-1 border-t">
<div className="space-y-0.5">
<Label htmlFor="ore-rounding" className="text-sm">{t('ore_rounding_label')}</Label>
<p className="text-xs text-muted-foreground">{t('ore_rounding_help')}</p>
</div>
<Switch
id="ore-rounding"
checked={oreRounding}
onCheckedChange={setOreRounding}
aria-label={t('ore_rounding_label')}
/>
</div>
)}
</div>
</CardContent>
</Card>
+21 -1
View File
@@ -6,7 +6,18 @@ import { validateBody } from '@/lib/api/validate'
import { K3ComponentSchema } from '@/lib/api/schemas'
import { getAsset, updateAsset } from '@/lib/bokslut/assets/asset-service'
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
import type { DepreciationMethod } from '@/types'
import type { AssetCategory, DepreciationMethod } from '@/types'
const ASSET_CATEGORIES: readonly AssetCategory[] = [
'immaterial',
'building',
'land_improvement',
'machinery',
'equipment',
'vehicle',
'computer',
'other_tangible',
] as const
const DEPRECIATION_METHODS: readonly DepreciationMethod[] = [
'linear',
@@ -19,6 +30,15 @@ const UpdateAssetSchema = z
.object({
name: z.string().min(1).optional(),
notes: z.string().nullable().optional(),
// Acquisition-basis corrections. The service (updateAsset) only permits
// these while the asset is neither disposed nor depreciated, returning
// ASSET_CORRECTION_BLOCKED (409) otherwise — they redefine the
// depreciation basis, so a post-posting change must go through storno.
category: z
.enum(ASSET_CATEGORIES as unknown as [AssetCategory, ...AssetCategory[]])
.optional(),
acquisition_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
acquisition_cost: z.number().positive().optional(),
salvage_value: z.number().nonnegative().optional(),
useful_life_months: z.number().int().positive().optional(),
depreciation_method: z
+27 -1
View File
@@ -204,7 +204,33 @@ export const GET = withRouteContext('assets.list', async (request, ctx) => {
const activeOnly = url.searchParams.get('active') === 'true'
try {
const data = await listAssets(supabase, companyId, { activeOnly })
return NextResponse.json({ data })
// Annotate each asset with whether any depreciation has been posted
// against it. The UI uses this to lock the acquisition-basis fields
// (date/cost/category) — once avskrivningar are booked a correction must
// go through storno (the service enforces the same rule server-side).
const postedAssetIds = new Set<string>()
if (data.length > 0) {
const { data: posted, error } = await supabase
.from('depreciation_schedules')
.select('asset_id')
.eq('company_id', companyId)
.in(
'asset_id',
data.map((a) => a.id),
)
.not('journal_entry_id', 'is', null)
if (error) throw new Error(`Failed to load depreciation status: ${error.message}`)
for (const row of (posted ?? []) as { asset_id: string }[]) {
postedAssetIds.add(row.asset_id)
}
}
const annotated = data.map((asset) => ({
...asset,
has_posted_depreciation: postedAssetIds.has(asset.id),
}))
return NextResponse.json({ data: annotated })
} catch (err) {
return errorResponse(err, log, { requestId })
}
@@ -4,7 +4,10 @@ import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { validateBody } from '@/lib/api/validate'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import { calculateBolagsskatt } from '@/lib/bokslut/tax-provision/bolagsskatt-calculator'
import {
calculateBolagsskatt,
sumPostedYearEndDispositions,
} from '@/lib/bokslut/tax-provision/bolagsskatt-calculator'
import { calculateSarskildLoneskatt } from '@/lib/bokslut/tax-provision/sarskild-loneskatt-calculator'
import {
listExistingPeriodiseringsfonder,
@@ -205,10 +208,24 @@ async function computeProposal(
fiscalYear: number,
): Promise<ProposedDisposition | null> {
switch (item.kind) {
case 'bolagsskatt':
case 'bolagsskatt': {
// Dispositioner are booked as source_type='year_end', which the income
// statement excludes — so net_result alone overstates resultat före skatt.
// Add the already-posted dispositions back (avsättning −, återföring +,
// SLP −, överavskrivningar −); bolagsskatt is sorted LAST so they are
// committed by now. Without this the booked tax ignores the avsättning
// (the original customer bug — too-high tax, ÅR/INK2 mismatch).
const incomeStatement = await generateIncomeStatement(supabase, companyId, fiscalPeriodId)
const dispositionsEffect = await sumPostedYearEndDispositions(
supabase,
companyId,
fiscalPeriodId,
)
return calculateBolagsskatt(supabase, companyId, fiscalPeriodId, {
resultBeforeTaxOverride: incomeStatement.net_result + dispositionsEffect,
manualAdjustments: item.manualAdjustments,
})
}
case 'sarskild_loneskatt':
return calculateSarskildLoneskatt(supabase, companyId, fiscalPeriodId, {
manualAdjustment: item.manualAdjustment,
@@ -0,0 +1,78 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: vi.fn(),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/core/bookkeeping/period-service', () => ({
lockPeriod: vi.fn(),
}))
import { requireAuth } from '@/lib/auth/require-auth'
import { lockPeriod } from '@/lib/core/bookkeeping/period-service'
import { POST } from '../route'
function lockRequest(): Request {
return createMockRequest('/api/bookkeeping/fiscal-periods/p1/lock', { method: 'POST' })
}
function mockAuth() {
;(requireAuth as ReturnType<typeof vi.fn>).mockResolvedValue({
user: { id: 'user-1' },
supabase: {},
error: null,
})
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('POST /api/bookkeeping/fiscal-periods/[id]/lock', () => {
it('locks the period and returns it on success', async () => {
mockAuth()
;(lockPeriod as ReturnType<typeof vi.fn>).mockResolvedValue({ id: 'p1', locked_at: '2026-06-15T00:00:00Z' })
const res = await POST(lockRequest(), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.id).toBe('p1')
})
// Regression: an unbooked-transactions failure must surface as a clear 400,
// not a generic 500. lockPeriod throws a plain Error (no code) with the
// Swedish count message; the route maps it to PERIOD_HAS_UNBOOKED_TRANSACTIONS.
it('maps the unbooked-transactions error to a 400, not a 500', async () => {
mockAuth()
;(lockPeriod as ReturnType<typeof vi.fn>).mockRejectedValue(
new Error('Kan inte låsa period: 3 affärstransaktion(er) saknar bokföring. Bokför alla transaktioner innan perioden låses.'),
)
const res = await POST(lockRequest(), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error.code).toBe('PERIOD_HAS_UNBOOKED_TRANSACTIONS')
})
it('maps an already-locked period to a 409', async () => {
mockAuth()
;(lockPeriod as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('Period is already locked'))
const res = await POST(lockRequest(), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(409)
const body = await res.json()
expect(body.error.code).toBe('PERIOD_LOCK_ALREADY_LOCKED')
})
it('maps a missing period to a 404', async () => {
mockAuth()
;(lockPeriod as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('Fiscal period not found'))
const res = await POST(lockRequest(), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(404)
const body = await res.json()
expect(body.error.code).toBe('PERIOD_NOT_FOUND')
})
})
@@ -30,6 +30,15 @@ export const POST = withRouteContext(
details: { reason: message },
})
}
// lockPeriod() refuses to lock a period that still has uncategorized
// business transactions (the count is in the thrown message). Surface it
// as a clear 400 instead of letting it fall through to a generic 500.
if (/saknar bokföring|okategoriserade affärstransaktion/i.test(message)) {
return errorResponseFromCode('PERIOD_HAS_UNBOOKED_TRANSACTIONS', opLog, {
requestId,
details: { reason: message },
})
}
return errorResponse(err, opLog, { requestId })
}
},
@@ -0,0 +1,201 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
createMockRouteParams,
parseJsonResponse,
createQueuedMockSupabase,
makeInvoice,
makeCustomer,
} from '@/tests/helpers'
import { eventBus } from '@/lib/events'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
const mockGetVatRules = vi.fn()
const mockGetAvailableVatRates = vi.fn()
vi.mock('@/lib/invoices/vat-rules', () => ({
getVatRules: (...args: unknown[]) => mockGetVatRules(...args),
getAvailableVatRates: (...args: unknown[]) => mockGetAvailableVatRates(...args),
}))
vi.mock('@/lib/currency/riksbanken', () => ({
fetchExchangeRate: vi.fn().mockResolvedValue(null),
convertToSEK: vi.fn(),
}))
import { PATCH } from '../route'
const VALID_BODY = {
customer_id: '11111111-1111-4111-8111-111111111111',
invoice_date: '2026-06-15',
due_date: '2026-07-15',
currency: 'SEK',
items: [{ description: 'Konsult', quantity: 10, unit: 'tim', unit_price: 1000, vat_rate: 25 }],
}
function patch(id: string, body: unknown = VALID_BODY) {
return PATCH(
createMockRequest(`/api/invoices/${id}`, { method: 'PATCH', body }),
createMockRouteParams({ id }),
)
}
describe('PATCH /api/invoices/[id]', () => {
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
mockGetVatRules.mockReturnValue({
treatment: 'standard_25',
rate: 25,
momsRuta: '05',
reverseChargeText: undefined,
})
mockGetAvailableVatRates.mockReturnValue([
{ rate: 25, label: '25%', treatment: 'standard_25' },
{ rate: 0, label: '0%', treatment: 'exempt' },
])
})
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const { status } = await parseJsonResponse(await patch('inv-1'))
expect(status).toBe(401)
})
it('returns 400 on an invalid body', async () => {
const { status } = await parseJsonResponse(await patch('inv-1', { currency: 'SEK' }))
expect(status).toBe(400)
})
it('returns 404 INVOICE_NOT_FOUND when the invoice does not exist', async () => {
enqueue({ data: null, error: { message: 'not found' } })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(404)
expect(body.error.code).toBe('INVOICE_NOT_FOUND')
})
it('returns 409 INVOICE_UPDATE_NOT_DRAFT for a sent invoice', async () => {
enqueue({
data: { id: 'inv-1', status: 'sent', invoice_number: 'F-1', journal_entry_id: null, is_self_billed: false },
error: null,
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_NOT_DRAFT')
})
it('refuses to edit a draft that already carries a journal entry', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: 'F-1', journal_entry_id: 'je-1', is_self_billed: false },
error: null,
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_NOT_DRAFT')
})
it('refuses to edit a received self-billing invoice', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: true },
error: null,
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_NOT_DRAFT')
})
it('returns 404 INVOICE_CUSTOMER_NOT_FOUND when the customer is missing', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: false },
error: null,
})
enqueue({ data: null, error: { message: 'no customer' } }) // customer lookup
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(404)
expect(body.error.code).toBe('INVOICE_CUSTOMER_NOT_FOUND')
})
it('updates a draft (header + items) and returns the refreshed invoice without emitting invoice.created', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit')
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: 'F-1', journal_entry_id: null, is_self_billed: false },
error: null,
}) // existing
enqueue({ data: makeCustomer({ id: 'customer-1', customer_type: 'swedish_business' }), error: null }) // customer
enqueue({ data: { vat_registered: true }, error: null }) // company_settings.vat_registered
enqueue({ data: [{ id: 'inv-1' }], error: null }) // update ... select('id')
enqueue({ data: [], error: null }) // delete invoice_items
enqueue({ data: null, error: null }) // insert invoice_items
enqueue({
data: makeInvoice({ id: 'inv-1', status: 'draft', invoice_number: 'F-1', total: 12500 }),
error: null,
}) // re-select complete invoice
const { status, body } = await parseJsonResponse<{ data: { id: string; status: string; invoice_number: string } }>(
await patch('inv-1'),
)
expect(status).toBe(200)
expect(body.data.id).toBe('inv-1')
// Editing a draft never re-issues it — status + number are unchanged and no
// invoice.created event is emitted.
expect(body.data.status).toBe('draft')
expect(body.data.invoice_number).toBe('F-1')
expect(emitSpy).not.toHaveBeenCalled()
})
it('returns 409 when the draft is sent/finalized concurrently (0-row update)', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: false },
error: null,
}) // existing
enqueue({ data: makeCustomer({ id: 'customer-1', customer_type: 'swedish_business' }), error: null }) // customer
enqueue({ data: { vat_registered: true }, error: null }) // settings
enqueue({ data: [], error: null }) // update matched 0 rows (status flipped)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_NOT_DRAFT')
})
it('passes through a VAT-rule violation from the shared builder', async () => {
mockGetAvailableVatRates.mockReturnValue([{ rate: 0, label: '0%', treatment: 'reverse_charge' }])
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: false },
error: null,
}) // existing
enqueue({ data: makeCustomer({ id: 'customer-1', customer_type: 'eu_business', vat_number_validated: true }), error: null }) // customer
enqueue({ data: { vat_registered: true }, error: null }) // settings
const { body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(body.error.code).toBe('INVOICE_CREATE_VAT_RULE_VIOLATION')
})
})
+158 -1
View File
@@ -4,8 +4,14 @@ import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { createLogger } from '@/lib/logger'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { UpdateInvoiceSchema } from '@/lib/api/schemas'
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
import type { InvoiceDocumentType } from '@/types'
ensureInitialized() // Module-level — wires the audit-log handler for invoice.draft_deleted.
@@ -121,3 +127,154 @@ export async function DELETE(
return NextResponse.json({ data: { cancelled: true, invoice_number: invoice.invoice_number } })
}
/**
* PATCH /api/invoices/[id]
*
* Edit a DRAFT invoice (or proforma / delivery note) in place — header fields
* AND line items. Only drafts are editable: a journal entry (verifikat) is
* created when an invoice is sent (mark-sent / send) or, for kontantmetoden, at
* payment, so a draft has no committed entry and BFL immutability (guard rail #1)
* does not yet apply. Sent / paid / cancelled / credited invoices are immutable
* and must be reversed via a credit note instead.
*
* The invoice's number and status are preserved — editing never (re)allocates a
* number nor changes lifecycle state, and never emits invoice.created (numbered
* drafts already emitted it at create; unnumbered ones emit on finalize). The
* validation + computation is shared with POST /api/invoices via
* buildInvoiceWriteData so VAT rules, ROT/RUT, accruals and totals stay identical.
*/
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
'invoice.update',
async (request, { supabase, companyId, log: ctxLog, requestId }, { params }) => {
const { id } = await params
const validation = await validateBody(request, UpdateInvoiceSchema, {
log: ctxLog,
operation: 'invoice.update',
})
if (!validation.success) return validation.response
const input = validation.data
const documentType: InvoiceDocumentType = input.document_type || 'invoice'
// Fetch the target. Only drafts (not sent, no committed verifikat, not a
// received self-billing document) may be edited.
const { data: existing, error: fetchError } = await supabase
.from('invoices')
.select('id, status, invoice_number, journal_entry_id, is_self_billed')
.eq('id', id)
.eq('company_id', companyId!)
.single()
if (fetchError || !existing) {
return errorResponseFromCode('INVOICE_NOT_FOUND', ctxLog, { requestId })
}
// journal_entry_id is belt-and-suspenders — a draft shouldn't carry one,
// but if some flow ever booked it, refuse the edit (the entry is immutable).
// Shared predicate (lib/invoices/is-editable-draft) — the single source of
// truth the detail and edit pages also gate on, so the rule can't drift.
if (!isEditableInvoiceDraft(existing)) {
return errorResponseFromCode('INVOICE_UPDATE_NOT_DRAFT', ctxLog, { requestId })
}
// Resolve the (possibly changed) customer.
const { data: customer, error: customerError } = await supabase
.from('customers')
.select('*')
.eq('id', input.customer_id)
.eq('company_id', companyId!)
.single()
if (customerError || !customer) {
return errorResponseFromCode('INVOICE_CUSTOMER_NOT_FOUND', ctxLog, {
requestId,
details: { customerId: input.customer_id },
})
}
const build = await buildInvoiceWriteData({
supabase,
companyId: companyId!,
customer,
documentType,
input,
})
if (!build.ok) {
if ('dbError' in build) {
ctxLog.error('invoice write build failed on a DB lookup', build.dbError as Error)
return errorResponse(build.dbError, ctxLog, { requestId })
}
return errorResponseFromCode(build.code, ctxLog, { requestId, details: build.details })
}
// Update the draft row. invoice_number + status are intentionally NOT in
// build.invoiceFields, so they are preserved. The .eq('status','draft')
// guard turns a concurrent send/finalize into a 0-row update (race), rather
// than silently rewriting a now-issued invoice.
// Öresavrundning is display-only and optional in the update body. Persist
// it when the editor sent a value; otherwise strip it so a partial update
// can't reset a draft's stored flag (build defaults an absent flag to null).
const updateFields =
input.ore_rounding === undefined
? (() => {
const { ore_rounding: _oreRounding, ...rest } = build.invoiceFields
return rest
})()
: build.invoiceFields
const { data: updated, error: updateError } = await supabase
.from('invoices')
.update({ ...updateFields, updated_at: new Date().toISOString() })
.eq('id', id)
.eq('company_id', companyId!)
.eq('status', 'draft')
.select('id')
if (updateError) {
ctxLog.error('invoice update failed', updateError, { invoiceId: id })
return errorResponseFromCode('INVOICE_CREATE_INSERT_FAILED', ctxLog, {
requestId,
details: { pgCode: updateError.code, pgMessage: updateError.message },
})
}
if (!updated || updated.length === 0) {
return errorResponseFromCode('INVOICE_UPDATE_NOT_DRAFT', ctxLog, { requestId })
}
// Replace line items wholesale. A draft has no journal entry or linked docs,
// so delete + reinsert is safe and lets the user add / remove / reorder rows
// freely. invoice_items cascade nothing else.
const { error: deleteItemsError } = await supabase
.from('invoice_items')
.delete()
.eq('invoice_id', id)
if (deleteItemsError) {
ctxLog.error('invoice items delete failed on update', deleteItemsError, { invoiceId: id })
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', ctxLog, {
requestId,
details: { pgCode: deleteItemsError.code, pgMessage: deleteItemsError.message },
})
}
const itemsToInsert = build.items.map((item) => ({ ...item, invoice_id: id }))
const { error: itemsError } = await supabase.from('invoice_items').insert(itemsToInsert)
if (itemsError) {
ctxLog.error('invoice items insert failed on update', itemsError, { invoiceId: id })
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', ctxLog, {
requestId,
details: { pgCode: itemsError.code, pgMessage: itemsError.message },
})
}
const { data: completeInvoice } = await supabase
.from('invoices')
.select('*, customer:customers(*), items:invoice_items(*)')
.eq('id', id)
.single()
return NextResponse.json({ data: completeInvoice })
},
{ requireWrite: true },
)
+21 -312
View File
@@ -4,22 +4,10 @@ import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { CreateInvoiceSchema, CreateCreditNoteSchema } from '@/lib/api/schemas'
import type { EntityType, AccountingMethod, Invoice, CreditNote, InvoiceDocumentType } from '@/types'
import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
import { createCreditNoteJournalEntry } from '@/lib/bookkeeping/invoice-entries'
import { cancelSchedulesForSource } from '@/lib/bookkeeping/accruals/service'
import { DEFAULT_DEFERRED_REVENUE_ACCOUNT } from '@/lib/bookkeeping/accruals/account-suggestions'
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
import {
computeDeduction,
computeInvoiceDeductionTotal,
validateInvoice as validateRotRut,
} from '@/lib/invoices/rot-rut-rules'
import {
encryptPersonnummer,
extractLast4,
validatePersonnummer,
} from '@/lib/salary/personnummer'
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { Logger } from '@/lib/logger'
@@ -121,190 +109,26 @@ export const POST = withRouteContext(
})
}
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. Mirrors lib/pending-operations/commit.ts commitCreateInvoice.
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 invoiceInput.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 = invoiceInput.items.some(
(item) => item.accrual_period_start && item.accrual_period_end,
)
if (hasAccrualItems) {
if (documentType !== 'invoice') {
return errorResponseFromCode('INVOICE_CREATE_ACCRUAL_INVALID', log, {
requestId,
details: { reason: 'document_type', documentType },
})
}
if (vatRules.treatment === 'reverse_charge' || vatRules.treatment === 'export') {
return errorResponseFromCode('INVOICE_CREATE_ACCRUAL_INVALID', log, {
requestId,
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 errorResponseFromCode('INVOICE_CREATE_ACCRUAL_INVALID', log, {
requestId,
details: { reason: 'accounting_method' },
})
}
}
// Free-text rows carry no amounts and are excluded from totals + VAT.
const subtotal = invoiceInput.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 invoiceInput.items) {
if (item.line_type === 'text') continue
const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate
if (!allowedRates.has(itemRate)) {
return errorResponseFromCode('INVOICE_CREATE_VAT_RULE_VIOLATION', log, {
requestId,
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 — same posture as the
// server-recomputed ROT/RUT amounts.
const overrideAccounts = Array.from(
new Set(
invoiceInput.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) {
log.error('revenue account validation query failed', accountsError)
return errorResponse(accountsError, log, { requestId })
}
const validSet = new Set((validAccounts ?? []).map((a) => a.account_number))
const invalid = overrideAccounts.filter((a) => !validSet.has(a))
if (invalid.length > 0) {
return errorResponseFromCode('INVOICE_CREATE_REVENUE_ACCOUNT_INVALID', log, {
requestId,
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 = !!invoiceInput.deduction_housing_designation?.trim()
const personnummerRaw = invoiceInput.deduction_personnummer?.trim() || ''
const personnummerProvided = personnummerRaw.length > 0
const validateInput = invoiceInput.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 errorResponseFromCode('INVOICE_CREATE_ROT_RUT_VALIDATION', log, {
requestId,
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 errorResponseFromCode('INVOICE_CREATE_ROT_RUT_PERSONNUMMER_INVALID', log, {
requestId,
details: { error: pnValid.error },
})
}
deductionPersonnummerEncrypted = encryptPersonnummer(personnummerRaw)
deductionPersonnummerLast4 = extractLast4(personnummerRaw)
}
}
const uniqueRates = new Set(
invoiceInput.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 (invoiceInput.currency !== 'SEK') {
const rateData = await fetchExchangeRate(invoiceInput.currency)
if (rateData) {
exchangeRate = rateData.rate
exchangeRateDate = rateData.date
subtotalSek = convertToSEK(subtotal, exchangeRate)
vatAmountSek = convertToSEK(vatAmount, exchangeRate)
totalSek = convertToSEK(total, exchangeRate)
}
// Shared validation + computation (VAT rules, accrual guards, totals,
// revenue-account override checks, server-side ROT/RUT, currency, item
// rows). Identical to the PATCH (draft edit) path — see build-invoice-write.
const build = await buildInvoiceWriteData({
supabase,
companyId: companyId!,
customer,
documentType,
input: invoiceInput,
})
if (!build.ok) {
if ('dbError' in build) {
log.error('invoice write build failed on a DB lookup', build.dbError as Error)
return errorResponse(build.dbError, log, { requestId })
}
return errorResponseFromCode(build.code, log, { requestId, details: build.details })
}
// Delivery notes are always numbered at insert (ignores save_as_draft);
// invoices/proformas get their F-number below or at finalize.
let invoiceNumber: string | null = null
if (documentType === 'delivery_note') {
const { data: dnNumber } = await supabase.rpc('generate_delivery_note_number', {
@@ -318,39 +142,8 @@ export const POST = withRouteContext(
.insert({
user_id: user.id,
company_id: companyId,
customer_id: invoiceInput.customer_id,
invoice_number: invoiceNumber,
invoice_date: invoiceInput.invoice_date,
due_date: invoiceInput.due_date,
delivery_date: invoiceInput.delivery_date ?? null,
currency: invoiceInput.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,
// Initialize remaining_amount to total - deduction for real invoices
// so the open-invoice queries (InvoicePicker, AR ledger, supplier
// matching) treat newly-created invoices as fully unpaid for the
// CUSTOMER's share — the Skatteverket portion is on 1513 and will be
// cleared when the agency pays out, not by the customer payment.
// Proformas, delivery notes and quotes have no payment obligation,
// so they keep the 0 default.
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: invoiceInput.your_reference,
our_reference: invoiceInput.our_reference,
notes: invoiceInput.notes,
document_type: documentType,
deduction_total: deductionTotal,
deduction_personnummer_encrypted: deductionPersonnummerEncrypted,
deduction_personnummer_last4: deductionPersonnummerLast4,
...build.invoiceFields,
})
.select()
.single()
@@ -363,91 +156,7 @@ export const POST = withRouteContext(
})
}
const items = invoiceInput.items.map((item, index) => {
// Free-text / blank rows carry no amounts and never book — store the
// description only and zero everything else.
if (item.line_type === 'text') {
return {
invoice_id: invoice.id,
sort_order: index,
line_type: 'text',
description: item.description ?? '',
quantity: 0,
unit: '',
unit_price: 0,
line_total: 0,
vat_rate: 0,
vat_amount: 0,
// Keys must match the product branch exactly — PostgREST rejects a
// bulk insert whose objects have differing key sets.
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 (rules above strip them
// implicitly because validateRotRut isn't invoked).
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 {
invoice_id: invoice.id,
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 already
// 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,
}
})
const items = build.items.map((item) => ({ ...item, invoice_id: invoice.id }))
const { error: itemsError } = await supabase.from('invoice_items').insert(items)
+2
View File
@@ -248,6 +248,8 @@ export const POST = withRouteContext(
remaining_amount: paidPrivately ? 0 : totalRounded,
paid_at: paidPrivately ? new Date().toISOString() : null,
notes: body.notes || null,
// Display-only öresavrundning override; null = off (no retroactive rounding).
ore_rounding: body.ore_rounding ?? null,
})
.select()
.single()
@@ -32,9 +32,26 @@ vi.mock('@/lib/bookkeeping/engine', () => ({
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
}))
// Booking-time duplicate guard — mocked so route tests exercise the WIRING
// (warn / force / mismatch); the detection query itself is unit-tested in
// lib/transactions/__tests__/booking-duplicate-detection.test.ts.
const mockDetectDup = vi.fn()
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
detectBookedDuplicateTransaction: (...args: unknown[]) => mockDetectDup(...args),
}))
// Behandlingshistorik append — mocked so we can assert the dismissal is
// persisted without reaching the service-role client.
const mockAppendProcessingHistory = vi.fn()
vi.mock('@/lib/processing-history/append', () => ({
appendProcessingHistory: (...args: unknown[]) => mockAppendProcessingHistory(...args),
}))
import { POST } from '../route'
const VALID_UUID = '550e8400-e29b-41d4-a716-446655440000'
const SIBLING_UUID = '660e8400-e29b-41d4-a716-446655440111'
const OTHER_UUID = '770e8400-e29b-41d4-a716-446655440222'
describe('POST /api/transactions/[id]/book', () => {
const mockUser = { id: 'user-1', email: 'test@test.se' }
@@ -53,6 +70,9 @@ describe('POST /api/transactions/[id]/book', () => {
reset()
eventBus.clear()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
// No booking-duplicate by default; guard tests override per-case.
mockDetectDup.mockResolvedValue(null)
mockAppendProcessingHistory.mockResolvedValue('evt-1')
})
it('returns 401 when not authenticated', async () => {
@@ -197,4 +217,110 @@ describe('POST /api/transactions/[id]/book', () => {
expect(status).toBe(500)
expect(body.error).toBe('Failed to update transaction')
})
// ── Booking-time duplicate guard ──────────────────────────────────────
it('returns 409 duplicate warning when a booked sibling shares date+amount', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
enqueue({ data: tx, error: null }) // fetch
mockDetectDup.mockResolvedValue({
transaction_id: SIBLING_UUID,
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: 'redan bokförd',
amount: -500,
})
const request = createMockRequest('/api/transactions/tx-1/book', { method: 'POST', body: validBody })
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { candidate: { transaction_id: string; voucher_label: string } } }
}>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_BOOK_POSSIBLE_DUPLICATE')
expect(body.error.details.candidate.transaction_id).toBe(SIBLING_UUID)
expect(body.error.details.candidate.voucher_label).toBe('A142')
// Critically: no verifikat is created when a duplicate is flagged.
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
// Blocking a duplicate is not a dismissal — nothing is logged.
expect(mockAppendProcessingHistory).not.toHaveBeenCalled()
})
it('books when force=true and the expected sibling still matches', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
const je = makeJournalEntry({ id: 'je-new' })
enqueue({ data: tx, error: null }) // fetch
enqueue({ data: null, error: null }) // update
mockDetectDup.mockResolvedValue({
transaction_id: SIBLING_UUID,
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: null,
amount: -500,
})
mockCreateJournalEntry.mockResolvedValue(je)
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: { ...validBody, force: true, expected_duplicate_transaction_id: SIBLING_UUID },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ success: boolean; journal_entry_id: string }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.journal_entry_id).toBe('je-new')
expect(mockCreateJournalEntry).toHaveBeenCalledTimes(1)
// The dismissal is recorded to behandlingshistorik (BFNAR 2013:2 kap 8).
expect(mockAppendProcessingHistory).toHaveBeenCalledWith(
expect.objectContaining({
eventType: 'BankTransactionDuplicateDismissed',
aggregateType: 'BankTransaction',
aggregateId: 'tx-1',
actor: { type: 'user', id: 'user-1' },
payload: expect.objectContaining({
transaction_id: 'tx-1',
dismissed_transaction_id: SIBLING_UUID,
}),
}),
)
})
it('rejects force=true when the expected sibling no longer matches the detected one', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
enqueue({ data: tx, error: null }) // fetch
mockDetectDup.mockResolvedValue({
transaction_id: SIBLING_UUID, // server detects this one…
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: null,
amount: -500,
})
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: { ...validBody, force: true, expected_duplicate_transaction_id: OTHER_UUID }, // …caller claims another
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH')
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
})
it('returns 400 when force=true is sent without expected_duplicate_transaction_id', async () => {
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: { ...validBody, force: true },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse<{ error: string }>(response)
expect(status).toBe(400)
})
})
+76 -1
View File
@@ -8,6 +8,10 @@ import { validateBody } from '@/lib/api/validate'
import { BookTransactionSchema } from '@/lib/api/schemas'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { detectBookedDuplicateTransaction } from '@/lib/transactions/booking-duplicate-detection'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { createLogger } from '@/lib/logger'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import type { Transaction } from '@/types'
ensureInitialized()
@@ -32,7 +36,7 @@ export async function POST(
const validation = await validateBody(request, BookTransactionSchema)
if (!validation.success) return validation.response
const { fiscal_period_id, entry_date, description, lines } = validation.data
const { fiscal_period_id, entry_date, description, lines, force, expected_duplicate_transaction_id } = validation.data
// Fetch transaction (validates ownership)
const { data: transaction, error: fetchError } = await supabase
@@ -54,6 +58,77 @@ export async function POST(
)
}
// Booking-time duplicate guard: if another transaction with the same
// date+amount+account is already booked, booking this one would double-count
// one real event (two verifikationer — felaktig bokföring per BFL). Warn; the
// user confirms with force=true bound to the reviewed sibling. Mirrors the
// match-invoice soft-duplicate guard.
const dupLog = createLogger('transactions.book', { companyId, userId: user.id })
try {
const candidate = await detectBookedDuplicateTransaction(supabase, companyId, {
id,
date: transaction.date,
amount: transaction.amount,
cash_account_id: transaction.cash_account_id ?? null,
})
if (!force) {
if (candidate) {
return errorResponseFromCode('TRANSACTION_BOOK_POSSIBLE_DUPLICATE', dupLog, {
details: { candidate },
})
}
} else if (!candidate || candidate.transaction_id !== expected_duplicate_transaction_id) {
// force=true is bound to a specific candidate. Re-detect and refuse the
// bypass unless it still matches, so a guessed id can't wave the guard.
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', dupLog, {
details: {
expected_duplicate_transaction_id: expected_duplicate_transaction_id ?? null,
detected_transaction_id: candidate?.transaction_id ?? null,
},
})
} else {
dupLog.warn('booking-time duplicate guard bypassed', {
reason: 'force=true',
transactionId: id,
dismissedTransactionId: candidate.transaction_id,
})
// Persist the dismissal to behandlingshistorik (BFNAR 2013:2 kap 8): the
// decision to book over a DETECTED possible double-booking is a
// bookkeeping act that must leave a durable, queryable record — a warn in
// the application log is ephemeral and does not satisfy the requirement.
// Best-effort — a logging failure must never block a legitimate booking.
try {
await appendProcessingHistory({
companyId,
correlationId: id,
aggregateType: 'BankTransaction',
aggregateId: id,
eventType: 'BankTransactionDuplicateDismissed',
payload: {
transaction_id: id,
dismissed_transaction_id: candidate.transaction_id,
dismissed_journal_entry_id: candidate.journal_entry_id,
amount_ore: Math.round(candidate.amount * 100),
entry_date: candidate.entry_date,
},
actor: { type: 'user', id: user.id },
occurredAt: new Date(),
})
} catch (logErr) {
dupLog.error('failed to append duplicate-dismissal behandlingshistorik', logErr as Error)
}
}
} catch (err) {
// Detection is fail-open for the non-force path; force requires a confirmed
// candidate, so a detection failure under force is rejected as a mismatch.
if (force) {
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', dupLog, {
details: { detection_failed: true },
})
}
dupLog.warn('booking-time duplicate detection failed (continuing)', err as Error)
}
// Create journal entry via the engine
let journalEntry
try {
@@ -38,6 +38,21 @@ vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
mockCreateTransactionJournalEntry(...args),
}))
// Booking-time duplicate guard — mocked to "no duplicate" by default so these
// tests exercise categorization, not the guard. The detection query is
// unit-tested in lib/transactions/__tests__/booking-duplicate-detection.test.ts.
const mockDetectDup = vi.fn()
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
detectBookedDuplicateTransaction: (...args: unknown[]) => mockDetectDup(...args),
}))
// Behandlingshistorik append — mocked so we can assert the dismissal is
// persisted without reaching the service-role client.
const mockAppendProcessingHistory = vi.fn()
vi.mock('@/lib/processing-history/append', () => ({
appendProcessingHistory: (...args: unknown[]) => mockAppendProcessingHistory(...args),
}))
const mockSaveUserMappingRule = vi.fn()
vi.mock('@/lib/bookkeeping/mapping-engine', () => ({
saveUserMappingRule: (...args: unknown[]) => mockSaveUserMappingRule(...args),
@@ -96,6 +111,9 @@ describe('POST /api/transactions/[id]/categorize', () => {
// Default: every mapped account exists and is active. Tests covering the
// missing-account path override this per-case.
mockFindMissingActiveAccounts.mockResolvedValue([])
// Default: no booking-time duplicate. The dedicated guard test overrides this.
mockDetectDup.mockResolvedValue(null)
mockAppendProcessingHistory.mockResolvedValue('evt-1')
})
it('returns 401 when not authenticated', async () => {
@@ -586,6 +604,84 @@ describe('POST /api/transactions/[id]/categorize', () => {
expect(body.journal_entry_id).toBe('je-1')
})
it('warns (409) and books nothing when a booked sibling shares date+amount', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
enqueue({ data: tx, error: null }) // fetch — guard runs right after, before any booking work
mockDetectDup.mockResolvedValue({
transaction_id: '660e8400-e29b-41d4-a716-446655440111',
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: 'redan bokförd',
amount: -500,
})
const request = createMockRequest('/api/transactions/tx-1/categorize', {
method: 'POST',
body: { is_business: true, category: 'income_services', confirm_no_match: true },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { candidate: { voucher_label: string } } }
}>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_BOOK_POSSIBLE_DUPLICATE')
expect(body.error.details.candidate.voucher_label).toBe('A142')
// The duplicate guard fires before any verifikat is created.
expect(mockCreateTransactionJournalEntry).not.toHaveBeenCalled()
// Blocking a duplicate is not a dismissal — nothing is logged.
expect(mockAppendProcessingHistory).not.toHaveBeenCalled()
})
it('persists a behandlingshistorik event when force=true dismisses a duplicate', async () => {
const SIBLING_UUID = '660e8400-e29b-41d4-a716-446655440111'
const tx = makeTransaction({ id: 'tx-1', amount: -500, merchant_name: 'GitHub', journal_entry_id: null })
enqueue({ data: tx, error: null }) // fetch
enqueue({ data: { entity_type: 'enskild_firma', fiscal_year_start_month: 1 }, error: null }) // settings
enqueue({ data: [{ id: 'period-1' }], error: null }) // ensureFiscalPeriod existing check
mockCreateTransactionJournalEntry.mockResolvedValue({ id: 'je-1' })
mockSaveUserMappingRule.mockResolvedValue(undefined)
enqueue({ data: [{ id: 'tx-1' }], error: null }) // tx update (CAS matched)
mockDetectDup.mockResolvedValue({
transaction_id: SIBLING_UUID,
journal_entry_id: 'je-existing',
voucher_label: 'A142',
entry_date: '2025-01-15',
description: null,
amount: -500,
})
const request = createMockRequest('/api/transactions/tx-1/categorize', {
method: 'POST',
body: {
is_business: true,
category: 'expense_software',
force: true,
expected_duplicate_transaction_id: SIBLING_UUID,
},
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ success: boolean; journal_entry_created: boolean }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.journal_entry_created).toBe(true)
// The dismissal is recorded to behandlingshistorik (BFNAR 2013:2 kap 8).
expect(mockAppendProcessingHistory).toHaveBeenCalledWith(
expect.objectContaining({
eventType: 'BankTransactionDuplicateDismissed',
aggregateType: 'BankTransaction',
aggregateId: 'tx-1',
actor: { type: 'user', id: 'user-1' },
payload: expect.objectContaining({ dismissed_transaction_id: SIBLING_UUID }),
}),
)
})
it('categorizes as private when is_business is false', async () => {
const tx = makeTransaction({
id: 'tx-1',
@@ -5,6 +5,8 @@ import { ensureInitialized } from '@/lib/init'
import { buildMappingResultFromCategory } from '@/lib/bookkeeping/category-mapping'
import { getTemplateById, buildMappingResultFromTemplate, validateTemplateForEntity } from '@/lib/bookkeeping/booking-templates'
import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
import { detectBookedDuplicateTransaction } from '@/lib/transactions/booking-duplicate-detection'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import { saveUserMappingRule, applySettlementAccount } from '@/lib/bookkeeping/mapping-engine'
import { upsertCounterpartyTemplate, buildMappingResultFromCounterpartyTemplate } from '@/lib/bookkeeping/counterparty-templates'
import { withRouteContext } from '@/lib/api/with-route-context'
@@ -144,6 +146,75 @@ export const POST = withRouteContext(
})
}
// Booking-time duplicate guard: this transaction is about to become a NEW
// verifikat. If another transaction on the same date+amount+account is
// already booked, booking this one double-counts one real affärshändelse
// (felaktig bokföring per BFL). Warn; the user confirms with force=true
// bound to the reviewed sibling. Mirrors the match-invoice soft-duplicate
// guard. Runs before any categorization work so the user resolves it first.
try {
const candidate = await detectBookedDuplicateTransaction(supabase, companyId, {
id,
date: transaction.date,
amount: transaction.amount,
cash_account_id: transaction.cash_account_id ?? null,
})
if (!body.force) {
if (candidate) {
return errorResponseFromCode('TRANSACTION_BOOK_POSSIBLE_DUPLICATE', txLog, {
requestId,
details: { candidate },
})
}
} else if (!candidate || candidate.transaction_id !== body.expected_duplicate_transaction_id) {
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', txLog, {
requestId,
details: {
expected_duplicate_transaction_id: body.expected_duplicate_transaction_id ?? null,
detected_transaction_id: candidate?.transaction_id ?? null,
},
})
} else {
txLog.warn('booking-time duplicate guard bypassed', {
reason: 'force=true',
requestId,
dismissedTransactionId: candidate.transaction_id,
})
// Persist the dismissal to behandlingshistorik (BFNAR 2013:2 kap 8) —
// booking over a DETECTED possible double-booking is a bookkeeping
// decision that needs a durable record. Best-effort; never blocks the
// booking.
try {
await appendProcessingHistory({
companyId,
correlationId: id,
aggregateType: 'BankTransaction',
aggregateId: id,
eventType: 'BankTransactionDuplicateDismissed',
payload: {
transaction_id: id,
dismissed_transaction_id: candidate.transaction_id,
dismissed_journal_entry_id: candidate.journal_entry_id,
amount_ore: Math.round(candidate.amount * 100),
entry_date: candidate.entry_date,
},
actor: { type: 'user', id: user.id },
occurredAt: new Date(),
})
} catch (logErr) {
txLog.error('failed to append duplicate-dismissal behandlingshistorik', logErr as Error)
}
}
} catch (err) {
if (body.force) {
return errorResponseFromCode('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH', txLog, {
requestId,
details: { detection_failed: true },
})
}
txLog.warn('booking-time duplicate detection failed (continuing)', err as Error)
}
const { data: settings } = await supabase
.from('company_settings')
.select('entity_type, fiscal_year_start_month')
+66
View File
@@ -0,0 +1,66 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { createLogger } from '@/lib/logger'
const log = createLogger('user/profile')
// User-scoped (not company-scoped) — same shape as /api/user/locale, so it
// opts out of withRouteContext and calls requireAuth() directly (MFA still
// enforced on hosted).
const BodySchema = z.object({
full_name: z.string().min(1).max(100),
})
export async function POST(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const parsed = BodySchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid name' }, { status: 400 })
}
const fullName = parsed.data.full_name.trim()
if (!fullName) {
return NextResponse.json({ error: 'Invalid name' }, { status: 400 })
}
// Source of truth: profiles.full_name. Read by the account menu
// (app/(dashboard)/layout.tsx), the first-name greetings, the agent context,
// and the AGI/KU contact-person field. RLS scopes the update to the caller's
// own row (profiles_update policy: auth.uid() = id).
const { error: updateError } = await supabase
.from('profiles')
.update({ full_name: fullName })
.eq('id', user.id)
if (updateError) {
return NextResponse.json({ error: 'Could not save name' }, { status: 500 })
}
// Best-effort: keep auth user_metadata.full_name in sync so the two stores
// don't drift. It seeds profiles via the handle_new_user trigger at signup
// and is wiped on account deletion as a display-name store. updateUserById
// REPLACES user_metadata wholesale, so read-merge-write to keep other keys.
try {
const admin = createServiceClient()
const { data: current } = await admin.auth.admin.getUserById(user.id)
const priorMeta = current?.user?.user_metadata ?? {}
await admin.auth.admin.updateUserById(user.id, {
user_metadata: { ...priorMeta, full_name: fullName },
})
} catch (syncError) {
log.warn('user_metadata full_name sync failed (non-blocking)', syncError)
}
return NextResponse.json({ data: { full_name: fullName } })
}
@@ -0,0 +1,359 @@
'use client'
import { useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { AlertTriangle, Loader2, Lock } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { Asset, AssetCategory, DepreciationMethod } from '@/types'
/** The list route annotates each asset with whether any depreciation has been
* posted against it. When true, the acquisition-basis fields are locked. */
type EditableAsset = Asset & { has_posted_depreciation?: boolean }
interface EditAssetDialogProps {
asset: EditableAsset
open: boolean
onOpenChange: (open: boolean) => void
onSaved: () => void
}
// Same category labels and depreciation hints as CreateAssetDialog (kept in
// sync deliberately — this register surface is Swedish-only, like creation).
const CATEGORY_OPTIONS: { value: AssetCategory; label: string }[] = [
{ value: 'computer', label: 'Dator / IT-utrustning' },
{ value: 'equipment', label: 'Inventarier' },
{ value: 'machinery', label: 'Maskiner' },
{ value: 'vehicle', label: 'Fordon' },
{ value: 'building', label: 'Byggnad' },
{ value: 'land_improvement', label: 'Markanläggning' },
{ value: 'immaterial', label: 'Immateriell tillgång' },
{ value: 'other_tangible', label: 'Övrig materiell tillgång' },
]
const DEPRECIATION_METHOD_OPTIONS: { value: DepreciationMethod; label: string; hint: string }[] = [
{
value: 'linear',
label: 'Linjär',
hint: 'Planenlig raklinje över nyttjandeperioden (ÅRL 4 kap 4§).',
},
{
value: 'declining_balance_30',
label: 'Räkenskapsenlig 30 %',
hint: 'Huvudregeln (IL 18 kap 13§) — 30 % degressivt på avskrivningsunderlaget.',
},
{
value: 'declining_balance_20',
label: 'Räkenskapsenlig 20 %',
hint: 'Kompletteringsregeln (IL 18 kap 17§) — 20 % degressivt. Vanlig för byggnader.',
},
{
value: 'restvardesavskrivning_25',
label: 'Restvärdeavskrivning 25 %',
hint: 'IL 18 kap 13§ st.3 — 25 % degressivt ner till angivet restvärde.',
},
]
export function EditAssetDialog({ asset, open, onOpenChange, onSaved }: EditAssetDialogProps) {
const { toast } = useToast()
const { canWrite } = useCanWrite()
// Once depreciation has been booked, acquisition date/cost/category are
// locked — a real change has to go through storno. The server enforces the
// same rule (ASSET_CORRECTION_BLOCKED); this just makes it visible up front.
const basisLocked = asset.has_posted_depreciation === true
const [name, setName] = useState(asset.name)
const [category, setCategory] = useState<AssetCategory>(asset.category)
const [acquisitionDate, setAcquisitionDate] = useState(asset.acquisition_date)
const [acquisitionCost, setAcquisitionCost] = useState(String(asset.acquisition_cost))
const [usefulLifeYears, setUsefulLifeYears] = useState(
String(Math.round(asset.useful_life_months / 12)),
)
const [depreciationMethod, setDepreciationMethod] = useState<DepreciationMethod>(
asset.depreciation_method,
)
const [restvardeTarget, setRestvardeTarget] = useState(
asset.restvarde_target != null ? String(asset.restvarde_target) : '',
)
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const isRestvarde = depreciationMethod === 'restvardesavskrivning_25'
const methodHint =
DEPRECIATION_METHOD_OPTIONS.find((o) => o.value === depreciationMethod)?.hint ?? ''
const handleSubmit = async () => {
setError(null)
const trimmedName = name.trim()
if (!trimmedName) {
setError('Namnet får inte vara tomt.')
return
}
// Send only what actually changed. This keeps a name-only edit on a
// depreciated asset from tripping the acquisition-basis guard, and avoids
// clobbering a useful_life_months value that isn't a clean multiple of 12.
const patch: Record<string, unknown> = {}
if (trimmedName !== asset.name) patch.name = trimmedName
if (!basisLocked) {
if (category !== asset.category) patch.category = category
if (acquisitionDate !== asset.acquisition_date) patch.acquisition_date = acquisitionDate
const cost = parseFloat(acquisitionCost)
if (!Number.isFinite(cost) || cost <= 0) {
setError('Anskaffningsvärdet måste vara större än 0.')
return
}
if (cost !== Number(asset.acquisition_cost)) patch.acquisition_cost = cost
}
const years = parseInt(usefulLifeYears, 10)
if (!Number.isFinite(years) || years <= 0) {
setError('Ange en avskrivningstid (minst 1 år).')
return
}
const months = years * 12
if (months !== asset.useful_life_months) patch.useful_life_months = months
if (depreciationMethod !== asset.depreciation_method) {
patch.depreciation_method = depreciationMethod
}
if (isRestvarde) {
const target = parseFloat(restvardeTarget)
const cost = !basisLocked ? parseFloat(acquisitionCost) : Number(asset.acquisition_cost)
if (!Number.isFinite(target) || target < 0) {
setError('Ange ett restvärde (0 kr eller högre).')
return
}
if (Number.isFinite(cost) && target >= cost) {
setError('Restvärdet måste vara lägre än anskaffningsvärdet.')
return
}
// Send the target when switching into restvärde or when it changed, so
// the method/target biconditional always holds.
if (
depreciationMethod !== asset.depreciation_method ||
target !== Number(asset.restvarde_target)
) {
patch.restvarde_target = target
}
}
if (Object.keys(patch).length === 0) {
toast({ title: 'Inga ändringar', description: 'Inget att spara.' })
onOpenChange(false)
return
}
setSubmitting(true)
try {
const res = await fetch(`/api/assets/${asset.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch),
})
const body = await res.json()
if (!res.ok) {
setError(getErrorMessage(body?.error ?? body) || 'Kunde inte spara ändringen.')
return
}
toast({ title: 'Tillgång uppdaterad', description: trimmedName })
onSaved()
} catch (err) {
setError(getErrorMessage(err))
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Ändra anläggningstillgång</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="edit-asset-name">Namn</Label>
<Input
id="edit-asset-name"
value={name}
onChange={(e) => setName(e.target.value)}
autoFocus
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="edit-asset-category">Kategori</Label>
<Select
value={category}
onValueChange={(v) => setCategory(v as AssetCategory)}
disabled={basisLocked}
>
<SelectTrigger id="edit-asset-category">
<SelectValue />
</SelectTrigger>
<SelectContent>
{CATEGORY_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="edit-asset-date">Anskaffat</Label>
<Input
id="edit-asset-date"
type="date"
value={acquisitionDate}
onChange={(e) => setAcquisitionDate(e.target.value)}
disabled={basisLocked}
className="tabular-nums"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="edit-asset-cost">Anskaffningsvärde (kr)</Label>
<Input
id="edit-asset-cost"
type="number"
step="1"
min="0"
value={acquisitionCost}
onChange={(e) => setAcquisitionCost(e.target.value)}
disabled={basisLocked}
className="tabular-nums"
/>
</div>
</div>
{basisLocked && (
<div className="flex items-start gap-2 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
<Lock className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>
Anskaffningsdatum, anskaffningsvärde och kategori är låsta eftersom avskrivningar
redan har bokförts. Återför avskrivningen (storno) eller använd avyttring för att
ändra grunduppgifterna. Namn, avskrivningstid och metod kan fortfarande justeras.
</span>
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="edit-asset-life">Avskrivningstid (år)</Label>
<Input
id="edit-asset-life"
type="number"
min="1"
max="50"
step="1"
value={usefulLifeYears}
onChange={(e) => setUsefulLifeYears(e.target.value)}
className="tabular-nums"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="edit-asset-method">Avskrivningsmetod</Label>
<Select
value={depreciationMethod}
onValueChange={(v) => setDepreciationMethod(v as DepreciationMethod)}
>
<SelectTrigger id="edit-asset-method">
<SelectValue />
</SelectTrigger>
<SelectContent>
{DEPRECIATION_METHOD_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">{methodHint}</p>
</div>
{basisLocked && depreciationMethod !== asset.depreciation_method && (
<div className="flex items-start gap-2 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>
Byte av avskrivningsmetod efter att avskrivning påbörjats. Enligt K2
(BFNAR 2016:10 p. 10.26) ska vald metod tillämpas konsekvent — ändra
bara vid särskilda skäl och lämna i så fall upplysning i bokslutet.
Ändringen gäller framåt; redan bokförda avskrivningar påverkas inte.
</span>
</div>
)}
{isRestvarde && (
<div className="space-y-1.5">
<Label htmlFor="edit-asset-restvarde">Restvärde (kr)</Label>
<Input
id="edit-asset-restvarde"
type="number"
min="0"
step="1"
value={restvardeTarget}
onChange={(e) => setRestvardeTarget(e.target.value)}
placeholder="t.ex. 5000"
className="tabular-nums"
/>
<p className="text-xs text-muted-foreground">
Avskrivningen stannar när bokfört värde når restvärdet. Restvärdet måste vara lägre
än anskaffningsvärdet.
</p>
</div>
)}
{error && (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
{error}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
Avbryt
</Button>
<Button
onClick={handleSubmit}
disabled={!canWrite || submitting}
title={
!canWrite ? 'Endast användare med skrivrättigheter kan ändra tillgångar.' : undefined
}
>
{!canWrite && <Lock className="mr-1 h-4 w-4" />}
{submitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Sparar…
</>
) : (
'Spara'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+3 -3
View File
@@ -50,10 +50,10 @@ const PAGE_ENTRIES: Entry[] = [
{ id: 'anläggningstillgångar', label: 'Anläggningstillgångar', icon: Package, href: '/assets', keywords: 'tillgångar assets' },
{ id: 'rapporter', label: 'Rapporter', icon: BarChart3, href: '/reports' },
{ id: 'rapport-resultatrapport', label: 'Visa rapport: Resultatrapport', icon: BarChart3, href: '/reports/resultatrapport', keywords: 'rapport resultat intäkter kostnader' },
{ id: 'rapport-balansrapport', label: 'Visa rapport: Balansrapport', icon: BarChart3, href: '/reports/balansrapport', keywords: 'rapport balans tillgångar skulder' },
{ id: 'rapport-saldobalans', label: 'Visa rapport: Saldobalans', icon: BarChart3, href: '/reports/trial-balance', keywords: 'rapport saldobalans trial balance' },
{ id: 'rapport-balansrapport', label: 'Visa rapport: Balansrapport', icon: BarChart3, href: '/reports/balansrapport', keywords: 'rapport balans tillgångar skulder saldo per konto' },
{ id: 'rapport-saldobalans', label: 'Visa rapport: Saldobalans', icon: BarChart3, href: '/reports/trial-balance', keywords: 'rapport saldobalans trial balance saldo per konto' },
{ id: 'rapport-moms', label: 'Visa rapport: Momsdeklaration', icon: BarChart3, href: '/reports/vat-declaration', keywords: 'rapport moms vat deklaration' },
{ id: 'rapport-huvudbok', label: 'Visa rapport: Huvudbok', icon: BookOpen, href: '/reports/huvudbok', keywords: 'rapport huvudbok ledger konto' },
{ id: 'rapport-huvudbok', label: 'Visa rapport: Huvudbok', icon: BookOpen, href: '/reports/huvudbok', keywords: 'rapport huvudbok ledger general konto saldo transaktioner per konto kontoutdrag kontoanalys kontokort kontohistorik balance account statement transactions' },
{ id: 'rapport-kundreskontra', label: 'Visa rapport: Kundreskontra', icon: Users, href: '/reports/kundreskontra', keywords: 'rapport kundreskontra ar kundfordringar' },
{ id: 'importera', label: 'Importera', icon: Upload, href: '/import' },
{ id: 'granskning', label: 'Granskning', icon: ClipboardCheck, href: '/pending', keywords: 'pending review' },
File diff suppressed because it is too large Load Diff
+124
View File
@@ -0,0 +1,124 @@
'use client'
import { useTranslations } from 'next-intl'
import { useState, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Plus } from 'lucide-react'
import { formatDate } from '@/lib/utils'
import type { FiscalPeriod } from '@/types'
import CreatePeriodDialog from '@/components/bookkeeping/CreatePeriodDialog'
/** Status of a fiscal period, in legal precedence: closed > locked > open. */
function periodStatus(p: FiscalPeriod): 'closed' | 'locked' | 'open' {
if (p.is_closed) return 'closed'
if (p.locked_at) return 'locked'
return 'open'
}
const STATUS_VARIANT: Record<'closed' | 'locked' | 'open', 'secondary' | 'warning' | 'success'> = {
closed: 'secondary',
locked: 'warning',
open: 'success',
}
/** ISO date one day after the latest period ends — seeds the create dialog so
* its suggestion chains forward onto the most recent year. UTC throughout to
* avoid timezone-offset date drift. */
function nextEntryDate(periods: FiscalPeriod[]): string {
if (periods.length === 0) {
return new Date().toISOString().split('T')[0]
}
const latestEnd = periods
.map((p) => p.period_end)
.sort((a, b) => a.localeCompare(b))
.at(-1)!
const d = new Date(latestEnd + 'T00:00:00Z')
d.setUTCDate(d.getUTCDate() + 1)
return d.toISOString().split('T')[0]
}
export function FiscalYearsManager() {
const t = useTranslations('settings_bookkeeping')
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
const [isLoading, setIsLoading] = useState(true)
const [hasError, setHasError] = useState(false)
const [dialogOpen, setDialogOpen] = useState(false)
const fetchPeriods = useCallback(async () => {
try {
const res = await fetch('/api/bookkeeping/fiscal-periods')
if (!res.ok) throw new Error('fetch failed')
const { data } = await res.json()
setPeriods((data as FiscalPeriod[]) || [])
setHasError(false)
} catch {
setHasError(true)
} finally {
setIsLoading(false)
}
}, [])
useEffect(() => { fetchPeriods() }, [fetchPeriods])
// Newest first — matches the API's ordering and reads most-recent-at-top.
const sorted = [...periods].sort((a, b) => b.period_start.localeCompare(a.period_start))
return (
<section className="space-y-4">
<div className="flex items-center justify-between gap-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{t('fy_heading')}
</h2>
<Button
variant="outline"
size="sm"
onClick={() => setDialogOpen(true)}
disabled={isLoading}
>
<Plus className="mr-1.5 h-4 w-4" />
{t('fy_create')}
</Button>
</div>
<p className="text-xs text-muted-foreground">{t('fy_help')}</p>
{isLoading ? (
<div className="space-y-2">
<Skeleton className="h-4 w-48" />
<Skeleton className="h-4 w-40" />
</div>
) : hasError ? (
<p className="text-sm text-muted-foreground">{t('fy_load_error')}</p>
) : sorted.length === 0 ? (
<p className="text-sm text-muted-foreground">{t('fy_empty')}</p>
) : (
<div className="divide-y divide-border">
{sorted.map((p) => {
const status = periodStatus(p)
return (
<div key={p.id} className="flex items-center justify-between gap-4 py-2">
<div className="min-w-0">
<span className="text-sm font-medium">{p.name}</span>
<span className="ml-2 text-sm text-muted-foreground tabular-nums">
{formatDate(p.period_start)} – {formatDate(p.period_end)}
</span>
</div>
<Badge variant={STATUS_VARIANT[status]}>{t(`fy_status_${status}`)}</Badge>
</div>
)
})}
</div>
)}
<CreatePeriodDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
entryDate={nextEntryDate(periods)}
periods={periods}
onCreated={fetchPeriods}
/>
</section>
)
}
@@ -6,6 +6,8 @@ import Link from 'next/link'
import { useLocale, useTranslations } from 'next-intl'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Sun, Moon, Monitor, LogOut, Languages, ExternalLink } from 'lucide-react'
import { useTheme } from 'next-themes'
import { createClient } from '@/lib/supabase/client'
@@ -30,9 +32,56 @@ export function AccountSettingsContent() {
const tCommon = useTranslations('common')
const tSettings = useTranslations('settings')
const [savingLocale, setSavingLocale] = useState(false)
const [fullName, setFullName] = useState('')
const [initialName, setInitialName] = useState('')
const [nameLoading, setNameLoading] = useState(true)
const [savingName, setSavingName] = useState(false)
useEffect(() => { setMounted(true) }, [])
// Pre-fill the name field from profiles.full_name. Self-contained client
// fetch — mirrors BankIdSettings.
useEffect(() => {
let active = true
;(async () => {
const { data: { user } } = await supabase.auth.getUser()
if (!user) { if (active) setNameLoading(false); return }
const { data } = await supabase
.from('profiles')
.select('full_name')
.eq('id', user.id)
.maybeSingle()
if (!active) return
setFullName(data?.full_name ?? '')
setInitialName(data?.full_name ?? '')
setNameLoading(false)
})()
return () => { active = false }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
async function handleSaveName() {
const trimmed = fullName.trim()
if (!trimmed || trimmed === initialName || savingName) return
setSavingName(true)
try {
const res = await fetch('/api/user/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ full_name: trimmed }),
})
if (!res.ok) throw new Error('Could not save')
setFullName(trimmed)
setInitialName(trimmed)
toast({ title: tSettings('name_saved') })
router.refresh()
} catch {
toast({ title: tSettings('name_save_failed'), variant: 'destructive' })
} finally {
setSavingName(false)
}
}
async function handleLogout() {
clearRecaptIdentity()
await supabase.auth.signOut()
@@ -68,8 +117,39 @@ export function AccountSettingsContent() {
return (
<div className="space-y-8">
{/* Appearance */}
{/* Name */}
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{tSettings('section_name')}
</h2>
<p className="text-sm text-muted-foreground max-w-md">
{tSettings('name_description')}
</p>
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="flex-1 space-y-2 sm:max-w-sm">
<Label htmlFor="full_name">{tSettings('name_label')}</Label>
<Input
id="full_name"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
placeholder={tSettings('name_placeholder')}
disabled={nameLoading || savingName}
maxLength={100}
/>
</div>
<Button
onClick={handleSaveName}
disabled={
nameLoading || savingName || !fullName.trim() || fullName.trim() === initialName
}
>
{savingName ? tCommon('saving') : tCommon('save')}
</Button>
</div>
</section>
{/* Appearance */}
<section className="space-y-4 border-t border-border pt-8">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{tSettings('section_appearance')}
</h2>
@@ -7,6 +7,7 @@ import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
import { SettingsLoadError } from '@/components/settings/SettingsLoadError'
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
import { PeriodLockingSettings } from '@/components/settings/PeriodLockingSettings'
import { FiscalYearsManager } from '@/components/settings/FiscalYearsManager'
import { VoucherSeriesManager } from '@/components/settings/VoucherSeriesManager'
import { VoucherSeriesPerSourceTypeForm } from '@/components/settings/VoucherSeriesPerSourceTypeForm'
import { applyDefaultSeriesToMap } from '@/lib/bookkeeping/voucher-series-resolver'
@@ -141,6 +142,11 @@ export function BookkeepingSettingsContent() {
</div>
</SettingsFormWrapper>
{/* Fiscal years */}
<div className="border-t border-border pt-8">
<FiscalYearsManager />
</div>
{/* Voucher series — per-source-type mapping */}
<div className="border-t border-border pt-8">
<VoucherSeriesPerSourceTypeForm
+28
View File
@@ -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
View File
@@ -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 —
+186 -1
View File
@@ -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(
+197 -16
View File
@@ -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
+25
View File
@@ -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)
})
})
+24
View File
@@ -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)
})
})
+432
View File
@@ -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 }
}
+20
View File
@@ -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
}
+24 -6
View File
@@ -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')
})
})
+255 -7
View File
@@ -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
View File
@@ -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}`)
+30 -2
View File
@@ -191,6 +191,12 @@
"description": "Manage your company and account"
},
"settings": {
"section_name": "Name",
"name_label": "Your name",
"name_description": "The name we use to address you and that appears as the contact person on some documents. We greet you by your first name, so put the name you go by first.",
"name_placeholder": "First name Last name",
"name_saved": "Name updated",
"name_save_failed": "Could not save name",
"section_appearance": "Appearance",
"section_language": "Language",
"language_description": "Choose the language for the interface. Invoices and reports always stay in Swedish.",
@@ -477,6 +483,7 @@
"useful_life_format": "{years} yr ({months} mo)",
"status_disposed": "Disposed",
"status_active": "Active",
"action_edit": "Edit",
"action_dispose": "Dispose",
"category_immaterial": "Intangible",
"category_building": "Building",
@@ -1121,6 +1128,14 @@
"series_heading": "Default voucher series",
"series_label": "Series",
"series_help": "Which series is preselected for manual bookkeeping. Can be changed per voucher.",
"fy_heading": "Fiscal years",
"fy_help": "Fiscal years are created automatically when you book or import data outside existing years, but you can also set up a new year in advance here. A new year must chain directly onto an existing year, and the prior year may need to be locked first.",
"fy_create": "Create fiscal year",
"fy_empty": "No fiscal years created yet.",
"fy_load_error": "Could not load fiscal years. Please try again.",
"fy_status_open": "Open",
"fy_status_locked": "Locked",
"fy_status_closed": "Closed",
"related_heading": "Related",
"related_fiscal_year": "Fiscal years and opening balances",
"related_chart_of_accounts": "Chart of accounts (BAS)"
@@ -2119,6 +2134,8 @@
"cancel": "Cancel"
},
"invoice_editor": {
"ore_rounding_label": "Öre rounding",
"ore_rounding_help": "Round the invoice total to whole kronor",
"back": "Back",
"article_label": "Article",
"article_placeholder": "Select article",
@@ -2192,6 +2209,12 @@
"toast_draft_saved_title": "Draft saved",
"toast_draft_saved_description": "The draft is in your invoice list. Open it to review and create the invoice.",
"save_draft_failed_title": "Could not save draft",
"title_edit": "Edit draft",
"subtitle_edit": "Change the draft and save. The invoice number is unchanged.",
"save_changes": "Save changes",
"toast_draft_updated_title": "Draft updated",
"toast_draft_updated_description": "Your changes have been saved.",
"update_failed_title": "Could not save your changes",
"mode_invoice": "Invoice",
"mode_self_billed": "Self-billing",
"viewer_disabled_tooltip": "You only have read-only access to this company",
@@ -2225,7 +2248,6 @@
"validation_description_required": "Description required",
"validation_quantity_min": "Minimum 0.01",
"validation_unit_required": "Unit required",
"validation_price_positive": "Price must be positive",
"validation_customer_required": "Select a customer",
"validation_invoice_date_required": "Invoice date required",
"validation_due_date_required": "Due date required",
@@ -2410,6 +2432,9 @@
"delete_dialog_cancel": "Cancel",
"delete_dialog_confirm": "Cancel invoice",
"finalize_action": "Review & create",
"edit_draft": "Edit",
"edit_not_allowed_title": "Cannot be edited",
"edit_not_allowed_description": "Only drafts can be edited. Posted or sent invoices must be credited instead.",
"finalize_dialog_title": "Create invoice?",
"finalize_dialog_number_label": "Invoice number",
"finalize_dialog_desc": "An invoice number is assigned and the draft becomes an invoice. You can send or cancel it afterwards, but can no longer delete it.",
@@ -2636,6 +2661,8 @@
"link_failed_title": "Could not link the journal entry"
},
"supplier_invoice_editor": {
"ore_rounding_label": "Öre rounding",
"ore_rounding_help": "Round the invoice total to whole kronor",
"page_title": "Register supplier invoice",
"no_period_warning": "You're creating a supplier invoice for a fiscal year that doesn't exist ({date}).",
"no_period_help": "Create the fiscal year first, or change the invoice date — the invoice can't be registered without one.",
@@ -2780,6 +2807,7 @@
"review_accrual_line_info": "Accrued {from} – {to}"
},
"supplier_invoice_detail": {
"ore_rounding": "Öre rounding",
"back": "Back",
"back_aria": "Back to supplier invoices",
"viewer_disabled_tooltip": "You only have read access in this company",
@@ -4054,7 +4082,7 @@
"desc_periodisk_sammanstallning": "EU sales of goods and services",
"desc_ne_declaration": "NE appendix for sole traders",
"desc_ink2_declaration": "Income tax return 2 for limited companies",
"desc_huvudbok": "All transactions grouped by account",
"desc_huvudbok": "Balance and all transactions per account",
"desc_grundbok": "Vouchers in registration order",
"desc_kundreskontra": "Outstanding receivables with aging",
"desc_supplier_ledger": "Outstanding payables with aging",
+30 -2
View File
@@ -191,6 +191,12 @@
"description": "Hantera ditt företag och konto"
},
"settings": {
"section_name": "Namn",
"name_label": "Ditt namn",
"name_description": "Namnet vi använder för att tilltala dig och som visas som kontaktperson på vissa underlag. Vi hälsar med ditt första namn, så skriv det du vill bli kallad först.",
"name_placeholder": "Förnamn Efternamn",
"name_saved": "Namnet har uppdaterats",
"name_save_failed": "Kunde inte spara namnet",
"section_appearance": "Utseende",
"section_language": "Språk",
"language_description": "Välj språket för gränssnittet. Fakturor och rapporter förblir alltid på svenska.",
@@ -477,6 +483,7 @@
"useful_life_format": "{years} år ({months} mån)",
"status_disposed": "Avyttrad",
"status_active": "Aktiv",
"action_edit": "Ändra",
"action_dispose": "Avyttra",
"category_immaterial": "Immateriell",
"category_building": "Byggnad",
@@ -1121,6 +1128,14 @@
"series_heading": "Standardserie för verifikationer",
"series_label": "Serie",
"series_help": "Vilken serie som förväljs vid manuell bokföring. Kan ändras per verifikation.",
"fy_heading": "Räkenskapsår",
"fy_help": "Räkenskapsår skapas automatiskt när du bokför eller importerar data utanför befintliga år, men du kan även lägga upp ett nytt år i förväg här. Ett nytt år måste ansluta direkt till ett befintligt år, och föregående år kan behöva låsas först.",
"fy_create": "Skapa nytt räkenskapsår",
"fy_empty": "Inga räkenskapsår har skapats än.",
"fy_load_error": "Kunde inte ladda räkenskapsår. Försök igen.",
"fy_status_open": "Öppet",
"fy_status_locked": "Låst",
"fy_status_closed": "Stängt",
"related_heading": "Relaterat",
"related_fiscal_year": "Räkenskapsår och ingående balanser",
"related_chart_of_accounts": "Kontoplan (BAS)"
@@ -2119,6 +2134,8 @@
"cancel": "Avbryt"
},
"invoice_editor": {
"ore_rounding_label": "Öresavrundning",
"ore_rounding_help": "Avrunda fakturatotal till hel krona",
"back": "Tillbaka",
"article_label": "Artikel",
"article_placeholder": "Välj artikel",
@@ -2192,6 +2209,12 @@
"toast_draft_saved_title": "Utkast sparat",
"toast_draft_saved_description": "Utkastet finns i fakturalistan. Öppna det för att granska och skapa fakturan.",
"save_draft_failed_title": "Kunde inte spara utkast",
"title_edit": "Redigera utkast",
"subtitle_edit": "Ändra utkastet och spara. Inget fakturanummer ändras.",
"save_changes": "Spara ändringar",
"toast_draft_updated_title": "Utkast uppdaterat",
"toast_draft_updated_description": "Ändringarna har sparats.",
"update_failed_title": "Kunde inte spara ändringarna",
"mode_invoice": "Faktura",
"mode_self_billed": "Självfaktura",
"viewer_disabled_tooltip": "Du har endast läsbehörighet i detta företag",
@@ -2225,7 +2248,6 @@
"validation_description_required": "Beskrivning krävs",
"validation_quantity_min": "Minst 0.01",
"validation_unit_required": "Enhet krävs",
"validation_price_positive": "Pris måste vara positivt",
"validation_customer_required": "Välj en kund",
"validation_invoice_date_required": "Fakturadatum krävs",
"validation_due_date_required": "Förfallodatum krävs",
@@ -2410,6 +2432,9 @@
"delete_dialog_cancel": "Avbryt",
"delete_dialog_confirm": "Makulera",
"finalize_action": "Granska & skapa",
"edit_draft": "Redigera",
"edit_not_allowed_title": "Kan inte redigeras",
"edit_not_allowed_description": "Bara utkast kan redigeras. Bokförda eller skickade fakturor måste krediteras istället.",
"finalize_dialog_title": "Skapa faktura?",
"finalize_dialog_number_label": "Fakturanummer",
"finalize_dialog_desc": "Ett fakturanummer tilldelas och utkastet blir en faktura. Du kan skicka eller makulera den efteråt, men inte längre ta bort den.",
@@ -2636,6 +2661,8 @@
"link_failed_title": "Kunde inte länka verifikationen"
},
"supplier_invoice_editor": {
"ore_rounding_label": "Öresavrundning",
"ore_rounding_help": "Avrunda fakturatotal till hel krona",
"page_title": "Registrera leverantörsfaktura",
"no_period_warning": "Du skapar en leverantörsfaktura för ett räkenskapsår som inte finns ({date}).",
"no_period_help": "Lägg upp räkenskapsåret först, eller ändra fakturadatumet – fakturan kan inte registreras utan ett räkenskapsår.",
@@ -2780,6 +2807,7 @@
"review_accrual_line_info": "Periodiseras {from} – {to}"
},
"supplier_invoice_detail": {
"ore_rounding": "Öresavrundning",
"back": "Tillbaka",
"back_aria": "Tillbaka till leverantörsfakturor",
"viewer_disabled_tooltip": "Du har endast läsbehörighet i detta företag",
@@ -4054,7 +4082,7 @@
"desc_periodisk_sammanstallning": "EU-försäljning av varor och tjänster",
"desc_ne_declaration": "NE-bilaga för enskild firma",
"desc_ink2_declaration": "Inkomstdeklaration 2 för aktiebolag",
"desc_huvudbok": "Alla transaktioner grupperade per konto",
"desc_huvudbok": "Saldo och alla transaktioner per konto",
"desc_grundbok": "Verifikationer i registreringsordning",
"desc_kundreskontra": "Utestående kundfordringar med åldersfördelning",
"desc_supplier_ledger": "Utestående leverantörsskulder med åldersfördelning",
@@ -0,0 +1,29 @@
-- Per-invoice öresavrundning toggle for customer and supplier invoices.
--
-- This is a DISPLAY-ONLY override. getDisplayTotal() (lib/invoices/rounding.ts)
-- reads this flag when rendering totals (invoice PDF, list, detail). The stored
-- subtotal/vat_amount/total/remaining_amount and the journal entries are NOT
-- affected — the exact öre amount remains the source of truth behind the scenes.
--
-- NULL semantics differ by table, enforced in the display helper, not here:
-- invoices — NULL inherits company_settings.ore_rounding (rounding has
-- always been company-default-on for customer invoices).
-- supplier_invoices — NULL means "off" (supplier invoices never had rounding;
-- we must not retroactively round historical rows).
--
-- Nullable, no default: existing rows stay NULL and keep their prior rendering.
-- New rows get an explicit boolean written by the create routes (defaulted from
-- the company-wide setting in the editor). No RLS/trigger impact — row-level
-- policies already cover every column.
alter table public.invoices
add column if not exists ore_rounding boolean;
comment on column public.invoices.ore_rounding is
'Per-invoice öresavrundning override (display-only). NULL inherits company_settings.ore_rounding. Does not affect stored amounts or journal entries.';
alter table public.supplier_invoices
add column if not exists ore_rounding boolean;
comment on column public.supplier_invoices.ore_rounding is
'Per-invoice öresavrundning override (display-only). NULL = off. Does not affect stored amounts or journal entries.';
@@ -0,0 +1,19 @@
-- Register the behandlingshistorik event emitted when a user dismisses the
-- booking-time duplicate guard (force=true) and books a transaction anyway.
--
-- Per BFNAR 2013:2 kap 8, the decision to book over a DETECTED possible
-- double-booking is a legally significant act and must leave a durable,
-- queryable record — not just an ephemeral application-log warn. The book /
-- categorize routes write it via appendProcessingHistory with aggregate_type
-- 'BankTransaction' (already permitted by the aggregate_type CHECK, so no
-- constraint change is needed — only the event-type catalog row).
--
-- processing_history.event_type has an FK to processing_event_types; an
-- unregistered type would fail the insert (and, since the append is best-effort,
-- be silently swallowed), so the event MUST be registered here.
INSERT INTO public.processing_event_types (event_type) VALUES
('BankTransactionDuplicateDismissed')
ON CONFLICT (event_type) DO NOTHING;
NOTIFY pgrst, 'reload schema';
+2
View File
@@ -352,6 +352,7 @@ export function makeInvoice(overrides: Partial<Invoice> = {}): Invoice {
vat_amount_sek: null,
total: 12500,
total_sek: null,
ore_rounding: null,
vat_treatment: 'standard_25',
vat_rate: 25,
moms_ruta: '10',
@@ -475,6 +476,7 @@ export function makeSupplierInvoice(
vat_amount_sek: null,
total: 10000,
total_sek: null,
ore_rounding: null,
vat_treatment: 'standard_25',
reverse_charge: false,
payment_reference: null,
+12 -2
View File
@@ -198,16 +198,26 @@ describe('assets table — immutability after disposal', () => {
userId: companyA.userId,
companyId: companyA.companyId,
})
// acquisition_date is included here because the asset-edit feature lets
// users correct it before depreciation is booked — the immutability
// trigger must NOT block it on a non-disposed asset.
await getPool().query(
`UPDATE public.assets SET acquisition_cost = 70000, useful_life_months = 72 WHERE id = $1`,
`UPDATE public.assets
SET acquisition_cost = 70000, useful_life_months = 72,
acquisition_date = '2025-08-15', category = 'computer'
WHERE id = $1`,
[assetId],
)
const { rows } = await getPool().query(
`SELECT acquisition_cost, useful_life_months FROM public.assets WHERE id = $1`,
`SELECT acquisition_cost, useful_life_months,
acquisition_date::text AS acquisition_date, category
FROM public.assets WHERE id = $1`,
[assetId],
)
expect(Number(rows[0]?.acquisition_cost)).toBe(70_000)
expect(rows[0]?.useful_life_months).toBe(72)
expect(rows[0]?.acquisition_date).toBe('2025-08-15')
expect(rows[0]?.category).toBe('computer')
})
it('disposal CHECK requires both disposed_at and disposed_proceeds', async () => {
+17
View File
@@ -659,6 +659,9 @@ export interface SupplierInvoice {
total: number
total_sek: number | null
/** Per-invoice öresavrundning override (display-only). null = off. */
ore_rounding: boolean | null
vat_treatment: VatTreatment
reverse_charge: boolean
@@ -797,6 +800,9 @@ export interface Invoice {
total: number
total_sek: number | null
/** Per-invoice öresavrundning override (display-only). null = inherit company_settings.ore_rounding. */
ore_rounding: boolean | null
// VAT
vat_treatment: VatTreatment
vat_rate: number
@@ -1056,6 +1062,8 @@ export interface CreateSupplierInvoiceInput {
reverse_charge?: boolean
payment_reference?: string
notes?: string
/** Per-invoice öresavrundning override (display-only). Omitted = null (off). */
ore_rounding?: boolean
items: CreateSupplierInvoiceItemInput[]
}
@@ -1092,6 +1100,8 @@ export interface CreateInvoiceInput {
/** Save as an unnumbered draft (no F-number, no invoice.created) until the
* user finalizes via "Granska & skapa". Lets the draft be hard-deleted. */
save_as_draft?: boolean
/** Per-invoice öresavrundning override (display-only). Omitted = null (inherit company setting). */
ore_rounding?: boolean
items: CreateInvoiceItemInput[]
}
@@ -2978,6 +2988,13 @@ export interface IngestResult {
transaction_ids: string[]
/** First insert error encountered, surfaced for debugging. Optional. */
first_error?: { message: string; code?: string | null; details?: string | null; hint?: string | null }
/**
* SHADOW-MODE counter: rows that an enforcing same-feed scope-drift dedup rule
* WOULD have treated as re-imports (IBAN-drift re-imports the external_id
* check misses). These are still imported — the field only measures how often
* the rule would fire, so it can be validated on real data before enforcement.
*/
shadow_scope_drift_candidates?: number
}
// ── Invoice extraction (used by invoice-inbox extension and core utils) ──