Files
accounted/app/(dashboard)/bookkeeping/page.tsx
T
Jakob WennbergandClaude Fable 5 aa72a75dfc feat(bookkeeping): concept toolbar, template booking, confirm-first posting (UI migration PR 4) (#1123)
* feat(bookkeeping): concept toolbar, template booking, confirm-first posting (UI migration PR 4)

The Bokforing page adopts the concept (scene 9) on top of the PR 3 kit:

- Toolbar in concept order with the FyPicker chip far right replacing the
  "Visar:" scope selector (same persisted scope, one-click change)
- "Nytt verifikat" is a SplitButton with three remembered modes: Tomt
  verifikat (existing editor, voucher-number hint kept), Bokfor fran mall
  (new centered TemplateBookDialog: existing booking_template_library
  data MRU-ordered, date + editable amount recomputing the kontering
  live via applyTemplate, Balanserar row, direct booking + MRU touch),
  and Skapa med assistenten (existing agent-sheet path; suggestion lands
  in Granskning). Last-used mode persists via ui_state.create_mode
- Draft posting goes through ConfirmDialog describing the outcome
  ("Bokfors som verifikat A-218: ...") with an indicative next-voucher
  preview; the success toast still shows the real number
- "Underlag saknas" becomes the row's only warning chip (Badge warning)
  instead of the bare triangle icon; exempt rows keep the muted glyph
- New lib/hooks/use-ui-state.ts: client read of ui_state to seed the
  split button's initial mode

No backend, migration or RPC changes. VAT-split math is applyTemplate,
already unit-tested in lib/bookkeeping/__tests__/template-library.test.ts;
split-button persistence is tested in lib/ui-state.

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

* fix(bookkeeping): use roundOre in TemplateBookDialog money math

The antipattern ratchet caught two hand-rolled Math.round(x*100)/100;
route them through lib/money roundOre like the rest of the codebase.

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

* docs: PR 4 decisions

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

* feat(bookkeeping): concept dry-table verifikat list (scene 9)

The list itself adopts the concept, verified against the artifact's
scene 9 markup: a borderless table (Verifikation / Datum / Beskrivning /
Belopp) with hover-revealed selection checkboxes, hover-revealed chevron,
and an animated grid-rows row expansion whose kontering renders as the
concept's vlines sub-table (uppercase hairline heads, Summa row).
Expansion actions become quiet underlined links (Visa detaljer, Skapa
andringsverifikation, Aterfor (storno), Kopiera); posting keeps its pill
+ ConfirmDialog. Drafts get a row-level Bokfor button like the concept.

All functionality preserved: batch "Inget underlag kravs" bar (above the
table), attachment counts + preview, no-doc-required toggle, out-of-
period + status badges, FX line amounts, sum footer, pagination. The
density toggle is dropped: the table has one density by design.

Fixes from verification: the list's i18n lives in the journal_list
namespace (new keys moved there; they rendered as raw keys otherwise),
and the sidebar brand Image gets explicit dimensions (Next dev warning).

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

* fix(bookkeeping): bulkbar appears only when a verifikat is selected

Concept behavior: no standing "Markera alla (62) / Markera alla utan
underlag" bar. The batch bar is hidden until the first row is selected
via its hover checkbox, then pops in with the count, the reason input,
Undanta underlagskrav, and quiet actions for Markera alla, the
filter-scoped bulk mark, and Avmarkera. All batch functionality kept,
just no chrome until it is needed.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 21:37:37 +02:00

218 lines
7.5 KiB
TypeScript

'use client'
import { useState, useEffect, useMemo } from 'react'
import dynamic from 'next/dynamic'
import { useRouter, useSearchParams } from 'next/navigation'
import { useTranslations } from 'next-intl'
import JournalEntryList from '@/components/bookkeeping/JournalEntryList'
import { type FormLine } from '@/components/bookkeeping/JournalEntryForm'
import type { CopyPrefill } from '@/components/bookkeeping/NewJournalEntryDialog'
import { DialogLoadingSkeleton } from '@/components/ui/dialog-loading-skeleton'
import { SplitButton } from '@/components/ui/split-button'
import { useAgentSheet } from '@/components/agent/AgentSheetProvider'
import { useUiState } from '@/lib/hooks/use-ui-state'
import { resolveInitialMode } from '@/lib/ui-state/client'
import { useToast } from '@/components/ui/use-toast'
import { Plus, LayoutTemplate, Sparkles } from 'lucide-react'
import { PageHeader } from '@/components/ui/page-header'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import type { JournalEntry, JournalEntryLine } from '@/types'
const NewJournalEntryDialog = dynamic(
() => import('@/components/bookkeeping/NewJournalEntryDialog'),
{ loading: DialogLoadingSkeleton },
)
const TemplateBookDialog = dynamic(
() => import('@/components/bookkeeping/TemplateBookDialog'),
{ loading: DialogLoadingSkeleton },
)
// SplitButton modes for "Nytt verifikat" (concept scene 9). The last-used
// mode persists per user in ui_state.create_mode.bookkeeping.
const CREATE_MODES = ['tomt', 'mall', 'assistent'] as const
interface NextVoucher {
next: number
series: string
}
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export default function BookkeepingPage() {
const { toast } = useToast()
const router = useRouter()
const searchParams = useSearchParams()
const copyFromId = useMemo<string | null>(() => {
const raw = searchParams.get('copy_from')
return raw && UUID_RE.test(raw) ? raw : null
}, [searchParams])
const [refreshKey, setRefreshKey] = useState(0)
const [showNewEntry, setShowNewEntry] = useState(false)
const [showTemplateDialog, setShowTemplateDialog] = useState(false)
const [copyPrefill, setCopyPrefill] = useState<CopyPrefill | null>(null)
const [isLoadingCopy, setIsLoadingCopy] = useState(false)
const [nextVoucher, setNextVoucher] = useState<NextVoucher | null>(null)
const t = useTranslations('bookkeeping')
const { openAgentSheet } = useAgentSheet()
const { uiState, loaded: uiStateLoaded } = useUiState()
// React to copy_from in URL: switch tab, fetch source entry, then clean URL.
// useSearchParams keeps this reactive even when navigation happens within the
// same route (e.g. clicking the Kopiera button in the expanded list row),
// which a one-shot useState initializer wouldn't notice.
/* eslint-disable react-hooks/set-state-in-effect -- URL→state sync requires sync setState */
useEffect(() => {
if (!copyFromId) return
setShowNewEntry(true)
setCopyPrefill(null)
setIsLoadingCopy(true)
fetch(`/api/bookkeeping/journal-entries/${copyFromId}`)
.then((res) => res.json())
.then(({ data, error }: { data?: JournalEntry; error?: string }) => {
if (error || !data) {
toast({
title: t('copy_failed_title'),
description: error || t('copy_source_missing'),
variant: 'destructive',
})
return
}
const sourceLines = ((data.lines || []) as JournalEntryLine[])
.slice()
.sort((a, b) => a.sort_order - b.sort_order)
const lines: FormLine[] = sourceLines.map((l) => {
const debit = Number(l.debit_amount) || 0
const credit = Number(l.credit_amount) || 0
return {
account_number: l.account_number,
debit_amount: debit > 0 ? debit.toFixed(2) : '',
credit_amount: credit > 0 ? credit.toFixed(2) : '',
line_description: l.line_description || '',
}
})
setCopyPrefill({
sourceId: copyFromId,
sourceVoucherLabel: formatVoucher(data),
lines,
description: data.description || '',
notes: data.notes || '',
})
})
.catch(() => {
toast({
title: t('copy_failed_title'),
description: t('copy_fetch_failed'),
variant: 'destructive',
})
})
.finally(() => {
setIsLoadingCopy(false)
// Clear copy_from so a refresh doesn't re-trigger and so clicking the
// same entry's Kopiera button again re-fires this effect.
router.replace('/bookkeeping')
})
}, [copyFromId, toast, router])
/* eslint-enable react-hooks/set-state-in-effect */
// Fetch the next voucher number for today's fiscal period + default series.
// Re-runs after each commit (refreshKey++) so the tab label stays current.
useEffect(() => {
let cancelled = false
fetch('/api/bookkeeping/voucher-sequences/next')
.then((r) => r.json())
.then(({ data }) => {
if (cancelled) return
if (data?.next != null) {
setNextVoucher({ next: data.next, series: data.series })
} else {
setNextVoucher(null)
}
})
.catch(() => {
if (!cancelled) setNextVoucher(null)
})
return () => {
cancelled = true
}
}, [refreshKey])
return (
<div className="space-y-8">
<PageHeader
title={t('title')}
action={
<SplitButton
// Remount once ui_state loads so the primary face re-resolves
// to the persisted last-used mode.
key={uiStateLoaded ? 'loaded' : 'initial'}
persistKey="bookkeeping"
initialModeKey={resolveInitialMode(uiState, 'bookkeeping', CREATE_MODES, 'tomt')}
options={[
{
key: 'tomt',
label: nextVoucher
? `${t('create_tomt')} (${nextVoucher.series}${nextVoucher.next})`
: t('create_tomt'),
icon: Plus,
description: t('create_tomt_desc'),
onSelect: () => {
setCopyPrefill(null)
setShowNewEntry(true)
},
},
{
key: 'mall',
label: t('create_mall'),
icon: LayoutTemplate,
description: t('create_mall_desc'),
onSelect: () => setShowTemplateDialog(true),
},
{
key: 'assistent',
label: t('create_with_assistant'),
icon: Sparkles,
description: t('create_assistent_desc'),
onSelect: () =>
openAgentSheet({
intentId: 'verifikation.draft',
contextRef: 'verifikation:new',
}),
},
]}
/>
}
/>
<JournalEntryList key={refreshKey} />
{showTemplateDialog && (
<TemplateBookDialog
open
onOpenChange={setShowTemplateDialog}
onCreated={() => setRefreshKey((k) => k + 1)}
/>
)}
{showNewEntry && (
<NewJournalEntryDialog
open
onOpenChange={(o) => {
setShowNewEntry(o)
if (!o) setCopyPrefill(null)
}}
onCreated={() => {
setRefreshKey((k) => k + 1)
setShowNewEntry(false)
setCopyPrefill(null)
}}
copyPrefill={copyPrefill}
isLoading={isLoadingCopy}
/>
)}
</div>
)
}