* feat(salary): validate employee clearing/kontonummer at entry Bank details on the "Anställda" form had no structural validation, so a typo in clearing/kontonummer was saved silently and only surfaced at Bankgirot LB generation (or never, on the SEPA path). Adds a shared validator (lib/salary/payment/bank-account.ts) wired into the create dialog, edit page, CreateEmployeeSchema, and the PATCH route: 4-digit clearing or 5-digit Swedbank (8xxxx), 5-11 digit account, both-or-neither. Mirrors encodeReceiverAccount so entry-time validation matches what the payout layer can encode. Update validates only when a bank field actually changes, so legacy free-text data stays editable. Includes a conservative clearing to bank-name hint (null for unknown ranges). Per-bank mod10/mod11 checksum deferred to a soft-warning follow-up. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(chart-of-accounts): styled delete warnings and bulk select-all Replace the native window.confirm() on single-account delete with the styled DestructiveConfirmDialog, and add to the prune dialog a master 'select all unused accounts' checkbox plus an explicit confirmation step before bulk deletion. New sv/en strings for the confirm titles and actions. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(salary): encrypt personnummer on v1 employee create; tolerate legacy plaintext on read The v1 REST create route stored personnummer unencrypted, which then threw ERR_CRYPTO_INVALID_AUTH_TAG on every decrypt-on-read path and 500'd the employees roster. Encrypt on write in v1 create, decrypt on read in the v1 list/detail/patch responses, and make decryptPersonnummer pass a raw 12-digit value through with a warn so a legacy plaintext row can't take the roster down. Encrypt seeded personnummer. Add a gated, idempotent backfill for existing rows. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): save a manual entry as a reusable template Add a "Spara som mall" action to the manual journal-entry form next to the existing "Anvand mall" picker, so users can capture a booking pattern the moment they work it out. Opens the shared TemplateForm (create mode) pre-seeded from the current lines via deriveTemplateLinesFromBooking, and saves through the existing POST /api/settings/booking-templates. Rendered in both the mobile and desktop layouts and in create + edit modes. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(pending): label all staged operation types The Granskning list rendered the raw snake_case operation_type (e.g. create_supplier_invoice_from_inbox) for any type missing from the label map, which hogs the meta row and wraps awkwardly on mobile. Add short sv/en labels for all operation types in OPERATION_RISK_TIERS, plus a humanized fallback for future ones, and simplify the label map to a plain operation_type -> i18n-key record (the icon/variant fields were dead). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(reports): let users file moms without a Skatteverket connection The momsdeklaration was never gated on the Skatteverket connection (it renders from the bookkeeping), but the not-connected "Anslut med BankID" card read as a wall. Make manual filing a first-class path: - Add a "Lämna in din momsdeklaration" card under the report with a PDF download (SKV 4700 layout, hela kronor) and a skatteverket.se link. - Add a momsdeklaration PDF route + template; buildManualFilingRows() rounds each ruta to whole kronor and recomputes ruta 49 per the SKV 4700 formula so it ties out. The PDF is a read/record copy, not a submission file (moms has no upload channel). - Offer PDF alongside Excel in the report's export menu. - Reframe the not-connected SkatteverketPanel to "Skicka direkt till Skatteverket (valfritt)". Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(salary): compact new-employee dialog and warn on bad account check digit Redesign NewEmployeeDialog into a compact layout: borderless sections split by hairline dividers (no per-section cards), a fixed header + scrolling body + solid footer (fixes content showing through the old sticky bar), and denser grids. EmployeeTaxCard gains a `flat` variant so the dialog can host it without card chrome; the edit page keeps the boxed version. Add non-blocking Swedish account check-digit validation (lib/bankgiro/account-number.ts): mod10 (reuses luhn) + mod11, with a clearing->method table from the Bankgirot "Bankernas kontonummeruppbyggnad" spec, cross-checked against jop-io/kontonummer.js and verified against a real account (Forex 9420/4172385). Surfaced as a soft warning in both employee forms; unrecognised clearings return 'unknown' so we never warn on a valid but unmapped account. Never blocks saving. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(invoices): configurable send time + editing for recurring invoices Re-register the accidentally-removed recurring cron (now hourly) and add a per-schedule send hour (Europe/Stockholm, DST-aware). The cron never sends for a past date, and the enabling migration pauses every existing schedule on deploy so nothing auto-sends behind a user's back; users reactivate consciously (with a confirm) or click "Skapa faktura nu" to send this month on demand. Automatic sending now requires a customer email. Adds a full edit flow (row click opens the prefilled form, PATCH), fixing the row-click 404. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): configure självfaktura via the invoice API Add an optional is_self_billed flag (plus external_invoice_number, self_billing_agreement_ref, received_date) to the public invoice-create endpoint so callers can register a received self-billing invoice (mottagen självfaktura, ML 17 kap 15§) via the API. It was previously only reachable from the internal dashboard route, so it was missing from the API docs. Extract the booking into a shared service (lib/invoices/self-billed-sale.ts) and refactor the internal /api/invoices/self-billed route to a thin wrapper over it, so the dashboard and the API cannot drift. Books as a sale (Debit 1510 / Credit 30xx+26xx) with the counterparty's number; no own number is consumed. Fields are plain optionals (no schema refine) so UpdateInvoiceSchema.omit() keeps working; required-when-self-billed is enforced in the route. Documented in the endpoint registry. No migration (columns already exist). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(settings): allow a partial voucher-series-per-source-type map In Zod 4 an enum-keyed z.record is exhaustive (every source_type required), so saving a default_voucher_series_per_source_type map that omits a source type (e.g. the newly added result_appropriation) failed with "expected string, received undefined". Use partialRecord so the map can be sparse; the engine falls back to series 'A' for any unmapped key. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(salary): resolve employer name via getCompanyDisplayName Payslip PDFs, the payslip email, AGI, KU10, and the BG/LB + SEPA payment files now resolve the employer name through getCompanyDisplayName (company_settings.company_name, falling back to companies.name), matching how invoices already display it. Read-side coalesce, so no migration or backfill: companies.name is write-once at onboarding and not authoritative for these surfaces. The sidebar company switcher uses the same coalesce for the non-active companies in the list. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * perf(kontoplan): index-only account usage counts + lighter reference load Add a covering index on journal_entry_lines (journal_entry_id, account_number) so get_account_usage_counts becomes an index-only scan (prod worst case ~440ms). Slim /api/bookkeeping/accounts/reference to return only the company's activation rows and merge against the client-bundled BAS_REFERENCE instead of re-sending the full ~1,300-account catalog every load, and defer the BAS catalog + usage counts off the first-paint critical path in ChartOfAccountsManager. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * i18n(salary): add bank-account checksum warning string sv/en strings for the employee bank-account (clearing/kontonummer) soft checksum warning shown by the create/edit forms. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs: update decision log Append the 2026-07-06/07 decision entries (salary employer-name coalesce, sidebar switcher, employees API personnummer fix, kontoplan load optimization, momsdeklaration manual filing, recurring invoices resend + reactivation + editing, "spara som mall", voucher-series partial map, and självfaktura via the invoice API). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: address compliance-review findings on recurring invoices + moms filing - recurring cron: close the double-send window with an atomic compare-and-set claim on last_run_at (release-on-failure) so two overlapping hourly runs can't both spawn from the same stale batch row - recurring edit dialog: force auto_send=false whenever the effective customer has no email, so a disabled-but-checked box can't PATCH auto_send=true after the async customer load - momsdeklaration manual-filing: truncate rutor to whole kronor (öretal faller bort per SFL 22 kap 1 §) instead of round-to-nearest, matching the SRU path Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
332 lines
12 KiB
TypeScript
332 lines
12 KiB
TypeScript
'use client'
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
|
import { useTranslations } from 'next-intl'
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
} from '@/components/ui/dialog'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Checkbox } from '@/components/ui/checkbox'
|
|
import { Input } from '@/components/ui/input'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import {
|
|
DestructiveConfirmDialog,
|
|
useDestructiveConfirm,
|
|
} from '@/components/ui/destructive-confirm-dialog'
|
|
import { Loader2, Search, Trash2 } from 'lucide-react'
|
|
|
|
interface PruneCandidate {
|
|
account_number: string
|
|
account_name: string
|
|
account_class: number
|
|
plan_type: string | null
|
|
is_active: boolean
|
|
in_bas_reference: boolean
|
|
}
|
|
|
|
interface PruneAccountsDialogProps {
|
|
open: boolean
|
|
onOpenChange: (open: boolean) => void
|
|
/** Called after a successful prune so the parent can refetch the chart. */
|
|
onPruned: () => void
|
|
}
|
|
|
|
/**
|
|
* Bulk deletion of unused accounts. Fetches the server-computed deletable set
|
|
* (dry run) and presents it in two groups — imported/custom accounts and
|
|
* untouched accounts from the seeded base plan. Nothing is preselected:
|
|
* deletion is opt-in per account or per group. Used accounts never appear
|
|
* here; the server re-verifies every guard at execute time anyway.
|
|
*/
|
|
export function PruneAccountsDialog({ open, onOpenChange, onPruned }: PruneAccountsDialogProps) {
|
|
const t = useTranslations('chart_of_accounts')
|
|
const tCommon = useTranslations('common')
|
|
const { toast } = useToast()
|
|
const { dialogProps: confirmDialogProps, confirm } = useDestructiveConfirm()
|
|
|
|
const [loading, setLoading] = useState(false)
|
|
const [candidates, setCandidates] = useState<PruneCandidate[]>([])
|
|
const [usedCount, setUsedCount] = useState(0)
|
|
const [selected, setSelected] = useState<Set<string>>(new Set())
|
|
const [searchQuery, setSearchQuery] = useState('')
|
|
const [isDeleting, setIsDeleting] = useState(false)
|
|
|
|
// Grouping only: imported/manually added accounts (the typical cleanup
|
|
// target) are listed separately from unused accounts in the seeded base
|
|
// plan, so users see what came from an import at a glance.
|
|
const isImportedOrCustom = useCallback(
|
|
(c: PruneCandidate) => !c.in_bas_reference || c.plan_type === 'full_bas',
|
|
[],
|
|
)
|
|
|
|
useEffect(() => {
|
|
if (!open) return
|
|
let cancelled = false
|
|
async function load() {
|
|
setLoading(true)
|
|
setCandidates([])
|
|
setSelected(new Set())
|
|
setSearchQuery('')
|
|
try {
|
|
const res = await fetch('/api/bookkeeping/accounts/prune', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ dry_run: true }),
|
|
})
|
|
if (!res.ok) throw new Error()
|
|
const { data } = await res.json()
|
|
if (cancelled) return
|
|
const deletable: PruneCandidate[] = data?.deletable ?? []
|
|
setCandidates(deletable)
|
|
setUsedCount((data?.used ?? []).length)
|
|
// Nothing starts selected — deletion is opt-in per account (or per
|
|
// group via the header checkbox), never a preloaded default.
|
|
} catch {
|
|
if (!cancelled) {
|
|
toast({ title: t('toast_prune_failed'), variant: 'destructive' })
|
|
onOpenChange(false)
|
|
}
|
|
} finally {
|
|
if (!cancelled) setLoading(false)
|
|
}
|
|
}
|
|
load()
|
|
return () => {
|
|
cancelled = true
|
|
}
|
|
}, [open, onOpenChange, t, toast])
|
|
|
|
// Charts bloated by an import easily reach hundreds of candidates — filter
|
|
// by number or name, same semantics as the kontoplan page search. Selection
|
|
// is keyed by account number, so it survives filter changes; the confirm
|
|
// button always shows the true selected count.
|
|
const filteredCandidates = useMemo(() => {
|
|
if (!searchQuery) return candidates
|
|
const q = searchQuery.toLowerCase()
|
|
return candidates.filter(
|
|
(c) => c.account_number.includes(q) || c.account_name.toLowerCase().includes(q),
|
|
)
|
|
}, [candidates, searchQuery])
|
|
|
|
const customGroup = useMemo(
|
|
() => filteredCandidates.filter(isImportedOrCustom),
|
|
[filteredCandidates, isImportedOrCustom],
|
|
)
|
|
const seedGroup = useMemo(
|
|
() => filteredCandidates.filter((c) => !isImportedOrCustom(c)),
|
|
[filteredCandidates, isImportedOrCustom],
|
|
)
|
|
|
|
// Master toggle spans both groups, scoped to the current filter so it only
|
|
// ever selects what the user can actually see.
|
|
const allFilteredChecked =
|
|
filteredCandidates.length > 0 &&
|
|
filteredCandidates.every((c) => selected.has(c.account_number))
|
|
|
|
function toggleAccount(accountNumber: string) {
|
|
setSelected((prev) => {
|
|
const next = new Set(prev)
|
|
if (next.has(accountNumber)) {
|
|
next.delete(accountNumber)
|
|
} else {
|
|
next.add(accountNumber)
|
|
}
|
|
return next
|
|
})
|
|
}
|
|
|
|
function toggleGroup(group: PruneCandidate[], checked: boolean) {
|
|
setSelected((prev) => {
|
|
const next = new Set(prev)
|
|
for (const c of group) {
|
|
if (checked) {
|
|
next.add(c.account_number)
|
|
} else {
|
|
next.delete(c.account_number)
|
|
}
|
|
}
|
|
return next
|
|
})
|
|
}
|
|
|
|
async function handlePrune() {
|
|
if (selected.size === 0) return
|
|
const confirmed = await confirm({
|
|
title: t('prune_confirm_title', { count: selected.size }),
|
|
description: t('prune_confirm_body'),
|
|
confirmLabel: t('prune_confirm', { count: selected.size }),
|
|
cancelLabel: tCommon('cancel'),
|
|
})
|
|
if (!confirmed) return
|
|
setIsDeleting(true)
|
|
try {
|
|
const res = await fetch('/api/bookkeeping/accounts/prune', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ dry_run: false, account_numbers: [...selected] }),
|
|
})
|
|
const body = await res.json().catch(() => null)
|
|
if (!res.ok) throw new Error(body?.error)
|
|
const deleted: string[] = body?.data?.deleted ?? []
|
|
const skipped: string[] = [
|
|
...(body?.data?.skipped ?? []),
|
|
...(body?.data?.not_found ?? []),
|
|
]
|
|
toast({
|
|
title: t('toast_pruned_title'),
|
|
description:
|
|
skipped.length > 0
|
|
? t('toast_pruned_with_skipped', { deleted: deleted.length, skipped: skipped.length })
|
|
: t('toast_pruned_description', { deleted: deleted.length }),
|
|
})
|
|
onPruned()
|
|
onOpenChange(false)
|
|
} catch (err) {
|
|
toast({
|
|
title: err instanceof Error && err.message ? err.message : t('toast_prune_failed'),
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setIsDeleting(false)
|
|
}
|
|
}
|
|
|
|
function renderGroup(group: PruneCandidate[], titleKey: 'prune_group_custom' | 'prune_group_seed', hintKey: 'prune_group_custom_hint' | 'prune_group_seed_hint') {
|
|
if (group.length === 0) return null
|
|
const allChecked = group.every((c) => selected.has(c.account_number))
|
|
return (
|
|
<div className="space-y-2">
|
|
<div className="flex items-start gap-3">
|
|
<Checkbox
|
|
checked={allChecked}
|
|
onCheckedChange={(checked) => toggleGroup(group, checked === true)}
|
|
className="mt-1"
|
|
aria-label={t(titleKey)}
|
|
/>
|
|
<div>
|
|
<p className="text-sm font-medium">
|
|
{t(titleKey)}{' '}
|
|
<span className="text-muted-foreground tabular-nums">({group.length})</span>
|
|
</p>
|
|
<p className="text-xs text-muted-foreground">{t(hintKey)}</p>
|
|
</div>
|
|
</div>
|
|
<div className="w-full rounded-lg border border-border divide-y divide-border">
|
|
{group.map((c) => (
|
|
<label
|
|
key={c.account_number}
|
|
className="flex min-w-0 items-center gap-3 px-3 py-2 text-sm cursor-pointer hover:bg-secondary/60 transition-colors duration-150"
|
|
>
|
|
<Checkbox
|
|
checked={selected.has(c.account_number)}
|
|
onCheckedChange={() => toggleAccount(c.account_number)}
|
|
/>
|
|
<span className="font-mono tabular-nums text-muted-foreground w-14 shrink-0">
|
|
{c.account_number}
|
|
</span>
|
|
<span className="min-w-0 flex-1 truncate">{c.account_name}</span>
|
|
{!c.is_active && (
|
|
<span className="ml-auto text-[10px] uppercase tracking-wider text-muted-foreground shrink-0">
|
|
{t('prune_inactive_badge')}
|
|
</span>
|
|
)}
|
|
</label>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<Dialog open={open} onOpenChange={(v) => !isDeleting && onOpenChange(v)}>
|
|
<DialogContent className="sm:max-w-2xl">
|
|
<DialogHeader>
|
|
<DialogTitle>{t('prune_title')}</DialogTitle>
|
|
<DialogDescription>{t('prune_description')}</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
{loading ? (
|
|
<div className="py-8 text-center text-sm text-muted-foreground">
|
|
<Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />
|
|
{t('prune_loading')}
|
|
</div>
|
|
) : candidates.length === 0 ? (
|
|
<p className="py-8 text-center text-sm text-muted-foreground">{t('prune_empty')}</p>
|
|
) : (
|
|
// min-w-0: DialogContent is a grid, and grid items default to
|
|
// min-width auto — without this, the nowrap (truncate) account
|
|
// names propagate their full width up and blow the dialog open
|
|
// horizontally instead of truncating.
|
|
<div className="min-w-0 space-y-3">
|
|
<div className="relative">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
|
<Input
|
|
placeholder={t('search_placeholder')}
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
className="pl-9"
|
|
/>
|
|
</div>
|
|
{filteredCandidates.length > 0 && (
|
|
<label className="flex items-center gap-3 text-sm cursor-pointer">
|
|
<Checkbox
|
|
checked={allFilteredChecked}
|
|
onCheckedChange={(checked) => toggleGroup(filteredCandidates, checked === true)}
|
|
aria-label={t('prune_select_all')}
|
|
/>
|
|
<span className="font-medium">
|
|
{t('prune_select_all')}{' '}
|
|
<span className="text-muted-foreground tabular-nums">
|
|
({filteredCandidates.length})
|
|
</span>
|
|
</span>
|
|
</label>
|
|
)}
|
|
<div className="space-y-4 max-h-[60vh] overflow-y-auto overflow-x-hidden pr-1">
|
|
{filteredCandidates.length === 0 ? (
|
|
<p className="py-6 text-center text-sm text-muted-foreground">{t('no_matches')}</p>
|
|
) : (
|
|
<>
|
|
{renderGroup(customGroup, 'prune_group_custom', 'prune_group_custom_hint')}
|
|
{renderGroup(seedGroup, 'prune_group_seed', 'prune_group_seed_hint')}
|
|
</>
|
|
)}
|
|
{usedCount > 0 && (
|
|
<p className="text-xs text-muted-foreground">
|
|
{t('prune_used_note', { count: usedCount })}
|
|
</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<DialogFooter>
|
|
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isDeleting}>
|
|
{tCommon('cancel')}
|
|
</Button>
|
|
<Button
|
|
variant="destructive"
|
|
onClick={handlePrune}
|
|
disabled={loading || isDeleting || selected.size === 0}
|
|
>
|
|
{isDeleting ? (
|
|
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
|
|
) : (
|
|
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
|
|
)}
|
|
{t('prune_confirm', { count: selected.size })}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
<DestructiveConfirmDialog {...confirmDialogProps} />
|
|
</>
|
|
)
|
|
}
|