Files
accounted/app/(dashboard)/transactions/page.tsx
T
MattssonandClaude Fable 5 f24b26a139 fix: similar-sweep currency remediation, security hardening and v1 API fixes (#1215)
* fix(security): gate replace_sie_import behind owner/admin membership

The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no
company_members lookup, no auth.uid() reference and no unauthorized raise,
while setting gnubok.allow_delete to disarm the BFL immutability and
retention triggers. Any caller holding a company_id and an import id could
hard delete another tenant's verifikationer. Confirmed live in production.

Applies the same fail closed owner/admin guard that undo_sie_import already
carries (migration 20260624120000), resolving the actor from
COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then
revokes EXECUTE from PUBLIC and anon. search_path and the raised
statement_timeout are restated, since CREATE OR REPLACE drops settings that
are not repeated.

userId is a required parameter on replaceSIEImport: the service client has a
NULL auth.uid(), so a caller without an explicit actor now fails to compile
rather than hitting the closed gate at runtime.

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

* fix(security): validate arcim OAuth callback state server side

The callback route is skipAuth and decoded the state parameter as plain
base64url JSON, trusting consentId and provider from it. A one time code was
minted at flow start and never read. An unauthenticated attacker who learned
a consent id could run an OAuth flow on their own provider account and post
the callback with a forged state, landing their tokens on another tenant's
consent, so the victim's next migration imported the attacker's ledger.

State is now an opaque randomBytes(32) pointer to a provider_otc row,
consumed by a single atomic UPDATE guarded on used_at IS NULL and
expires_at, so a replay loses the row lock race and updates nothing.
provider is read from provider_consents rather than trusted from the client.
provider_otc already existed for exactly this purpose and was never wired up.

Also scopes getConsent to an owning company, closing a cross tenant status
oracle where the preview and migrate paths echoed a consent's status before
the scoped check ran.

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

* fix(security): scope documents storage to company_id (phase A)

The documents bucket policies matched on auth.uid(), and upload keys were
documents/{userId}/..., so company membership was never consulted. Removing a
member revoked nothing: their session still authenticated and they kept
direct Storage read access to every receipt, supplier invoice and bank
statement they had uploaded. The same bug was fixed for sie-files in
20260416120000; this bucket was left behind.

Phase A is additive. Company scoped policies are added alongside the
uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and
reads accept either layout so nothing breaks mid migration. Phase C, which
drops the old policies, is gated on the backfill reporting zero remaining
legacy prefix objects.

The policy compares the company segment as text rather than casting to uuid
the way sie-files does: this bucket holds keys whose second segment is not a
uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix
qual runs before the cast, so a planner reordering would raise 22P02 and fail
the whole query instead of filtering the row out.

deleteDocument now removes both candidate keys. Removing only the stored
pointer would leave a readable orphan copy of a document the user asked to
erase.

The backfill script is included but has never been run. It defaults to dry
run, refuses .env.local by name, and verifies each copy is readable and
SHA-256 identical before repointing the row.

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

* fix(security): enforce events:read scope and membership on /api/events

This was the only one of the three validateApiKey call sites with no
downstream guard: v1 and the MCP server both check scope and re-verify
company membership, this route did neither. An events:read scope existed and
was documented as gating the endpoint but was never called, so a legacy key
falling back to DEFAULT_SCOPES read the full log. The bound company id went
straight from the api_keys row into a service role query, so a key whose user
had been removed from the company kept reading.

Adds the scope check before any database access, re-verifies company_members
with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead
of ignoring it, applies minimisePayload so the pull surface can never return
a wider payload than the push surface, and replaces the three flat error
strings with the canonical envelope.

Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is
gated on mutations in with-api-v1, so a read gets the same treatment as every
other v1 read endpoint.

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

* perf(bookkeeping): sweep remaining journal_entries!inner embeds

A previous refactor removed this pattern from lib/reports and introduced
fetchEntryLines, but the class was never swept. Seventeen sites remained and
had become the top application consumer of production database time:
measured across the resulting query shapes, 32,694 calls and 25,848 seconds
of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at
7,962ms against the 8s statement_timeout, which surfaced to users as 500s on
the booking path.

PostgREST compiles an embed with filters on the embedded side into a
correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops
Postgres reordering the join, so each query walked the whole
journal_entry_lines table across all tenants. Driving from the entries side
instead turns that into two indexed round trips.

Converted sites keep their existing shape: the helper reattaches the parent
entry under the same key the embed produced. Several conversions also remove
a latent silent truncation where an unpaginated query was capped at
PostgREST's 1000 row ceiling.

Two deliberate exceptions. The free text ilike legs of the MCP display query
stay on the embed, because each is capped at legLimit and that cap drives the
truncation contract the tool reports, while the helper is unbounded. The
accounts route moves to the existing get_account_usage_counts RPC instead,
since its embed was a head count and the helper returns rows.

commitEntry's write path is untouched: the change there is confined to the
read query of the pre-commit dimension rule check.

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

* fix(api): anchor v1 list cursors on created_at

Page two returned page one, forever, while still advertising a fresh
next_cursor. The three routes sorted by and encoded a Postgres date column,
which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor
timestamp as full ISO-8601 and returned null, so the keyset filter was never
applied and has_more never went false. An integrator syncing verifikat looped
on the newest rows indefinitely.

The transactions route already solved this and its comment names the trap;
the fix was never ported. All three now order and encode on created_at with
an id tie break, matching the transactions keyset predicate exactly.
ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change
sort semantics on the route that currently works.

Default ordering therefore moves from business date to insert order. Every
business date is still on the row, and the invoices list gains date_from and
date_to filters so a date range is still reachable; the other two already had
them.

The tests use an in-memory PostgREST that actually evaluates the filters,
because the repo's pass-through mock cannot catch this class of bug: the bug
is that the filter is never sent. They walk to exhaustion with a hard
iteration cap, so an unterminated walk fails instead of hanging.

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

* fix(api): separate dry run from commit in the idempotency hash

The request hash was built from url.pathname, which excludes the query
string, so a dry run and its commit hashed identically. Following the flow
documented in dry-run.ts, re-issuing the request with the same
Idempotency-Key returned the cached preview with Idempotent-Replayed set and
wrote nothing, while reporting 200. An agent or integrator saw success for a
write that never happened.

dry_run is folded into the hash only when true, not as an unconditional
boolean. Including it as false would change the hash of every ordinary write,
and with a 24h idempotency TTL any key in flight across the deploy would fail
the request_hash comparison and 409 on a legitimate retry. Both hash call
sites now go through one shared helper so they cannot drift into a permanent
cache miss, and dry run responses are no longer stored at all.

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

* ci: install the Bedrock SDK out of tree in the compliance review

The Swedish accounting compliance gate had failed ten consecutive runs and so
was posting nothing. With --no-package-lock npm discarded the lockfile and
re-resolved the whole tree from package.json, floating @hookform/resolvers to
5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0.

Installing into the parent of the checkout resolves only that one package, so
an unrelated peer conflict can never take the gate down again. Node still
finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH
would not have worked, as it is CommonJS only. --legacy-peer-deps was
rejected because it masks future genuine peer conflicts and still reifies the
full tree.

The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that
package.json and check:guards enforce after the streaming outage. That drift
went unnoticed because the pin guard only inspects package.json and the
lockfile, never workflow files.

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

* build(docker): generate crontabs from vercel.json

vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were
byte identical to each other. Self hosted deployments therefore never sent
recurring invoices, never dispatched webhooks and never cleaned up
idempotency keys. tax-deadlines also ran once a year on 2 January instead of
daily, and documents/verify weekly instead of daily.

Extension crons are included rather than excluded. The Dockerfile copies the
whole tree before building, so every extension cron route is compiled into
the image regardless of the enabled preset, and each returns 200 when its
extension is unconfigured, so curl -sf logs no failure. Two such entries were
already present in the crontab for extensions absent from the preset, which
settles the intent.

documents/verify is treated as drift rather than a self hosted concession:
the weekly cadence was present in the hosted crontab too, and the run is
capped at 200 documents walking a nulls-first queue, so weekly drains the
integrity queue seven times slower on a check that exists for BFL retention.

webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day
on self hosted. A gentler tick would silently stretch the first retry, since
the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line
place to change that.

A parity test asserts the path sets match minus a documented exclusion list,
and ratchets three cron routes that are currently scheduled nowhere so they
are named rather than silently rotting.

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

* chore(observability): add a provider agnostic error sink

There is no error tracking in this codebase: logs go to console and Vercel
retention and nowhere else, nothing alerts on the 16 cron jobs, and seven
code comments across lib, app, components and extensions asserted that Sentry
captures errors when Sentry is not a dependency. The two most recent bug
fixes on this repo were both discovered by customer email.

This adds the sink, not a vendor. No dependency is taken: the interface has a
no-op default and a registration point, so behaviour is unchanged until an
adapter is registered. Releases are tagged from the build id already inlined
by next.config.ts.

Redaction moved out of lib/logger.ts into a leaf module that both the logger
and the sink import, so there is one denylist and no path from application
data to a third party can skip the personnummer regex, including direct sink
calls that bypass the logger. That matters here because these logs carry
personnummer and financial data.

verifyCronSecret now reports its own 401s, which covers all 16 jobs without
touching a route file and catches the case where CRON_SECRET is rotated
without updating the scheduler and every job silently 401s forever. The
threshold is one failure rather than the backup alert's three: suppressing
the first occurrence is precisely how an outage stays invisible.

The seven misleading comments are corrected to describe what the code
actually does, including the two cases that still are not covered: the client
side one, since the sink is server side, and a warn level call that is not
forwarded.

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

* fix: remediate the 2026-07-26 similar-sweep findings across all surfaces

Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with
one agent per finding; every behavioural fix carries a regression test proven
to fail at HEAD. Full status, corrections to the sweep, refusals and open
decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md.

Structural roots closed:
- resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking
  1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING
- ledger-line-amount.ts: journal_entry_lines.currency labels the document,
  not the amount; SQL pre-filter decoy proven and fixed
- sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the
  exploitable salary payslip-line PATCH and KPI preferences sinks fixed
- tests/schema: migration-replay phantom-column guard (13k+ refs, closed
  CHECK sets, onConflict targets); found 28 real defects, all fixed, all
  four baselines now empty
- three new ratchet guards: sek-labelled-amount, cross-extension-import,
  ungated-extension-route

Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap),
RC input VAT mismatch wired on web + both MCP callers, missing-underlag
resource delegates to the shared RPC predicate, push-notifications consent
polarity fail-closed, deadlines undo honours requested state, silent-failure
and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/
Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites
with isSwedishUserMessage extended.

Also includes the parallel session's MCP invoice tools (update_invoice,
recurring schedules, invoice deliveries) which share files with the sweep
work and are verified green together.

13 new migrations are NOT applied anywhere; they apply via branch merge.
20260726120000 backfills 1247 supplier-invoice rows. pg tests for new
DDL are written but unrun (no local Postgres).

Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0
errors, check:guards passing, MCP payload 57475/57500.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(migrations): rename replace_sie_import migration off main's 20260726090000 version

origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping
our replace_sie_import migration on the same version would abort the Supabase
apply with a schema_migrations_pkey duplicate at merge time.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): remediate pre-publish deep-review findings across all slices

A 13-agent review of the full branch diff surfaced 1 critical, 5 high and
~45 further findings; this commit resolves them in one pass:

- replace_sie_import / undo_sie_import: p_user_id honored only for
  service_role callers; any other caller is pinned to auth.uid()
  (impersonation gate bypass), authz raise errcode 42501 mapped to a
  Swedish 403 in the route, new caller-guard migration for undo
- bulk_book_transactions refuses homogeneous non-SEK batches instead of
  writing foreign magnitudes into SEK ledger columns
- credit-note cap trigger: company-match on credited_invoice_id, no
  cross-tenant figures in exception text
- link_voucher RPCs resolve NULL invoice currency as SEK end to end
- personal-number ciphertext CHECK split into NOT VALID + VALIDATE
- same-currency foreign settlements clear 1510 at booking rate and book
  realized diff to 3960/7960; rate-less foreign write paths refuse
- receivables revaluation covers partially_paid and outstanding amounts
- period lock guard paginates candidates past the PostgREST 1000 cap
- documents: service-client storage removals after authz, dual-layout
  reads in integrity cron and archive export, backfill delete-source
  sweep actually deletes with hash verification and shared-key grouping
- invoice matching normalizes NULL/lowercase currencies (regression),
  duplicate candidates stop claiming amount matches they never ran
- match-invoice aborts on any booking failure (no paid-without-verifikat)
- refresh-exchange-rate reverts on concurrent booking (TOCTOU window)
- KPI preferences upsert arbiter aligned to the company-scoped constraint
- personnummer_last4 stripped from all salary responses incl. MCP tools
- worked-hours batch restores destroyed rows on conflict and error paths
- MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit
  on tag_journal_lines overflow, auto_send schedules stage as high risk
- observability sink redacts emails/IBANs/API keys and keeps redacted
  stacks in prod; assorted small guards (safe-return-to /@, dry_run=True,
  cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings
  call removed)

Full dispositions, deferred items and hand-verified accounting numbers
are documented in the PR body and DECISIONS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(personnummer): implement masking and encryption for personal numbers with tests

* fix(review): address CI and compliance-bot findings for PR #1215

pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role
GUC, so both service-role simulations (runAsServiceRole and the
invoice-delivery test's local helper) never satisfied auth.role() =
'service_role' and every legitimate p_user_id path failed closed; the
shared helper now sets both GUC shapes plus SET LOCAL ROLE with a
fail-loud sanity check, and the delivery test reuses it. The link-voucher
migration had recreated both RPCs from pre-rewrite file text,
reintroducing the NULL-unsafe membership pattern the
null-safe-tenant-guards ratchet bans; both guards now use
public.caller_is_company_member() with all currency changes preserved.

Compliance bots: the customers export now emits the standard masked form
instead of raw AES-256-GCM ciphertext in the Org-/personnummer column,
and maskCustomerRow returns a non-round-trippable placeholder on decrypt
failure instead of 500ing the list. MCP parity: gnubok_lock_period's
staging pre-check now runs the exact countUnbookedInPeriod the commit
path enforces (exported from period-service; local mirror deleted), and
gnubok_agi_status resolves AGI state run-scoped so a correction run no
longer renders as already filed.

Declined with evidence: PR-Agent's opening-balances null-zeroing concern
(all mergeable columns are NOT NULL with defaults per 20260713101000).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): address codex review findings on PR #1215

