Files
accounted/components/common/CashAccountSelector.tsx
T
Jakob Wennberg c74b19df1b Accounted rebrand + swarm-skill cleanup + bank-reconciliation fixes (#643)
* feat(reconciliation): close the bank-feed loop on voucher links and re-tag mis-typed opening balances

Two related fixes to bank reconciliation correctness:

1. Auto-reconcile on voucher link. Linking an invoice or supplier invoice to
   an existing voucher previously advanced only the invoice — the bank
   transaction that paid it kept sitting in the Transactions inbox with a null
   journal_entry_id. linkInvoiceToVoucher / linkSupplierInvoiceToVoucher now
   call autoReconcileTransactionForLinkedVoucher (lib/reconciliation), which
   links the bank transaction to the same verifikat when exactly one unbooked
   line matches it. Best-effort and post-commit: a failure here never fails the
   link. The result surfaces reconciledTransactionId; the inbox row leaves the
   list and the UI shows link_success_tx_reconciled.

2. Re-tag mis-typed opening balances. getReconciliationStatus and the GL-line
   matching RPCs identify a cash account's ingående balans solely by
   journal_entries.source_type='opening_balance'. Companies migrated from other
   systems often booked the bank IB as an ordinary voucher (source_type
   'import' or 'manual'), so it was never excluded and surfaced as a phantom
   reconciliation difference equal to the opening balance. Adds:
   - migration mark_entry_as_opening_balance: a GUC-gated carve-out in the
     immutability trigger plus a SECURITY DEFINER RPC that validates the entry
     (balance-sheet lines only, dated on a fiscal-period boundary), flips the
     source_type, and writes an audit row — no blanket data sweep.
   - POST /api/reconciliation/bank/mark-opening-balance + MarkOpeningBalanceSchema.
   - BankReconciliationView action to trigger it from the IB diff.

The gnubok_create_voucher executor now accepts a typed is_opening_balance flag
and derives source_type='opening_balance' only after validating class 1/2 lines
on the period start, so new IBs land correctly typed.

Covered by lib/reconciliation auto-reconcile tests, voucher-executors tests,
and a mark-entry-as-opening-balance pg-real test.

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

* chore: rebrand gnubok → Accounted and prune swarm agent skills

Product rebrand and skills housekeeping. No runtime behaviour change.

Rebrand: replace user-visible "gnubok" with "Accounted" across docs, READMEs,
in-code comments, doc-site content, MCP skill/resource prose, and the
gnubok-mcp package description. The MCP resource URI scheme is moved gnubok://
→ Accounted:// consistently across resource registrations, the event-type
comment, and the resource/skill tests. Deliberately preserved as stable
identifiers (NOT rebranded): the gnubok-company-id cookie, gnubok_sk_ / gnubok_inv_
token prefixes, the gnubok-mcp npm bridge name, and the AGI <gem:Programnamn>
value (kept 'gnubok' per its source comment — it is the software identifier sent
to Skatteverket and must not churn across visual rebrands).

Skills: remove the 27 swarm-* agent SKILL.md atoms (no longer used; already
absent from the agent_atom_registry in prod), refresh the remaining skill docs,
add the .claude/rules/ path-scoped rule set, and regenerate the
seed_agent_atom_bodies migration + .skill-body-manifest.json via
`npm run skills:generate` so the DB-backed skill bodies match the trimmed set.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 10:52:01 +02:00

151 lines
4.6 KiB
TypeScript

'use client'
import { useEffect, useState } from 'react'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useCompany } from '@/contexts/CompanyContext'
import type { CashAccount } from '@/types'
const STORAGE_KEY_PREFIX = 'Accounted:cash-account:'
interface Props {
/**
* Current selection — a BAS ledger account number ('1930', '1932', …).
* `null` would only be meaningful if "all accounts" were an option, which
* isn't currently supported (reconciliation is always single-account).
*/
value: string
onChange: (accountNumber: string) => void
/**
* Optional label above the select. Pass null to render without a label.
*/
label?: string | null
/**
* Called once after the initial fetch completes so callers can suppress a
* skeleton until the selector is ready.
*/
onReady?: () => void
className?: string
}
/**
* Cash account selector for reconciliation, drift, and any UI that scopes a
* read to a particular settlement account (1930 SEK, 1932 EUR, …).
*
* Loads /api/cash-accounts for the active company, persists the last selection
* per company in sessionStorage, and renders the same Select primitive as the
* fiscal-year picker so the UX stays consistent.
*
* sessionStorage (not localStorage) so the selection clears when the tab/
* session ends. The data is a UI preference, not a credential; persisting
* which BAS account a company uses across sessions in browser storage would
* couple company id + financial account reference for the lifetime of the
* browser profile (GDPR Art. 25(2) data minimisation, ISO 27001 A.8.12).
*/
export function CashAccountSelector({
value,
onChange,
label = 'Konto',
onReady,
className,
}: Props) {
const { company } = useCompany()
const [accounts, setAccounts] = useState<CashAccount[]>([])
const [loaded, setLoaded] = useState(false)
useEffect(() => {
if (!company?.id) {
onReady?.()
return
}
let cancelled = false
;(async () => {
const res = await fetch('/api/cash-accounts')
if (!res.ok) {
if (!cancelled) {
setLoaded(true)
onReady?.()
}
return
}
const { data } = await res.json()
if (cancelled) return
const fetched: CashAccount[] = data || []
// is_primary first (already ordered on the server), then by ledger code.
setAccounts(fetched)
setLoaded(true)
// Restore last selection or pick the primary as default.
if (typeof window !== 'undefined') {
const stored = window.sessionStorage.getItem(STORAGE_KEY_PREFIX + company.id)
const inFetched = (ledger: string) =>
fetched.some(a => a.ledger_account === ledger)
if (stored && inFetched(stored)) {
if (stored !== value) onChange(stored)
} else {
const primary = fetched.find(a => a.is_primary)
const fallback = primary ?? fetched[0]
if (fallback && fallback.ledger_account !== value) {
onChange(fallback.ledger_account)
}
}
}
onReady?.()
})()
return () => {
cancelled = true
}
// onReady excluded — lifecycle callback, shouldn't retrigger on parent renders.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [company?.id])
const handleChange = (next: string) => {
if (company?.id && typeof window !== 'undefined') {
window.sessionStorage.setItem(STORAGE_KEY_PREFIX + company.id, next)
}
onChange(next)
}
// Fallback when the table is empty (fresh company, no PSD2 connections yet):
// show a single hardcoded '1930' option so the rest of the UI still works.
const options = accounts.length > 0
? accounts.map(a => ({
value: a.ledger_account,
label: `${a.ledger_account} ${a.name ?? a.iban ?? a.currency}`,
}))
: [{ value: '1930', label: '1930 Bankkonto' }]
return (
<div className={className}>
{label && <Label>{label}</Label>}
<div className={`flex items-center gap-2 ${label ? 'mt-1' : ''}`}>
<Select
value={value}
onValueChange={handleChange}
disabled={!loaded && accounts.length === 0}
>
<SelectTrigger className="w-full sm:w-[280px]">
<SelectValue placeholder={loaded ? 'Välj konto' : 'Laddar…'} />
</SelectTrigger>
<SelectContent>
{options.map(o => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
)
}