feat(skattekonto): bulk Bokför + inline single-row booking (fewer clicks) (#1535)

* feat(skattekonto): bulk Bokför and inline single-row booking

Booking a year of skattekonto events took 6 clicks per row (list, Bokför,
review page, Bokför, confirm, navigate back), even for a +1 kr
intäktsränta row.

- GET /skattekonto/transaktioner now attaches a deterministic
  booking_suggestion per unbooked row (one hoisted skattekonto_rules +
  entity_type fetch via the new attachBookingSuggestions), shown as muted
  text on the inbox row ('Bokförs mot 8314 ...').
- New POST /skattekonto/transaktioner/bokfor-batch (Zod, max 200 ids):
  sequential draft+commit per row server-side (no orphan drafts), per-row
  results, never aborts on a row failure. Commit attribution: bulk_accept
  for real batches, user_accept for the one-row inline flow. A failed
  commit keeps the linked draft (degrades to the old review flow).
- Inbox: hover-reveal checkboxes on eligible SKV rows (suggestion
  present, no duplicate hint, unbooked, genomförd), separate skvSelectedIds
  set, bulkbar 'Bokför valda (N)' with ONE summary ConfirmationDialog
  grouped by suggestion with per-group sums, chunked batchProgress, ONE
  aggregate toast, local state patch with exit animation.
- Single-row: new SkattekontoBookDialog (dynamic import) replaces the
  draft-then-window.location detour on both /transactions and /skattekonto;
  'Öppna som utkast' keeps the old draft path via router.push.

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

* fix(skattekonto): batch booking guards for unsettled rows, double-post race and locked periods

- reject status != booked rows in the batch flow with NOT_SETTLED before
  any draft exists (server no longer trusts client eligibility); the
  single-row draft endpoint keeps its behaviour
- make the journal_entry_id backlink a conditional claim (update where
  journal_entry_id is null, select affected rows): zero affected rows maps
  to ALREADY_BOOKED and commitEntry only runs after a won claim, so two
  concurrent submissions can no longer double-post the same row
- detect the period-lock trigger signature in the batch catch and map it
  to PERIOD_LOCKED with Swedish text instead of UNKNOWN with raw DB output
- SkattekontoBookDialog: rows with no matched rule no longer get the
  guaranteed-422 draft CTA; they route to the existing match flow and to
  manual verifikat creation in /bookkeeping
- pass an explicit skv_book_dialog.commit_warning key for the
  direct-commit warning instead of ConfirmationDialog's hardcoded default

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

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-12 21:00:57 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 7cf0e34434
commit dea5e31756
13 changed files with 1884 additions and 156 deletions
@@ -0,0 +1,253 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import { Loader2 } from 'lucide-react'
import type {
SkattekontoBatchResult,
SkattekontoBatchRowResult,
SkattekontoTransactionWithSuggestion,
} from '@/types/skatteverket'
/**
* Inline booking for one skattekonto row: confirm-and-post without leaving
* the list (convention 10: confirm up front). The primary "Bokför" runs the
* server-side draft+commit (bokfor-batch with one id) so the row lands as a
* posted verifikat in one step; "Öppna som utkast" preserves the old
* draft-then-review path, but with a client-side navigation instead of a
* full reload.
*
* Suggestion states drive the layout:
* - object: rule matched → direct booking is the primary action
* - null: computed, no rule matched → the draft endpoint re-derives the same
* null rule and rejects with NO_COUNTER_ACCOUNT, so no draft CTA here;
* route to the match flow (onMatch) or manual creation in /bookkeeping
* - undefined: not computed (kommande rows) → plain draft confirm
*/
export default function SkattekontoBookDialog({
row,
open,
onOpenChange,
onBooked,
onMatch,
}: {
row: SkattekontoTransactionWithSuggestion | null
open: boolean
onOpenChange: (open: boolean) => void
onBooked: (rowId: string, result: SkattekontoBatchRowResult) => void
// Opens the existing "Matcha mot verifikat" flow for this row; the dialog
// closes itself first. Optional: callers without a match flow fall back to
// manual verifikat creation only.
onMatch?: () => void
}) {
const t = useTranslations('skv_book_dialog')
const { toast } = useToast()
const router = useRouter()
const [isBooking, setIsBooking] = useState(false)
const [isOpeningDraft, setIsOpeningDraft] = useState(false)
if (!row) return null
const amount = Number(row.belopp_skatteverket)
const suggestion = row.booking_suggestion
const canBookDirectly = suggestion != null
// null (not undefined) means the rules were evaluated and none matched:
// the draft endpoint would be a guaranteed 422 (NO_COUNTER_ACCOUNT).
const noRuleMatched = suggestion === null
async function handleBook() {
if (!row) return
setIsBooking(true)
try {
const res = await fetch(
'/api/extensions/ext/skatteverket/skattekonto/transaktioner/bokfor-batch',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: [row.id] }),
},
)
const json = await res.json()
if (!res.ok) {
toast({
title: t('book_failed'),
description: getErrorMessage(json, { statusCode: res.status }),
variant: 'destructive',
})
return
}
const result = (json.data as SkattekontoBatchResult).results[0]
if (!result) {
toast({ title: t('book_failed'), variant: 'destructive' })
return
}
if (result.ok) {
onOpenChange(false)
onBooked(row.id, result)
return
}
if (result.error_code === 'COMMIT_FAILED' && result.journal_entry_id) {
// The draft exists and is linked: hand the user over to it instead
// of leaving a half-done state behind a destructive toast.
toast({
title: t('commit_failed_title'),
description: result.error_message,
variant: 'destructive',
})
onOpenChange(false)
router.push(`/bookkeeping/${result.journal_entry_id}`)
return
}
toast({
title: t('book_failed'),
description: result.error_message,
variant: 'destructive',
})
} catch (err) {
toast({
title: t('book_failed'),
description: err instanceof Error ? getErrorMessage(err) : undefined,
variant: 'destructive',
})
} finally {
setIsBooking(false)
}
}
async function handleOpenDraft() {
if (!row) return
setIsOpeningDraft(true)
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 mapper would discard the route's own Swedish reason.
toast({
title: t('book_failed'),
description: getErrorMessage(json, { statusCode: res.status }),
variant: 'destructive',
})
return
}
toast({ title: t('draft_created_title'), description: t('draft_created_description') })
onOpenChange(false)
router.push(`/bookkeeping/${json.data.entry.id}`)
} catch (err) {
toast({
title: t('book_failed'),
description: err instanceof Error ? getErrorMessage(err) : undefined,
variant: 'destructive',
})
} finally {
setIsOpeningDraft(false)
}
}
function handleMatchInstead() {
onOpenChange(false)
onMatch?.()
}
function handleManualCreate() {
// /bookkeeping owns manual verifikat creation ("Nytt verifikat" in the
// page header); there is no dedicated create route to deep-link.
onOpenChange(false)
router.push('/bookkeeping')
}
return (
<ConfirmationDialog
open={open}
onOpenChange={onOpenChange}
title={t('title')}
isSubmitting={isBooking || isOpeningDraft}
confirmLabel={
canBookDirectly
? t('confirm_book')
: noRuleMatched
? onMatch
? t('match_cta')
: t('manual_create_cta')
: t('open_draft')
}
// A draft is still editable: the immutable-verifikat warning only
// applies when the confirm commits directly.
warningText={canBookDirectly ? t('commit_warning') : ''}
onConfirm={
canBookDirectly
? handleBook
: noRuleMatched
? onMatch
? handleMatchInstead
: handleManualCreate
: handleOpenDraft
}
extraActions={
canBookDirectly ? (
<Button
variant="ghost"
onClick={handleOpenDraft}
disabled={isBooking || isOpeningDraft}
className="min-h-11 w-full sm:w-auto text-muted-foreground"
>
{isOpeningDraft && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t('open_draft')}
</Button>
) : noRuleMatched && onMatch ? (
<Button
variant="ghost"
onClick={handleManualCreate}
disabled={isBooking || isOpeningDraft}
className="min-h-11 w-full sm:w-auto text-muted-foreground"
>
{t('manual_create_cta')}
</Button>
) : undefined
}
>
<dl className="space-y-3 py-2 text-sm">
<div className="flex items-baseline justify-between gap-4">
<dt className="shrink-0 text-muted-foreground">{t('event_label')}</dt>
<dd className="text-right">{row.transaktionstext}</dd>
</div>
<div className="flex items-baseline justify-between gap-4">
<dt className="text-muted-foreground">{t('date_label')}</dt>
<dd className="tabular-nums">{formatDate(row.transaktionsdatum)}</dd>
</div>
<div className="flex items-baseline justify-between gap-4">
<dt className="text-muted-foreground">{t('amount_label')}</dt>
<dd className={cn('tabular-nums', amount > 0 && 'text-success')}>
{amount > 0 ? '+' : ''}
{formatCurrency(amount)}
</dd>
</div>
{suggestion ? (
<div className="flex items-baseline justify-between gap-4">
<dt className="text-muted-foreground">{t('posting_label')}</dt>
<dd className="text-right tabular-nums">
{t('posting_value', {
account: suggestion.account_name
? `${suggestion.account} ${suggestion.account_name}`
: suggestion.account,
})}
</dd>
</div>
) : suggestion === null ? (
<p className="pt-1 text-xs leading-5 text-muted-foreground">
{t('no_rule_matched')}
</p>
) : null}
</dl>
</ConfirmationDialog>
)
}
@@ -3,11 +3,13 @@
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { TD_CLASS, QUIET_LINK_CLASS } from '@/components/ui/dry-table'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { AlertCircle, Landmark, Link2, Loader2 } from 'lucide-react'
import type {
SkattekontoBookingSuggestion,
SkattekontoMatchSuggestion,
StoredSkattekontoTransaction,
} from '@/types/skatteverket'
@@ -21,13 +23,21 @@ import type {
export default function SkattekontoInboxCard({
row,
matchSuggestion,
bookingSuggestion,
processing,
selectable,
isSelected,
onToggleSelect,
onBokfor,
onMatch,
}: {
row: StoredSkattekontoTransaction
matchSuggestion?: SkattekontoMatchSuggestion | null
bookingSuggestion?: SkattekontoBookingSuggestion | null
processing: boolean
selectable?: boolean
isSelected?: boolean
onToggleSelect?: (id: string) => void
onBokfor: (row: StoredSkattekontoTransaction) => void
onMatch: (row: StoredSkattekontoTransaction) => void
}) {
@@ -46,8 +56,30 @@ export default function SkattekontoInboxCard({
: t('duplicate_title_draft')
return (
<tr className="group transition-colors duration-150 hover:bg-secondary/35">
<td className={cn(TD_CLASS, 'w-0 !p-0')} aria-hidden="true"></td>
<tr
className={cn(
'group transition-colors duration-150 hover:bg-secondary/35',
isSelected && 'bg-secondary/40',
)}
>
{/* Hover-revealed selection checkbox (concept .cb) */}
{/* Zero-width cell: the checkbox hangs in the left page margin so
the date column can sit flush with the page edge. */}
<td className={cn(TD_CLASS, 'relative w-0 !p-0')}>
{selectable && (
<Checkbox
checked={isSelected}
onCheckedChange={() => onToggleSelect?.(row.id)}
aria-label={t('select_row')}
className={cn(
'absolute -left-5 top-1/2 -translate-y-1/2 transition-opacity duration-150 md:-left-6',
isSelected
? 'opacity-100'
: 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100',
)}
/>
)}
</td>
<td className={cn(TD_CLASS, '!pl-0 whitespace-nowrap tabular-nums text-muted-foreground')}>
{formatDate(row.transaktionsdatum)}
</td>
@@ -64,6 +96,18 @@ export default function SkattekontoInboxCard({
{duplicateLabel}
</Badge>
)}
{/* What "Bokför" will do: the deterministic rule match, muted so it
reads as information, not state. Suppressed on likely duplicates
where linking (not booking) is the recommended action. */}
{bookingSuggestion && !matchSuggestion && (
<span className="hidden shrink-0 whitespace-nowrap text-xs text-muted-foreground md:inline">
{t('suggestion_line', {
account: bookingSuggestion.account_name
? `${bookingSuggestion.account} ${bookingSuggestion.account_name}`
: bookingSuggestion.account,
})}
</span>
)}
</span>
</td>
<td