fix(ux): smoothness follow-ups - detail pages, batches, toasts, and the last edges (#1633)

* fix(ux): smoothness follow-ups - detail pages, batches, toasts, and the last edges

Follow-up batch to #1629: the six documented deferred items from
dev_docs/loading_states_analysis.md, in the same vocabulary (first-load-only
takeovers, background reconcile behind mounted content, row/button-level
pending, sequence guards).

- Invoice detail pages: kundfaktura and leverantorsfaktura detail no longer
  blank the whole page for one-field changes. fetchInvoice shows the blocking
  spinner/skeleton only before the first paint (or when the pager steps to a
  different invoice); Bokfor / status / finalize / payment / send / Attestera /
  Markera betald / kreditera refetch behind the mounted page, the acting
  button shows a spinner-in-button, and the handlers await the refetch so
  pending covers until the content reflects the new state. The supplier
  detail's single isProcessing boolean became processingAction so the spinner
  lands on the clicked button only. (The leverantorsfakturor LIST
  try/catch/res.ok item was already fixed by #1629.)

- useDestructiveConfirm: confirm(opts, action?) can now carry the destructive
  operation, so the dialog's existing isLoading spinner actually shows while
  it runs, dismissal is blocked meanwhile, and confirm resolves false if the
  action throws. Adopted at the /transactions row delete and the supplier-
  invoice detail delete (which previously permitted duplicate DELETEs with
  zero feedback).

- Batch parallelization: new lib/concurrency.ts mapWithConcurrency (bounded
  worker pool, order-preserving, tested). /transactions batch categorize /
  ignore / delete run per-row requests 5 at a time instead of strictly
  sequentially; the bulkbar counter ticks per completed row.

- Toast-spam reduction: batch categorize rows run silent (exit animation,
  count decrement and state patch stay; no per-row Bokford or generic failure
  toast) and ONE aggregate toast reports "N bokforda[, M misslyckades]" with
  a single Angra alla action that pools the same /uncategorize endpoint over
  every booked row (per-row undo is feasible today, so the aggregate is too).
  Interactive escalations (SI/CI match suggestions, duplicate warning,
  activate-account) deliberately keep their dialogs.

- Underlag row-click flash: InvoiceInboxWorkspace handleSelect seeds the
  detail pane synchronously from the clicked list row and starts the document
  load in parallel with the detail GET (which hydrates on arrival), so a row
  click never flashes the onboarding/empty state, and a stale-response guard
  keeps a slow fetch from overwriting a newer selection.

- #1629 round-2 edges: /pending holds the loading state when a fetch for a
  not-yet-loaded tab FAILS (never renders the previous tab's rows under the
  new tab's header, and never fakes an empty state); /transactions clears
  transactions/skvRows (+ count/paging) and bumps both fetch sequences on
  company switch, and loadSkvRows got the same sequence-guard pattern as
  fetchTransactions.

Gates: full vitest suite green (14772 passed), tsc byte-identical to the
origin/main baseline (stash-diffed), eslint 0 errors on touched files
(warnings identical to baseline), check:guards green, package-lock untouched.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(ui): harden action feedback against stale responses and failures

Address the seven CodeRabbit findings on #1633:

- invoices/[id] + supplier-invoices/[id]: latest-request guard in
  fetchInvoice (sequence token) so a mutation refresh overlapping pager
  navigation can never commit invoice A's state under invoice B's URL;
  the deferred related-document writes are guarded too
- supplier-invoices/[id]: try/catch/finally in approve/book/mark-paid/
  credit/uncredit so a rejected fetch()/json() clears processingAction
  instead of leaving every invoice action disabled until reload
- transactions: extend the skattekonto sequence guard to the
  connection-status write so a status response started under the
  previous company cannot flip the reconnect banner for the new one
- transactions: runCategorize resolves { ok, journalEntryId } so the
  batch aggregate counts a 200-with-null-journal-entry booking (flag
  flip) as success instead of narrating it as misslyckades; Angra alla
  only targets rows with an actual verifikat, since the storno endpoint
  rejects rows without one
- transactions: shared undoneIdsRef lets "Angra alla" cancel a pending
  finishBooking state patch; a fresh booking clears its row's entry so
  re-booked rows still get their delayed patch
- InvoiceInboxWorkspace: monotonic request tokens for the detail and
  document reads so a same-item reload cannot resolve out of order and
  paint a stale snapshot or document URL
- messages: ICU plural for the success part of both partial batch
  descriptions in sv and en (1 bokford, not 1 bokforda)

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Jakob Wennberg <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-08-17 14:30:25 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 43a71aec3c
commit 93541d7186
12 changed files with 780 additions and 253 deletions
+43 -7
View File
@@ -1,6 +1,6 @@
'use client'
import { useState, useEffect, use } from 'react'
import { useState, useEffect, useRef, use } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { useLocale, useTranslations } from 'next-intl'
@@ -181,6 +181,12 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
const statusLabel = (status: InvoiceStatus): string => t(`status_${status}`)
const reminderLevelLabel = (level: 1 | 2 | 3): string => t(`reminder_level_${level}`)
// Latest-request guard for fetchInvoice. A mutation refresh can overlap the
// pager stepping to a sibling invoice (the component stays mounted, only
// `id` changes), and without it the older response would commit invoice A's
// state under invoice B's URL. Only the newest request may write state.
const fetchSeqRef = useRef(0)
useEffect(() => {
fetchInvoice()
}, [id])
@@ -214,7 +220,13 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
}
async function fetchInvoice() {
setIsLoading(true)
const seq = ++fetchSeqRef.current
// The blocking spinner is reserved for the first load (or stepping to a
// different invoice via the pager). Refetches after Bokför / status
// change / finalize / payment / send reconcile BEHIND the mounted page:
// a one-field state change must not collapse the whole detail view to a
// spinner, reset scroll, and remount every card.
if (!invoice || invoice.id !== id) setIsLoading(true)
// Settings depend only on the active company, so start them with the main
// invoice batch instead of waiting for the invoice row first.
@@ -260,6 +272,10 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
deliveriesPromise,
])
// A newer fetch owns the page now (pager step or later refresh): commit
// nothing from this one, not even the not-found redirect.
if (seq !== fetchSeqRef.current) return
if (error || !data) {
toast({
title: t('load_failed_title'),
@@ -306,6 +322,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
}
const settingsRes = await settingsPromise
if (seq !== fetchSeqRef.current) return
if (settingsRes) {
const settings = settingsRes.data
setOreRounding(settings?.ore_rounding ?? true)
@@ -352,6 +369,10 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
.single()
: Promise.resolve(null),
]).then(([creditNoteRes, originalRes, convertedRes]) => {
// Deferred writes need the same guard: they land after first paint
// and would otherwise attach the previous invoice's related documents
// to the one the pager has since navigated to.
if (seq !== fetchSeqRef.current) return
setCreditNote(creditNoteRes?.data ? (creditNoteRes.data as Invoice) : null)
if (originalRes?.data) {
setOriginalInvoice(originalRes.data as Invoice)
@@ -400,7 +421,9 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
} else {
toast({ title: t('booked_title'), description: t('booked_description') })
}
fetchInvoice()
// Awaited so the Bokför button's pending state covers the in-place
// refresh: the spinner stops when the page shows the booked state.
await fetchInvoice()
} catch (error) {
toast({
title: t('book_failed_title'),
@@ -453,7 +476,9 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
title: t('status_update_toast_title'),
description: t('status_update_toast_description', { status: statusLabel(status).toLowerCase() }),
})
fetchInvoice()
// Awaited: the acting button keeps its pending state until the page
// reflects the new status (the refetch runs behind the mounted content).
await fetchInvoice()
} catch (error) {
toast({
title: t('status_update_failed_title'),
@@ -810,7 +835,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
})
setShowFinalizeDialog(false)
fetchInvoice()
await fetchInvoice()
} catch (error) {
toast({
title: t('finalize_failed_title'),
@@ -1073,7 +1098,13 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
disabled={isUpdating || !canWrite}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
{canWrite ? <Send className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{isUpdating ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : canWrite ? (
<Send className="mr-2 h-4 w-4" />
) : (
<Lock className="mr-2 h-4 w-4" />
)}
{t('mark_as_sent')}
</Button>
)}
@@ -1451,6 +1482,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
<span className="text-sm text-muted-foreground">{t('not_booked_yet')}</span>
{canWrite && (
<Button size="sm" onClick={openBookConfirm} disabled={isUpdating}>
{isUpdating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t('book_action')}
</Button>
)}
@@ -1774,7 +1806,11 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
onClick={() => updateStatus('cancelled')}
disabled={isUpdating}
>
<XCircle className="mr-2 h-4 w-4" />
{isUpdating ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<XCircle className="mr-2 h-4 w-4" />
)}
{t('cancel_action')}
</Button>
)}
+6
View File
@@ -387,6 +387,12 @@ export default function PendingOperationsPage() {
} catch {
if (!isCurrent()) return
toast({ title: 'Kunde inte ladda operationer', variant: 'destructive' })
// The rows on screen belong to another tab (or no load has succeeded
// yet): dropping the loading state here would render those foreign rows
// under this tab's header as if they were its content. Hold the loading
// state instead; the toast says why, and the next tab switch or
// realtime echo retries.
if (loadedTabRef.current !== activeTab) return
}
if (!isCurrent()) return
setIsLoading(false)
+198 -94
View File
@@ -1,6 +1,6 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { useState, useEffect, useMemo, useRef } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
@@ -13,7 +13,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { ArrowLeft, CheckCircle, CreditCard, FileText, Trash2, Lock, Undo2, Info, Pencil, Plus, CalendarClock, Paperclip } from 'lucide-react'
import { ArrowLeft, CheckCircle, CreditCard, FileText, Trash2, Lock, Undo2, Info, Loader2, Pencil, Plus, CalendarClock, Paperclip } from 'lucide-react'
import LinkVoucherPicker from '@/components/invoices/LinkVoucherPicker'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { formatDate, cn } from '@/lib/utils'
@@ -97,7 +97,13 @@ export default function SupplierInvoiceDetailPage() {
const [paymentAccount, setPaymentAccount] = useState('1930')
const [accounts, setAccounts] = useState<BASAccount[]>([])
const [areAccountsLoading, setAreAccountsLoading] = useState(false)
const [isProcessing, setIsProcessing] = useState(false)
// Which action is in flight, not just whether one is: the acting button
// shows the spinner while the others only disable. A single boolean put
// identical pending feedback (none) on every button at once.
const [processingAction, setProcessingAction] = useState<
'approve' | 'book' | 'mark_paid' | 'credit' | 'uncredit' | 'delete' | null
>(null)
const isProcessing = processingAction !== null
const [duplicateCandidates, setDuplicateCandidates] = useState<
Array<{
id: string
@@ -113,6 +119,13 @@ export default function SupplierInvoiceDetailPage() {
const [editLines, setEditLines] = useState<EditableLine[]>([])
const { dialogProps: confirmDialogProps, confirm: confirmAction } = useDestructiveConfirm()
// Latest-request guard for fetchInvoice. A mutation refetch can overlap the
// pager stepping to a sibling invoice (the component stays mounted, only
// params.id changes), and without it the older response would commit
// invoice A's row and payment-form defaults under invoice B's URL. Only the
// newest request may write state.
const fetchSeqRef = useRef(0)
const statusLabels = useMemo<Record<string, string>>(() => ({
registered: t('status_registered'),
approved: t('status_approved'),
@@ -125,13 +138,20 @@ export default function SupplierInvoiceDetailPage() {
}), [t])
async function fetchInvoice() {
setIsLoading(true)
const seq = ++fetchSeqRef.current
// Blocking skeleton only before the first paint (or when the pager steps
// to a different invoice). Attest/Bokför/Markera betald/kreditera each
// refetch after their mutation: those reconcile behind the mounted page
// instead of swapping the whole detail for a skeleton and back.
if (!invoice || invoice.id !== params.id) setIsLoading(true)
// try/finally: a dropped connection or a non-JSON error page makes
// res.json() throw, and this runs from an effect, so the rejection is
// unhandled and isLoading would stay true: a spinner that never resolves.
try {
const res = await fetch(`/api/supplier-invoices/${params.id}`)
const body = await res.json().catch(() => null)
// A newer fetch owns the page now: commit nothing from this one.
if (seq !== fetchSeqRef.current) return
// See the identical fix in suppliers/[id]: `body.error` is the canonical
// envelope object, and rendering an object as a toast description throws
// out of the root layout into global-error.
@@ -147,13 +167,16 @@ export default function SupplierInvoiceDetailPage() {
setPaymentDate(new Date().toISOString().split('T')[0])
}
} catch (err) {
if (seq !== fetchSeqRef.current) return
toast({
title: t('load_failed_title'),
description: getErrorMessage(err, { context: 'supplier_invoice' }),
variant: 'destructive',
})
} finally {
setIsLoading(false)
// A stale request must not stop the newest one's skeleton early: only
// the request that still owns the page resolves the loading state.
if (seq === fetchSeqRef.current) setIsLoading(false)
}
}
@@ -293,38 +316,53 @@ export default function SupplierInvoiceDetailPage() {
}, [accounts.length, isPayDialogOpen])
async function handleApprove() {
setIsProcessing(true)
const res = await fetch(`/api/supplier-invoices/${params.id}/approve`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: t('approve_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: t('approved_title'), description: t('approved_description') })
fetchInvoice()
setProcessingAction('approve')
// try/catch/finally like handleDelete: a rejected fetch()/res.json()
// must not skip the reset below, or isProcessing keeps every invoice
// action disabled until a full page reload.
try {
const res = await fetch(`/api/supplier-invoices/${params.id}/approve`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: t('approve_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: t('approved_title'), description: t('approved_description') })
// Awaited: the Attestera button keeps its spinner until the page shows
// the approved state (the refetch runs behind the mounted content).
await fetchInvoice()
}
} catch (err) {
toast({ title: t('approve_failed_title'), description: getErrorMessage(err, { context: 'supplier_invoice' }), variant: 'destructive' })
} finally {
setProcessingAction(null)
}
setIsProcessing(false)
}
// #967: deferred booking: create the registration verifikat afterwards.
async function handleBook() {
setIsProcessing(true)
const res = await fetch(`/api/supplier-invoices/${params.id}/book`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: t('book_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else if (Array.isArray(result.warnings) && result.warnings.length > 0) {
// Booked, but a follow-up is needed (e.g. periodiseringar failed).
toast({ title: t('booked_title'), description: t('booked_with_warnings_description'), variant: 'destructive' })
fetchInvoice()
} else {
toast({ title: t('booked_title'), description: t('booked_description') })
fetchInvoice()
setProcessingAction('book')
try {
const res = await fetch(`/api/supplier-invoices/${params.id}/book`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: t('book_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else if (Array.isArray(result.warnings) && result.warnings.length > 0) {
// Booked, but a follow-up is needed (e.g. periodiseringar failed).
toast({ title: t('booked_title'), description: t('booked_with_warnings_description'), variant: 'destructive' })
await fetchInvoice()
} else {
toast({ title: t('booked_title'), description: t('booked_description') })
await fetchInvoice()
}
} catch (err) {
toast({ title: t('book_failed_title'), description: getErrorMessage(err, { context: 'supplier_invoice' }), variant: 'destructive' })
} finally {
setProcessingAction(null)
}
setIsProcessing(false)
}
async function handleMarkPaid(force: boolean = false) {
setIsProcessing(true)
setProcessingAction('mark_paid')
// When the user has edited the booking rows in this session, forward
// them so the server validates balance and posts via createJournalEntry
// directly. Otherwise the server picks the default routing (clearing
@@ -342,39 +380,44 @@ export default function SupplierInvoiceDetailPage() {
})
: undefined
const res = await fetch(`/api/supplier-invoices/${params.id}/mark-paid`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: parseFloat(payAmount),
payment_date: paymentDate,
payment_account: paymentAccount,
...(force ? { force: true } : {}),
...(linesPayload ? { lines: linesPayload } : {}),
}),
})
const result = await res.json()
if (!res.ok) {
if (result?.error?.code === 'SI_PAID_LIKELY_DUPLICATE' && Array.isArray(result.error.details?.candidates)) {
setDuplicateCandidates(result.error.details.candidates)
setIsPayDialogOpen(false)
} else {
toast({ title: t('payment_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
}
} else {
toast({
title: result.status === 'paid' ? t('paid_title') : t('partial_payment_title'),
// The paid amount is in the invoice's currency (the dialog's helper
// text says so): the toast must not relabel it as kr.
description: t('amount_registered_description', {
amount: formatCurrency(parseFloat(payAmount), invoice?.currency || 'SEK'),
try {
const res = await fetch(`/api/supplier-invoices/${params.id}/mark-paid`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: parseFloat(payAmount),
payment_date: paymentDate,
payment_account: paymentAccount,
...(force ? { force: true } : {}),
...(linesPayload ? { lines: linesPayload } : {}),
}),
})
setIsPayDialogOpen(false)
setDuplicateCandidates(null)
fetchInvoice()
const result = await res.json()
if (!res.ok) {
if (result?.error?.code === 'SI_PAID_LIKELY_DUPLICATE' && Array.isArray(result.error.details?.candidates)) {
setDuplicateCandidates(result.error.details.candidates)
setIsPayDialogOpen(false)
} else {
toast({ title: t('payment_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
}
} else {
toast({
title: result.status === 'paid' ? t('paid_title') : t('partial_payment_title'),
// The paid amount is in the invoice's currency (the dialog's helper
// text says so): the toast must not relabel it as kr.
description: t('amount_registered_description', {
amount: formatCurrency(parseFloat(payAmount), invoice?.currency || 'SEK'),
}),
})
setIsPayDialogOpen(false)
setDuplicateCandidates(null)
await fetchInvoice()
}
} catch (err) {
toast({ title: t('payment_failed_title'), description: getErrorMessage(err, { context: 'supplier_invoice' }), variant: 'destructive' })
} finally {
setProcessingAction(null)
}
setIsProcessing(false)
}
async function handleCredit() {
@@ -385,34 +428,56 @@ export default function SupplierInvoiceDetailPage() {
variant: 'warning',
})
if (!ok) return
setIsProcessing(true)
const res = await fetch(`/api/supplier-invoices/${params.id}/credit`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: t('credit_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: t('credit_success_title') })
fetchInvoice()
setProcessingAction('credit')
try {
const res = await fetch(`/api/supplier-invoices/${params.id}/credit`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: t('credit_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: t('credit_success_title') })
await fetchInvoice()
}
} catch (err) {
toast({ title: t('credit_failed_title'), description: getErrorMessage(err, { context: 'supplier_invoice' }), variant: 'destructive' })
} finally {
setProcessingAction(null)
}
setIsProcessing(false)
}
async function handleDelete() {
const ok = await confirmAction({
// The DELETE runs as the confirm's action: the dialog holds open with its
// pending spinner until the server answers (it used to close on click and
// leave the destructive icon button active with no feedback until the
// route swap, permitting duplicate DELETEs).
await confirmAction({
title: t('delete_confirm_title'),
description: t('delete_confirm_description'),
confirmLabel: t('delete_confirm_label'),
variant: 'destructive',
}, async () => {
setProcessingAction('delete')
try {
const res = await fetch(`/api/supplier-invoices/${params.id}`, { method: 'DELETE' })
const result = await res.json()
if (!res.ok) {
toast({ title: t('delete_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: t('deleted_title') })
router.push('/supplier-invoices')
return
}
} catch (err) {
toast({
title: t('delete_failed_title'),
description: getErrorMessage(err, { context: 'supplier_invoice' }),
variant: 'destructive',
})
}
// Only cleared on failure: on success the pending state rides through
// the route swap instead of re-enabling the button mid-navigation.
setProcessingAction(null)
})
if (!ok) return
const res = await fetch(`/api/supplier-invoices/${params.id}`, { method: 'DELETE' })
const result = await res.json()
if (!res.ok) {
toast({ title: t('delete_failed_title'), description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: t('deleted_title') })
router.push('/supplier-invoices')
}
}
async function handleUncredit() {
@@ -423,23 +488,32 @@ export default function SupplierInvoiceDetailPage() {
variant: 'warning',
})
if (!ok) return
setIsProcessing(true)
const res = await fetch(`/api/supplier-invoices/${params.id}/uncredit`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
setProcessingAction('uncredit')
try {
const res = await fetch(`/api/supplier-invoices/${params.id}/uncredit`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({
title: t('uncredit_failed_title'),
description: getErrorMessage(result, { context: 'supplier_invoice' }),
variant: 'destructive',
})
} else {
toast({
title: t('uncredit_success_title'),
description: t('uncredit_success_description'),
})
await fetchInvoice()
}
} catch (err) {
toast({
title: t('uncredit_failed_title'),
description: getErrorMessage(result, { context: 'supplier_invoice' }),
description: getErrorMessage(err, { context: 'supplier_invoice' }),
variant: 'destructive',
})
} else {
toast({
title: t('uncredit_success_title'),
description: t('uncredit_success_description'),
})
fetchInvoice()
} finally {
setProcessingAction(null)
}
setIsProcessing(false)
}
if (isLoading) {
@@ -534,7 +608,13 @@ export default function SupplierInvoiceDetailPage() {
disabled={isProcessing || !canWrite}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
{canWrite ? <CheckCircle className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{processingAction === 'approve' ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : canWrite ? (
<CheckCircle className="mr-2 h-4 w-4" />
) : (
<Lock className="mr-2 h-4 w-4" />
)}
{t('approve')}
</Button>
)}
@@ -554,7 +634,13 @@ export default function SupplierInvoiceDetailPage() {
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
aria-label={t('delete_confirm_label')}
>
{canWrite ? <Trash2 className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
{processingAction === 'delete' ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : canWrite ? (
<Trash2 className="h-4 w-4" />
) : (
<Lock className="h-4 w-4" />
)}
</Button>
)}
{['approved', 'overdue', 'partially_paid'].includes(invoice.status) && (
@@ -574,7 +660,13 @@ export default function SupplierInvoiceDetailPage() {
disabled={isProcessing || !canWrite}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
{canWrite ? <FileText className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{processingAction === 'credit' ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : canWrite ? (
<FileText className="mr-2 h-4 w-4" />
) : (
<Lock className="mr-2 h-4 w-4" />
)}
{t('credit_note_button')}
</Button>
)}
@@ -587,7 +679,13 @@ export default function SupplierInvoiceDetailPage() {
disabled={isProcessing || !canWrite}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
{canWrite ? <Undo2 className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{processingAction === 'uncredit' ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : canWrite ? (
<Undo2 className="mr-2 h-4 w-4" />
) : (
<Lock className="mr-2 h-4 w-4" />
)}
{t('uncredit_button')}
</Button>
)}
@@ -908,7 +1006,13 @@ export default function SupplierInvoiceDetailPage() {
disabled={isProcessing || !canWrite}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
{canWrite ? <CheckCircle className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{processingAction === 'book' ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : canWrite ? (
<CheckCircle className="mr-2 h-4 w-4" />
) : (
<Lock className="mr-2 h-4 w-4" />
)}
{t('book_action')}
</Button>
</div>
File diff suppressed because it is too large Load Diff