Files
accounted/components/bookkeeping/ActivateAccountsDialog.tsx
T
Mattsson f9ea9c0082 Add/pdf and templates (#705)
* fix(invoices): apply configured voucher series to payments + preview next voucher

The booking engine resolves the series from
default_voucher_series_per_source_type, but the global "Standardserie"
dropdown wrote a separate field the engine ignored, and cash-method invoice
payments (invoice_cash_payment) weren't exposed in settings — so configured
series were silently dropped to "A".

- Expose cash/private payment source types in the per-source-type form
- Write the global default through to the map on save, keeping overrides
- Resolve voucher-sequences/next by source_type (+date) to match the engine
- Show the upcoming voucher (V2) in the payment dialog title
- Share resolveInvoicePaymentSourceType so preview and booking can't drift

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

* fix(salary): keep AGI panel in sync with Skatteverket signing state

The AGI panel mixed run-scoped generation state (agi_generated_at,
agi_declarations) with period-scoped submission state (extension_data
agi_submission_{period}), so the two could drift and present
contradictory UI. Reconcile them:

- Auto-detect a Mina Sidor BankID signature: while awaiting_signing,
  poll /agi/kvittenser on mount and on tab refocus so the panel flips
  to "signed" (hiding the signing actions) without a manual
  "Hamta kvittens" click.
- Warn instead of offering to sign when the locked granskningsunderlag
  predates the run's latest AGI generation (draftIsStale) — avoids
  filing superseded figures.
- Self-heal a stale "AGI-XML saknas" error once the run's AGI is
  (re)generated out-of-band (MCP/API/other tab).
- Refetch the salary run on tab focus so agi_generated_at reflects
  out-of-band generation without a hard reload.
- /agi/lasUpp now clears the cached agi_submission_{period} record, so
  unlocking drops the panel back to the pre-submission state instead of
  stranding it on a released "redo att signeras" draft.

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

* feat: Implement VAT registration handling and invoice item line types

- Added VAT registration check in commitCreateInvoice to set VAT rate to 0% for non-VAT registered companies.
- Updated invoice creation logic to reflect 'exempt' VAT treatment and adjusted related fields accordingly.
- Introduced support for free-text and blank spacer rows in invoice items by adding a new line_type field.
- Enhanced invoice and credit note handling to accommodate new line types.
- Added new localized messages for text rows in English and Swedish.
- Created tests for salary run approval logic, ensuring bank details are validated correctly.
- Implemented effective net payout calculation for salary runs, considering tax overrides.
- Added SQL migrations to support new invoice item line types and accounting method awareness for linking invoices to vouchers.

* feat(articles): artikelregister with revenue account + VAT rate per article

Article register (non-inventory) with per-article VAT rate and optional
BAS class-3 revenue-account override. Includes API routes, UI pages,
MCP tools, pending-operation staging, and the activate-or-create
account flow (ACCOUNTS_NOT_IN_CHART -> ActivateAccountsDialog,
unknown numbers -> AddAccountDialog) reusing the journal entry UX.

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

* feat(bookkeeping): no-doc-required batch + bulk-missing endpoints

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

* feat(payments): supplier payment lines + cash-method invoice matching

Shared payment-line proposal for supplier invoices, improved
match-invoice/match-supplier-invoice flows (kontantmetoden-aware),
and voucher-link support without requiring a 151x clearing entry.

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

* feat(bookkeeping): new journal entry dialog, SIE import tweaks, misc

New journal entry dialog component, journal list/page updates,
invoice editor updates, SIE import adjustments, transaction ingest
and api-key tweaks, pr-agent workflow update.

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

* feat(invoices): implement tax reduction features and localization updates

* feat(tests): add VAT registration gate to pending operations commit tests

---------

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

165 lines
5.4 KiB
TypeScript

'use client'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Loader2, Plus } from 'lucide-react'
export interface ActivateAccountsDialogProps {
open: boolean
accountNumbers: string[]
onConfirm: () => Promise<void> | void
onCancel: () => void
// Optional: invoked when the user wants to create a custom (non-BAS) account
// for a number that isn't in the BAS catalogue. The host should close this
// dialog and open AddAccountDialog prefilled with the number.
onCreateUnknown?: (accountNumber: string) => void
// Confirm button label. Defaults to the bookkeeping wording; non-booking
// hosts (e.g. the article register) pass their own.
confirmLabel?: string
}
interface BasLookupRow {
account_number: string
account_name: string | null
known: boolean
}
export function ActivateAccountsDialog({
open,
accountNumbers,
onConfirm,
onCancel,
onCreateUnknown,
confirmLabel,
}: ActivateAccountsDialogProps) {
const [rows, setRows] = useState<BasLookupRow[]>([])
const [loading, setLoading] = useState(false)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (!open || accountNumbers.length === 0) return
let cancelled = false
setLoading(true)
fetch(`/api/bookkeeping/accounts/bas-lookup?numbers=${encodeURIComponent(accountNumbers.join(','))}`)
.then((r) => r.json())
.then((body) => {
if (cancelled) return
setRows((body?.data as BasLookupRow[]) || [])
})
.catch(() => {
if (cancelled) return
setRows(accountNumbers.map((n) => ({ account_number: n, account_name: null, known: false })))
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [open, accountNumbers])
const knownRows = rows.filter((r) => r.known)
const unknownRows = rows.filter((r) => !r.known)
// Disable confirm when any entered number isn't a valid BAS account: activating
// only the knowns would leave the unknowns to fail again on retry.
const canConfirm = knownRows.length > 0 && unknownRows.length === 0 && !submitting
async function handleConfirm() {
setSubmitting(true)
try {
await onConfirm()
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={(next) => { if (!next) onCancel() }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Aktivera konton</DialogTitle>
<DialogDescription>
{knownRows.length > 0
? 'Följande konton behöver aktiveras i din kontoplan innan bokföringen kan slutföras.'
: 'Inga giltiga BAS-konton att aktivera.'}
</DialogDescription>
</DialogHeader>
<div className="space-y-2 text-sm">
{loading && (
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Hämtar kontouppgifter...
</div>
)}
{!loading && knownRows.length > 0 && (
<ul className="divide-y divide-border rounded-md border">
{knownRows.map((r) => (
<li key={r.account_number} className="flex items-baseline gap-3 px-3 py-2">
<span className="font-mono text-foreground w-14 shrink-0">{r.account_number}</span>
<span className="truncate">{r.account_name}</span>
</li>
))}
</ul>
)}
{!loading && unknownRows.length > 0 && (
<div className="rounded-md border border-warning/40 bg-warning/5 px-3 py-2 text-xs text-warning-foreground">
<p className="font-medium">Finns inte i BAS-katalogen:</p>
<p className="mt-1 font-mono">{unknownRows.map((r) => r.account_number).join(', ')}</p>
<p className="mt-1 text-warning-foreground/80">
Skapa dem som egna konton, eller kontrollera inmatningen.
</p>
{onCreateUnknown && (
<div className="mt-2 flex flex-wrap gap-1.5">
{unknownRows.map((r) => (
<Button
key={r.account_number}
type="button"
variant="outline"
size="sm"
className="h-8 text-xs"
onClick={() => onCreateUnknown(r.account_number)}
>
<Plus className="mr-1 h-3 w-3" />
Skapa {r.account_number}
</Button>
))}
</div>
)}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={onCancel} disabled={submitting}>
Avbryt
</Button>
<Button onClick={handleConfirm} disabled={!canConfirm}>
{submitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Aktiverar...
</>
) : (
<>
<Plus className="mr-2 h-4 w-4" />
{confirmLabel ?? 'Aktivera och bokför'}
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}