Files
accounted/app/(dashboard)/bookkeeping/page.tsx
T
Jakob WennbergandClaude Opus 4.8 4dfd790de5 feat(bookkeeping): Ny verifikat modal, ledger-style list, SIE no-underlag exemptions (#698)
* feat(bookkeeping): Ny verifikat modal, ledger-style list, SIE no-underlag exemptions

Verifikat UX
- "Ny verifikat" opens in a modal (NewJournalEntryDialog) instead of an inline tab;
  the review step renders inline in the dialog rather than stacking a second dialog.
- JournalEntryForm: konteringsrader are the focus, with a compact pre-filled metadata
  bar (datum/serie/text/valuta/period) on top; verifikationstext auto-fills from the
  first row's account.
- JournalEntryList: belopp shown on collapsed rows; expanded view is an aligned
  Konto/Benämning/Debet/Kredit table.

SIE imports no longer flood "Att hantera: saknade underlag"
- Import gains an opt-in (off by default) toggle to mark imported verifikat as "Inget
  underlag krävs"; a "Rekommenderas vid migrering" badge nudges it for historical years.
- Multi-select batch-mark in the list for selective cleanup.
- Filter-scoped bulk mark (POST /api/bookkeeping/no-doc-required/bulk-missing): marks
  every missing-doc verifikat matching the active filters across all pages, with a
  dry_run count to confirm scope — the scalable remedy for a post-import flood.
- Shared helper markEntriesNoDocRequired + per-entry batch route.

Tests: no-doc helper, batch route, bulk-missing route.

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

* fix(bookkeeping): address PR #698 review findings

- JournalEntryForm: restore the explicit "no underlag" acknowledgement in the
  modal's inline review. When no document is attached, the confirm button reads
  "Bokför utan underlag" (BFL 5 kap 6-7 §§), equivalent to the blocking dialog the
  non-bare flow shows — the bare path no longer posts behind only a passive banner.
- batch no-doc route: guard the ownership query with source_type IN
  NEEDS_DOC_SOURCE_TYPES so a crafted request can't exempt non-document-requiring
  entries (defense in depth on top of company + posted scoping).
- bulk-missing route: resolve doc/exemption status by querying only the candidate
  ids (chunked) instead of loading the company's full document_attachments and
  journal_entry_no_doc_required tables into memory — data minimisation + bounded
  memory for large migrations (the most-repeated reviewer finding).

Triaged as non-issues (left as-is): partial-import exemption (gated on
result.success == zero errors), reason write-back (sidecar row is FK-linked and
carries the reason), and "bulk-exempting manual entries" (consistent with the
existing per-entry NoDocRequiredToggle). No DB migration — reuses the existing
journal_entry_no_doc_required table.

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

* fix(bookkeeping): centralize bulk-missing date/series validation in Zod

Move the ISO-date and verifikationsserie format checks into the Zod schema so
malformed input is rejected with a clean 400 instead of being silently nulled
(or, for a shaped-but-invalid date, throwing a 500 via fetchAllRows). The date
refinement rejects values like 9999-99-99 / 2026-02-30 that a bare
/^\d{4}-\d{2}-\d{2}$/ regex lets through. Addresses the PR #698 reviewer nit on
split schema-vs-runtime validation. +2 route tests.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 20:41:30 +02:00

190 lines
6.5 KiB
TypeScript

'use client'
import { useState, useEffect, useMemo } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Button } from '@/components/ui/button'
import JournalEntryList from '@/components/bookkeeping/JournalEntryList'
import { type FormLine } from '@/components/bookkeeping/JournalEntryForm'
import NewJournalEntryDialog, { type CopyPrefill } from '@/components/bookkeeping/NewJournalEntryDialog'
import ChartOfAccountsManager from '@/components/bookkeeping/ChartOfAccountsManager'
import { useToast } from '@/components/ui/use-toast'
import { Lock, Plus } from 'lucide-react'
import { PageHeader } from '@/components/ui/page-header'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import type { JournalEntry, JournalEntryLine } from '@/types'
interface NextVoucher {
next: number
series: string
}
type TabValue = 'journal' | 'accounts'
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 [activeTab, setActiveTab] = useState<TabValue>('journal')
const [showNewEntry, setShowNewEntry] = 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')
// 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={
<div className="flex gap-2 w-full sm:w-auto">
<Button
className="w-full sm:w-auto"
onClick={() => {
setCopyPrefill(null)
setShowNewEntry(true)
}}
>
<Plus className="mr-2 h-4 w-4" />
{t('tab_new_entry')}
{nextVoucher && (
<span className="ml-1 text-primary-foreground/70 tabular-nums">
({nextVoucher.series}{nextVoucher.next})
</span>
)}
</Button>
<Button variant="outline" asChild className="w-full sm:w-auto">
<Link href="/bookkeeping/year-end">
<Lock className="mr-2 h-4 w-4" />
{t('year_end')}
</Link>
</Button>
</div>
}
/>
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as TabValue)}>
<TabsList>
<TabsTrigger value="journal">{t('tab_journal')}</TabsTrigger>
<TabsTrigger value="accounts">{t('tab_accounts')}</TabsTrigger>
</TabsList>
<TabsContent value="journal" forceMount className="space-y-4">
<JournalEntryList key={refreshKey} />
</TabsContent>
<TabsContent value="accounts" forceMount>
<ChartOfAccountsManager />
</TabsContent>
</Tabs>
<NewJournalEntryDialog
open={showNewEntry}
onOpenChange={(o) => {
setShowNewEntry(o)
if (!o) setCopyPrefill(null)
}}
onCreated={() => {
setRefreshKey((k) => k + 1)
setShowNewEntry(false)
setCopyPrefill(null)
}}
copyPrefill={copyPrefill}
isLoading={isLoadingCopy}
/>
</div>
)
}