* feat: implement skattekonto drift detection and alerting - Add skattekonto drift computation logic to compare Skatteverket's saldo with GL 1630 sum. - Implement alerting mechanism for significant drift changes, with throttling to prevent alert spamming. - Introduce database functions to sum GL 1630 entries and list unbooked skattekonto rows. feat: create own account transfer detection - Develop logic to detect transfers between a company's own cash accounts based on counterparty IBAN. - Implement tests to validate detection logic under various scenarios, including matching and non-matching IBANs. feat: establish cash accounts as a first-class entity - Create cash_accounts table to manage routable cash accounts, replacing ad-hoc JSONB structures. - Implement functions for listing, upserting, and managing cash accounts, including primary account designation. feat: enhance GL line reconciliation functionality - Modify get_unlinked_1930_lines RPC to accept any account number for reconciliation, improving flexibility for different currencies. - Update related functions to ensure compatibility with the new cash_accounts structure. feat: capture counterparty IBAN in transactions - Add counterparty_iban column to transactions table to facilitate intra-account transfer detection. - Create index for efficient lookups based on counterparty IBAN. * feat: Enhance cash account handling and reconciliation processes - Updated reconciliation routes to enforce cash account validation for all account numbers, including '1930'. - Improved error handling for unknown cash accounts in reconciliation status and unmatched entries routes. - Changed CashAccountSelector to use sessionStorage instead of localStorage for better data privacy. - Fixed mapping for employer payroll taxes to route to the correct account (2730 instead of 2731). - Added safety checks for company IDs in the guessCounterAccount function to prevent injection vulnerabilities. - Introduced atomic RPC for setting primary cash accounts to avoid intermediate states during updates. - Seeded default cash accounts for new companies to ensure reconciliation routes are accessible from day one. - Updated email notifications for drift detection to avoid exposing sensitive financial data. - Enhanced bank reconciliation logic to handle multi-currency transactions correctly. - Renamed and updated tests to reflect changes in the underlying RPCs and ensure accurate coverage. - Migrated existing cash account rules to correct mappings in compliance with Swedish accounting standards.
151 lines
4.6 KiB
TypeScript
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 = 'gnubok: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>
|
|
)
|
|
}
|