feat(supplier-invoices): dokument-forst editor rebuild (prototype shell + 4 flow optimizations) (#1653)
* refactor(supplier-invoices): extract payload builder and form hooks, pin wire contract with parity tests Zero visual/behavioral change. Pulls the pure payload builder (buildSupplierInvoicePayload + inferVatTreatment + vatRateFromAi) out of NewSupplierInvoiceForm into lib/supplier-invoices/form-payload.ts and pins it with a mode/feature-matrix parity test suite (document_id vs inbox, privately paid due-date default, reverse charge rate forcing, accrual attach/drop, dimensions bags, apply_slp validity, FX parsing, empty-string stripping, ore_rounding passthrough). Also extracts, verbatim: the VatRateCell/RcRateSelect cells, the reference data loading hook (suppliers/accounts/settings/periods), the inbox AI prefill hook (exposing applyInboxItem for reuse), and the submit orchestration hook (endpoint chooser, three submit paths, duplicate-number conflict recovery, inbox field sync-back). Deliberately NOT moved: the effect-ordering couplings (pendingAccountFillRef/accountFillTick supplier-defaults dance, the icke-momsregistrerad gross-up re-run keyed on hasPrefilled, the RC accrual-clearing effect, per-currency FX touched flags) stay in the component untouched; their ordering semantics are load-bearing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(supplier-invoices): dokument-forst editor rebuild with prototype shell and four flow optimizations Rebuilds NewSupplierInvoiceForm to the approved Leverantorsflodet prototype: single 640px column, flat sections (Underlag first, then Leverantor, Fakturauppgifter, Kontering, Forval, Summering), honest state marks (RequiredMark, sage checks for binary facts, muted row counts), a single ochre next-step line (aria-live polite) whose link focuses the missing field, and a sticky bottom action bar with the live total that binds to the dialog scroll container in bare mode and the page panel scroll standalone. Dokument-forst (1): the standalone upload now tries the invoice-inbox pipeline over HTTP first (POST upload, poll items/:id past 'processing'), then runs the same applyInboxItem prefill path as an inbox arrival (settle tint on filled fields, reset(getValues()) dirty baseline, submit through the convert endpoint so the document links and the item is stamped). Extension off or extraction failed degrades to the plain /api/documents attachment; manual entry is never blocked. Total cross-check (2): optional "Totalt enligt fakturan" field in Summering, client-only compare against the displayed payable (sage match line, terracotta diff line), prefilled from extraction totals. Duplicate advisory (3): new index-only GET /api/supplier-invoices/exists (withRouteContext + validateQuery, mirrors the partial unique index's credited/reversed exclusion, full route tests), debounce-called on fakturanummer change; terracotta field-adjacent line with a link to the existing invoice. The structured 409 conflict dialog stays the backstop. Terms-based due date (4): muted caption "Fran leverantorens villkor (N dagar)" when auto-set, re-derives on invoice-date and supplier change, stops the moment the user or the AI supplies a date; terms 0 leaves the field empty with "Star pa fakturan". OCR hint (5): "Anvands i betalningsfilen." under the payment reference when the chosen supplier has bankgiro or plusgiro. Table model: rows start empty; the ghost tfoot entry row (never part of form state) commits an account via the existing AccountCombobox (opens on focus, Enter commits) and moves focus to the new row's amount cell; the supplier default/history fill plants the first row when the table is empty. Row controls are hover-revealed via HOVER_REVEAL_CLASS at a 24px hit area with per-row aria-labels carrying the description. The primary button is never disabled pre-click for writable users (in-flight only); every submit-time hard block stays in onSubmit; viewers keep the lock treatment. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(supplier-invoices): re-run gross-up per apply, guard deferred prefill, honest un-plant - Gross-up/zero-rate pass for icke momsregistrerade re-runs per applied extraction (applyCount bumps in applyInboxItem) instead of keying on the one-shot hasPrefilled flag: a remove + re-upload could previously push AI 25 % rates to the convert endpoint with the moms columns hidden. - Deferred extraction on the standalone upload path no longer overwrites what the user typed mid-poll: the result auto-applies only while the form is pristine (live isDirty ref), otherwise it is buffered behind a quiet "Tolkning klar" click-to-apply line. Inbox arrivals are unchanged. - Supplier-switch un-plant keeps rows the user edited in ANY field, not just amount (plant-time snapshot compare in lib/supplier-invoices/planted-rows.ts, since dirtyFields is unreliable for appended array rows), clearing only the stale account; untouched plant-created rows are still removed and rows that existed before the fill are never removed. - default_expense_account plants now register in plantedRef too, so a supplier switch un-plants them under the same rules as history plants. - applyInboxItem reads suppliers through a ref: the 90 s poll no longer resolves matched suppliers against a stale empty list. - The duplicate advisory bumps its seq in the clear branch, so an in-flight exists response cannot resurrect a warning under a cleared field. - Drop 7 orphaned supplier_invoice_editor keys from both message files. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(supplier-invoices): retry the entry-row focus hand-off on the next frame A single requestAnimationFrame after appending the row can fire before the new amount input's ref is mounted, silently dropping the focus hand-off (observed in headless verification). One retry frame makes the signature interaction reliable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(supplier-invoices): deterministic entry-row focus hand-off via effect The rAF retry still lost to the dialog focus scope re-parking focus when the entry input remounts mid-commit. An effect keyed on the pending row index runs after the new row's input has mounted and wins deterministically. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(supplier-invoices): comma-tolerant amount cell and surviving focus routing The focus trace exposed two real issues behind a probe mystery: the amount cell was type=number (ArrowDown decrements money by 0.01, Enter fires the form's implicit submit mid-edit, and Swedish comma decimals are rejected outright), and the supplier menu's close-autofocus yanked focus back to the trigger, undoing the routed hand-off to the invoice-number field. AmountCell mirrors VatRateCell's draft pattern: text input with decimal inputMode, digits-and-one-separator whitelist, Enter commits via blur. The supplier DropdownMenuContent prevents default close autofocus. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(supplier-invoices): show comma decimals in the amount cell display Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(supplier-invoices): stop dialog grid item overflowing small viewports min-w-0 on the form root (DialogContent is display:grid, so the kontering table's min-w otherwise forces the column past narrow screens) and wrap the sticky-bar action cluster. 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:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
dc311726de
commit
93e99012d7
@@ -37,7 +37,7 @@ export default function NewSupplierInvoiceDialog({
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
className="sm:max-w-4xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto"
|
||||
className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto"
|
||||
// A half-typed invoice must survive an accidental backdrop click or a
|
||||
// stray Escape (nested comboboxes and date pickers portal outside the
|
||||
// dialog). Closing is explicit: the header X or Avbryt. Same
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,178 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { LEGAL_VAT_RATES } from '@/lib/vat/supplier-invoice-line-checks'
|
||||
import { rateToPctString } from '@/lib/supplier-invoices/form-payload'
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
|
||||
export function VatRateCell({ value, onChange }: { value: number; onChange: (v: number) => void }) {
|
||||
const t = useTranslations('supplier_invoice_editor')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
// Local draft so the user can type "12," or "12." mid-keystroke without the
|
||||
// controlled input snapping back to a parsed integer.
|
||||
const [draft, setDraft] = useState(() => rateToPctString(value))
|
||||
|
||||
// Re-sync from form value only when the field isn't focused: keeps AI
|
||||
// prefill / supplier defaults / dropdown picks flowing in without clobbering
|
||||
// active typing.
|
||||
useEffect(() => {
|
||||
if (document.activeElement !== inputRef.current) {
|
||||
setDraft(rateToPctString(value))
|
||||
}
|
||||
}, [value])
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
value={draft}
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
onBlur={() => setDraft(rateToPctString(value))}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value
|
||||
// Strict whitelist: digits with at most one decimal separator.
|
||||
// Blocks "2-22", "100-2", "1.2.3", letters, signs: the keystroke
|
||||
// is dropped before reaching the draft.
|
||||
if (raw !== '' && !/^\d*[.,]?\d*$/.test(raw)) return
|
||||
const normalized = raw.replace(',', '.')
|
||||
if (normalized === '' || normalized === '.') {
|
||||
setDraft(raw)
|
||||
onChange(0)
|
||||
return
|
||||
}
|
||||
const parsed = parseFloat(normalized)
|
||||
if (!Number.isFinite(parsed)) {
|
||||
setDraft(raw)
|
||||
return
|
||||
}
|
||||
const clamped = Math.min(100, Math.max(0, parsed))
|
||||
// Snap the draft back when the parsed value falls outside [0, 100]
|
||||
// so the input can never display a rate the form won't apply.
|
||||
setDraft(clamped === parsed ? raw : String(clamped))
|
||||
onChange(clamped / 100)
|
||||
}}
|
||||
className="h-8 px-2 pr-6 text-right text-[13px] tabular-nums"
|
||||
aria-label={t('col_vat_rate')}
|
||||
/>
|
||||
<span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground pointer-events-none">
|
||||
%
|
||||
</span>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
aria-label={t('vat_rate_presets_aria')}
|
||||
>
|
||||
<ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="min-w-[6rem]">
|
||||
{LEGAL_VAT_RATES.map((preset) => (
|
||||
<DropdownMenuItem
|
||||
key={preset}
|
||||
onSelect={() => onChange(preset)}
|
||||
className="justify-end tabular-nums"
|
||||
>
|
||||
{Math.round(preset * 100)} %
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Self-assessment rate picker shown in place of the Momssats cell when an
|
||||
// invoice is reverse charge. The supplier charges no VAT (the line vat_rate is
|
||||
// 0); this is the Swedish statutory rate the buyer self-assesses at: 25%
|
||||
// huvudregeln for EU services, 12%/6% for reduced-rated services (ML 6 kap 34 §).
|
||||
/**
|
||||
* Money amount cell: text input with decimal inputMode so Swedish comma
|
||||
* decimals work (type=number rejects them and adds spinner arrows that
|
||||
* decrement money on ArrowDown). Enter commits via blur instead of
|
||||
* triggering the form's implicit submit.
|
||||
*/
|
||||
export function AmountCell({
|
||||
value,
|
||||
onChange,
|
||||
inputRef,
|
||||
className,
|
||||
}: {
|
||||
value: number
|
||||
onChange: (v: number) => void
|
||||
inputRef?: (el: HTMLInputElement | null) => void
|
||||
className?: string
|
||||
}) {
|
||||
const innerRef = useRef<HTMLInputElement | null>(null)
|
||||
// Display Swedish comma decimals; parsing accepts both comma and dot.
|
||||
const toDisplay = (v: number) => (v ? String(v).replace('.', ',') : '')
|
||||
const [draft, setDraft] = useState(() => toDisplay(value))
|
||||
|
||||
useEffect(() => {
|
||||
if (document.activeElement !== innerRef.current) {
|
||||
setDraft(toDisplay(value))
|
||||
}
|
||||
}, [value])
|
||||
|
||||
return (
|
||||
<Input
|
||||
ref={(el) => {
|
||||
innerRef.current = el
|
||||
inputRef?.(el)
|
||||
}}
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
placeholder="0,00"
|
||||
className={className}
|
||||
value={draft}
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
onBlur={() => setDraft(toDisplay(value))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
e.currentTarget.blur()
|
||||
}
|
||||
}}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value
|
||||
if (raw !== '' && !/^-?\d*[.,]?\d*$/.test(raw)) return
|
||||
setDraft(raw)
|
||||
const normalized = raw.replace(',', '.')
|
||||
if (normalized === '' || normalized === '.' || normalized === '-') {
|
||||
onChange(0)
|
||||
return
|
||||
}
|
||||
const parsed = parseFloat(normalized)
|
||||
onChange(Number.isFinite(parsed) ? parsed : 0)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function RcRateSelect({ value, onChange }: { value: number; onChange: (v: number) => void }) {
|
||||
const t = useTranslations('supplier_invoice_editor')
|
||||
return (
|
||||
<Select value={String(value ?? 0.25)} onValueChange={(v) => onChange(parseFloat(v))}>
|
||||
<SelectTrigger className="h-8 tabular-nums" aria-label={t('col_rc_vat_rate')}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0.25" className="tabular-nums">25 %</SelectItem>
|
||||
<SelectItem value="0.12" className="tabular-nums">12 %</SelectItem>
|
||||
<SelectItem value="0.06" className="tabular-nums">6 %</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import type { UseFormGetValues, UseFormReset, UseFormSetValue } from 'react-hook-form'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { suggestBalanceAccount } from '@/lib/bookkeeping/accruals/account-suggestions'
|
||||
import { countCalendarMonths } from '@/lib/bookkeeping/accruals/compute'
|
||||
import {
|
||||
vatRateFromAi,
|
||||
type SupplierInvoiceFormData,
|
||||
type SupplierInvoiceLineItem,
|
||||
} from '@/lib/supplier-invoices/form-payload'
|
||||
import type { Supplier, InvoiceExtractionResult } from '@/types'
|
||||
|
||||
export interface InboxItemData {
|
||||
id: string
|
||||
extracted_data: InvoiceExtractionResult | null
|
||||
matched_supplier_id: string | null
|
||||
document_id: string | null
|
||||
}
|
||||
|
||||
interface UseInboxPrefillParams {
|
||||
inboxItemId: string | null
|
||||
suppliersLoaded: boolean
|
||||
suppliers: Supplier[]
|
||||
setValue: UseFormSetValue<SupplierInvoiceFormData>
|
||||
replace: (items: SupplierInvoiceLineItem[]) => void
|
||||
reset: UseFormReset<SupplierInvoiceFormData>
|
||||
getValues: UseFormGetValues<SupplierInvoiceFormData>
|
||||
toast: ReturnType<typeof useToast>['toast']
|
||||
t: ReturnType<typeof useTranslations>
|
||||
/** Called for each scalar form field the extraction filled (settle tint hosts). */
|
||||
onFieldPrefilled?: (field: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The AI-extraction prefill for the supplier-invoice editor. Owns the
|
||||
* extraction state (extractedData/originalExtracted, matched supplier flag,
|
||||
* loading + one-shot guards) and the effect that loads an inbox item when the
|
||||
* form is opened with ?inbox_item_id. `applyInboxItem` is the reusable core:
|
||||
* the dokument-först upload flow feeds the same function, so both arrival
|
||||
* paths share one prefill semantics (incl. the reset(getValues()) baseline
|
||||
* that keeps the unsaved-changes prompt quiet).
|
||||
*/
|
||||
export function useInboxPrefill({
|
||||
inboxItemId,
|
||||
suppliersLoaded,
|
||||
suppliers,
|
||||
setValue,
|
||||
replace,
|
||||
reset,
|
||||
getValues,
|
||||
toast,
|
||||
t,
|
||||
onFieldPrefilled,
|
||||
}: UseInboxPrefillParams) {
|
||||
const [extractedData, setExtractedData] = useState<InvoiceExtractionResult | null>(null)
|
||||
const [originalExtracted, setOriginalExtracted] = useState<InvoiceExtractionResult | null>(null)
|
||||
const [hasMatchedSupplier, setHasMatchedSupplier] = useState(false)
|
||||
const [isLoadingInbox, setIsLoadingInbox] = useState(!!inboxItemId)
|
||||
const [hasPrefilled, setHasPrefilled] = useState(false)
|
||||
// Bumped once per applied extraction. Effects that must re-run after every
|
||||
// apply (not just the first: a remove + re-upload applies again) depend on
|
||||
// this instead of the one-shot `hasPrefilled` flag.
|
||||
const [applyCount, setApplyCount] = useState(0)
|
||||
|
||||
// The dokument-forst upload path calls applyInboxItem from long-lived
|
||||
// closures (the 90 s extraction poll captures the starting render), so the
|
||||
// supplier list is read through a ref: otherwise an extraction that lands
|
||||
// after the suppliers finished loading resolves against a stale [] and the
|
||||
// matched supplier is silently dropped.
|
||||
const suppliersRef = useRef(suppliers)
|
||||
useEffect(() => {
|
||||
suppliersRef.current = suppliers
|
||||
}, [suppliers])
|
||||
|
||||
const applyInboxItem = useCallback(
|
||||
(item: InboxItemData): boolean => {
|
||||
const extracted = item.extracted_data
|
||||
if (!extracted) return false
|
||||
|
||||
setExtractedData(extracted)
|
||||
setOriginalExtracted(extracted)
|
||||
|
||||
// Supplier
|
||||
if (
|
||||
item.matched_supplier_id &&
|
||||
suppliersRef.current.find((s) => s.id === item.matched_supplier_id)
|
||||
) {
|
||||
setValue('supplier_id', item.matched_supplier_id)
|
||||
setHasMatchedSupplier(true)
|
||||
onFieldPrefilled?.('supplier_id')
|
||||
}
|
||||
|
||||
// Scalar invoice fields
|
||||
if (extracted.invoice?.invoiceNumber) {
|
||||
setValue('supplier_invoice_number', extracted.invoice.invoiceNumber)
|
||||
onFieldPrefilled?.('supplier_invoice_number')
|
||||
}
|
||||
if (extracted.invoice?.invoiceDate) {
|
||||
setValue('invoice_date', extracted.invoice.invoiceDate)
|
||||
onFieldPrefilled?.('invoice_date')
|
||||
}
|
||||
if (extracted.invoice?.dueDate) {
|
||||
setValue('due_date', extracted.invoice.dueDate)
|
||||
onFieldPrefilled?.('due_date')
|
||||
}
|
||||
if (extracted.invoice?.paymentReference) {
|
||||
setValue('payment_reference', extracted.invoice.paymentReference)
|
||||
onFieldPrefilled?.('payment_reference')
|
||||
}
|
||||
if (extracted.invoice?.currency) {
|
||||
setValue('currency', extracted.invoice.currency)
|
||||
onFieldPrefilled?.('currency')
|
||||
}
|
||||
|
||||
// Line items: keep the single empty default if AI returned nothing,
|
||||
// otherwise replace it with the extracted lines. When the document
|
||||
// states a service window of 2+ calendar months (insurance period,
|
||||
// license term), pre-fill periodisering on every positive line: the
|
||||
// user sees the panel and can remove it before booking.
|
||||
if (extracted.lineItems && extracted.lineItems.length > 0) {
|
||||
// AI-extracted values are untrusted input: only accept strict
|
||||
// ISO-8601 dates before they reach form state (and later the API).
|
||||
const isIsoDate = (v: unknown): v is string =>
|
||||
typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v)
|
||||
const spsRaw = extracted.invoice?.servicePeriodStart
|
||||
const speRaw = extracted.invoice?.servicePeriodEnd
|
||||
const sps = isIsoDate(spsRaw) ? spsRaw : null
|
||||
const spe = isIsoDate(speRaw) ? speRaw : null
|
||||
let prefillAccrual = false
|
||||
if (sps && spe && spe >= sps) {
|
||||
try {
|
||||
prefillAccrual = countCalendarMonths(sps, spe) >= 2
|
||||
} catch {
|
||||
prefillAccrual = false
|
||||
}
|
||||
}
|
||||
replace(
|
||||
extracted.lineItems.map((li) => {
|
||||
const amount = typeof li.lineTotal === 'number' ? li.lineTotal : 0
|
||||
const withAccrual = prefillAccrual && amount > 0
|
||||
return {
|
||||
description: li.description || '',
|
||||
amount,
|
||||
// Extraction never suggests accounts (forcibly nulled at parse
|
||||
// time) and a silent default misbooks: leave empty so the user
|
||||
// (or the supplier default) makes the call.
|
||||
account_number: '',
|
||||
// Deliberately unconditional: for icke momsregistrerade the
|
||||
// zeroing effect grosses the net amount up by this rate
|
||||
// before forcing it to 0, so the rate must arrive intact.
|
||||
vat_rate: vatRateFromAi(li.vatRate),
|
||||
accrual_period_start: withAccrual ? (sps as string) : undefined,
|
||||
accrual_period_end: withAccrual ? (spe as string) : undefined,
|
||||
// No account yet → generic 1790; toggleAccrual re-suggests the
|
||||
// same way once the user picks one.
|
||||
accrual_balance_account: withAccrual
|
||||
? suggestBalanceAccount('expense', '')
|
||||
: undefined,
|
||||
}
|
||||
}),
|
||||
)
|
||||
onFieldPrefilled?.('items')
|
||||
}
|
||||
|
||||
// Treat the AI prefill as the new baseline: otherwise the unsaved-
|
||||
// changes prompt fires the moment the user navigates away, even if
|
||||
// they didn't touch anything.
|
||||
reset(getValues())
|
||||
setHasPrefilled(true)
|
||||
setApplyCount((c) => c + 1)
|
||||
return true
|
||||
},
|
||||
[setValue, replace, reset, getValues, onFieldPrefilled],
|
||||
)
|
||||
|
||||
// One-shot: load inbox item and prefill form. Runs after suppliers are
|
||||
// loaded so we can resolve matched_supplier_id to a real picker value.
|
||||
// Gate on `suppliersLoaded`, not `suppliers.length > 0`: otherwise the
|
||||
// effect never fires for users who haven't booked a supplier yet and
|
||||
// the "Laddar uppgifter från inkorgen…" spinner sticks forever.
|
||||
useEffect(() => {
|
||||
if (!inboxItemId || hasPrefilled || !suppliersLoaded) return
|
||||
let cancelled = false
|
||||
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/extensions/ext/invoice-inbox/items/${inboxItemId}`)
|
||||
const json = await res.json()
|
||||
if (cancelled) return
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: t('inbox_load_failed_title'),
|
||||
description: json?.error || t('inbox_load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsLoadingInbox(false)
|
||||
return
|
||||
}
|
||||
|
||||
const item = json.data as InboxItemData
|
||||
if (!item.extracted_data) {
|
||||
setIsLoadingInbox(false)
|
||||
setHasPrefilled(true)
|
||||
return
|
||||
}
|
||||
|
||||
applyInboxItem(item)
|
||||
} catch (err) {
|
||||
if (cancelled) return
|
||||
toast({
|
||||
title: t('inbox_load_failed_title'),
|
||||
description: err instanceof Error ? getErrorMessage(err) : t('unknown_error'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
if (!cancelled) setIsLoadingInbox(false)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [inboxItemId, suppliersLoaded, suppliers])
|
||||
|
||||
return {
|
||||
extractedData,
|
||||
originalExtracted,
|
||||
hasMatchedSupplier,
|
||||
setHasMatchedSupplier,
|
||||
isLoadingInbox,
|
||||
hasPrefilled,
|
||||
applyCount,
|
||||
applyInboxItem,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import type { Supplier, BASAccount, EntityType, FiscalPeriod } from '@/types'
|
||||
|
||||
/**
|
||||
* Reference data for the supplier-invoice editor: suppliers, the BAS chart,
|
||||
* company settings (entity type, accounting method, öresavrundning default,
|
||||
* dimensions, VAT registration) and fiscal periods. Extracted verbatim from
|
||||
* NewSupplierInvoiceForm; the fetch-once-on-mount semantics are unchanged.
|
||||
*/
|
||||
export function useSupplierInvoiceData() {
|
||||
const [suppliers, setSuppliers] = useState<Supplier[]>([])
|
||||
const [suppliersLoaded, setSuppliersLoaded] = useState(false)
|
||||
const [accounts, setAccounts] = useState<BASAccount[]>([])
|
||||
const [entityType, setEntityType] = useState<EntityType>('enskild_firma')
|
||||
const [accountingMethod, setAccountingMethod] = useState<'accrual' | 'cash'>('accrual')
|
||||
// Öresavrundning is display-only; defaults to the company-wide setting and is
|
||||
// overridable per invoice via the toggle in the totals section.
|
||||
const [oreRounding, setOreRounding] = useState<boolean>(true)
|
||||
// Dimension tagging (kostnadsställe/projekt). Affordances render only when
|
||||
// company_settings.dimensions_enabled: the same UI-visibility gate as
|
||||
// JournalEntryForm.
|
||||
const [dimensionsEnabled, setDimensionsEnabled] = useState(false)
|
||||
// Icke momsregistrerad verksamhet has no right to deduct input VAT: the
|
||||
// moms controls disappear and every line books at 0 % (the gross amount IS
|
||||
// the cost). Defaults true so registered companies keep the 25 % prefill
|
||||
// while /api/settings is still in flight.
|
||||
const [vatRegistered, setVatRegistered] = useState(true)
|
||||
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
|
||||
const [periodsLoaded, setPeriodsLoaded] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchSuppliers() {
|
||||
try {
|
||||
const res = await fetch('/api/suppliers')
|
||||
const { data } = await res.json()
|
||||
setSuppliers(data || [])
|
||||
} finally {
|
||||
setSuppliersLoaded(true)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchAccounts() {
|
||||
const res = await fetch('/api/bookkeeping/accounts')
|
||||
const { data } = await res.json()
|
||||
setAccounts(data || [])
|
||||
}
|
||||
|
||||
async function fetchEntityType() {
|
||||
try {
|
||||
const res = await fetch('/api/settings')
|
||||
const { data } = await res.json()
|
||||
if (data?.entity_type) setEntityType(data.entity_type)
|
||||
// Cash method books at payment, not registration: drives whether the
|
||||
// out-of-period warning is relevant (see willBookAtRegistration).
|
||||
if (data?.accounting_method === 'cash' || data?.accounting_method === 'accrual') {
|
||||
setAccountingMethod(data.accounting_method)
|
||||
}
|
||||
if (typeof data?.ore_rounding === 'boolean') setOreRounding(data.ore_rounding)
|
||||
setDimensionsEnabled(data?.dimensions_enabled === true)
|
||||
// Only an explicit false gates: a missing column or failed fetch keeps
|
||||
// the registered-company behavior.
|
||||
if (data?.vat_registered === false) setVatRegistered(false)
|
||||
} catch {
|
||||
// Default to enskild_firma / accrual, dimension affordances hidden
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchPeriods() {
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/fiscal-periods')
|
||||
const { data } = await res.json()
|
||||
setPeriods(data || [])
|
||||
} catch {
|
||||
// Non-critical: the server still hard-blocks an out-of-period booking.
|
||||
} finally {
|
||||
setPeriodsLoaded(true)
|
||||
}
|
||||
}
|
||||
|
||||
fetchSuppliers()
|
||||
fetchAccounts()
|
||||
fetchEntityType()
|
||||
fetchPeriods()
|
||||
}, [])
|
||||
|
||||
return {
|
||||
suppliers,
|
||||
setSuppliers,
|
||||
suppliersLoaded,
|
||||
accounts,
|
||||
entityType,
|
||||
accountingMethod,
|
||||
oreRounding,
|
||||
setOreRounding,
|
||||
dimensionsEnabled,
|
||||
vatRegistered,
|
||||
periods,
|
||||
periodsLoaded,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useRef, type RefObject } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { countCalendarMonths } from '@/lib/bookkeeping/accruals/compute'
|
||||
import { findIllegalVatRateRow } from '@/lib/vat/supplier-invoice-line-checks'
|
||||
import { rateToPctString, type SupplierInvoiceFormData } from '@/lib/supplier-invoices/form-payload'
|
||||
import type { InvoiceExtractionResult } from '@/types'
|
||||
|
||||
// The existing invoice surfaced on a duplicate-number conflict, used to drive
|
||||
// the resolution dialog (open it / uncredit-and-retry).
|
||||
export interface ExistingSupplierInvoice {
|
||||
id: string
|
||||
supplier_invoice_number: string
|
||||
status: string
|
||||
credit_note_id: string | null
|
||||
}
|
||||
|
||||
// Canonical create/convert response. On failure `error` is the structured
|
||||
// envelope's inner object ({ code, message, details }); a few legacy convert
|
||||
// paths still return a flat string, so accept both.
|
||||
export interface CreateResult {
|
||||
data?: { id: string; arrival_number: number }
|
||||
warnings?: Array<{ code: string; message: string }>
|
||||
error?:
|
||||
| string
|
||||
| {
|
||||
code?: string
|
||||
message?: string
|
||||
message_en?: string
|
||||
details?: { existing?: ExistingSupplierInvoice | null }
|
||||
}
|
||||
}
|
||||
|
||||
interface UseSupplierInvoiceSubmitParams {
|
||||
t: ReturnType<typeof useTranslations>
|
||||
ta: ReturnType<typeof useTranslations>
|
||||
toast: ReturnType<typeof useToast>['toast']
|
||||
isEF: boolean
|
||||
/** Inbox item to convert (route chooser + best-effort field sync-back). */
|
||||
inboxItemId: string | null
|
||||
originalExtracted: InvoiceExtractionResult | null
|
||||
buildPayload: (data: SupplierInvoiceFormData) => unknown
|
||||
reset: (data: SupplierInvoiceFormData) => void
|
||||
finishCreate: (invoiceId?: string) => void
|
||||
documentUploadInProgress: boolean
|
||||
documentUploadFailed: boolean
|
||||
showNoPeriodWarning: boolean
|
||||
canUseAccrual: boolean
|
||||
invoiceNumberInputRef: RefObject<HTMLInputElement | null>
|
||||
/**
|
||||
* Focus router for the always-enabled primary: called instead of a toast
|
||||
* when a required field is missing (supplier, invoice number, row account),
|
||||
* in the same priority order as the next-step line. Optional so the hook
|
||||
* can ship before the shell rebuild wires it.
|
||||
*/
|
||||
onMissingField?: (
|
||||
field: 'supplier' | 'invoice_number' | 'rows' | 'row_account',
|
||||
rowIndex?: number,
|
||||
) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit orchestration for the supplier-invoice editor: endpoint chooser
|
||||
* (plain create vs inbox convert), the three submit paths (EF/private direct,
|
||||
* AB review, register-and-match), duplicate-number conflict recovery and the
|
||||
* best-effort inbox field sync-back. Extracted verbatim from
|
||||
* NewSupplierInvoiceForm; both endpoints validate CreateSupplierInvoiceSchema
|
||||
* and return the canonical error envelope.
|
||||
*/
|
||||
export function useSupplierInvoiceSubmit({
|
||||
t,
|
||||
ta,
|
||||
toast,
|
||||
isEF,
|
||||
inboxItemId,
|
||||
originalExtracted,
|
||||
buildPayload,
|
||||
reset,
|
||||
finishCreate,
|
||||
documentUploadInProgress,
|
||||
documentUploadFailed,
|
||||
showNoPeriodWarning,
|
||||
canUseAccrual,
|
||||
invoiceNumberInputRef,
|
||||
onMissingField,
|
||||
}: UseSupplierInvoiceSubmitParams) {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [showReview, setShowReview] = useState(false)
|
||||
const [pendingData, setPendingData] = useState<SupplierInvoiceFormData | null>(null)
|
||||
|
||||
// Match-on-create state
|
||||
const [showBankPicker, setShowBankPicker] = useState(false)
|
||||
const [pendingTransactionId, setPendingTransactionId] = useState<string | null>(null)
|
||||
// The button's onClick and the form's onSubmit run in the same React event
|
||||
// batch, so a `useState`-backed submitMode would still hold the previous
|
||||
// render's value when onSubmit reads it. A ref bridges the two synchronous
|
||||
// handlers; the matching state mirror only drives the review-dialog UI.
|
||||
const submitModeRef = useRef<'register' | 'register_and_match'>('register')
|
||||
|
||||
// Conflict state for duplicate-supplier-invoice-number
|
||||
const [conflict, setConflict] = useState<{
|
||||
message: string
|
||||
existing: ExistingSupplierInvoice | null
|
||||
} | null>(null)
|
||||
const [isResolvingConflict, setIsResolvingConflict] = useState(false)
|
||||
|
||||
// Persist user edits back into the inbox item's extracted_data so the
|
||||
// inbox stays in sync with what was actually booked. Best-effort: a
|
||||
// failed PATCH never blocks the registration.
|
||||
async function patchInboxFieldsIfChanged(data: SupplierInvoiceFormData) {
|
||||
if (!inboxItemId || !originalExtracted) return
|
||||
const supplierField: Record<string, unknown> = {}
|
||||
const invoiceField: Record<string, unknown> = {}
|
||||
|
||||
if (originalExtracted.invoice?.invoiceNumber !== data.supplier_invoice_number) {
|
||||
invoiceField.invoiceNumber = data.supplier_invoice_number || null
|
||||
}
|
||||
if (originalExtracted.invoice?.invoiceDate !== data.invoice_date) {
|
||||
invoiceField.invoiceDate = data.invoice_date || null
|
||||
}
|
||||
if (originalExtracted.invoice?.dueDate !== data.due_date) {
|
||||
invoiceField.dueDate = data.due_date || null
|
||||
}
|
||||
if ((originalExtracted.invoice?.paymentReference || null) !== (data.payment_reference || null)) {
|
||||
invoiceField.paymentReference = data.payment_reference || null
|
||||
}
|
||||
if (originalExtracted.invoice?.currency !== data.currency) {
|
||||
invoiceField.currency = data.currency
|
||||
}
|
||||
|
||||
if (Object.keys(supplierField).length === 0 && Object.keys(invoiceField).length === 0) return
|
||||
|
||||
try {
|
||||
await fetch(`/api/extensions/ext/invoice-inbox/items/${inboxItemId}/fields`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...(Object.keys(supplierField).length ? { supplier: supplierField } : {}),
|
||||
...(Object.keys(invoiceField).length ? { invoice: invoiceField } : {}),
|
||||
}),
|
||||
})
|
||||
} catch {
|
||||
// Best-effort sync; don't block registration on this.
|
||||
}
|
||||
}
|
||||
|
||||
// Single submit endpoint chooser: convert when we came from inbox, plain
|
||||
// POST otherwise. Both endpoints validate the same CreateSupplierInvoiceSchema
|
||||
// and return the same canonical error envelope ({ error: { code, message,
|
||||
// details } }): including the recoverable duplicate-number 409.
|
||||
async function postCreate(data: SupplierInvoiceFormData): Promise<{
|
||||
ok: boolean
|
||||
status: number
|
||||
result: CreateResult
|
||||
}> {
|
||||
const url = inboxItemId
|
||||
? `/api/extensions/ext/invoice-inbox/items/${inboxItemId}/convert`
|
||||
: '/api/supplier-invoices'
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(buildPayload(data)),
|
||||
})
|
||||
const result = await res.json()
|
||||
if (
|
||||
res.ok &&
|
||||
(result as CreateResult).warnings?.some((warning) => warning.code === 'DOCUMENT_LINK_FAILED')
|
||||
) {
|
||||
toast({
|
||||
title: t('document_link_warning_title'),
|
||||
description: t('document_link_warning_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
return { ok: res.ok, status: res.status, result }
|
||||
}
|
||||
|
||||
function onSubmit(data: SupplierInvoiceFormData) {
|
||||
if (documentUploadInProgress) {
|
||||
toast({
|
||||
title: t('document_upload_in_progress_title'),
|
||||
description: t('document_upload_in_progress_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
if (documentUploadFailed) {
|
||||
toast({
|
||||
title: t('document_upload_failed_title'),
|
||||
description: t('document_upload_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
// Hard block: under faktureringsmetoden (and for privately-paid kvitton) a
|
||||
// verifikation is posted at registration, and BFL 5 kap kräver att
|
||||
// verifikationsnumret ligger i en obruten serie inom ett räkenskapsår. No
|
||||
// räkenskapsår for the invoice date → no compliant voucher can exist, so we
|
||||
// refuse rather than register an unbooked invoice. Kontantmetoden books at
|
||||
// payment, so it is intentionally not blocked here (see showNoPeriodWarning).
|
||||
if (showNoPeriodWarning) {
|
||||
toast({
|
||||
title: t('warning_title'),
|
||||
description: t('no_period_warning', { date: data.invoice_date }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
if (!data.supplier_id) {
|
||||
if (onMissingField) onMissingField('supplier')
|
||||
else toast({ title: t('supplier_missing_title'), description: t('supplier_missing_description'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
if (!data.supplier_invoice_number) {
|
||||
if (onMissingField) onMissingField('invoice_number')
|
||||
else toast({ title: t('invoice_number_missing_title'), description: t('invoice_number_missing_description'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
// The dokument-först table starts with zero rows (the ghost entry row is
|
||||
// never part of form state): an empty items array must route to the entry
|
||||
// input instead of slipping past the per-row account check below.
|
||||
if (data.items.length === 0) {
|
||||
if (onMissingField) onMissingField('rows')
|
||||
else {
|
||||
toast({
|
||||
title: t('account_missing_title'),
|
||||
description: t('account_missing_description', { row: 1 }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
const rowWithoutAccount = data.items.findIndex((item) => !item.account_number)
|
||||
if (rowWithoutAccount !== -1) {
|
||||
if (onMissingField) onMissingField('row_account', rowWithoutAccount)
|
||||
else {
|
||||
toast({
|
||||
title: t('account_missing_title'),
|
||||
description: t('account_missing_description', { row: rowWithoutAccount + 1 }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
// Only 25/12/6/0 % are legal Swedish VAT rates (ML 2023:200). The free-text
|
||||
// VatRateCell clamps to [0, 100] but accepts anything in between, so block
|
||||
// illegal rates here. Reverse-charge invoices skip this: their line vat_rate
|
||||
// is forced to 0 and RcRateSelect already restricts the self-assessed rate.
|
||||
if (!data.reverse_charge) {
|
||||
const rowWithIllegalRate = findIllegalVatRateRow(data.items)
|
||||
if (rowWithIllegalRate !== -1) {
|
||||
toast({
|
||||
title: t('illegal_vat_rate_title'),
|
||||
description: t('illegal_vat_rate_description', {
|
||||
row: rowWithIllegalRate + 1,
|
||||
rate: rateToPctString(data.items[rowWithIllegalRate].vat_rate),
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
// A row with an open periodisering panel must carry a complete period of
|
||||
// at least two calendar months before the invoice can be booked.
|
||||
const invalidAccrual = canUseAccrual && data.items.some((item) => {
|
||||
if (item.accrual_balance_account == null) return false
|
||||
if (!item.accrual_period_start || !item.accrual_period_end) return true
|
||||
if (item.accrual_period_end < item.accrual_period_start) return true
|
||||
return countCalendarMonths(item.accrual_period_start, item.accrual_period_end) < 2
|
||||
})
|
||||
if (invalidAccrual) {
|
||||
toast({
|
||||
title: ta('incomplete_toast_title'),
|
||||
description: ta('incomplete_toast_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (submitModeRef.current === 'register_and_match') {
|
||||
// Open the bank-transaction picker; actual create happens on pick.
|
||||
// For AB the review dialog is shown after a transaction is picked.
|
||||
setPendingData(data)
|
||||
setShowBankPicker(true)
|
||||
return
|
||||
}
|
||||
|
||||
// Privately-paid skips the AB review dialog: the toggle itself is the
|
||||
// explicit user intent, and the resulting verifikat is just expense + VAT
|
||||
// against the owner account (2893/2018). Same path for EF.
|
||||
if (isEF || data.paid_with_private_funds) {
|
||||
setPendingData(data)
|
||||
handleDirectSubmit(data)
|
||||
} else {
|
||||
setPendingData(data)
|
||||
setShowReview(true)
|
||||
}
|
||||
}
|
||||
|
||||
// EF: create + auto-approve, no review dialog. Privately-paid invoices land
|
||||
// here too and skip auto-approve since they're already in status='paid'.
|
||||
async function handleDirectSubmit(data: SupplierInvoiceFormData) {
|
||||
setIsSubmitting(true)
|
||||
await patchInboxFieldsIfChanged(data)
|
||||
const { ok, status, result } = await postCreate(data)
|
||||
|
||||
if (!ok) {
|
||||
// EF/direct path also hits the duplicate-number 409 (e.g. converting an
|
||||
// inbox receipt whose number was already registered): offer recovery
|
||||
// instead of a dead-end toast.
|
||||
if (!tryHandleDuplicateConflict(status, result)) {
|
||||
handleCreateError(status, result)
|
||||
}
|
||||
setIsSubmitting(false)
|
||||
return
|
||||
}
|
||||
if (!result.data) {
|
||||
setIsSubmitting(false)
|
||||
return
|
||||
}
|
||||
|
||||
// Clear dirty state so useUnsavedChanges doesn't fire the
|
||||
// beforeunload prompt while we navigate away on a successful submit.
|
||||
reset(data)
|
||||
|
||||
if (data.paid_with_private_funds) {
|
||||
toast({
|
||||
title: t('expense_registered_title'),
|
||||
description: t('arrival_number_label', { number: result.data.arrival_number }),
|
||||
})
|
||||
finishCreate()
|
||||
setIsSubmitting(false)
|
||||
return
|
||||
}
|
||||
|
||||
// Auto-approve for EF
|
||||
const approveRes = await fetch(`/api/supplier-invoices/${result.data.id}/approve`, { method: 'POST' })
|
||||
if (!approveRes.ok) {
|
||||
toast({
|
||||
title: t('warning_title'),
|
||||
description: t('auto_approve_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
finishCreate(result.data.id)
|
||||
} else {
|
||||
toast({ title: t('invoice_registered_title'), description: t('arrival_number_label', { number: result.data.arrival_number }) })
|
||||
finishCreate()
|
||||
}
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
|
||||
// AB: create after review dialog. If a bank transaction was picked first
|
||||
// (register-and-match flow), also match the new invoice to it.
|
||||
async function handleConfirm() {
|
||||
if (!pendingData) return
|
||||
setIsSubmitting(true)
|
||||
await patchInboxFieldsIfChanged(pendingData)
|
||||
const { ok, status, result } = await postCreate(pendingData)
|
||||
|
||||
if (ok && result.data) {
|
||||
const invoiceId = result.data.id
|
||||
const arrivalNumber = result.data.arrival_number
|
||||
setShowReview(false)
|
||||
// Clear dirty state: see comment in handleDirectSubmit.
|
||||
reset(pendingData)
|
||||
|
||||
if (pendingTransactionId) {
|
||||
const matchRes = await fetch(`/api/transactions/${pendingTransactionId}/match-supplier-invoice`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ supplier_invoice_id: invoiceId }),
|
||||
})
|
||||
const matchResult = await matchRes.json()
|
||||
setPendingTransactionId(null)
|
||||
submitModeRef.current = 'register'
|
||||
|
||||
if (matchRes.ok) {
|
||||
toast({
|
||||
title: t('invoice_registered_and_matched_title'),
|
||||
description: t('invoice_registered_and_matched_description', { number: arrivalNumber }),
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: t('invoice_registered_match_failed_title'),
|
||||
description: getErrorMessage(matchResult, { context: 'supplier_invoice', statusCode: matchRes.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
} else {
|
||||
toast({ title: t('invoice_registered_title'), description: t('arrival_number_label', { number: arrivalNumber }) })
|
||||
}
|
||||
|
||||
finishCreate(invoiceId)
|
||||
} else {
|
||||
// Treat duplicate-number as a recoverable conflict; everything else as a hard error.
|
||||
if (!tryHandleDuplicateConflict(status, result)) {
|
||||
handleCreateError(status, result)
|
||||
}
|
||||
}
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
|
||||
// Detect the recoverable duplicate-supplier-invoice-number conflict and open
|
||||
// the resolution dialog. Both the inbox `convert` route and the plain create
|
||||
// route return the same structured 409 envelope, so this works for every
|
||||
// submit path. Returns true when handled (caller should skip the error toast).
|
||||
function tryHandleDuplicateConflict(status: number, result: CreateResult): boolean {
|
||||
const err = result.error
|
||||
if (
|
||||
status !== 409 ||
|
||||
typeof err !== 'object' ||
|
||||
err === null ||
|
||||
err.code !== 'SI_CREATE_DUPLICATE_INVOICE_NUMBER'
|
||||
) {
|
||||
return false
|
||||
}
|
||||
// Close the review dialog if it was the path that triggered the conflict;
|
||||
// a no-op for the EF/direct paths where it was never opened.
|
||||
setShowReview(false)
|
||||
setConflict({
|
||||
message: err.message || t('duplicate_default_message'),
|
||||
existing: err.details?.existing ?? null,
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
// Shared error toast for non-conflict failures.
|
||||
function handleCreateError(status: number, result: CreateResult) {
|
||||
toast({
|
||||
title: t('register_invoice_failed_title'),
|
||||
description: getErrorMessage(result, { context: 'supplier_invoice', statusCode: status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
|
||||
async function handleUncreditAndRetry() {
|
||||
if (!conflict?.existing) return
|
||||
const existingId = conflict.existing.id
|
||||
const existingNumber = conflict.existing.supplier_invoice_number
|
||||
setIsResolvingConflict(true)
|
||||
|
||||
const uncreditRes = await fetch(
|
||||
`/api/supplier-invoices/${existingId}/uncredit`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
const uncreditResult = await uncreditRes.json()
|
||||
if (!uncreditRes.ok) {
|
||||
toast({
|
||||
title: t('uncredit_failed_title'),
|
||||
description: getErrorMessage(uncreditResult, { context: 'supplier_invoice', statusCode: uncreditRes.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsResolvingConflict(false)
|
||||
return
|
||||
}
|
||||
|
||||
setConflict(null)
|
||||
|
||||
if (!pendingData) {
|
||||
setIsResolvingConflict(false)
|
||||
return
|
||||
}
|
||||
|
||||
const { ok, status, result } = await postCreate(pendingData)
|
||||
setIsResolvingConflict(false)
|
||||
|
||||
if (ok && result.data) {
|
||||
toast({
|
||||
title: t('uncredit_and_register_success_title'),
|
||||
description: t('arrival_number_label', { number: result.data.arrival_number }),
|
||||
})
|
||||
reset(pendingData)
|
||||
finishCreate(result.data.id)
|
||||
return
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('uncredit_but_register_failed_title'),
|
||||
description: t('uncredit_but_register_failed_description', {
|
||||
number: existingNumber,
|
||||
reason: getErrorMessage(result, { context: 'supplier_invoice', statusCode: status }),
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
|
||||
function handlePickNewNumber() {
|
||||
setConflict(null)
|
||||
setTimeout(() => invoiceNumberInputRef.current?.focus(), 0)
|
||||
}
|
||||
|
||||
// Match-on-create: register the invoice, then match the picked transaction.
|
||||
// EF goes straight through (auto-approve included). AB stores the picked
|
||||
// transaction and routes through the same review dialog as the plain
|
||||
// register flow: handleConfirm picks up the match step on confirmation.
|
||||
async function handlePickTransaction(transactionId: string) {
|
||||
if (!pendingData) return
|
||||
setShowBankPicker(false)
|
||||
|
||||
if (!isEF) {
|
||||
setPendingTransactionId(transactionId)
|
||||
setShowReview(true)
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
await patchInboxFieldsIfChanged(pendingData)
|
||||
const { ok, status, result } = await postCreate(pendingData)
|
||||
|
||||
if (!ok || !result.data) {
|
||||
if (!tryHandleDuplicateConflict(status, result)) {
|
||||
handleCreateError(status, result)
|
||||
}
|
||||
setIsSubmitting(false)
|
||||
return
|
||||
}
|
||||
|
||||
const invoiceId = result.data.id
|
||||
const arrivalNumber = result.data.arrival_number
|
||||
|
||||
// Auto-approve before matching, so the invoice is in the 'approved' state
|
||||
// that match-supplier-invoice expects (it accepts registered too, but
|
||||
// EF's expectation is fully-booked).
|
||||
await fetch(`/api/supplier-invoices/${invoiceId}/approve`, { method: 'POST' })
|
||||
|
||||
const matchRes = await fetch(`/api/transactions/${transactionId}/match-supplier-invoice`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ supplier_invoice_id: invoiceId }),
|
||||
})
|
||||
const matchResult = await matchRes.json()
|
||||
setIsSubmitting(false)
|
||||
submitModeRef.current = 'register'
|
||||
|
||||
if (matchRes.ok) {
|
||||
toast({
|
||||
title: t('invoice_registered_and_matched_title'),
|
||||
description: t('invoice_registered_and_matched_description', { number: arrivalNumber }),
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: t('invoice_registered_match_failed_title'),
|
||||
description: getErrorMessage(matchResult, { context: 'supplier_invoice', statusCode: matchRes.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
reset(pendingData)
|
||||
finishCreate(invoiceId)
|
||||
}
|
||||
|
||||
return {
|
||||
isSubmitting,
|
||||
showReview,
|
||||
setShowReview,
|
||||
pendingData,
|
||||
showBankPicker,
|
||||
setShowBankPicker,
|
||||
setPendingTransactionId,
|
||||
submitModeRef,
|
||||
conflict,
|
||||
setConflict,
|
||||
isResolvingConflict,
|
||||
onSubmit,
|
||||
handleConfirm,
|
||||
handleUncreditAndRetry,
|
||||
handlePickNewNumber,
|
||||
handlePickTransaction,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user