- restore 20260726140000 to its preview-recorded content and restate the
  NULL-safe tenant guard under 20260727130000: a recorded migration version
  never re-runs, so the in-place edit could not reach the preview branch
- replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap
  warning texts and update the pinned test expectations
- drop the em dash in the fiscal-periods route comment
- strip trailing whitespace in import-existing.test.ts

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(reports): raise timeout on real PDF render tests

renderToBuffer does real @react-pdf layout work and exceeds the 5s
default when the full suite saturates the CPU; tests pass in isolation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 03:34:56 +02:00

2967 lines
119 KiB
TypeScript

'use client'
import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import type { SupabaseClient } from '@supabase/supabase-js'
import dynamic from 'next/dynamic'
import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { ToastAction } from '@/components/ui/toast'
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
import { DataList, DataListEmpty } from '@/components/ui/data-list'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { TH_CLASS, QUIET_LINK_CLASS } from '@/components/ui/dry-table'
import { Loader2, Search } from 'lucide-react'
import TransactionStatusBar from '@/components/transactions/TransactionStatusBar'
import BankSyncStatusChip from '@/components/transactions/BankSyncStatusChip'
import { ContextPicker, type ContextPickerItem } from '@/components/common/ContextPicker'
import { AttnLine } from '@/components/ui/attn-line'
import BankSyncNowButton from '@/components/transactions/BankSyncNowButton'
import TransactionInboxCard from '@/components/transactions/TransactionInboxCard'
import TransactionHistoryList from '@/components/transactions/TransactionHistoryList'
import InboxZeroState from '@/components/transactions/InboxZeroState'
import SkattekontoInboxCard from '@/components/transactions/SkattekontoInboxCard'
import type { BookedDuplicateCandidate } from '@/lib/transactions/booking-duplicate-detection'
import { DialogLoadingSkeleton } from '@/components/ui/dialog-loading-skeleton'
import { getDefaultAccountForCategory, getDefaultVatTreatmentForCategory } from '@/lib/bookkeeping/category-mapping'
import { getTemplateById, type BookingTemplate } from '@/lib/bookkeeping/booking-templates'
import { isCounterpartyTemplateId, extractCounterpartyId } from '@/lib/bookkeeping/counterparty-templates'
import { isLibraryTemplateId } from '@/lib/bookkeeping/template-library'
import type {
TransactionWithInvoice,
ViewMode,
CategorizeHandler,
} from '@/components/transactions/transaction-types'
import type {
SkattekontoTransactionWithSuggestion,
StoredSkattekontoTransaction,
} from '@/types/skatteverket'
import { findBankSkvCounterparts } from '@/lib/skatteverket/bank-counterpart'
import { useCompany } from '@/contexts/CompanyContext'
import { useRealtimeSupabase } from '@/lib/hooks/use-realtime-supabase'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import type { TransactionCategory, CreateTransactionInput, Invoice, Customer, SupplierInvoice, Supplier, VatTreatment, EntityType, LinePatternEntry, BookingTemplateLibrary, CashAccount } from '@/types'
import type { SuggestedTemplate } from '@/lib/transactions/category-suggestions'
import { isImportedTransaction } from '@/lib/transactions/origin'
import { computeJeUnderlagStatus, type JeUnderlagStatus } from '@/lib/transactions/underlag-status'
function InlineDialogContentLoading() {
return (
<div className="space-y-4 py-4" role="status">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-24 w-full" />
<Skeleton className="h-10 w-40" />
</div>
)
}
const TransactionForm = dynamic(() => import('@/components/transactions/TransactionForm'), { loading: InlineDialogContentLoading })
const BatchCategorySelector = dynamic(() => import('@/components/transactions/BatchCategorySelector'), { loading: DialogLoadingSkeleton })
const InvoiceMatchDialog = dynamic(() => import('@/components/transactions/InvoiceMatchDialog'), { loading: DialogLoadingSkeleton })
const MatchVoucherDialog = dynamic(
() => import('@/components/transactions/MatchVoucherDialog').then((module) => module.MatchVoucherDialog),
{ loading: DialogLoadingSkeleton },
)
const InvoicePicker = dynamic(() => import('@/components/transactions/InvoicePicker'), { loading: InlineDialogContentLoading })
const SupplierInvoicePicker = dynamic(() => import('@/components/transactions/SupplierInvoicePicker'), { loading: InlineDialogContentLoading })
const MatchAllocationDialog = dynamic(() => import('@/components/transactions/MatchAllocationDialog'), { loading: DialogLoadingSkeleton })
const BulkBookDialog = dynamic(() => import('@/components/transactions/BulkBookDialog'), { loading: DialogLoadingSkeleton })
const TransactionBookingDialog = dynamic(() => import('@/components/transactions/TransactionBookingDialog'), { loading: DialogLoadingSkeleton })
const TransactionAttachDocumentDialog = dynamic(
() => import('@/components/transactions/TransactionAttachDocumentDialog'),
{ loading: DialogLoadingSkeleton },
)
const QuickReviewDialog = dynamic(() => import('@/components/transactions/QuickReviewDialog'), { loading: DialogLoadingSkeleton })
const EditTransactionTitleDialog = dynamic(
() => import('@/components/transactions/EditTransactionTitleDialog'),
{ loading: DialogLoadingSkeleton },
)
const SkattekontoMatchDialog = dynamic(
() => import('@/components/skattekonto/SkattekontoMatchDialog').then((module) => module.SkattekontoMatchDialog),
{ loading: DialogLoadingSkeleton },
)
const DuplicateBookingDialog = dynamic(
() => import('@/components/transactions/DuplicateBookingDialog'),
{ loading: DialogLoadingSkeleton },
)
const TemplatePicker = dynamic(() => import('@/components/transactions/TemplatePicker'), { loading: InlineDialogContentLoading })
type InvoiceWithCustomer = Invoice & { customer?: Customer }
type SupplierInvoiceWithSupplier = SupplierInvoice & { supplier?: Supplier }
// Source filter for the merged inbox (concept scene 10 account chooser):
// everything, one cash account ('acct:<id>'), bank rows not yet tied to a
// registered cash account ('bank:other'), all bank rows ('bank': the fallback
// split when no cash accounts are registered), or the skattekonto side.
type SourceFilter = 'all' | 'bank' | 'bank:other' | 'skatteverket' | `acct:${string}`
const SOURCE_FILTER_STORAGE_KEY = 'Accounted:transaction-source-filter:v1'
// Journal-entry ids get interpolated into the supplier-invoice .or() filter
// string in the underlag-badge effect below. They come from journal_entries.id
// (DB-sourced), but this guard keeps the interpolated list UUID-only, matching
// /api/documents/counts.
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
// Validates a persisted value. Stale acct:<id> entries (account removed or
// disabled) are caught later by the sourceItems stale-filter guard.
function isSourceFilter(value: string | null): value is SourceFilter {
return (
value === 'all' ||
value === 'bank' ||
value === 'bank:other' ||
value === 'skatteverket' ||
(value?.startsWith('acct:') ?? false)
)
}
function buildInvoiceMap(rows: InvoiceWithCustomer[] | null): Record<string, InvoiceWithCustomer> {
if (!rows) return {}
return rows.reduce<Record<string, InvoiceWithCustomer>>((acc, inv) => {
acc[inv.id] = inv
return acc
}, {})
}
function buildSupplierInvoiceMap(
rows: SupplierInvoiceWithSupplier[] | null,
): Record<string, SupplierInvoiceWithSupplier> {
if (!rows) return {}
return rows.reduce<Record<string, SupplierInvoiceWithSupplier>>((acc, inv) => {
acc[inv.id] = inv
return acc
}, {})
}
// Fetch the potential invoice/supplier-invoice matches referenced by a page
// of transactions in one parallel round trip. A single-query PostgREST embed
// on potential_supplier_invoice_id is blocked until that FK exists in the
// prod schema cache (see DECISIONS.md 2026-07-06).
async function fetchPotentialMatches(
supabase: SupabaseClient,
rows: { potential_invoice_id: string | null; potential_supplier_invoice_id: string | null }[],
) {
const potentialInvoiceIds = rows
.filter((t) => t.potential_invoice_id)
.map((t) => t.potential_invoice_id)
const potentialSupplierInvoiceIds = rows
.filter((t) => t.potential_supplier_invoice_id)
.map((t) => t.potential_supplier_invoice_id)
const [invoiceResult, supplierInvoiceResult] = await Promise.all([
potentialInvoiceIds.length > 0
? supabase.from('invoices').select('*, customer:customers(*)').in('id', potentialInvoiceIds)
: Promise.resolve({ data: null, error: null }),
potentialSupplierInvoiceIds.length > 0
? supabase.from('supplier_invoices').select('*, supplier:suppliers(*)').in('id', potentialSupplierInvoiceIds)
: Promise.resolve({ data: null, error: null }),
])
// Non-fatal: the transaction list still renders without match hints, but
// log so a DB failure isn't mistaken for "no potential match".
if (invoiceResult.error) {
console.error('[fetchPotentialMatches] invoices query failed', invoiceResult.error)
}
if (supplierInvoiceResult.error) {
console.error('[fetchPotentialMatches] supplier_invoices query failed', supplierInvoiceResult.error)
}
return {
invoiceMap: buildInvoiceMap(invoiceResult.data),
supplierInvoiceMap: buildSupplierInvoiceMap(supplierInvoiceResult.data),
}
}
interface QuickReviewState {
transaction: TransactionWithInvoice
category: TransactionCategory
label: string
template: BookingTemplate | null
templateId: string | undefined
linePattern: LinePatternEntry[] | null
}
export default function TransactionsPage() {
const { company } = useCompany()
const companyId = company?.id ?? null
const t = useTranslations('transactions')
const [transactions, setTransactions] = useState<TransactionWithInvoice[]>([])
const [isLoading, setIsLoading] = useState(true)
const [mode, setMode] = useState<ViewMode>('inbox')
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [isCreating, setIsCreating] = useState(false)
const [templateSuggestions, setTemplateSuggestions] = useState<Record<string, SuggestedTemplate[]>>({})
const [processingId, setProcessingId] = useState<string | null>(null)
const [searchTerm, setSearchTerm] = useState('')
// Batch selection: hover checkboxes + bulkbar (concept), no mode toggle.
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [showBatchSelector, setShowBatchSelector] = useState(false)
const [batchProgress, setBatchProgress] = useState<{ done: number; total: number } | null>(null)
// Row expansion (concept foldout): one open row at a time, mirroring the
// verifikat list.
const [expandedTxId, setExpandedTxId] = useState<string | null>(null)
// Invoice match dialog
const [matchDialogOpen, setMatchDialogOpen] = useState(false)
const [selectedTransaction, setSelectedTransaction] = useState<TransactionWithInvoice | null>(null)
const [isConfirmingMatch, setIsConfirmingMatch] = useState(false)
// Booking dialog (journal entry form)
const [bookingDialogOpen, setBookingDialogOpen] = useState(false)
const [bookingDialogTransaction, setBookingDialogTransaction] = useState<TransactionWithInvoice | null>(null)
const [bookingDialogTemplate, setBookingDialogTemplate] = useState<BookingTemplateLibrary | null>(null)
// Attach-underlag dialog (tx→doc mirror of the Documents view's matcher)
const [attachDocTx, setAttachDocTx] = useState<TransactionWithInvoice | null>(null)
// Underlag status per booked journal_entry_id: drives the per-row
// "Underlag"/"Underlag saknas" badges in history view.
const [jeUnderlagStatus, setJeUnderlagStatus] = useState<Record<string, JeUnderlagStatus>>({})
// JE ids already requested (in-flight or done) so the enrichment effect
// never refetches on unrelated transactions-state changes.
const requestedJeIdsRef = useRef<{ companyId: string | null; ids: Set<string> }>({
companyId: null,
ids: new Set(),
})
// Template picker dialog
const [templatePickerOpen, setTemplatePickerOpen] = useState(false)
const [templatePickerTransaction, setTemplatePickerTransaction] = useState<TransactionWithInvoice | null>(null)
// Invoice picker dialog (manual match)
const [invoicePickerOpen, setInvoicePickerOpen] = useState(false)
const [invoicePickerTransaction, setInvoicePickerTransaction] = useState<TransactionWithInvoice | null>(null)
const [supplierInvoicePickerOpen, setSupplierInvoicePickerOpen] = useState(false)
const [supplierInvoicePickerTransaction, setSupplierInvoicePickerTransaction] = useState<TransactionWithInvoice | null>(null)
const [splitMatchOpen, setSplitMatchOpen] = useState(false)
const [splitMatchTransaction, setSplitMatchTransaction] = useState<TransactionWithInvoice | null>(null)
// "Matcha mot befintlig verifikation": link a bank tx to an already-booked
// voucher (salary, Fortnox import, manual entry) with no new bokföring.
const [matchVoucherTx, setMatchVoucherTx] = useState<TransactionWithInvoice | null>(null)
const [bulkBookOpen, setBulkBookOpen] = useState(false)
const [isMatchingSupplierFromPicker, setIsMatchingSupplierFromPicker] = useState(false)
const [isMatchingFromPicker, setIsMatchingFromPicker] = useState(false)
// Quick review dialog (suggestion review before booking)
const [quickReviewOpen, setQuickReviewOpen] = useState(false)
const [quickReview, setQuickReview] = useState<QuickReviewState | null>(null)
// Prong B: prompt to match against an open supplier invoice instead of
// categorizing direct to 2440. Triggered by a 409 TX_CATEGORIZE_SUGGEST_SI_MATCH.
const [siMatchSuggestion, setSiMatchSuggestion] = useState<{
transactionId: string
retry: () => Promise<string | null>
candidates: Array<{
supplier_invoice_id: string
invoice_number: string
invoice_date: string
remaining_amount: number
currency: string
supplier_name: string | null
}>
} | null>(null)
const [siMatchProcessing, setSiMatchProcessing] = useState(false)
// Prong B (customer side): prompt to match against an unpaid customer
// invoice instead of categorizing direct to 1510 on an inbound bank tx.
// Triggered by a 409 TX_CATEGORIZE_SUGGEST_CI_MATCH.
const [ciMatchSuggestion, setCiMatchSuggestion] = useState<{
transactionId: string
retry: () => Promise<string | null>
candidates: Array<{
invoice_id: string
invoice_number: string | null
invoice_date: string
remaining_amount: number
currency: string
customer_name: string | null
match_reason: 'ocr_exact' | 'name_amount_fuzzy'
}>
} | null>(null)
const [ciMatchProcessing, setCiMatchProcessing] = useState(false)
// Booking-time duplicate guard (TRANSACTION_BOOK_POSSIBLE_DUPLICATE): the
// server found this affärshändelse already booked: either another booked
// transaction sharing this one's date+amount+bank account, OR an unlinked
// voucher that already books the amount on the bank account (a paid invoice,
// a salary payout). Surface the existing verifikat and let the user book
// anyway: genuinely repeated same-day payments (e.g. identical Swish
// transfers) are legitimate. "Bokför ändå" retries with force bound to the
// reviewed candidate via expected_duplicate_journal_entry_id (present on both
// candidate kinds), which the server re-detects so a stale id can't wave it.
const [duplicateWarning, setDuplicateWarning] = useState<{
transactionId: string
retry: () => Promise<string | null>
candidate: BookedDuplicateCandidate
} | null>(null)
const [duplicateProcessing, setDuplicateProcessing] = useState(false)
// Dashboard layout already resolved the effective entity type from settings.
const entityType = company?.entity_type ?? 'enskild_firma'
// Pagination
const [hasMore, setHasMore] = useState(false)
const [isLoadingMore, setIsLoadingMore] = useState(false)
// True uncategorized count from DB (not limited by pagination)
const [totalUncategorizedCount, setTotalUncategorizedCount] = useState<number | null>(null)
// Set of transaction IDs that are animating out (just categorized)
const [exitingIds, setExitingIds] = useState<Set<string>>(new Set())
// Skattekonto rows (unmatched, status='booked'). Loaded if the
// Skatteverket extension is enabled and connected. 503/401 → silently
// hidden (extension disabled or user not connected).
const [skvRows, setSkvRows] = useState<SkattekontoTransactionWithSuggestion[]>([])
const [skvProcessingId, setSkvProcessingId] = useState<string | null>(null)
const [skvMatchTarget, setSkvMatchTarget] = useState<StoredSkattekontoTransaction | null>(
null,
)
// True when an SKV connection exists but is dead (needs_reconsent, or
// expired with no refresh left). Drives the reconnect banner: without it
// a user whose token died sees an empty skattekonto and has no reason to
// ever visit the settings panel where the reconnect prompt lives.
const [skvNeedsReconnect, setSkvNeedsReconnect] = useState(false)
// One browser-wide source filter, persisted (#1105) so the choice
// survives reloads. Defaults to 'all'.
const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all')
useEffect(() => {
try {
const stored = window.localStorage.getItem(SOURCE_FILTER_STORAGE_KEY)
if (isSourceFilter(stored)) setSourceFilter(stored)
} catch {
// localStorage may be unavailable. Keep the default in-memory state.
}
}, [])
const handleSourceFilterChange = useCallback((next: SourceFilter) => {
setSourceFilter(next)
try {
window.localStorage.setItem(SOURCE_FILTER_STORAGE_KEY, next)
} catch {
// localStorage may be unavailable. The in-memory filter still works.
}
}, [])
// Registered cash accounts (cash_accounts): the account chooser's rows,
// with PSD2 balances when the bank reports them.
const [cashAccounts, setCashAccounts] = useState<CashAccount[]>([])
const { toast } = useToast()
const { dialogProps: confirmDialogProps, confirm } = useDestructiveConfirm()
// Bank transaction whose title is being edited (null = dialog closed).
const [editTitleTarget, setEditTitleTarget] = useState<TransactionWithInvoice | null>(null)
const supabase = useRealtimeSupabase()
const searchParams = useSearchParams()
const highlightId = searchParams.get('highlight')
// Tracks the last highlight target we acted on so re-renders don't re-trigger
// the auto-open every time the user closes the categorize panel.
const handledHighlightRef = useRef<string | null>(null)
const refreshTransactionsInFlightRef = useRef(false)
const refreshTransactionsQueuedRef = useRef(false)
// Computed lists
const uncategorizedTransactions = useMemo(
() => transactions
.filter((t) => t.is_business === null && !t.is_ignored && !exitingIds.has(t.id))
.sort((a, b) => {
const aHasMatch = a.potential_invoice || a.potential_supplier_invoice ? 1 : 0
const bHasMatch = b.potential_invoice || b.potential_supplier_invoice ? 1 : 0
if (aHasMatch !== bHasMatch) return bHasMatch - aHasMatch
return b.date.localeCompare(a.date)
}),
[exitingIds, transactions],
)
// Merged inbox: bank tx + SKV rows interleaved by date. Source filter
// narrows to one side. SKV rows always go after bank rows on the same
// date: bank tx tend to have invoice-match suggestions and we'd rather
// surface those first.
type InboxItem =
| { source: 'bank'; date: string; data: TransactionWithInvoice }
| { source: 'skatteverket'; date: string; data: SkattekontoTransactionWithSuggestion }
const skvUnmatched = useMemo(
() => skvRows.filter((row) => !row.journal_entry_id),
[skvRows],
)
const bankToSkvHints = useMemo(
() => findBankSkvCounterparts({
bankRows: uncategorizedTransactions.map((transaction) => ({
id: transaction.id,
date: transaction.date,
amount: transaction.amount,
})),
skvRows: skvUnmatched,
}),
[skvUnmatched, uncategorizedTransactions],
)
const inboxItems = useMemo<InboxItem[]>(() => {
const items: InboxItem[] = []
const query = searchTerm.trim().toLowerCase()
if (sourceFilter !== 'skatteverket') {
for (const tx of uncategorizedTransactions) {
if (
sourceFilter.startsWith('acct:') &&
tx.cash_account_id !== sourceFilter.slice('acct:'.length)
) {
continue
}
if (sourceFilter === 'bank:other' && tx.cash_account_id != null) continue
if (
query &&
!tx.description?.toLowerCase().includes(query) &&
!tx.date.includes(query) &&
!String(tx.amount).includes(query)
) {
continue
}
items.push({ source: 'bank', date: tx.date, data: tx })
}
}
if (sourceFilter === 'all' || sourceFilter === 'skatteverket') {
// Inbox only shows SKV rows that need action (no verifikat yet).
for (const r of skvRows) {
if (r.journal_entry_id) continue
if (exitingIds.has(r.id)) continue
if (
query &&
!r.transaktionstext?.toLowerCase().includes(query) &&
!r.transaktionsdatum.includes(query) &&
!String(r.belopp_skatteverket).includes(query)
) {
continue
}
items.push({ source: 'skatteverket', date: r.transaktionsdatum, data: r })
}
}
return items.sort((a, b) => {
if (a.date !== b.date) return b.date.localeCompare(a.date)
// Same date → bank first so invoice-match cards lead.
if (a.source !== b.source) return a.source === 'bank' ? -1 : 1
return 0
})
}, [exitingIds, searchTerm, skvRows, sourceFilter, uncategorizedTransactions])
// Account chooser (concept scene 10): the source picker doubles as a
// balance readout. The total sums only SEK ledgers (mixing currencies into
// one figure would be a lie); null hides the annotation entirely.
const totalSourceBalance = useMemo(() => {
const sekBalances = cashAccounts.filter((a) => a.currency === 'SEK' && a.balance != null)
if (sekBalances.length === 0) return null
return sekBalances.reduce((sum, a) => sum + (a.balance ?? 0), 0)
}, [cashAccounts])
const hasUnassignedBankRows = useMemo(
() => uncategorizedTransactions.some((tx) => tx.cash_account_id == null),
[uncategorizedTransactions],
)
const sourceItems = useMemo<ContextPickerItem[]>(() => {
const showSkvSource = skvRows.length > 0
const items: ContextPickerItem[] = [
{
id: 'all',
label: t('source_all_label'),
annotation: totalSourceBalance != null ? formatCurrency(totalSourceBalance) : undefined,
},
]
for (const account of cashAccounts) {
items.push({
id: `acct:${account.id}`,
label: `${account.name || t('source_account_fallback')} ${account.ledger_account}`,
annotation:
account.balance != null ? formatCurrency(account.balance, account.currency) : undefined,
})
}
if (cashAccounts.length === 0 && showSkvSource) {
// No registered cash accounts yet: keep the plain bank/skattekonto split.
items.push({ id: 'bank', label: t('source_bank_label') })
} else if (cashAccounts.length > 0 && hasUnassignedBankRows) {
items.push({ id: 'bank:other', label: t('source_bank_other') })
}
if (showSkvSource) {
items.push({ id: 'skatteverket', label: t('source_skatteverket_label') })
}
return items
}, [cashAccounts, hasUnassignedBankRows, skvRows.length, t, totalSourceBalance])
// A narrowed filter can go stale (account disabled, skv rows drained,
// "övriga" bucket emptied): fall back to everything rather than filtering
// the inbox down to an invisible source.
useEffect(() => {
if (sourceFilter === 'all') return
if (!sourceItems.some((item) => item.id === sourceFilter)) setSourceFilter('all')
}, [sourceFilter, sourceItems])
// Rows the bulkbar's "Markera alla" can select: the visible bank rows
// (skattekonto rows aren't batch-bookable).
const selectableInboxIds = useMemo(
() => inboxItems.filter((item) => item.source === 'bank').map((item) => item.data.id),
[inboxItems],
)
const PAGE_SIZE = 200
// Account chooser rows: the registered, enabled cash accounts. One fetch
// per company; balances refresh with the page (bank sync triggers a
// router.refresh via the sync toast flow).
useEffect(() => {
if (!companyId) return
let cancelled = false
fetch('/api/cash-accounts?enabled_only=true')
.then((res) => (res.ok ? res.json() : { data: [] }))
.then((json: { data?: CashAccount[] }) => {
if (!cancelled) setCashAccounts(json.data ?? [])
})
.catch(() => {
if (!cancelled) setCashAccounts([])
})
return () => {
cancelled = true
}
}, [companyId])
const loadSkvRows = useCallback(async () => {
// Connection health, fetched alongside the rows: any failure (extension
// disabled, capability gate, not connected) just hides the banner.
void (async () => {
try {
const res = await fetch('/api/extensions/ext/skatteverket/status')
if (!res.ok) {
setSkvNeedsReconnect(false)
return
}
const s = (await res.json()) as {
connected?: boolean
disabled?: boolean
needsReconsent?: boolean
expired?: boolean
canRefresh?: boolean
}
setSkvNeedsReconnect(
Boolean(
s.connected &&
!s.disabled &&
(s.needsReconsent || (s.expired && !s.canRefresh)),
),
)
} catch {
setSkvNeedsReconnect(false)
}
})()
try {
const res = await fetch('/api/extensions/ext/skatteverket/skattekonto/transaktioner')
if (!res.ok) {
setSkvRows([])
return
}
const json = await res.json()
const booked = (json.data?.booked ?? []) as SkattekontoTransactionWithSuggestion[]
// Keep all booked SKV rows in state: inbox view filters to obokförda
// (journal_entry_id null), history view shows all of them (matched
// and unmatched) interleaved with bank tx by date.
setSkvRows(booked)
} catch {
setSkvRows([])
}
}, [])
const fetchTransactions = useCallback(async (showLoading = false, includeSkvRows = false) => {
if (!companyId) return
if (showLoading) setIsLoading(true)
if (includeSkvRows) void loadSkvRows()
try {
const [{ data: txData, error: txError }, { count: uncatCount }] = await Promise.all([
supabase
.from('transactions')
.select('*')
.eq('company_id', companyId)
.order('date', { ascending: false })
.limit(PAGE_SIZE),
supabase
.from('transactions')
.select('*', { count: 'exact', head: true })
.eq('company_id', companyId)
.is('is_business', null)
// Same predicate as lib/worklist countUnbookedTransactions: ignored
// rows are handled, not pending.
.eq('is_ignored', false),
])
if (txError) {
toast({ title: t('load_failed_title'), description: t('load_failed_description'), variant: 'destructive' })
return
}
const rows = txData || []
const { invoiceMap, supplierInvoiceMap } = await fetchPotentialMatches(supabase, rows)
const transactionsWithInvoices: TransactionWithInvoice[] = rows.map((t) => ({
...t,
potential_invoice: t.potential_invoice_id ? invoiceMap[t.potential_invoice_id] : undefined,
potential_supplier_invoice: t.potential_supplier_invoice_id
? supplierInvoiceMap[t.potential_supplier_invoice_id]
: undefined,
}))
setTransactions(transactionsWithInvoices)
setTotalUncategorizedCount(uncatCount ?? 0)
setHasMore(rows.length >= PAGE_SIZE)
} finally {
if (showLoading) setIsLoading(false)
}
}, [companyId, loadSkvRows, supabase, t, toast])
const refreshTransactions = useCallback(async () => {
if (!companyId) return
if (refreshTransactionsInFlightRef.current) {
refreshTransactionsQueuedRef.current = true
return
}
refreshTransactionsInFlightRef.current = true
try {
do {
refreshTransactionsQueuedRef.current = false
await fetchTransactions(false, false)
} while (refreshTransactionsQueuedRef.current)
} finally {
refreshTransactionsInFlightRef.current = false
refreshTransactionsQueuedRef.current = false
}
}, [companyId, fetchTransactions])
async function loadMoreTransactions() {
if (!companyId) return
setIsLoadingMore(true)
const offset = transactions.length
const { data: txData, error: txError } = await supabase
.from('transactions')
.select('*')
.eq('company_id', companyId)
.order('date', { ascending: false })
.range(offset, offset + PAGE_SIZE - 1)
if (txError || !txData) {
setIsLoadingMore(false)
return
}
setHasMore(txData.length >= PAGE_SIZE)
const { invoiceMap, supplierInvoiceMap } = await fetchPotentialMatches(supabase, txData)
const newTransactions: TransactionWithInvoice[] = txData.map((t) => ({
...t,
potential_invoice: t.potential_invoice_id ? invoiceMap[t.potential_invoice_id] : undefined,
potential_supplier_invoice: t.potential_supplier_invoice_id
? supplierInvoiceMap[t.potential_supplier_invoice_id]
: undefined,
}))
setTransactions((prev) => [...prev, ...newTransactions])
setIsLoadingMore(false)
}
// Underlag-status enrichment for booked rows. Five RLS-scoped reads per
// 150-id chunk (PostgREST .in() URL-length convention, see
// lib/worklist/categories.ts): the JEs' source types, which JEs have a
// current-version document, which are covered by a supplier invoice's
// retained document (BFL 5 kap 7 § hänvisning: registration/payment FK or a
// supplier_invoice_payments row: mirrors the verifikat_without_documents
// RPC), and which are exempted via journal_entry_no_doc_required.
// Incremental: only fetches JE ids not yet requested, so
// loadMoreTransactions pages are covered without refetching.
// Soft-fails to "no badges" on error.
useEffect(() => {
if (!companyId) return
if (requestedJeIdsRef.current.companyId !== companyId) {
requestedJeIdsRef.current = { companyId, ids: new Set() }
setJeUnderlagStatus({})
}
const requested = requestedJeIdsRef.current.ids
const newIds = Array.from(
new Set(
transactions
.map((tx) => tx.journal_entry_id)
.filter((id): id is string => !!id && !requested.has(id)),
),
)
if (newIds.length === 0) return
newIds.forEach((id) => requested.add(id))
;(async () => {
const IN_CLAUSE_CHUNK = 150
const merged: Record<string, JeUnderlagStatus> = {}
for (let i = 0; i < newIds.length; i += IN_CLAUSE_CHUNK) {
const chunk = newIds.slice(i, i + IN_CLAUSE_CHUNK)
// Only UUIDs reach the interpolated .or() string (the .in() array
// filters are already injection-safe).
const chunkInList = `(${chunk.filter((id) => UUID_RE.test(id)).join(',')})`
const [entriesRes, docsRes, siRefRes, sipRefRes, exemptRes] = await Promise.all([
supabase
.from('journal_entries')
.select('id, source_type')
// Same posted-only scope as countVerifikatMissingDocument:
// reversed/corrected entries fall out of the result set and the
// row renders no badge: a storno'd verifikation must never grow
// an "Underlag saknas" attach affordance.
.eq('status', 'posted')
.in('id', chunk)
.eq('company_id', companyId),
supabase
.from('document_attachments')
.select('journal_entry_id')
.in('journal_entry_id', chunk)
.eq('company_id', companyId)
.eq('is_current_version', true),
supabase
.from('supplier_invoices')
.select(
'registration_journal_entry_id, payment_journal_entry_id, document:document_attachments(journal_entry_id)',
)
.eq('company_id', companyId)
.not('document_id', 'is', null)
.or(
`registration_journal_entry_id.in.${chunkInList},payment_journal_entry_id.in.${chunkInList}`,
),
supabase
.from('supplier_invoice_payments')
.select(
'journal_entry_id, supplier_invoice:supplier_invoices(document_id, document:document_attachments(journal_entry_id))',
)
.eq('company_id', companyId)
.in('journal_entry_id', chunk),
supabase
.from('journal_entry_no_doc_required')
.select('journal_entry_id')
.in('journal_entry_id', chunk)
.eq('company_id', companyId),
])
// Soft-fail: keep the chunks that already succeeded.
if (entriesRes.error || docsRes.error || siRefRes.error || sipRefRes.error || exemptRes.error) break
const jeIdsWithDocs = new Set(
(docsRes.data ?? []).map((d) => d.journal_entry_id as string),
)
for (const si of (siRefRes.data ?? []) as unknown as {
registration_journal_entry_id: string | null
payment_journal_entry_id: string | null
document: { journal_entry_id: string | null } | null
}[]) {
if (!si.document?.journal_entry_id) continue // unanchored: not underlag
if (si.registration_journal_entry_id) jeIdsWithDocs.add(si.registration_journal_entry_id)
if (si.payment_journal_entry_id) jeIdsWithDocs.add(si.payment_journal_entry_id)
}
for (const sip of (sipRefRes.data ?? []) as unknown as {
journal_entry_id: string | null
supplier_invoice: {
document_id: string | null
document: { journal_entry_id: string | null } | null
} | null
}[]) {
if (sip.journal_entry_id && sip.supplier_invoice?.document?.journal_entry_id) {
jeIdsWithDocs.add(sip.journal_entry_id)
}
}
const exemptIds = new Set(
(exemptRes.data ?? []).map((e) => e.journal_entry_id as string),
)
Object.assign(
merged,
computeJeUnderlagStatus(entriesRes.data ?? [], jeIdsWithDocs, exemptIds),
)
}
// The merge is an idempotent keyed write, so it stays valid across
// unrelated transactions-state changes (booking a row, deletes,
// load-more); only a company switch invalidates it. No cleanup-based
// cancellation: that would orphan ids already marked as requested.
if (requestedJeIdsRef.current.companyId === companyId && Object.keys(merged).length > 0) {
setJeUnderlagStatus((prev) => ({ ...prev, ...merged }))
}
})()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [transactions, companyId])
async function fetchCategorySuggestions(txIds: string[]) {
if (txIds.length === 0) return
try {
const response = await fetch('/api/transactions/suggest-categories', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transaction_ids: txIds }),
})
if (!response.ok) throw new Error('Failed to fetch suggestions')
const data = await response.json()
if (data.template_suggestions) {
setTemplateSuggestions(data.template_suggestions)
}
} catch {
// Non-critical
}
}
// Fetch the initial page. Entity type is already available from CompanyContext.
useEffect(() => {
void fetchTransactions(true, true)
}, [fetchTransactions])
useEffect(() => {
if (!companyId) return
let cancelled = false
const refreshFromRealtime = async () => {
if (cancelled) return
await refreshTransactions()
}
const channel = supabase
.channel(`transactions:list:${companyId}`)
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'transactions',
filter: `company_id=eq.${companyId}`,
},
() => {
void refreshFromRealtime()
},
)
.subscribe()
return () => {
cancelled = true
void supabase.removeChannel(channel)
}
}, [companyId, refreshTransactions, supabase])
// Scroll the targeted row into view when arriving via
// /transactions?highlight=<id>. Callers are inbox "Öppna transaktionen",
// payment-booking dialog, and supplier-invoice cross-link: all "go look
// at this row", not "start booking". The legacy auto-open-template-picker
// behavior was removed in v5: booking happens in the inbox workspace now.
// Runs once per distinct highlight id so closing/scrolling away doesn't
// re-trigger it.
useEffect(() => {
if (!highlightId) return
if (handledHighlightRef.current === highlightId) return
if (transactions.length === 0) return
const tx = transactions.find((t) => t.id === highlightId)
if (!tx) return
handledHighlightRef.current = highlightId
// Defer the scroll until React has committed the list to the DOM.
// Without rAF the data-tx-id node may not exist yet when this fires
// immediately after fetchTransactions resolves.
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const el = document.querySelector(`[data-tx-id="${tx.id}"]`)
if (el && 'scrollIntoView' in el) {
el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
})
})
}, [highlightId, transactions])
// Auto-fetch suggestions when transactions load
useEffect(() => {
const uncatIds = transactions
.filter((t) => t.is_business === null)
.map((t) => t.id)
.slice(0, 50)
if (uncatIds.length > 0) {
fetchCategorySuggestions(uncatIds)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [transactions.length])
const handleCategorize: CategorizeHandler = async (id, isBusiness, category, vatTreatment, accountOverride, templateId, inboxItemId) => {
return runCategorize({ id, isBusiness, category, vatTreatment, accountOverride, templateId, inboxItemId, confirmNoMatch: false })
}
async function runCategorize(args: {
id: string
isBusiness: boolean
category?: TransactionCategory
vatTreatment?: VatTreatment
accountOverride?: string
templateId?: string
inboxItemId?: string
confirmNoMatch: boolean
// Set after the user confirms the booking-time duplicate warning. force
// bypasses the guard; the bypass is bound to the reviewed candidate's
// voucher (journal_entry_id), present on both a sibling-transaction and a
// ledger-only voucher candidate.
force?: boolean
expectedDuplicateJournalEntryId?: string
}): Promise<string | null> {
const { id, isBusiness, category, vatTreatment, accountOverride, templateId, inboxItemId, confirmNoMatch, force, expectedDuplicateJournalEntryId } = args
try {
setProcessingId(id)
const response = await fetch(`/api/transactions/${id}/categorize`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
is_business: isBusiness,
category,
vat_treatment: vatTreatment,
account_override: accountOverride,
template_id: templateId,
inbox_item_id: inboxItemId,
...(confirmNoMatch ? { confirm_no_match: true } : {}),
...(force && expectedDuplicateJournalEntryId
? { force: true, expected_duplicate_journal_entry_id: expectedDuplicateJournalEntryId }
: {}),
}),
})
const result = await response.json()
if (!response.ok) {
if (
result?.error?.code === 'TX_CATEGORIZE_SUGGEST_SI_MATCH' &&
Array.isArray(result.error.details?.candidates)
) {
// Prong B: invite the user to match the open supplier invoice
// instead of booking a plain 2440 categorization that would later
// create a duplicate when they hit "Markera som betald".
setSiMatchSuggestion({
transactionId: id,
retry: () => runCategorize({ ...args, confirmNoMatch: true }),
candidates: result.error.details.candidates,
})
setProcessingId(null)
return null
}
if (
result?.error?.code === 'TX_CATEGORIZE_SUGGEST_CI_MATCH' &&
Array.isArray(result.error.details?.candidates)
) {
// Prong B (customer side): invite the user to match the unpaid
// customer invoice instead of booking a plain 1510 categorization
// that would later create a duplicate.
setCiMatchSuggestion({
transactionId: id,
retry: () => runCategorize({ ...args, confirmNoMatch: true }),
candidates: result.error.details.candidates,
})
setProcessingId(null)
return null
}
if (result?.error?.code === 'TX_CATEGORIZE_INVALID_ACCOUNT') {
// The user picked a library template (or typed an account
// override) whose account isn't in this company's kontoplan.
// Mirror the ACCOUNTS_NOT_IN_CHART flow with a one-click
// "Aktivera och bokför": pull the BAS name if known so the
// toast carries real context.
// Validate the BAS account number is a plain 4-digit string before
// embedding it in any fetch URL/body: the value comes from the
// server error envelope but defense-in-depth.
const rawAccountNumber: unknown = result.error.details?.accountNumber
const accountNumber: string | undefined =
typeof rawAccountNumber === 'string' && /^\d{4}$/.test(rawAccountNumber)
? rawAccountNumber
: undefined
let displayName = accountNumber ?? ''
if (accountNumber) {
try {
const lookupRes = await fetch(`/api/bookkeeping/accounts/bas-lookup?numbers=${encodeURIComponent(accountNumber)}`)
if (lookupRes.ok) {
const lookup = await lookupRes.json() as { data?: Array<{ account_number: string; account_name: string | null; known?: boolean }> }
const hit = lookup.data?.find((r) => r.account_number === accountNumber)
if (hit?.account_name) displayName = `${accountNumber} - ${hit.account_name}`
}
} catch { /* fall through to the plain number */ }
}
let invalidAccountActivateInFlight = false
toast({
title: 'Kontot finns inte i din kontoplan',
description: accountNumber
? `Kontot ${displayName} är inte aktiverat.`
: 'Kontot är inte aktiverat.',
variant: 'destructive',
action: accountNumber ? (
<ToastAction altText="Aktivera och bokför" onClick={async () => {
if (invalidAccountActivateInFlight) return
invalidAccountActivateInFlight = true
try {
const activateRes = await fetch('/api/bookkeeping/accounts/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_numbers: [accountNumber] }),
})
if (!activateRes.ok) {
const errBody = await activateRes.json().catch(() => null)
toast({
title: 'Kunde inte aktivera kontot',
description: getErrorMessage(errBody, { statusCode: activateRes.status }),
variant: 'destructive',
})
return
}
const activateBody = await activateRes.json()
if (Array.isArray(activateBody.unknown) && activateBody.unknown.length > 0) {
toast({
title: 'Kontot finns inte i BAS-planen',
description: `Lägg till ${accountNumber} manuellt i Kontoplan.`,
variant: 'destructive',
})
return
}
await runCategorize(args)
} finally {
invalidAccountActivateInFlight = false
}
}}>
Aktivera och bokför
</ToastAction>
) : undefined,
})
setProcessingId(null)
return null
}
if (result?.error?.code === 'ACCOUNTS_NOT_IN_CHART') {
// The mapped template/category references one or more accounts
// that aren't active in this company's kontoplan. Without an
// inline action the user has to navigate to settings, activate
// each account, and come back: surface a one-click "Aktivera
// och bokför" instead.
const accountNumbers: string[] =
(Array.isArray(result.error.account_numbers) && result.error.account_numbers) ||
(Array.isArray(result.error.details?.account_numbers) && result.error.details.account_numbers) ||
[]
// Synchronous in-flight flag per toast closure: a double-click
// would otherwise fire two activate+categorize pairs, where the
// second categorize races the first's verifikation insert.
let activateInFlight = false
toast({
title: 'Kontot finns inte i din kontoplan',
description: `Bokföringsmallen kräver att följande konton aktiveras: ${accountNumbers.join(', ')}.`,
variant: 'destructive',
action: accountNumbers.length > 0 ? (
<ToastAction altText="Aktivera och bokför" onClick={async () => {
if (activateInFlight) return
activateInFlight = true
try {
const activateRes = await fetch('/api/bookkeeping/accounts/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_numbers: accountNumbers }),
})
if (!activateRes.ok) {
const errBody = await activateRes.json().catch(() => null)
toast({
title: 'Kunde inte aktivera konton',
description: getErrorMessage(errBody, { statusCode: activateRes.status }),
variant: 'destructive',
})
return
}
const activateBody = await activateRes.json()
// unknown[] = numbers not in BAS reference at all. Those
// can't be auto-created; tell the user to add them manually.
if (Array.isArray(activateBody.unknown) && activateBody.unknown.length > 0) {
toast({
title: 'Kunde inte hitta alla konton',
description: `Lägg till ${activateBody.unknown.join(', ')} manuellt i Kontoplan.`,
variant: 'destructive',
})
return
}
await runCategorize(args)
} finally {
activateInFlight = false
}
}}>
Aktivera och bokför
</ToastAction>
) : undefined,
})
setProcessingId(null)
return null
}
if (
result?.error?.code === 'TRANSACTION_BOOK_POSSIBLE_DUPLICATE' &&
result.error.details?.candidate
) {
// Booking-time duplicate guard fired. Don't dead-end on a toast that
// merely says "book anyway" with no way to do so: open a dialog with
// the already-booked sibling and let the user confirm. "Bokför ändå"
// re-runs with force bound to this candidate (server re-detects it).
const candidate = result.error.details.candidate as BookedDuplicateCandidate
setDuplicateWarning({
transactionId: id,
retry: () =>
runCategorize({
...args,
force: true,
expectedDuplicateJournalEntryId: candidate.journal_entry_id,
}),
candidate,
})
setProcessingId(null)
return null
}
toast({
title: 'Kategorisering misslyckades',
description: getErrorMessage(result, { context: 'transaction', statusCode: response.status }),
variant: 'destructive',
})
setProcessingId(null)
return null
}
// Mark as exiting for animation, then update state
setExitingIds((prev) => new Set(prev).add(id))
setTotalUncategorizedCount((prev) => Math.max(0, (prev ?? 1) - 1))
if (result.journal_entry_created) {
toast({
title: 'Bokförd',
action: (
<ToastAction altText="Ångra kategorisering" onClick={async () => {
try {
const undoRes = await fetch(`/api/transactions/${id}/uncategorize`, { method: 'POST' })
if (undoRes.ok) {
setTransactions((prev) =>
prev.map((t) =>
t.id === id
? { ...t, is_business: null, category: null as unknown as TransactionCategory, journal_entry_id: null }
: t
)
)
setTotalUncategorizedCount((prev) => (prev ?? 0) + 1)
toast({ title: t('undone_title'), description: t('undone_description') })
} else {
const errData = await undoRes.json()
toast({
title: 'Kunde inte ångra',
description: getErrorMessage(errData, { context: 'transaction', statusCode: undoRes.status }),
variant: 'destructive',
})
}
} catch {
toast({ title: t('undo_failed_title'), description: t('undo_failed_description'), variant: 'destructive' })
}
}}>
Ångra
</ToastAction>
),
})
} else if (result.journal_entry_error) {
toast({ title: 'Delvis bokförd', description: `Verifikation kunde inte skapas: ${result.journal_entry_error}`, variant: 'destructive' })
} else {
toast({ title: t('partially_booked_title'), description: t('partially_booked_description') })
}
// Update transaction in state after a brief delay for animation
setExitingIds((prev) => new Set(prev).add(id))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) =>
t.id === id
? { ...t, is_business: isBusiness, category: result.category, journal_entry_id: result.journal_entry_id }
: t
)
)
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(id)
return next
})
setProcessingId(null)
}, 350)
return result.journal_entry_id || null
} catch {
toast({ title: t('booking_failed_title'), description: t('booking_failed_description'), variant: 'destructive' })
setProcessingId(null)
return null
}
}
async function handleMatchSuggestedInvoice(transactionId: string, invoiceId: string) {
setCiMatchProcessing(true)
try {
const response = await fetch(`/api/transactions/${transactionId}/match-invoice`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ invoice_id: invoiceId }),
})
const result = await response.json()
if (!response.ok) {
toast({
title: 'Matchning misslyckades',
description: getErrorMessage(result, { context: 'transaction', statusCode: response.status }),
variant: 'destructive',
})
setCiMatchProcessing(false)
return
}
toast({ title: t('customer_invoice_matched_title'), description: t('customer_invoice_matched_description') })
setCiMatchSuggestion(null)
setExitingIds((prev) => new Set(prev).add(transactionId))
setTotalUncategorizedCount((prev) => Math.max(0, (prev ?? 1) - 1))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) =>
t.id === transactionId
? {
...t,
invoice_id: invoiceId,
is_business: true,
journal_entry_id: result.journal_entry_id ?? t.journal_entry_id,
}
: t
)
)
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(transactionId)
return next
})
}, 350)
} catch {
toast({ title: t('match_failed_title'), description: t('match_failed_description_retry'), variant: 'destructive' })
} finally {
setCiMatchProcessing(false)
}
}
async function handleMatchSuggestedSupplierInvoice(transactionId: string, supplierInvoiceId: string) {
setSiMatchProcessing(true)
try {
const response = await fetch(`/api/transactions/${transactionId}/match-supplier-invoice`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ supplier_invoice_id: supplierInvoiceId }),
})
const result = await response.json()
if (!response.ok) {
toast({
title: 'Matchning misslyckades',
description: getErrorMessage(result, { context: 'transaction', statusCode: response.status }),
variant: 'destructive',
})
setSiMatchProcessing(false)
return
}
toast({ title: t('supplier_invoice_matched_title'), description: t('supplier_invoice_matched_description') })
setSiMatchSuggestion(null)
setExitingIds((prev) => new Set(prev).add(transactionId))
setTotalUncategorizedCount((prev) => Math.max(0, (prev ?? 1) - 1))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) =>
t.id === transactionId
? {
...t,
supplier_invoice_id: supplierInvoiceId,
is_business: true,
journal_entry_id: result.journal_entry_id ?? t.journal_entry_id,
}
: t
)
)
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(transactionId)
return next
})
}, 350)
} catch {
toast({ title: t('match_failed_title'), description: t('match_failed_description_retry'), variant: 'destructive' })
} finally {
setSiMatchProcessing(false)
}
}
async function handleIgnoreTransaction(tx: TransactionWithInvoice) {
// Mirrors BankReconciliationView's ignore flow: Ignorera is fully
// reversible, but the row vanishes immediately: confirmation before the
// write plus an Ångra toast gives two recovery affordances. The
// "Ignorerade transaktioner" card on Rapporter → Bankavstämning is the
// standing third.
const ok = await confirm({
title: 'Ignorera transaktionen?',
description: `${tx.description}, ${formatCurrency(tx.amount, tx.currency)} (${formatDate(tx.date)}) försvinner från listan utan att bokföras. Använd bara för poster som inte är affärshändelser, t.ex. dubbletter eller överföringar mellan egna konton. Riktiga köp och betalningar ska bokföras. Du kan återställa den under Bankavstämning när som helst.`,
confirmLabel: 'Ignorera',
cancelLabel: 'Avbryt',
variant: 'warning',
})
if (!ok) return
setTemplatePickerOpen(false)
try {
const res = await fetch(`/api/transactions/${tx.id}/ignore`, { method: 'POST' })
const result = await res.json()
if (!res.ok || result.error) {
toast({
title: 'Kunde inte ignorera transaktionen',
description: typeof result.error === 'string' ? result.error : undefined,
variant: 'destructive',
})
return
}
setExitingIds((prev) => new Set(prev).add(tx.id))
setTotalUncategorizedCount((prev) => Math.max(0, (prev ?? 1) - 1))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) => (t.id === tx.id ? { ...t, is_ignored: true } : t))
)
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(tx.id)
return next
})
}, 350)
toast({
title: 'Transaktionen ignorerad',
description: `${tx.description}, ${formatCurrency(tx.amount, tx.currency)}`,
action: (
<ToastAction altText="Ångra ignorera" onClick={() => void handleUnignoreTransaction(tx.id)}>
Ångra
</ToastAction>
),
})
} catch {
toast({ title: 'Kunde inte ignorera transaktionen', variant: 'destructive' })
}
}
async function handleUnignoreTransaction(transactionId: string) {
try {
const res = await fetch(`/api/transactions/${transactionId}/ignore`, { method: 'DELETE' })
const result = await res.json()
if (!res.ok || result.error) {
toast({ title: 'Kunde inte återställa transaktionen', variant: 'destructive' })
return
}
setTransactions((prev) =>
prev.map((t) => (t.id === transactionId ? { ...t, is_ignored: false } : t))
)
setTotalUncategorizedCount((prev) => (prev ?? 0) + 1)
} catch {
toast({ title: 'Kunde inte återställa transaktionen', variant: 'destructive' })
}
}
async function handleConfirmInvoiceMatch(opts?: {
force?: boolean
expected_journal_entry_id?: string
lines?: Array<{
account_number: string
debit_amount: number
credit_amount: number
line_description?: string
}>
}) {
if (!selectedTransaction) return
const isSupplier = !!selectedTransaction.potential_supplier_invoice
const isCustomer = !!selectedTransaction.potential_invoice
if (!isSupplier && !isCustomer) return
setIsConfirmingMatch(true)
try {
const url = isSupplier
? `/api/transactions/${selectedTransaction.id}/match-supplier-invoice`
: `/api/transactions/${selectedTransaction.id}/match-invoice`
const body: Record<string, unknown> = isSupplier
? { supplier_invoice_id: selectedTransaction.potential_supplier_invoice!.id }
: { invoice_id: selectedTransaction.potential_invoice!.id }
if (!isSupplier && opts?.force) {
body.force = true
// Bind the override to the candidate the user saw in the dialog.
// The server re-detects the candidate and rejects the bypass if
// the id doesn't match, so an empty value here surfaces as a
// clean validation error instead of silently widening the guard.
if (opts.expected_journal_entry_id) {
body.expected_journal_entry_id = opts.expected_journal_entry_id
}
}
// User-edited journal entry rows from the match dialog. Forwarded
// verbatim; the server validates balance and posts via
// createJournalEntry directly. Default routing applies when omitted.
if (opts?.lines && opts.lines.length >= 2) {
body.lines = opts.lines
}
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const result = await response.json()
if (!response.ok) {
toast({
title: isSupplier ? 'Leverantörsfakturamatchning misslyckades' : 'Fakturamatchning misslyckades',
description: getErrorMessage(result, { context: 'transaction' }),
variant: 'destructive',
})
setIsConfirmingMatch(false)
return
}
const label = isSupplier
? `Leverantörsfaktura ${selectedTransaction.potential_supplier_invoice!.supplier_invoice_number} markerad som betald`
: `Faktura ${selectedTransaction.potential_invoice!.invoice_number} markerad som betald`
toast({ title: isSupplier ? 'Leverantörsfaktura matchad' : 'Faktura matchad', description: label })
setMatchDialogOpen(false)
// Mark as exiting for animation
setExitingIds((prev) => new Set(prev).add(selectedTransaction.id))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) =>
t.id === selectedTransaction.id
? isSupplier
? {
...t,
supplier_invoice_id: selectedTransaction.potential_supplier_invoice?.id || null,
potential_supplier_invoice: undefined,
is_business: true,
journal_entry_id: result.journal_entry_id,
}
: {
...t,
invoice_id: selectedTransaction.potential_invoice?.id || null,
potential_invoice_id: null,
potential_invoice: undefined,
is_business: true,
category: 'income_services' as TransactionCategory,
journal_entry_id: result.journal_entry_id,
}
: t
)
)
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(selectedTransaction.id)
return next
})
setSelectedTransaction(null)
setIsConfirmingMatch(false)
}, 350)
} catch {
toast({ title: t('match_failed_title'), description: t('match_failed_transaction'), variant: 'destructive' })
setIsConfirmingMatch(false)
}
}
async function handleLinkToExistingVoucher(journalEntryId: string) {
if (!selectedTransaction) return
const invoiceId = selectedTransaction.potential_invoice?.id ?? null
setIsConfirmingMatch(true)
try {
const response = await fetch(
`/api/transactions/${selectedTransaction.id}/link-journal-entry`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
journal_entry_id: journalEntryId,
...(invoiceId ? { invoice_id: invoiceId } : {}),
}),
},
)
const result = await response.json()
if (!response.ok) {
toast({
title: 'Kunde inte koppla till befintlig verifikation',
description: getErrorMessage(result, { context: 'transaction' }),
variant: 'destructive',
})
setIsConfirmingMatch(false)
return
}
const voucherLabel = (result as { voucher_label?: string }).voucher_label ?? ''
toast({
title: 'Bankhändelsen kopplad',
description: voucherLabel
? `Kopplad till verifikation ${voucherLabel}. Ingen ny bokföring skapad.`
: 'Ingen ny bokföring skapad.',
})
setMatchDialogOpen(false)
// Animate out + update local state, same pattern as handleConfirmInvoiceMatch.
setExitingIds((prev) => new Set(prev).add(selectedTransaction.id))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) =>
t.id === selectedTransaction.id
? {
...t,
invoice_id: invoiceId,
potential_invoice_id: null,
potential_invoice: undefined,
is_business: true,
journal_entry_id: journalEntryId,
}
: t,
),
)
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(selectedTransaction.id)
return next
})
setSelectedTransaction(null)
setIsConfirmingMatch(false)
}, 350)
} catch {
toast({
title: 'Koppling misslyckades',
description: t('voucher_link_failed_description'),
variant: 'destructive',
})
setIsConfirmingMatch(false)
}
}
function openMatchVoucherDialog(transaction: TransactionWithInvoice) {
setMatchVoucherTx(transaction)
}
// Called by MatchVoucherDialog after /api/reconciliation/bank/link succeeds.
// The row is now booked (journal_entry_id set, is_business true) so the inbox
// filter drops it: animate it out the same way as the invoice-link path.
function handleVoucherLinked(transactionId: string, journalEntryId: string, voucherLabel: string) {
toast({
title: 'Bankhändelsen kopplad',
description: voucherLabel
? `Kopplad till verifikation ${voucherLabel}. Ingen ny bokföring skapad.`
: 'Ingen ny bokföring skapad.',
})
setMatchVoucherTx(null)
setExitingIds((prev) => new Set(prev).add(transactionId))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) =>
t.id === transactionId
? { ...t, is_business: true, journal_entry_id: journalEntryId }
: t,
),
)
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(transactionId)
return next
})
}, 350)
}
async function handleMatchInvoice(transactionId: string, invoiceId: string): Promise<boolean> {
try {
const response = await fetch(`/api/transactions/${transactionId}/match-invoice`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ invoice_id: invoiceId }),
})
const result = await response.json()
if (!response.ok) {
toast({ title: 'Fakturamatchning misslyckades', description: getErrorMessage(result, { context: 'transaction' }), variant: 'destructive' })
return false
}
const transaction = transactions.find((t) => t.id === transactionId)
const invoiceNumber = transaction?.potential_invoice?.invoice_number || ''
setTransactions((prev) =>
prev.map((t) =>
t.id === transactionId
? {
...t,
invoice_id: invoiceId,
potential_invoice_id: null,
potential_invoice: undefined,
is_business: true,
category: 'income_services' as TransactionCategory,
journal_entry_id: result.journal_entry_id,
}
: t
)
)
toast({ title: 'Faktura matchad', description: `Faktura ${invoiceNumber} markerad som betald` })
return true
} catch {
toast({ title: t('match_failed_title'), description: t('match_failed_with_invoice'), variant: 'destructive' })
return false
}
}
function handleSelectInvoiceFromPicker(invoice: Invoice & { customer?: Customer }) {
if (!invoicePickerTransaction) return
// Don't POST directly from the picker. Route through the confirm dialog
// so the user sees the JE preview (Debet 1930 / Kredit 1510, or the cash
// variant) before the booking is created. Same UX as the auto-suggested
// path. Closes the picker and opens the match dialog with the picked
// invoice attached as potential_invoice.
const tx = invoicePickerTransaction
setInvoicePickerOpen(false)
setInvoicePickerTransaction(null)
setSelectedTransaction({ ...tx, potential_invoice: invoice })
setMatchDialogOpen(true)
}
function handleSelectSupplierInvoiceFromPicker(invoice: SupplierInvoice & { supplier?: Supplier }) {
if (!supplierInvoicePickerTransaction) return
// Route through the confirm dialog so the supplier-side JE preview
// (Debet 2440 / Kredit 1930, or kontant-variant) is shown before commit.
const tx = supplierInvoicePickerTransaction
setSupplierInvoicePickerOpen(false)
setSupplierInvoicePickerTransaction(null)
setSelectedTransaction({ ...tx, potential_supplier_invoice: invoice })
setMatchDialogOpen(true)
}
function openInvoiceMatchPicker(transaction: TransactionWithInvoice) {
if (transaction.amount >= 0) {
setInvoicePickerTransaction(transaction)
setInvoicePickerOpen(true)
} else {
setSupplierInvoicePickerTransaction(transaction)
setSupplierInvoicePickerOpen(true)
}
}
function openSplitMatchDialog(transaction: TransactionWithInvoice) {
setSplitMatchTransaction(transaction)
setSplitMatchOpen(true)
}
// Selected-tx derivation for bulk-book eligibility.
// The action bar shows "Bokför i klump" only when ≥2 txs are selected,
// share the same date, and same direction (all income or all expense):
// matches the RPC's same-day + same-direction invariants so the user
// doesn't submit a guaranteed-fail batch.
const selectedTransactions = useMemo(
() => transactions.filter((t) => selectedIds.has(t.id)),
[transactions, selectedIds],
)
const bulkBookEligible = useMemo(() => {
if (selectedTransactions.length < 2) return false
const first = selectedTransactions[0]!
return selectedTransactions.every(
(t) => t.date === first.date && (t.amount > 0) === (first.amount > 0),
)
}, [selectedTransactions])
async function handleBulkBookSuccess() {
// Animate every selected tx out of the inbox, then refetch and clear
// the selection state. Mirrors the per-tx match success animation.
const ids = Array.from(selectedIds)
setExitingIds((prev) => {
const next = new Set(prev)
for (const id of ids) next.add(id)
return next
})
await refreshTransactions()
setSelectedIds(new Set())
setTimeout(() => {
setExitingIds((prev) => {
const next = new Set(prev)
for (const id of ids) next.delete(id)
return next
})
}, 350)
}
async function handleSplitMatchSuccess() {
if (!splitMatchTransaction) return
const txId = splitMatchTransaction.id
// Mark the tx as exiting to trigger the same removal animation the
// single-match flow uses, then drop it from the inbox once the refetch
// confirms it's booked. Mirrors the pattern at the supplier-invoice
// match success path below.
setExitingIds((prev) => new Set(prev).add(txId))
await refreshTransactions()
setTimeout(() => {
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(txId)
return next
})
}, 350)
}
async function handleCreateTransaction(data: CreateTransactionInput) {
setIsCreating(true)
try {
// Create through the server route so the payload is validated server-side
// (shared CreateTransactionSchema) and the DB CHECK applies: the browser
// client must never be the only guard on a mutation.
const response = await fetch('/api/transactions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
date: data.date,
description: data.description,
amount: data.amount,
currency: data.currency,
category: data.category,
notes: data.notes,
}),
})
const result = await response.json()
if (!response.ok) {
toast({
title: 'Kunde inte skapa transaktion',
description: getErrorMessage(result, { context: 'transaction', statusCode: response.status }),
variant: 'destructive',
})
return
}
toast({ title: 'Transaktion tillagd', description: `${data.description} har lagts till` })
setTransactions([result.data, ...transactions])
setIsDialogOpen(false)
} catch {
toast({ title: 'Kunde inte skapa transaktion', description: t('booking_failed_description'), variant: 'destructive' })
} finally {
setIsCreating(false)
}
}
async function handleDeleteTransaction(id: string) {
const transaction = transactions.find((t) => t.id === id)
if (!transaction) return
const ok = await confirm({
title: 'Ta bort transaktion',
description: `Är du säker på att du vill ta bort "${transaction.description}"? Åtgärden kan inte ångras.`,
confirmLabel: 'Ta bort',
variant: 'destructive',
})
if (!ok) return
try {
const response = await fetch(`/api/transactions/${id}`, { method: 'DELETE' })
if (!response.ok) {
const result = await response.json()
toast({
title: 'Kunde inte ta bort',
description: getErrorMessage(result, { context: 'transaction' }),
variant: 'destructive',
})
return
}
setTransactions((prev) => prev.filter((t) => t.id !== id))
toast({ title: t('deleted_title'), description: t('deleted_description') })
} catch {
toast({
title: 'Kunde inte ta bort',
description: t('delete_failed_description'),
variant: 'destructive',
})
}
}
function openEditTitleDialog(transaction: TransactionWithInvoice) {
setEditTitleTarget(transaction)
}
// Persist a new title via PATCH. Returns true on success so the dialog can
// close; updates the local list optimistically (description + edited tag).
async function handleSaveTitle(description: string): Promise<boolean> {
const target = editTitleTarget
if (!target) return false
try {
const response = await fetch(`/api/transactions/${target.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description }),
})
const result = await response.json()
if (!response.ok) {
toast({
title: t('edit_title_failed'),
description: getErrorMessage(result, { context: 'transaction' }),
variant: 'destructive',
})
return false
}
const updated = result.data as { description: string; title_edited_at: string | null }
setTransactions((prev) =>
prev.map((tx) =>
tx.id === target.id
? { ...tx, description: updated.description, title_edited_at: updated.title_edited_at }
: tx,
),
)
toast({ title: t('edit_title_saved') })
return true
} catch {
toast({ title: t('edit_title_failed'), variant: 'destructive' })
return false
}
}
async function handleSkvBokfor(row: StoredSkattekontoTransaction) {
setSkvProcessingId(row.id)
try {
const res = await fetch(
`/api/extensions/ext/skatteverket/skattekonto/transaktioner/${row.id}/bokfor`,
{ method: 'POST' },
)
const json = await res.json()
if (!res.ok) {
// Map the parsed body plus the status, never `new Error(json.error)`:
// the Error constructor stringifies a non-string body field, and the
// mapper would discard the route's own Swedish reason.
toast({
title: 'Kunde inte bokföra',
description: getErrorMessage(json, { statusCode: res.status }),
variant: 'destructive',
})
return
}
toast({
title: 'Utkast skapat',
description: t('review_in_bookkeeping_description'),
})
window.location.href = `/bookkeeping/${json.data.entry.id}`
} catch (err) {
toast({
title: 'Kunde inte bokföra',
description: err instanceof Error ? getErrorMessage(err) : undefined,
variant: 'destructive',
})
} finally {
setSkvProcessingId(null)
}
}
function handleSkvMatched() {
// After a successful match, drop the row from the inbox: it's now
// linked to a verifikat. Trigger an exit animation first.
if (skvMatchTarget) {
const id = skvMatchTarget.id
setExitingIds(prev => new Set(prev).add(id))
setTimeout(() => {
setSkvRows(prev => prev.filter(r => r.id !== id))
setExitingIds(prev => {
const next = new Set(prev)
next.delete(id)
return next
})
}, 350)
}
}
function handleTransactionBooked(
transactionId: string,
journalEntryId: string,
attachedDocumentId?: string | null,
// True when the duplicate guard's match action LINKED the transaction to
// an existing voucher instead of creating a new one.
matched?: boolean,
) {
setExitingIds((prev) => new Set(prev).add(transactionId))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) =>
t.id === transactionId
? {
...t,
is_business: true,
journal_entry_id: journalEntryId,
// Existing pin wins: the link route only pins when the tx
// had none (document_id IS NULL guard).
document_id: t.document_id ?? attachedDocumentId ?? null,
}
: t
)
)
setExitingIds((prev) => {
const next = new Set(prev)
next.delete(transactionId)
return next
})
}, 350)
setBookingDialogOpen(false)
setBookingDialogTransaction(null)
setBookingDialogTemplate(null)
if (matched) {
toast({ title: 'Bankhändelsen kopplad', description: 'Ingen ny bokföring skapad.' })
} else {
toast({ title: 'Bokförd' })
}
}
function openAttachDocumentDialog(transaction: TransactionWithInvoice) {
setAttachDocTx(transaction)
}
function handleDocumentAttached(transactionId: string, documentId: string) {
setTransactions((prev) =>
prev.map((t) => (t.id === transactionId ? { ...t, document_id: documentId } : t))
)
// Booked row: the attach route propagated the doc onto the verifikation,
// so flip the JE status optimistically too. Read the JE id off the
// dialog's own subject (attachDocTx), not the transactions snapshot:
// the list may have changed (load-more, booking) while the dialog was
// open, and a stale find() would silently skip the badge flip.
const jeId =
attachDocTx?.id === transactionId ? attachDocTx.journal_entry_id : null
if (jeId) {
setJeUnderlagStatus((prev) => ({ ...prev, [jeId]: 'has' }))
}
}
// Batch mode handlers
function toggleBatchSelect(id: string) {
setSelectedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
function exitBatchMode() {
setSelectedIds(new Set())
}
async function handleBatchDelete() {
// Only user-created rows can be deleted; imported (bank sync / CSV) rows are
// ignore-only. Split the selection so we never fire a delete the server
// would 409, and tell the user how many were skipped. Mirrors the server
// guard in DELETE /api/transactions/[id].
const selected = Array.from(selectedIds)
const ids: string[] = []
let skippedImported = 0
for (const id of selected) {
const tx = transactions.find((t) => t.id === id)
if (tx && isImportedTransaction(tx)) skippedImported++
else ids.push(id)
}
if (ids.length === 0) {
toast({
title: 'Inget att ta bort',
description: 'De valda transaktionerna är importerade och kan endast ignoreras, inte raderas.',
variant: 'destructive',
})
return
}
const ok = await confirm({
title: `Ta bort ${ids.length} transaktioner?`,
description:
skippedImported > 0
? `${skippedImported} importerade transaktioner hoppas över (kan endast ignoreras). Åtgärden kan inte ångras.`
: 'Åtgärden kan inte ångras.',
confirmLabel: 'Ta bort',
variant: 'destructive',
})
if (!ok) return
const deletedIds = new Set<string>()
setBatchProgress({ done: 0, total: ids.length })
let successes = 0
const failures: string[] = []
for (let i = 0; i < ids.length; i++) {
try {
const response = await fetch(`/api/transactions/${ids[i]}`, { method: 'DELETE' })
if (response.ok) {
successes++
deletedIds.add(ids[i])
} else {
const tx = transactions.find((t) => t.id === ids[i])
failures.push(tx?.description || ids[i])
}
} catch {
failures.push(ids[i])
}
setBatchProgress({ done: i + 1, total: ids.length })
}
if (deletedIds.size > 0) {
setTransactions((prev) => prev.filter((t) => !deletedIds.has(t.id)))
}
setBatchProgress(null)
if (failures.length === 0 && skippedImported === 0) {
toast({ title: 'Klart', description: `${successes} transaktioner borttagna` })
} else {
const parts = [`${successes} borttagna`]
if (failures.length > 0) parts.push(`${failures.length} misslyckades`)
if (skippedImported > 0) parts.push(`${skippedImported} importerade kunde inte raderas`)
toast({
title: 'Delvis klart',
description: parts.join(', '),
variant: 'destructive',
})
}
exitBatchMode()
}
async function handleBatchIgnore() {
const ids = Array.from(selectedIds)
const ok = await confirm({
title: `Ignorera ${ids.length} transaktioner?`,
description: 'Transaktionerna försvinner från listan utan att bokföras. Du kan återställa dem under Bankavstämning.',
confirmLabel: 'Ignorera',
cancelLabel: 'Avbryt',
variant: 'warning',
})
if (!ok) return
const ignoredIds = new Set<string>()
setBatchProgress({ done: 0, total: ids.length })
let successes = 0
const failures: string[] = []
for (let i = 0; i < ids.length; i++) {
try {
const res = await fetch(`/api/transactions/${ids[i]}/ignore`, { method: 'POST' })
if (res.ok) {
successes++
ignoredIds.add(ids[i])
} else {
const tx = transactions.find((t) => t.id === ids[i])
failures.push(tx?.description || ids[i])
}
} catch {
failures.push(ids[i])
}
setBatchProgress({ done: i + 1, total: ids.length })
}
if (ignoredIds.size > 0) {
setExitingIds((prev) => {
const next = new Set(prev)
for (const id of ignoredIds) next.add(id)
return next
})
setTotalUncategorizedCount((prev) => Math.max(0, (prev ?? ignoredIds.size) - ignoredIds.size))
setTimeout(() => {
setTransactions((prev) =>
prev.map((t) => (ignoredIds.has(t.id) ? { ...t, is_ignored: true } : t))
)
setExitingIds((prev) => {
const next = new Set(prev)
for (const id of ignoredIds) next.delete(id)
return next
})
}, 350)
}
setBatchProgress(null)
if (failures.length === 0) {
toast({
title: 'Klart',
description: `${successes} transaktioner ignorerade`,
action: (
<ToastAction altText="Öppna Bankavstämning" asChild>
<Link href="/reports/bank-reconciliation">Bankavstämning</Link>
</ToastAction>
),
})
} else {
toast({
title: 'Delvis klart',
description: `${successes} ignorerade, ${failures.length} misslyckades`,
variant: 'destructive',
})
}
exitBatchMode()
}
async function handleBatchCategorize(category: TransactionCategory, vatTreatment?: VatTreatment) {
const ids = Array.from(selectedIds)
setBatchProgress({ done: 0, total: ids.length })
let successes = 0
const failures: string[] = []
for (let i = 0; i < ids.length; i++) {
const result = await handleCategorize(ids[i], true, category, vatTreatment)
if (result) {
successes++
} else {
const tx = transactions.find((t) => t.id === ids[i])
failures.push(tx?.description || ids[i])
}
setBatchProgress({ done: i + 1, total: ids.length })
}
setBatchProgress(null)
setShowBatchSelector(false)
if (failures.length === 0) {
toast({ title: 'Klart', description: `${successes} transaktioner bokförda` })
} else {
toast({
title: 'Delvis klart',
description: `${successes} lyckades, ${failures.length} misslyckades: ${failures.slice(0, 3).join(', ')}${failures.length > 3 ? '...' : ''}`,
variant: 'destructive',
})
}
exitBatchMode()
}
function openMatchDialog(transaction: TransactionWithInvoice) {
setSelectedTransaction(transaction)
setMatchDialogOpen(true)
}
function openCategoryDialog(transaction: TransactionWithInvoice) {
setTemplatePickerTransaction(transaction)
setTemplatePickerOpen(true)
}
function handleTemplateSelected(template: BookingTemplate) {
setTemplatePickerOpen(false)
const tx = templatePickerTransaction
if (!tx) return
// Library templates aren't validated server-side via template_id; the
// template's debit/credit + VAT drive the booking through account_override.
const templateId = isLibraryTemplateId(template.id) ? undefined : template.id
setQuickReview({ transaction: tx, category: template.fallback_category, label: template.name_sv, template, templateId, linePattern: null })
setQuickReviewOpen(true)
}
function handleOpenTemplateReview(transaction: TransactionWithInvoice, templateId: string) {
if (isCounterpartyTemplateId(templateId)) {
const cpSuggestion = templateSuggestions[transaction.id]?.find(ts => ts.template_id === templateId)
if (!cpSuggestion) return
setQuickReview({
transaction,
category: transaction.amount < 0 ? 'expense_other' : 'income_services',
label: cpSuggestion.name_sv,
template: { id: templateId, name_sv: cpSuggestion.name_sv } as BookingTemplate,
templateId: undefined,
linePattern: cpSuggestion.line_pattern ?? null,
})
setQuickReviewOpen(true)
return
}
const template = getTemplateById(templateId)
if (!template) return
setQuickReview({
transaction,
category: template.fallback_category,
label: template.name_sv,
template,
templateId: template.id,
linePattern: null,
})
setQuickReviewOpen(true)
}
function handleChangeTemplate() {
setQuickReviewOpen(false)
if (quickReview?.transaction) {
setTemplatePickerTransaction(quickReview.transaction)
setTemplatePickerOpen(true)
}
}
function handleManualBooking() {
setTemplatePickerOpen(false)
if (templatePickerTransaction) {
setBookingDialogTransaction(templatePickerTransaction)
setBookingDialogTemplate(null)
setBookingDialogOpen(true)
}
}
// Complex (multi-leg or otherwise non-convertible) library template picked
// from the transaction modal: route into the manual booking dialog with
// the template pre-applied against the transaction's amount.
function handlePickLibraryTemplate(raw: BookingTemplateLibrary) {
if (!templatePickerTransaction) return
setBookingDialogTransaction(templatePickerTransaction)
setBookingDialogTemplate(raw)
setTemplatePickerOpen(false)
setBookingDialogOpen(true)
}
async function handleQuickReviewConfirm(
id: string,
category: TransactionCategory,
vatTreatment: VatTreatment | undefined,
accountOverride: string | undefined,
templateId?: string
): Promise<string | null> {
let journalEntryId: string | null
if (!templateId && quickReview?.template?.id && isCounterpartyTemplateId(quickReview.template.id)) {
const cpTemplateId = extractCounterpartyId(quickReview.template.id)
const cpCategorize = async (): Promise<{ ok: boolean; journalEntryId: string | null; result: { error?: { code?: string; account_numbers?: string[]; details?: { account_numbers?: string[] } }; journal_entry_id?: string | null }; status: number }> => {
const r = await fetch(`/api/transactions/${id}/categorize`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ is_business: true, counterparty_template_id: cpTemplateId }),
})
const b = await r.json()
return { ok: r.ok, status: r.status, result: b, journalEntryId: b?.journal_entry_id || null }
}
const { ok: cpOk, status: cpStatus, result, journalEntryId: cpJeId } = await cpCategorize()
if (!cpOk) {
if (result?.error?.code === 'ACCOUNTS_NOT_IN_CHART') {
const accountNumbers: string[] =
(Array.isArray(result.error.account_numbers) && result.error.account_numbers) ||
(Array.isArray(result.error.details?.account_numbers) && result.error.details?.account_numbers) ||
[]
// Synchronous in-flight flag per toast closure: see same pattern
// in runCategorize. Double-click on the counterparty-template
// retry would race the second cpCategorize against the first's
// verifikation insert.
let activateInFlight = false
toast({
title: 'Kontot finns inte i din kontoplan',
description: `Motpartsmallen kräver att följande konton aktiveras: ${accountNumbers.join(', ')}.`,
variant: 'destructive',
action: accountNumbers.length > 0 ? (
<ToastAction altText="Aktivera och bokför" onClick={async () => {
if (activateInFlight) return
activateInFlight = true
try {
const activateRes = await fetch('/api/bookkeeping/accounts/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_numbers: accountNumbers }),
})
if (!activateRes.ok) {
const errBody = await activateRes.json().catch(() => null)
toast({ title: 'Kunde inte aktivera konton', description: getErrorMessage(errBody, { statusCode: activateRes.status }), variant: 'destructive' })
return
}
const activateBody = await activateRes.json()
if (Array.isArray(activateBody.unknown) && activateBody.unknown.length > 0) {
toast({ title: 'Kunde inte hitta alla konton', description: `Lägg till ${activateBody.unknown.join(', ')} manuellt under Inställningar → Kontoplan.`, variant: 'destructive' })
return
}
const retry = await cpCategorize()
// Gate on retry.ok alone: a 200 with null journal_entry_id
// is allowed by the declared type (e.g. already-categorized
// flag flip), and showing "Kategorisering misslyckades"
// after the server returned success is misleading. The state
// update conditionally writes the journal_entry_id when it's
// actually present.
if (retry.ok) {
setExitingIds((prev) => new Set(prev).add(id))
setTransactions((prev) =>
prev.map((t) =>
t.id === id
? { ...t, is_business: true, ...(retry.journalEntryId ? { journal_entry_id: retry.journalEntryId } : {}) }
: t
)
)
toast({ title: 'Bokförd' })
} else {
toast({ title: 'Kategorisering misslyckades', description: getErrorMessage(retry.result, { context: 'transaction', statusCode: retry.status }), variant: 'destructive' })
}
} finally {
activateInFlight = false
}
}}>
Aktivera och bokför
</ToastAction>
) : undefined,
})
} else {
toast({ title: 'Kategorisering misslyckades', description: getErrorMessage(result, { context: 'transaction', statusCode: cpStatus }), variant: 'destructive' })
}
// Close the review dialog on hard errors: the toast (with action if
// ACCOUNTS_NOT_IN_CHART) carries the message and the recovery path.
setQuickReviewOpen(false)
setQuickReview(null)
return null
}
setExitingIds((prev) => new Set(prev).add(id))
journalEntryId = cpJeId
} else {
journalEntryId = await handleCategorize(id, true, category, vatTreatment, accountOverride, templateId)
}
// Always close: whether the server created a verifikation, returned a
// structured 4xx (ACCOUNTS_NOT_IN_CHART, INVALID_MAPPING, …), or hit a
// partial-success path. The toast from runCategorize already communicates
// the outcome; keeping the dialog open serves no purpose.
setQuickReviewOpen(false)
setQuickReview(null)
return journalEntryId
}
return (
<div className="space-y-8">
{/* Page header (concept scene 10): title + Importera split button */}
<TransactionStatusBar onOpenCreateDialog={() => setIsDialogOpen(true)} />
{skvNeedsReconnect && (
<AttnLine action={{ label: t('skv_reconnect_cta'), href: '/settings/tax' }}>
{t('skv_reconnect_body')}
</AttnLine>
)}
{/* Toolbar (concept order): [Att bokföra/Alla-seg] [sök] [Välj flera]
... [source ContextPicker far right] */}
<div className="flex flex-wrap items-center gap-2">
<div className="inline-flex shrink-0 gap-0.5 rounded-lg bg-muted/70 p-[3px]" role="tablist">
<button
type="button"
role="tab"
aria-selected={mode === 'inbox'}
onClick={() => setMode('inbox')}
className={`inline-flex items-center gap-1.5 rounded-md px-3.5 py-[5px] text-[12.5px] transition-colors duration-150 ${
mode === 'inbox'
? 'border border-border bg-card font-medium text-foreground'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{t('mode_inbox')}
{(totalUncategorizedCount ?? uncategorizedTransactions.length) > 0 && (
<span className="rounded-full bg-secondary px-1.5 text-[10px] font-medium tabular-nums">
{totalUncategorizedCount ?? uncategorizedTransactions.length}
</span>
)}
</button>
<button
type="button"
role="tab"
aria-selected={mode === 'history'}
onClick={() => setMode('history')}
className={`rounded-md px-3.5 py-[5px] text-[12.5px] transition-colors duration-150 ${
mode === 'history'
? 'border border-border bg-card font-medium text-foreground'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{t('mode_all')}
</button>
</div>
<div className="relative min-w-[220px] max-w-xs flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Sök transaktioner…"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="h-9 pl-10"
/>
</div>
{/* Account chooser (convention 8): the one context chip, far right.
Per-cash-account rows with balances (concept scene 10); hidden
only when there is nothing beyond "Alla källor" to choose. */}
{mode === 'inbox' && sourceItems.length > 1 && (
<div className="ml-auto">
<ContextPicker
value={sourceFilter}
onChange={(id) => handleSourceFilterChange(id as SourceFilter)}
triggerLabel={(() => {
const active =
sourceItems.find((item) => item.id === sourceFilter) ?? sourceItems[0]
return active.annotation ? `${active.label} · ${active.annotation}` : active.label
})()}
items={sourceItems}
/>
</div>
)}
</div>
{/* Content based on mode */}
{isLoading ? (
<DataList className="stagger-enter">
{[1, 2, 3].map((i) => (
<div key={i} className="flex items-center gap-3 px-4 py-3">
<Skeleton className="h-5 w-5 rounded" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-48 rounded" />
<Skeleton className="h-3 w-24 rounded" />
</div>
<Skeleton className="h-5 w-20 rounded" />
</div>
))}
</DataList>
) : mode === 'inbox' ? (
inboxItems.length === 0 ? (
searchTerm || sourceFilter !== 'all' ? (
<DataListEmpty
title="Inga träffar"
description={searchTerm ? t('no_search_results') : t('source_empty')}
/>
) : (
<InboxZeroState
hasTransactions={transactions.length > 0 || skvRows.length > 0}
onCreateTransaction={() => setIsDialogOpen(true)}
/>
)
) : (
<div>
{/* Bulkbar (concept): hidden until at least one transaction is
selected via the hover checkboxes, then it pops in with the
count and the batch actions. */}
{selectedIds.size > 0 && (
<div className="flex flex-wrap items-center gap-x-5 gap-y-2 border-b border-border px-1 py-2.5 text-[12.5px] animate-fade-in">
{batchProgress ? (
<span className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
{t('batch_progress', { done: batchProgress.done, total: batchProgress.total })}
</span>
) : (
<>
<span className="whitespace-nowrap">
<strong className="font-semibold tabular-nums">{selectedIds.size}</strong>{' '}
{t('bulkbar_selected', { count: selectedIds.size })}
</span>
<Button size="sm" onClick={() => setShowBatchSelector(true)}>
{t('batch_book')}
</Button>
{/* Bulk-book (samlingsverifikation): only when ≥2 selected
on the same date + same direction. Disabled state
explains why via title. */}
<Button
size="sm"
variant="outline"
onClick={() => setBulkBookOpen(true)}
disabled={!bulkBookEligible}
title={!bulkBookEligible ? t('batch_bulk_book_hint') : undefined}
>
{t('batch_bulk_book')}
</Button>
<button type="button" className={QUIET_LINK_CLASS} onClick={handleBatchIgnore}>
{t('batch_ignore')}
</button>
<button
type="button"
className={cn(QUIET_LINK_CLASS, 'hover:text-destructive')}
onClick={handleBatchDelete}
>
{t('batch_delete')}
</button>
{selectedIds.size < selectableInboxIds.length && (
<button
type="button"
className={QUIET_LINK_CLASS}
onClick={() => setSelectedIds(new Set(selectableInboxIds))}
>
{t('batch_select_all', { count: selectableInboxIds.length })}
</button>
)}
<button type="button" className={QUIET_LINK_CLASS} onClick={exitBatchMode}>
{t('batch_clear')}
</button>
</>
)}
</div>
)}
{/* Negative margin + matching padding: lets the hover-revealed
checkbox/chevron hang into the page margins without being
clipped by the overflow container, while the columns stay
flush with the page edges. */}
<div className="-mx-5 overflow-x-auto px-5 md:-mx-8 md:px-8">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={cn(TH_CLASS, 'w-0 !p-0')} aria-hidden="true"></th>
<th className={cn(TH_CLASS, '!pl-0')}>{t('th_date')}</th>
<th className={cn(TH_CLASS, 'w-full')}>{t('th_description')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_amount')}</th>
<th className={cn(TH_CLASS, 'text-right !pr-0')}>{t('th_status')}</th>
</tr>
</thead>
<tbody className="stagger-enter">
{inboxItems.map(item =>
item.source === 'bank' ? (
<TransactionInboxCard
key={`bank-${item.data.id}`}
transaction={item.data}
skvCounterpartDate={bankToSkvHints.get(item.data.id)}
processingId={processingId}
isSelected={selectedIds.has(item.data.id)}
isExpanded={expandedTxId === item.data.id}
onToggleExpand={(id) =>
setExpandedTxId((prev) => (prev === id ? null : id))
}
entityType={entityType}
onCategorize={handleCategorize}
onOpenMatchDialog={openMatchDialog}
onOpenMatchInvoicePicker={openInvoiceMatchPicker}
onOpenSplitMatch={openSplitMatchDialog}
onOpenMatchVoucher={openMatchVoucherDialog}
onOpenAttachDocument={openAttachDocumentDialog}
onOpenCategoryDialog={openCategoryDialog}
onDelete={handleDeleteTransaction}
onIgnore={handleIgnoreTransaction}
onEditTitle={openEditTitleDialog}
onToggleSelect={toggleBatchSelect}
/>
) : (
<SkattekontoInboxCard
key={`skv-${item.data.id}`}
row={item.data}
matchSuggestion={item.data.match_suggestion}
processing={skvProcessingId === item.data.id}
onBokfor={handleSkvBokfor}
onMatch={r => setSkvMatchTarget(r)}
/>
),
)}
</tbody>
</table>
</div>
</div>
)
) : (
<TransactionHistoryList
transactions={transactions}
skvRows={skvRows}
searchTerm={searchTerm}
sourceFilter={
sourceFilter === 'all' || sourceFilter === 'skatteverket' ? sourceFilter : 'bank'
}
onSourceFilterChange={handleSourceFilterChange}
jeUnderlagStatus={jeUnderlagStatus}
onOpenMatchDialog={openMatchDialog}
onOpenCategoryDialog={openCategoryDialog}
onOpenAttachDocument={openAttachDocumentDialog}
onOpenMatchVoucher={openMatchVoucherDialog}
onDelete={handleDeleteTransaction}
onSkvBokfor={handleSkvBokfor}
onSkvMatch={r => setSkvMatchTarget(r)}
hasMore={hasMore}
isLoadingMore={isLoadingMore}
onLoadMore={loadMoreTransactions}
/>
)}
{/* Footer status line (concept): honest counter from the visible
rows + bank sync status/actions + the Bankavstämning path (the
ignore flows point users there). */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-1 text-xs text-muted-foreground">
{mode === 'inbox' && (
<span className="tabular-nums">{t('footer_to_handle', { count: inboxItems.length })}</span>
)}
<BankSyncStatusChip />
<BankSyncNowButton />
<Link
href="/reports/bank-reconciliation"
className="ml-auto transition-colors duration-150 hover:text-foreground"
>
Bankavstämning →
</Link>
</div>
{/* Dialogs */}
{showBatchSelector && (
<BatchCategorySelector
open
onOpenChange={setShowBatchSelector}
selectedCount={selectedIds.size}
onSelectCategory={handleBatchCategorize}
progress={batchProgress}
/>
)}
{matchDialogOpen && (
<InvoiceMatchDialog
open
onOpenChange={setMatchDialogOpen}
transaction={selectedTransaction}
isConfirming={isConfirmingMatch}
onConfirm={handleConfirmInvoiceMatch}
onLinkToExisting={handleLinkToExistingVoucher}
/>
)}
{matchVoucherTx && (
<MatchVoucherDialog
open
onOpenChange={(o) => { if (!o) setMatchVoucherTx(null) }}
transaction={matchVoucherTx}
onLinked={handleVoucherLinked}
/>
)}
{splitMatchOpen && (
<MatchAllocationDialog
open
onOpenChange={(o) => {
setSplitMatchOpen(o)
if (!o) setSplitMatchTransaction(null)
}}
transaction={splitMatchTransaction}
onSuccess={handleSplitMatchSuccess}
/>
)}
{bulkBookOpen && (
<BulkBookDialog
open
onOpenChange={setBulkBookOpen}
transactions={selectedTransactions}
onSuccess={handleBulkBookSuccess}
/>
)}
{bookingDialogOpen && (
<TransactionBookingDialog
open
onOpenChange={(o) => {
setBookingDialogOpen(o)
if (!o) setBookingDialogTemplate(null)
}}
transaction={bookingDialogTransaction}
preselectedTemplate={bookingDialogTemplate}
onBooked={handleTransactionBooked}
/>
)}
{attachDocTx && (
<TransactionAttachDocumentDialog
open
onOpenChange={(o) => {
if (!o) setAttachDocTx(null)
}}
transaction={attachDocTx}
onAttached={handleDocumentAttached}
/>
)}
{templatePickerOpen && <Dialog open onOpenChange={setTemplatePickerOpen}>
<DialogContent className="max-w-lg max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Bokför transaktion</DialogTitle>
</DialogHeader>
{templatePickerTransaction && (
<div className="flex items-center justify-between gap-3 text-sm">
<span className="truncate text-muted-foreground">{templatePickerTransaction.description}</span>
<span className="font-medium tabular-nums flex-shrink-0">
{templatePickerTransaction.amount > 0 ? '+' : ''}{formatCurrency(templatePickerTransaction.amount, templatePickerTransaction.currency)}
</span>
</div>
)}
{/* Alternate paths as quiet links (concept vact): the templates are
the main content, not three stacked buttons. */}
<div className="flex flex-wrap items-center gap-x-5 gap-y-2">
<button type="button" className={QUIET_LINK_CLASS} onClick={handleManualBooking}>
Bokför manuellt
</button>
{templatePickerTransaction && templatePickerTransaction.amount > 0 && (
<button
type="button"
className={QUIET_LINK_CLASS}
onClick={() => {
const tx = templatePickerTransaction
setTemplatePickerOpen(false)
setInvoicePickerTransaction(tx)
setInvoicePickerOpen(true)
}}
>
Matcha med faktura
</button>
)}
{templatePickerTransaction && (
<button
type="button"
className={QUIET_LINK_CLASS}
onClick={() => void handleIgnoreTransaction(templatePickerTransaction)}
>
Ignorera transaktionen
</button>
)}
</div>
<TemplatePicker
direction={templatePickerTransaction && templatePickerTransaction.amount < 0 ? 'expense' : 'income'}
entityType={entityType as EntityType}
suggestedTemplates={templatePickerTransaction ? templateSuggestions[templatePickerTransaction.id] : undefined}
onSelect={handleTemplateSelected}
onSelectCounterparty={(templateId) => {
if (!templatePickerTransaction) return
setTemplatePickerOpen(false)
handleOpenTemplateReview(templatePickerTransaction, templateId)
}}
onPickLibraryTemplate={handlePickLibraryTemplate}
/>
</DialogContent>
</Dialog>}
{invoicePickerOpen && <Dialog
open
onOpenChange={(open) => {
if (isMatchingFromPicker) return
setInvoicePickerOpen(open)
if (!open) setInvoicePickerTransaction(null)
}}
>
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{t('dialog_match_invoice')}</DialogTitle>
</DialogHeader>
{invoicePickerTransaction && (
<>
<div className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
<span className="truncate text-muted-foreground">{invoicePickerTransaction.description}</span>
<span className="font-medium tabular-nums flex-shrink-0 ml-3 text-success">
+{formatCurrency(invoicePickerTransaction.amount, invoicePickerTransaction.currency)}
</span>
</div>
<InvoicePicker
transaction={invoicePickerTransaction}
onSelect={handleSelectInvoiceFromPicker}
isProcessing={isMatchingFromPicker}
/>
</>
)}
</DialogContent>
</Dialog>}
{supplierInvoicePickerOpen && <Dialog
open
onOpenChange={(open) => {
if (isMatchingSupplierFromPicker) return
setSupplierInvoicePickerOpen(open)
if (!open) setSupplierInvoicePickerTransaction(null)
}}
>
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Matcha med leverantörsfaktura</DialogTitle>
</DialogHeader>
{supplierInvoicePickerTransaction && (
<>
<div className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
<span className="truncate text-muted-foreground">{supplierInvoicePickerTransaction.description}</span>
<span className="font-medium tabular-nums flex-shrink-0 ml-3">
{formatCurrency(supplierInvoicePickerTransaction.amount, supplierInvoicePickerTransaction.currency)}
</span>
</div>
<SupplierInvoicePicker
transaction={supplierInvoicePickerTransaction}
onSelect={handleSelectSupplierInvoiceFromPicker}
isProcessing={isMatchingSupplierFromPicker}
/>
</>
)}
</DialogContent>
</Dialog>}
{quickReviewOpen && (
<QuickReviewDialog
key={quickReview?.transaction.id ?? '' + String(quickReview?.category) + String(quickReview?.templateId) + String(quickReview?.template?.id)}
open
onOpenChange={setQuickReviewOpen}
transaction={quickReview?.transaction ?? null}
category={quickReview?.category ?? null}
categoryLabel={quickReview?.label ?? ''}
defaultAccount={
// For library templates (no templateId but a template object), use the
// template's debit account as the default; otherwise fall back to the
// category's default account.
!quickReview?.templateId && quickReview?.template
? quickReview.template.debit_account
: quickReview?.category ? getDefaultAccountForCategory(quickReview.category) : ''
}
defaultVat={
!quickReview?.templateId && quickReview?.template
? (quickReview.template.vat_treatment ?? 'none')
: quickReview?.category ? (getDefaultVatTreatmentForCategory(quickReview.category) ?? 'none') : 'none'
}
entityType={entityType as EntityType}
template={quickReview?.template ?? null}
templateId={quickReview?.templateId}
counterpartyLinePattern={quickReview?.linePattern ?? null}
onConfirm={handleQuickReviewConfirm}
onChangeTemplate={handleChangeTemplate}
/>
)}
{isDialogOpen && <Dialog open onOpenChange={setIsDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('dialog_add_transaction')}</DialogTitle>
</DialogHeader>
<TransactionForm onSubmit={handleCreateTransaction} isLoading={isCreating} />
</DialogContent>
</Dialog>}
<DestructiveConfirmDialog {...confirmDialogProps} />
{editTitleTarget && (
<EditTransactionTitleDialog
open
onOpenChange={(v) => {
if (!v) setEditTitleTarget(null)
}}
currentTitle={editTitleTarget.description ?? ''}
originalTitle={editTitleTarget.original_description ?? null}
onSave={handleSaveTitle}
/>
)}
{skvMatchTarget && (
<SkattekontoMatchDialog
row={skvMatchTarget}
open
onClose={() => setSkvMatchTarget(null)}
onMatched={handleSkvMatched}
/>
)}
{/* Prong B: match-against-supplier-invoice suggestion */}
{siMatchSuggestion && <Dialog
open
onOpenChange={(open) => {
if (!open) setSiMatchSuggestion(null)
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('dialog_match_supplier_invoice')}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Det finns en öppen leverantörsfaktura med samma belopp från samma leverantör. Matcha mot
fakturan istället för att bokföra direkt på leverantörsskuldskontot, annars skapas en
dubblerad verifikation som måste stornas (BFL 5 kap 5 §).
</p>
<div className="space-y-2 rounded-md border bg-muted/30 p-3">
{siMatchSuggestion?.candidates.map((c) => (
<div key={c.supplier_invoice_id} className="flex items-center justify-between gap-3 text-sm">
<div className="min-w-0">
<div className="font-medium">
{c.supplier_name || 'Leverantör'} · {c.invoice_number}
</div>
<div className="text-xs text-muted-foreground tabular-nums">
{formatDate(c.invoice_date)} · kvar {formatCurrency(c.remaining_amount, c.currency)}
</div>
</div>
<Button
size="sm"
onClick={() => handleMatchSuggestedSupplierInvoice(siMatchSuggestion.transactionId, c.supplier_invoice_id)}
disabled={siMatchProcessing}
>
Matcha
</Button>
</div>
))}
</div>
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button variant="outline" onClick={() => setSiMatchSuggestion(null)}>
Avbryt
</Button>
<Button
variant="outline"
onClick={async () => {
const retry = siMatchSuggestion?.retry
setSiMatchSuggestion(null)
if (retry) await retry()
}}
disabled={siMatchProcessing}
>
Bokför på leverantörsskulder ändå
</Button>
</div>
</div>
</DialogContent>
</Dialog>}
{/* Prong B (customer side): match-against-customer-invoice suggestion */}
{ciMatchSuggestion && <Dialog
open
onOpenChange={(open) => {
if (!open) setCiMatchSuggestion(null)
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('dialog_match_customer_invoice')}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Det finns en obetald kundfaktura med samma belopp från samma kund. Matcha mot fakturan
istället för att bokföra direkt mot kundfordringskontot, annars skapas en dubblerad
verifikation som måste stornas (BFL 5 kap 5 §).
</p>
<div className="space-y-2 rounded-md border bg-muted/30 p-3">
{ciMatchSuggestion?.candidates.map((c) => (
<div key={c.invoice_id} className="flex items-center justify-between gap-3 text-sm">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">
{c.customer_name || 'Kund'} · {c.invoice_number ?? '-'}
</span>
{c.match_reason === 'ocr_exact' && (
<Badge variant="success">{t('badge_exact_ocr')}</Badge>
)}
</div>
<div className="text-xs text-muted-foreground tabular-nums">
{formatDate(c.invoice_date)} · kvar {formatCurrency(c.remaining_amount, c.currency)}
</div>
</div>
<Button
size="sm"
onClick={() => handleMatchSuggestedInvoice(ciMatchSuggestion.transactionId, c.invoice_id)}
disabled={ciMatchProcessing}
>
Matcha
</Button>
</div>
))}
</div>
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button variant="outline" onClick={() => setCiMatchSuggestion(null)}>
Avbryt
</Button>
<Button
variant="outline"
onClick={async () => {
const retry = ciMatchSuggestion?.retry
setCiMatchSuggestion(null)
if (retry) await retry()
}}
disabled={ciMatchProcessing}
>
Bokför på kundfordringar ändå
</Button>
</div>
</div>
</DialogContent>
</Dialog>}
{duplicateWarning && <DuplicateBookingDialog
candidate={duplicateWarning.candidate}
processing={duplicateProcessing}
onCancel={() => setDuplicateWarning(null)}
// Ledger-only candidate (transaction_id null, e.g. a verifikat from an
// SIE import): the primary action links the bank line to the existing
// voucher instead of double-booking it. Success refreshes the same
// state a MatchVoucherDialog link does.
matchTransaction={
transactions.find((tx) => tx.id === duplicateWarning.transactionId) ?? {
id: duplicateWarning.transactionId,
}
}
onMatched={(transactionId, journalEntryId, voucherLabel) => {
setDuplicateWarning(null)
handleVoucherLinked(transactionId, journalEntryId, voucherLabel)
}}
onBookAnyway={async () => {
const retry = duplicateWarning?.retry
setDuplicateProcessing(true)
try {
setDuplicateWarning(null)
if (retry) await retry()
} finally {
setDuplicateProcessing(false)
}
}}
/>}
</div>
)
}