Fix/cus fee 28 (#820)

* feat(invoices): add Plusgiro input to bank details settings

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

Adds validatePlusgiroNumber/formatPlusgiroNumber helpers + tests.

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

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

Two user-reported bugs:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(sie-export): paginate journal entries and lines to prevent truncation

* fix(bookkeeping): keep the Verifikat/Utkast toggle reachable on an empty list

The journal entry list early-returned a pristine empty card whenever the visible list was empty and no filter was active, returning before the Verifikat/Utkast toggle rendered. This stranded users with only drafts (no posted entries) and users who emptied the drafts list, who then had to use the main menu to get back to posted entries.

Narrow the early return to a genuinely empty ledger (committed view, no drafts, no filters); make the in-list empty placeholder context-aware (no drafts / no filter matches / no posted entries yet); resolve the draft count before clearing loading on an empty committed list to avoid a toggle flicker.

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

* fix(enable-banking): persist psu_type and reuse it on reconnect

Reconnecting a bank connection re-derived psu_type from the company entity_type every time (aktiebolag -> 'business'), silently overriding the type the user actually authorized with. A connection that only signs as 'personal' — common for AB owners who use a personal Mobile BankID, notably at Handelsbanken — flipped back to 'business' on every consent renewal and failed at the bank's signing step.

- Add nullable bank_connections.psu_type column (idempotent migration)
- Persist psu_type on connect; on reconnect reuse the stored value (explicit client override still wins)
- Let users switch account type (Företag/Privat) from the reconnect button
- Tests for persistence, reuse, and override

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

* fix(import): set maxDuration=300 on bank-file execute to prevent timeout

A full-year bank file (300+ rows) runs a sequential per-row ingest that takes ~85s of server time. The execute route set no maxDuration, so it inherited the platform default and was killed mid-run — the import "spins then aborts" for the user. Match the SIE import route and give it a 5-minute budget.

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

* fix(transactions): add assistant entry point on transaction rows

The agent ("Lena") could only be reached from Dokumentinkorgen, and only once an underlag was matched to a transaction. Transaktioner is the most common starting point for booking, so users could not start a booking with the assistant from there at all.

Add a per-row "Fråga [namn]" button on unbooked transaction rows that opens the existing transaction.categorization intent with the row's transaction_id. The intent already reads any linked underlag, so it works whether or not a receipt is attached. No new logic — only the missing entry point.

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

* feat(invoices): enable Swish payment QR on invoices

Flip SHOW_SWISH_ON_INVOICE on so the Swish row and payment QR render on the invoice PDF, and make the "Visa Swish" settings toggle live (it was hardcoded disabled). The preview-pdf route now builds the QR too, so it shows in forhandsvisning. Position the QR in the top-right of the payment box. No Swish API integration -- the QR is generated offline and prefills the customer Swish app; reconciliation stays via bank matching.

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

* fix(bookkeeping): scope verifikat list to current year, add storno action, clarify correction preview

Three UI fixes from user feedback; no engine logic changed.

- List defaults to the current räkenskapsår instead of all years. Voucher
  numbers run per fiscal year (one A42/year), so showing every year at once
  made them look like duplicates. New resolveCurrentPeriodId helper.
- Add 'Återför (storno)' action on the entry detail page and list row, wiring
  the existing reverseEntry — a pure reversal (BFL 5 kap 5§) with no
  replacement, distinct from 'Rätta'.
- Correction 'Effekt per konto' preview now labels a removed account 'tas bort'
  (vs a bare dash) and warns when the proposal is unbalanced; dialog explains
  the rows are the full new verifikat.

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

* feat(bank_connections): add psu_type column to persist chosen authorization type

* feat(errors): add CannotReverseStornoError for handling reversal of storno or correction entries

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-06-29 16:34:51 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 4f0a7b1db0
commit 60e33c4b51
29 changed files with 948 additions and 183 deletions
+4 -2
View File
@@ -22,8 +22,10 @@ import { CAPABILITY } from '@/lib/entitlements/keys'
//
// Page-specific triggers (e.g. "Granska med assistent" on a supplier invoice)
// still call useAgentSheet() directly from their own buttons because they
// know exactly which entity to pass. (Per-transaction help is reached from
// Dokumentinkorgen, not a transactions-page row button.)
// know exactly which entity to pass. (Per-transaction help has its own
// row-level "Fråga [namn]" button in TransactionInboxCard — and the matching
// "Fråga assistenten" in Dokumentinkorgen — both passing a transaction_id the
// pathname-only FAB can't know.)
export default function AgentTrigger() {
const { openAgentSheet, isOpen, identity } = useAgentSheet()
const pathname = usePathname()
@@ -178,7 +178,14 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
{/* Corrected lines (editable) */}
<div className="space-y-2">
<p className="text-sm font-medium">Rättade rader</p>
<div className="space-y-1">
<p className="text-sm font-medium">Rättade rader</p>
<p className="text-xs text-muted-foreground">
Det här är hela den nya verifikationen — alla konton som ska finnas kvar måste stå
kvar. Tar du bort ett konto nollställs det (stornon återför det). Vill du bara återföra
hela verifikatet utan att ersätta det, använd Återför (storno) istället.
</p>
</div>
<div className="space-y-2">
{lines.map((line, index) => (
+23 -5
View File
@@ -4,6 +4,7 @@ import { AccountNumber } from '@/components/ui/account-number'
import {
buildCorrectionRows,
formatSignedAmount,
type AccountRow,
type CorrectionLineInput,
} from '@/components/bookkeeping/correction-preview-rows'
import type { JournalEntryLine } from '@/types'
@@ -28,6 +29,18 @@ export default function CorrectionPreview({ originalLines, correctedLines }: Pro
return (Number.isFinite(d) && d > 0) || (Number.isFinite(c) && c > 0)
})
// An account that was on the original but the user dropped from the rättelse:
// the storno still drains it to zero (delta = −original). Flag it so the cell
// reads "tas bort" instead of a bare "–", which would imply "unchanged".
const isRemoved = (row: AccountRow) =>
hasAnyCorrection && !row.correctionPresent && Math.abs(row.original) >= 0.005
// The per-account deltas sum to the corrected lines' debit − credit. A non-zero
// sum means the proposed rättelse is not yet balanced — surface that here so the
// förändring column is read as a work-in-progress, not a miscalculation.
const netDelta = rows.reduce((sum, r) => sum + r.delta, 0)
const unbalanced = hasAnyCorrection && Math.abs(netDelta) >= 0.005
if (rows.length === 0) return null
return (
@@ -62,8 +75,8 @@ export default function CorrectionPreview({ originalLines, correctedLines }: Pro
<td className={`px-3 py-1.5 text-right tabular-nums ${signClass(row.storno)}`}>
{formatSignedAmount(row.storno)}
</td>
<td className={`px-3 py-1.5 text-right tabular-nums ${signClass(row.correction)}`}>
{hasAnyCorrection ? formatSignedAmount(row.correction) : '–'}
<td className={`px-3 py-1.5 text-right tabular-nums ${isRemoved(row) ? 'text-muted-foreground' : signClass(row.correction)}`}>
{!hasAnyCorrection ? '–' : isRemoved(row) ? 'tas bort' : formatSignedAmount(row.correction)}
</td>
<td
className={`px-3 py-1.5 text-right tabular-nums border-l font-medium ${signClass(row.delta)}`}
@@ -96,8 +109,8 @@ export default function CorrectionPreview({ originalLines, correctedLines }: Pro
</div>
<div>
<dt className="text-muted-foreground">Rättelse</dt>
<dd className={`tabular-nums ${signClass(row.correction)}`}>
{hasAnyCorrection ? formatSignedAmount(row.correction) : '–'}
<dd className={`tabular-nums ${isRemoved(row) ? 'text-muted-foreground' : signClass(row.correction)}`}>
{!hasAnyCorrection ? '–' : isRemoved(row) ? 'tas bort' : formatSignedAmount(row.correction)}
</dd>
</div>
</dl>
@@ -107,8 +120,13 @@ export default function CorrectionPreview({ originalLines, correctedLines }: Pro
<p className="text-xs text-muted-foreground">
Förändring = storno + rättelse. Det är det netto som tillkommer ovanpå originalet när du
bokför.
bokför. Ett konto du tar bort nollställs av stornon.
</p>
{unbalanced && (
<p className="text-xs text-destructive">
Förslaget balanserar inte ännu – debet och kredit i rättelsen måste vara lika.
</p>
)}
</div>
)
}
+139 -31
View File
@@ -26,15 +26,17 @@ import {
STORAGE_KEY_PREFIX as FISCAL_YEAR_STORAGE_KEY_PREFIX,
ALL_YEARS_VALUE as FISCAL_YEAR_ALL_VALUE,
} from '@/components/common/FiscalYearSelector'
import { ChevronDown, ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, Paperclip, AlertTriangle, CircleSlash, Loader2, BookOpen, X, Copy, Lock, Search, SlidersHorizontal } from 'lucide-react'
import { ChevronDown, ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, Paperclip, AlertTriangle, CircleSlash, Loader2, BookOpen, X, Copy, Lock, Search, SlidersHorizontal, RotateCcw } from 'lucide-react'
import { formatDate, formatCurrency } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { resolveCurrentPeriodId } from '@/lib/bookkeeping/suggest-fiscal-period'
import { Input } from '@/components/ui/input'
import { AccountNumber } from '@/components/ui/account-number'
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
import NoDocRequiredToggle from '@/components/bookkeeping/NoDocRequiredToggle'
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
import JournalEntryStatusBadge from '@/components/bookkeeping/JournalEntryStatusBadge'
import AttachmentPreviewSheet from '@/components/bookkeeping/AttachmentPreviewSheet'
import { useToast } from '@/components/ui/use-toast'
@@ -92,6 +94,8 @@ export default function JournalEntryList() {
const [bulkReason, setBulkReason] = useState('')
const [bulkSubmitting, setBulkSubmitting] = useState(false)
const [correctionEntry, setCorrectionEntry] = useState<JournalEntry | null>(null)
const [reverseEntryTarget, setReverseEntryTarget] = useState<JournalEntry | null>(null)
const [isReversing, setIsReversing] = useState(false)
const [previewEntryId, setPreviewEntryId] = useState<string | null>(null)
const [sortBy, setSortBy] = useState<SortBy>('date_desc')
const [sortHydrated, setSortHydrated] = useState(false)
@@ -214,41 +218,53 @@ export default function JournalEntryList() {
setPageSizeHydrated(true)
}, [company?.id])
// Restore the persisted fiscal-year selection (per company), reading the same
// localStorage key FiscalYearSelector writes. The selector lives inside the
// filter dialog and only mounts when opened, so we resolve the saved scope
// here — independent of the dialog — to keep the initial fetch correct.
// periodHydrated gates the first fetch so the list loads already scoped.
useEffect(() => {
if (company?.id && typeof window !== 'undefined') {
const stored = window.localStorage.getItem(FISCAL_YEAR_STORAGE_KEY_PREFIX + company.id)
setPeriodId(stored && stored !== FISCAL_YEAR_ALL_VALUE ? stored : null)
} else {
setPeriodId(null)
}
setPeriodHydrated(true)
}, [company?.id])
// Fetch fiscal periods so the active räkenskapsår can be labelled on the
// filter bar without opening the dialog (BFL period-orientation: the user
// should always see which year the ledger is scoped to). Read-only — the
// dialog's FiscalYearSelector still owns selection; this copy resolves the
// name for display.
// Fetch fiscal periods AND resolve the initial fiscal-year scope in one pass.
// The list is period-oriented (BFL): verifikationsnummer run as an unbroken
// series *per räkenskapsår*, so the same number (e.g. A42) recurs once per
// year. Showing every year at once makes those look like duplicates and makes
// a bare "A42" reference ambiguous — so we default to the räkenskapsår the
// user is currently in rather than "all years". An explicit "Alla
// räkenskapsår" choice (persisted as ALL_YEARS_VALUE) is still honoured.
// Resolving the scope here — not in the dialog's FiscalYearSelector, which
// only mounts when opened — keeps the first fetch correct. periodHydrated
// gates that first fetch so the list loads already scoped to the resolved year.
useEffect(() => {
if (!company?.id) {
setPeriods([])
setPeriodId(null)
setPeriodHydrated(true)
return
}
let cancelled = false
;(async () => {
let fetched: FiscalPeriod[] = []
try {
const res = await fetch('/api/bookkeeping/fiscal-periods')
if (!res.ok) return
const { data } = await res.json()
if (!cancelled) setPeriods((data || []) as FiscalPeriod[])
if (res.ok) {
const { data } = await res.json()
fetched = (data || []) as FiscalPeriod[]
}
} catch {
// Non-critical — the chip falls back to the active-filter count badge.
// Non-critical — fall through with an empty list (scope stays "all years").
}
if (cancelled) return
setPeriods(fetched)
const stored =
typeof window !== 'undefined'
? window.localStorage.getItem(FISCAL_YEAR_STORAGE_KEY_PREFIX + company.id)
: null
if (stored === FISCAL_YEAR_ALL_VALUE) {
// User explicitly chose "all years" — respect it.
setPeriodId(null)
} else if (stored && fetched.some((p) => p.id === stored)) {
setPeriodId(stored)
} else {
// No (valid) saved scope → default to the current räkenskapsår.
const today = new Date().toISOString().split('T')[0]
setPeriodId(resolveCurrentPeriodId(fetched, today))
}
setPeriodHydrated(true)
})()
return () => {
cancelled = true
@@ -299,13 +315,21 @@ export default function JournalEntryList() {
const loadedEntries = data || []
setEntries(loadedEntries)
setCount(total || 0)
// The pristine empty card vs. the (toggle-bearing) "drafts exist" state hinges
// on draftCount. When the committed list comes back empty, resolve the draft
// count BEFORE clearing loading so the toggle doesn't flash out for a frame on
// a stale count of 0. Every other case refreshes the badge in the background.
if (loadedEntries.length === 0 && listMode === 'committed') {
await fetchDraftCount()
} else {
fetchDraftCount()
}
setLoading(false)
// Fetch attachment counts for the loaded entries
const ids = loadedEntries.map((e: JournalEntry) => e.id)
fetchAttachmentCounts(ids)
fetchDraftCount()
}
// Cheap count-only query for the "Utkast" badge — all years, so the badge
@@ -364,6 +388,35 @@ export default function JournalEntryList() {
}
}
// Pure reversal (storno) of a posted verifikat — books a stornoverifikation
// with no replacement, per BFL 5 kap 5§. Routes through the engine's
// reverseEntry (storno + reverses_id link; original → 'reversed', never
// deleted). "Rätta" stays the path for booking a replacement entry instead.
const handleReverse = async () => {
const target = reverseEntryTarget
if (!target) return
setIsReversing(true)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${target.id}/reverse`, { method: 'POST' })
const result = await res.json()
if (res.ok) {
const storno = result.data
toast({
title: t('toast_reverse_done_title'),
description: t('toast_reverse_done_description', { voucher: formatVoucher(storno ?? {}) }),
})
setReverseEntryTarget(null)
await fetchEntries()
} else {
toast({ title: t('toast_reverse_failed'), description: getErrorMessage(result, { context: 'journal_entry' }), variant: 'destructive' })
}
} catch {
toast({ title: t('toast_reverse_failed'), variant: 'destructive' })
} finally {
setIsReversing(false)
}
}
// A posted, document-requiring entry with no attachment yet and not already
// exempt — i.e. the rows that show the warning triangle. Only these can be
// batch-marked "Inget underlag krävs".
@@ -560,7 +613,12 @@ export default function JournalEntryList() {
})
}
if (!loading && entries.length === 0 && !hasActiveFilters) {
// Pristine, untouched ledger: nothing posted, no drafts, no filters, and we're
// on the committed view. ONLY this genuinely-empty case may short-circuit the
// whole component — every other empty state (a draft exists, or we're in the
// drafts view) must fall through to the main render below so the
// Verifikat/Utkast toggle stays reachable.
if (!loading && entries.length === 0 && !hasActiveFilters && listMode === 'committed' && draftCount === 0) {
return (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12">
@@ -897,14 +955,32 @@ export default function JournalEntryList() {
</CardContent>
</Card>
) : filteredEntries.length === 0 ? (
// Empty placeholder, scoped to the situation: an empty drafts view, a
// filtered committed view with no matches, or a committed view with no
// posted entries yet (but drafts exist — hence we got here, not the
// pristine early return above).
<Card>
<CardContent className="flex flex-col items-center justify-center py-12">
<div className="p-4 rounded-full bg-muted mb-4">
<Search className="h-6 w-6 text-muted-foreground" />
{listMode === 'drafts' || !hasActiveFilters ? (
<BookOpen className="h-6 w-6 text-muted-foreground" />
) : (
<Search className="h-6 w-6 text-muted-foreground" />
)}
</div>
<h3 className="text-lg font-medium mb-1">{t('no_results_title')}</h3>
<h3 className="text-lg font-medium mb-1">
{listMode === 'drafts'
? t('empty_drafts_title')
: hasActiveFilters
? t('no_results_title')
: t('empty_title')}
</h3>
<p className="text-sm text-muted-foreground text-center max-w-sm">
{t('no_results_description')}
{listMode === 'drafts'
? t('empty_drafts_description')
: hasActiveFilters
? t('no_results_description')
: t('empty_description')}
</p>
</CardContent>
</Card>
@@ -1276,6 +1352,17 @@ export default function JournalEntryList() {
{t('create_correction')}
</Button>
)}
{canWrite && entry.status === 'posted' && entry.source_type !== 'storno' && entry.source_type !== 'correction' && (
<Button
variant="outline"
size="sm"
className="w-full sm:w-auto"
onClick={() => setReverseEntryTarget(entry)}
>
<RotateCcw className="mr-2 h-4 w-4" />
{t('reverse_action')}
</Button>
)}
<Button
variant="outline"
size="sm"
@@ -1365,6 +1452,27 @@ export default function JournalEntryList() {
/>
)}
{/* Reverse (storno) confirmation dialog */}
{reverseEntryTarget && (
<ConfirmationDialog
open={!!reverseEntryTarget}
onOpenChange={(open) => { if (!open && !isReversing) setReverseEntryTarget(null) }}
onConfirm={handleReverse}
isSubmitting={isReversing}
title={t('reverse_confirm_title')}
warningText={t('reverse_warning')}
confirmLabel={t('reverse_confirm_label')}
>
<div className="flex items-start gap-3 rounded-lg border bg-muted/50 p-4">
<RotateCcw className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0" />
<div className="text-sm">
<p className="font-medium mb-1">{t('reverse_dialog_heading', { voucher: formatVoucher(reverseEntryTarget) })}</p>
<p className="text-muted-foreground">{t('reverse_dialog_body')}</p>
</div>
</div>
</ConfirmationDialog>
)}
{/* Attachment preview sheet */}
<AttachmentPreviewSheet
entryId={previewEntryId}
@@ -22,8 +22,8 @@ describe('buildCorrectionRows', () => {
const rows = buildCorrectionRows(original, corrected)
expect(rows).toEqual([
{ account_number: '1930', original: -1000, storno: 1000, correction: -1200, delta: -200 },
{ account_number: '5410', original: 1000, storno: -1000, correction: 1200, delta: 200 },
{ account_number: '1930', original: -1000, storno: 1000, correction: -1200, delta: -200, correctionPresent: true },
{ account_number: '5410', original: 1000, storno: -1000, correction: 1200, delta: 200, correctionPresent: true },
])
})
@@ -46,6 +46,7 @@ describe('buildCorrectionRows', () => {
storno: -1000,
correction: 0,
delta: -1000,
correctionPresent: false,
})
expect(rows.find((r) => r.account_number === '5420')).toEqual({
account_number: '5420',
@@ -53,6 +54,7 @@ describe('buildCorrectionRows', () => {
storno: 0,
correction: 1000,
delta: 1000,
correctionPresent: true,
})
expect(rows.find((r) => r.account_number === '1930')).toEqual({
account_number: '1930',
@@ -60,6 +62,7 @@ describe('buildCorrectionRows', () => {
storno: 1000,
correction: -1000,
delta: 0,
correctionPresent: true,
})
})
@@ -92,6 +95,7 @@ describe('buildCorrectionRows', () => {
storno: -1000,
correction: 1500.5,
delta: 500.5,
correctionPresent: true,
})
})
@@ -111,6 +115,37 @@ describe('buildCorrectionRows', () => {
expect(rows[0].correction).toBe(0)
})
it('flags a removed account: storno drains it, correctionPresent is false', () => {
// The reported scenario: a sale-shaped verifikat where the user drops the
// revenue line (3001) from the rättelse. The storno still reverses 3001
// (delta = −original), and correctionPresent=false lets the UI label it
// "tas bort" rather than rendering a bare "–".
const original = [
makeJournalEntryLine({ account_number: '1510', debit_amount: 0, credit_amount: 1875 }),
makeJournalEntryLine({ account_number: '2611', debit_amount: 375, credit_amount: 0 }),
makeJournalEntryLine({ account_number: '3001', debit_amount: 1500, credit_amount: 0 }),
]
const corrected = [
{ account_number: '2611', debit_amount: 375, credit_amount: 0 },
{ account_number: '1510', debit_amount: 0, credit_amount: 1875 },
]
const rows = buildCorrectionRows(original, corrected)
expect(rows.find((r) => r.account_number === '3001')).toEqual({
account_number: '3001',
original: 1500,
storno: -1500,
correction: 0,
delta: -1500,
correctionPresent: false,
})
// The kept accounts net to zero and stay flagged as present.
expect(rows.find((r) => r.account_number === '1510')?.delta).toBe(0)
expect(rows.find((r) => r.account_number === '1510')?.correctionPresent).toBe(true)
expect(rows.find((r) => r.account_number === '2611')?.delta).toBe(0)
expect(rows.find((r) => r.account_number === '2611')?.correctionPresent).toBe(true)
})
it('rounds to öre to avoid 0.1+0.2 drift', () => {
const original = [
makeJournalEntryLine({ account_number: '5410', debit_amount: 0.1, credit_amount: 0 }),
@@ -12,6 +12,14 @@ export interface AccountRow {
storno: number
correction: number
delta: number
/**
* True when this account appears on at least one (4-digit) corrected line.
* Lets the UI tell apart an account the user removed from the rättelse — which
* the storno then zeroes (delta = −original) — from one that was never part of
* the correction at all. Without this distinction a removed account renders as
* a bare "–", reading as "unchanged" when it is in fact being drained.
*/
correctionPresent: boolean
}
function toNumber(v: string | number | null | undefined): number {
@@ -44,7 +52,14 @@ export function buildCorrectionRows(
const ensure = (acc: string): AccountRow => {
let row = map.get(acc)
if (!row) {
row = { account_number: acc, original: 0, storno: 0, correction: 0, delta: 0 }
row = {
account_number: acc,
original: 0,
storno: 0,
correction: 0,
delta: 0,
correctionPresent: false,
}
map.set(acc, row)
}
return row
@@ -63,6 +78,7 @@ export function buildCorrectionRows(
const net = toNumber(line.debit_amount) - toNumber(line.credit_amount)
const row = ensure(line.account_number)
row.correction += net
row.correctionPresent = true
}
for (const row of map.values()) {
+7 -9
View File
@@ -4,7 +4,6 @@ import { useTranslations } from 'next-intl'
import { useState, useCallback } from 'react'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { useToast } from '@/components/ui/use-toast'
import type { CompanySettings } from '@/types'
@@ -113,17 +112,16 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
/>
</div>
{/* Swish on invoices is "coming soon" — the toggle is disabled until the
payment-QR flow ships (gated by SHOW_SWISH_ON_INVOICE in pdf-template). */}
<div className="flex items-center justify-between opacity-60">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-2">
<Label>{t('show_swish_label')}</Label>
<Badge variant="secondary" className="text-[10px]">{t('coming_soon')}</Badge>
</div>
<Label>{t('show_swish_label')}</Label>
<p className="text-xs text-muted-foreground">{t('show_swish_help')}</p>
</div>
<Switch checked={false} disabled aria-label={t('show_swish_label')} />
<Switch
checked={settings.invoice_show_swish ?? false}
onCheckedChange={(v) => saveToggle('invoice_show_swish', v)}
aria-label={t('show_swish_label')}
/>
</div>
<div className="flex items-center justify-between">
@@ -25,6 +25,7 @@ import {
FileText,
Link2,
Loader2,
MessageCircle,
MoreHorizontal,
Paperclip,
Pencil,
@@ -46,6 +47,7 @@ import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-exten
const HAS_AI_EXTRACTION = ENABLED_EXTENSION_IDS.has('document-extraction')
import { TransactionAttachmentIndicator } from './TransactionAttachmentIndicator'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { useAgentSheet } from '@/components/agent/AgentSheetProvider'
import type { TransactionWithInvoice, CategorizeHandler } from './transaction-types'
interface TransactionInboxCardProps {
@@ -104,6 +106,11 @@ export default function TransactionInboxCard({
// Attaching underlag is a write — hide the affordance from viewers so they
// don't dead-end on a 403 (mirrors the gate in TransactionHistoryList).
const { canWrite } = useCanWrite()
// The transaction-side entry point to the assistant ("Lena"). openAgentSheet
// hands this specific bank line to the transaction.categorization intent —
// the mirror of "Fråga assistenten" in Dokumentinkorgen, so the user can
// start a booking with the agent from the inbox they actually live in.
const { openAgentSheet, identity } = useAgentSheet()
const isProcessing = processingId === transaction.id
const isDisabled = processingId !== null && processingId !== transaction.id
const isIncome = transaction.amount > 0
@@ -142,6 +149,12 @@ export default function TransactionInboxCard({
// Unbooked rows are still actionable (match, split, edit, categorize) — that
// includes imported bank rows, which are the whole point of the inbox.
const isUnbooked = !transaction.journal_entry_id
// "Fråga [namn]" hands the row to the assistant for categorization/booking.
// Only on unbooked rows (nothing to categorize once it's a verifikat) and
// only after the user has built their agent in /onboarding/agent
// (identity.isVerified) — same gate as the FAB / AgentSparkleButton.
const assistantName = identity.displayName?.trim() || 'min assistent'
const showAskAssistant = isUnbooked && identity.isVerified
// ...but only rows the USER created in the app may be deleted. Imported rows
// (bank sync / CSV) are ignore-only — mirrors the server guard in
// DELETE /api/transactions/[id]. See lib/transactions/origin.ts.
@@ -326,13 +339,35 @@ export default function TransactionInboxCard({
<Link2 className="h-4 w-4" />
</Button>
)}
{/* The Paperclip indicator next to the description
(TransactionAttachmentIndicator) is the single click
target for opening the underlag. We deliberately don't
duplicate that with a second icon in the trailing slot.
Per-transaction agent help has moved to Dokumentinkorgen:
match the underlag to the transaction and ask from there,
where the receipt/invoice is in view. */}
{/* "Fråga [namn]" — hand this bank line to the assistant for
categorization/booking. The transaction-side entry point to
the agent, mirroring "Fråga assistenten" in Dokumentinkorgen.
The intent reads any linked underlag automatically, so it
works whether or not the row already has a receipt attached.
Icon-only ghost so it sits quietly in the row's action
group. (The Paperclip indicator next to the description
stays the single click target for opening the underlag —
we don't duplicate that here.) */}
{showAskAssistant && (
<Button
variant="ghost"
size="icon"
className="h-9 w-9 text-muted-foreground hover:text-foreground"
onClick={(e) => {
e.stopPropagation()
openAgentSheet({
intentId: 'transaction.categorization',
intentArgs: { transaction_id: transaction.id },
contextRef: `transaction:${transaction.id}`,
})
}}
aria-label={`Fråga ${assistantName}`}
title={`Fråga ${assistantName}`}
disabled={isProcessing || isDisabled}
>
<MessageCircle className="h-4 w-4" />
</Button>
)}
{/* Secondary actions (split, edit, delete) collapse into a ⋯
overflow menu so the row stays uncluttered. */}
{showOverflowMenu && (