Bug/skv konto numbers (#498)
* feat(skattekonto): add overdue transactions handling and split logic * feat: enhance transaction handling and loading states - Update BalanceHero component to display last synced date and additional information about Skatteverket updates. - Refactor BookDirectlyDialog to simplify transaction linking logic and improve UI for transaction selection. - Revamp InvoiceInboxWorkspace layout for better responsiveness and user experience, including improved skeleton loading states. - Introduce new loading states for ExtensionWorkspace to match the live layout and improve user feedback during data fetching. - Implement exchange rate fetching in QuickReviewDialog, ensuring transactions are always processed in SEK with error handling for rate fetching. - Add structured error handling for unavailable exchange rates in the transaction API. * feat(skattekonto): add 'Skattekonto – saldo & transaktioner' scope and update authorization checks * feat: implement reverse charge handling in supplier invoice calculations and UI
This commit is contained in:
@@ -178,7 +178,7 @@ export default function AccountCombobox({ value, accounts, onChange }: AccountCo
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="1930"
|
||||
placeholder="Sök konto…"
|
||||
className="font-mono h-8"
|
||||
autoComplete="off"
|
||||
/>
|
||||
|
||||
@@ -13,12 +13,17 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, Plus, Trash2, AlertTriangle, Search, Check } from 'lucide-react'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
|
||||
import { ActivateAccountsDialog } from '@/components/bookkeeping/ActivateAccountsDialog'
|
||||
import {
|
||||
useSubmitWithAccountActivation,
|
||||
throwOnStructuredError,
|
||||
} from '@/lib/hooks/use-submit-with-account-activation'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import type { BASAccount, FiscalPeriod, InvoiceExtractionResult } from '@/types'
|
||||
|
||||
interface InboxItem {
|
||||
@@ -139,8 +144,7 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
const [notes, setNotes] = useState<string>('')
|
||||
const [lines, setLines] = useState<FormLine[]>(() => buildPrefillLines(item))
|
||||
|
||||
// Transaction link state
|
||||
const [linkToTransaction, setLinkToTransaction] = useState<boolean>(!!item.matched_transaction_id)
|
||||
// Transaction picker — optional selection.
|
||||
const [selectedTransactionId, setSelectedTransactionId] = useState<string | null>(
|
||||
item.matched_transaction_id
|
||||
)
|
||||
@@ -155,7 +159,6 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
if (!open) return
|
||||
setEntryDate(item.extracted_data?.invoice?.invoiceDate || new Date().toISOString().slice(0, 10))
|
||||
setLines(buildPrefillLines(item))
|
||||
setLinkToTransaction(!!item.matched_transaction_id)
|
||||
setSelectedTransactionId(item.matched_transaction_id)
|
||||
const supplier = item.extracted_data?.supplier?.name?.trim() || ''
|
||||
const invoiceNum = item.extracted_data?.invoice?.invoiceNumber?.trim() || ''
|
||||
@@ -168,10 +171,10 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
// the prefilled amounts so foreign-currency invoices follow the SEK
|
||||
// figure on the actual bank movement.
|
||||
const selectedTransactionAmount = useMemo(() => {
|
||||
if (!linkToTransaction || !selectedTransactionId) return null
|
||||
if (!selectedTransactionId) return null
|
||||
const tx = transactions.find((t) => t.id === selectedTransactionId)
|
||||
return tx?.amount ?? null
|
||||
}, [linkToTransaction, selectedTransactionId, transactions])
|
||||
}, [selectedTransactionId, transactions])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
@@ -227,9 +230,10 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
}
|
||||
}, [entryDate, periods, periodId])
|
||||
|
||||
// Fetch unmatched transactions when the link toggle turns on
|
||||
// Fetch unmatched transactions whenever the dialog opens — the picker
|
||||
// is always visible now (selection is optional).
|
||||
useEffect(() => {
|
||||
if (!open || !linkToTransaction) return
|
||||
if (!open) return
|
||||
let cancelled = false
|
||||
setIsLoadingTransactions(true)
|
||||
const targetAmount = item.extracted_data?.totals?.total ?? null
|
||||
@@ -254,7 +258,7 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
}
|
||||
})()
|
||||
return () => { cancelled = true }
|
||||
}, [open, linkToTransaction, item.extracted_data?.totals?.total])
|
||||
}, [open, item.extracted_data?.totals?.total])
|
||||
|
||||
const filteredTransactions = useMemo(() => {
|
||||
const term = txSearch.trim().toLowerCase()
|
||||
@@ -294,45 +298,45 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
if (description.trim().length === 0) return 'Fyll i beskrivning'
|
||||
if (lines.some((l) => l.account_number.trim().length === 0)) return 'Alla rader behöver ett konto'
|
||||
if (!totals.balanced) return 'Debet och kredit måste vara lika'
|
||||
if (linkToTransaction && !selectedTransactionId) return 'Välj en banktransaktion att koppla till'
|
||||
return null
|
||||
}, [isSubmitting, entryDate, periodId, description, lines, totals.balanced, linkToTransaction, selectedTransactionId])
|
||||
}, [isSubmitting, entryDate, periodId, description, lines, totals.balanced])
|
||||
|
||||
const canSubmit = !isSubmitting && disabledReason === null
|
||||
|
||||
const postBooking = useCallback(async () => {
|
||||
const payload = {
|
||||
fiscal_period_id: periodId,
|
||||
entry_date: entryDate,
|
||||
description: description.trim(),
|
||||
notes: notes.trim() || undefined,
|
||||
lines: lines.map((l) => ({
|
||||
account_number: l.account_number.trim(),
|
||||
debit_amount: parseFloat(l.debit_amount) || 0,
|
||||
credit_amount: parseFloat(l.credit_amount) || 0,
|
||||
})),
|
||||
transaction_id: selectedTransactionId ?? undefined,
|
||||
}
|
||||
const res = await fetch(
|
||||
`/api/extensions/ext/invoice-inbox/items/${item.id}/book-direct`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
}
|
||||
)
|
||||
return (await throwOnStructuredError(res)) as {
|
||||
data?: { journal_entry?: { voucher_series: string; voucher_number: number } }
|
||||
}
|
||||
}, [periodId, entryDate, description, notes, lines, selectedTransactionId, item.id])
|
||||
|
||||
const { runSubmit, dialog: activationDialog, confirm: confirmActivation, cancel: cancelActivation } =
|
||||
useSubmitWithAccountActivation(postBooking)
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
if (!canSubmit) return
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const payload = {
|
||||
fiscal_period_id: periodId,
|
||||
entry_date: entryDate,
|
||||
description: description.trim(),
|
||||
notes: notes.trim() || undefined,
|
||||
lines: lines.map((l) => ({
|
||||
account_number: l.account_number.trim(),
|
||||
debit_amount: parseFloat(l.debit_amount) || 0,
|
||||
credit_amount: parseFloat(l.credit_amount) || 0,
|
||||
})),
|
||||
transaction_id: linkToTransaction ? selectedTransactionId ?? undefined : undefined,
|
||||
}
|
||||
const res = await fetch(
|
||||
`/api/extensions/ext/invoice-inbox/items/${item.id}/book-direct`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
}
|
||||
)
|
||||
const json = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: 'Kunde inte bokföra',
|
||||
description: json.error || 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
const json = await runSubmit()
|
||||
const voucher = json?.data?.journal_entry
|
||||
toast({
|
||||
title: 'Bokfört',
|
||||
@@ -342,13 +346,24 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
})
|
||||
await onSuccess()
|
||||
onOpenChange(false)
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.message === 'cancelled') {
|
||||
// User dismissed the activation dialog — no toast needed
|
||||
} else {
|
||||
const anyErr = err as { body?: unknown; status?: number }
|
||||
toast({
|
||||
title: 'Kunde inte bokföra',
|
||||
description: getErrorMessage(anyErr.body ?? err, {
|
||||
context: 'journal_entry',
|
||||
statusCode: anyErr.status,
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}, [
|
||||
canSubmit, periodId, entryDate, description, notes, lines,
|
||||
linkToTransaction, selectedTransactionId, item.id, toast, onSuccess, onOpenChange,
|
||||
])
|
||||
}, [canSubmit, runSubmit, toast, onSuccess, onOpenChange])
|
||||
|
||||
const targetAmount = item.extracted_data?.totals?.total ?? null
|
||||
const targetCurrency = item.extracted_data?.invoice?.currency ?? 'SEK'
|
||||
@@ -417,89 +432,90 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Transaction link toggle + picker */}
|
||||
{/* Transaction picker — always shown, selection is optional. */}
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="bd-link-tx" className="text-sm">
|
||||
Koppla till banktransaktion
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Slå på om dokumentet motsvarar en redan-bokad bankhändelse. Annars
|
||||
bokförs det som en fristående verifikation.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="bd-link-tx"
|
||||
checked={linkToTransaction}
|
||||
onCheckedChange={setLinkToTransaction}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-sm">Koppla till banktransaktion (valfritt)</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Välj en transaktion om dokumentet motsvarar en redan-bokad
|
||||
bankhändelse — den bokas då samtidigt. Lämna tom för en
|
||||
fristående verifikation.
|
||||
</p>
|
||||
</div>
|
||||
{linkToTransaction && (
|
||||
<div className="space-y-2 pt-2 border-t">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Sök på beskrivning…"
|
||||
value={txSearch}
|
||||
onChange={(e) => setTxSearch(e.target.value)}
|
||||
className="pl-10"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div className="max-h-56 overflow-y-auto rounded-md border">
|
||||
{isLoadingTransactions ? (
|
||||
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" /> Laddar…
|
||||
</div>
|
||||
) : filteredTransactions.length === 0 ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
Inga okategoriserade transaktioner.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y">
|
||||
{filteredTransactions.slice(0, 30).map((tx) => {
|
||||
const isSelected = selectedTransactionId === tx.id
|
||||
return (
|
||||
<li key={tx.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'w-full flex items-center justify-between gap-3 px-3 py-2.5 text-left text-sm transition-colors',
|
||||
isSelected
|
||||
? 'bg-primary/10 border-l-2 border-primary'
|
||||
: 'border-l-2 border-transparent hover:bg-accent/40'
|
||||
)}
|
||||
onClick={() => setSelectedTransactionId(tx.id)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<span className="shrink-0 w-4 flex items-center justify-center">
|
||||
{isSelected ? (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
) : null}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate">{tx.description}</p>
|
||||
<p className="text-xs text-muted-foreground tabular-nums">{tx.date}</p>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'tabular-nums text-sm shrink-0',
|
||||
tx.amount < 0 ? 'text-destructive' : 'text-foreground'
|
||||
)}
|
||||
>
|
||||
{formatCurrency(tx.amount, tx.currency || 'SEK')}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Sök på beskrivning…"
|
||||
value={txSearch}
|
||||
onChange={(e) => setTxSearch(e.target.value)}
|
||||
className="pl-10"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="max-h-56 overflow-y-auto rounded-md border">
|
||||
{isLoadingTransactions ? (
|
||||
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" /> Laddar…
|
||||
</div>
|
||||
) : filteredTransactions.length === 0 ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
Inga okategoriserade transaktioner.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y">
|
||||
{filteredTransactions.slice(0, 30).map((tx) => {
|
||||
const isSelected = selectedTransactionId === tx.id
|
||||
return (
|
||||
<li key={tx.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'w-full flex items-center justify-between gap-3 px-3 py-2.5 text-left text-sm transition-colors',
|
||||
isSelected
|
||||
? 'bg-primary/10 border-l-2 border-primary'
|
||||
: 'border-l-2 border-transparent hover:bg-accent/40'
|
||||
)}
|
||||
onClick={() =>
|
||||
setSelectedTransactionId(isSelected ? null : tx.id)
|
||||
}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<span className="shrink-0 w-4 flex items-center justify-center">
|
||||
{isSelected ? (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
) : null}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate">{tx.description}</p>
|
||||
<p className="text-xs text-muted-foreground tabular-nums">{tx.date}</p>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'tabular-nums text-sm shrink-0',
|
||||
tx.amount < 0 ? 'text-destructive' : 'text-foreground'
|
||||
)}
|
||||
>
|
||||
{formatCurrency(tx.amount, tx.currency || 'SEK')}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
{selectedTransactionId && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground hover:text-foreground underline"
|
||||
onClick={() => setSelectedTransactionId(null)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
Rensa val
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Journal entry lines */}
|
||||
@@ -685,6 +701,12 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
<ActivateAccountsDialog
|
||||
open={activationDialog.open}
|
||||
accountNumbers={activationDialog.accountNumbers}
|
||||
onConfirm={confirmActivation}
|
||||
onCancel={cancelActivation}
|
||||
/>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -61,33 +61,55 @@ function timeAgo(isoDate: string): string {
|
||||
return `${days} dag${days > 1 ? 'ar' : ''} sedan`
|
||||
}
|
||||
|
||||
// Mirrors the live layout (two cards: company info + financials) so the
|
||||
// transition from the route-level loading.tsx to data-loaded content has no
|
||||
// visible reflow. Keep in sync with app/(dashboard)/e/[sector]/[slug]/loading.tsx.
|
||||
function ProfileSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-6 w-16" />
|
||||
<Skeleton className="h-6 w-16" />
|
||||
<Skeleton className="h-6 w-16" />
|
||||
</div>
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<CardHeader className="space-y-2">
|
||||
<Skeleton className="h-5 w-48" />
|
||||
<Skeleton className="h-3.5 w-40" />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
<div className="flex items-start gap-2">
|
||||
<Skeleton className="h-3.5 w-3.5 mt-0.5 shrink-0" />
|
||||
<Skeleton className="h-3.5 flex-1 max-w-[260px]" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3.5 w-3.5 shrink-0" />
|
||||
<Skeleton className="h-3.5 w-48" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3.5 w-3.5 shrink-0" />
|
||||
<Skeleton className="h-3.5 w-36" />
|
||||
</div>
|
||||
<div className="pt-2 border-t space-y-1.5">
|
||||
<Skeleton className="h-3 w-24" />
|
||||
<Skeleton className="h-3 w-44" />
|
||||
</div>
|
||||
<div className="pt-2 border-t space-y-1.5">
|
||||
<Skeleton className="h-3 w-20" />
|
||||
<Skeleton className="h-3 w-full" />
|
||||
<Skeleton className="h-3 w-3/4" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-32 mt-2" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardHeader className="space-y-2">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-3.5 w-44" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-12 w-full" />
|
||||
<div key={i} className="space-y-1.5">
|
||||
<Skeleton className="h-3 w-20" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@@ -24,6 +24,7 @@ type Status =
|
||||
const SCOPE_LABELS: Record<string, string> = {
|
||||
momsdeklaration: 'Momsdeklaration',
|
||||
inkforetag: 'Företagsinformation',
|
||||
skahmst: 'Skattekonto – saldo & transaktioner',
|
||||
skattekonto: 'Skattekonto',
|
||||
agd: 'Arbetsgivardeklaration',
|
||||
}
|
||||
@@ -175,7 +176,7 @@ export function SkatteverketConnectPanel() {
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
{!scopes.includes('skattekonto') && (
|
||||
{!scopes.includes('skahmst') && !scopes.includes('skattekonto') && (
|
||||
<p className="mt-3 text-sm text-foreground">
|
||||
Behörigheten för Skattekonto saknas — koppla från och anslut igen
|
||||
för att aktivera saldo- och transaktionsvyn.
|
||||
|
||||
@@ -67,6 +67,12 @@ export default function QuickReviewDialog({
|
||||
const [showUploadZone, setShowUploadZone] = useState(false)
|
||||
const [showVatDropdown, setShowVatDropdown] = useState(false)
|
||||
const [isOpeningDoc, setIsOpeningDoc] = useState(false)
|
||||
// Mirror of `transaction` so we can patch in a freshly-fetched SEK conversion
|
||||
// before the user confirms — the verifikation must always be in SEK and the
|
||||
// engine reads these fields straight off the transaction row.
|
||||
const [enrichedTx, setEnrichedTx] = useState<TransactionWithInvoice | null>(transaction)
|
||||
const [rateLoading, setRateLoading] = useState(false)
|
||||
const [rateError, setRateError] = useState<string | null>(null)
|
||||
|
||||
const preAttachedDocumentId = transaction?.document_id ?? null
|
||||
|
||||
@@ -112,21 +118,74 @@ export default function QuickReviewDialog({
|
||||
fetchAccounts()
|
||||
}, [])
|
||||
|
||||
// Reset local mirror whenever the underlying transaction changes (the parent
|
||||
// reuses the dialog instance across rows).
|
||||
useEffect(() => {
|
||||
setEnrichedTx(transaction)
|
||||
setRateError(null)
|
||||
}, [transaction])
|
||||
|
||||
// Backfill the SEK conversion on demand. resolveSekAmount silently falls
|
||||
// back to the raw foreign amount when amount_sek/exchange_rate are null,
|
||||
// which means the user would see misleading "kr" values in the verifikation
|
||||
// and the engine would post the wrong number to the books.
|
||||
useEffect(() => {
|
||||
if (!open || !transaction) return
|
||||
const needsRate =
|
||||
!!transaction.currency &&
|
||||
transaction.currency !== 'SEK' &&
|
||||
(transaction.amount_sek == null || transaction.exchange_rate == null)
|
||||
if (!needsRate) return
|
||||
|
||||
let cancelled = false
|
||||
setRateLoading(true)
|
||||
setRateError(null)
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/transactions/${transaction.id}/refresh-exchange-rate`, {
|
||||
method: 'POST',
|
||||
})
|
||||
const json = await res.json()
|
||||
if (cancelled) return
|
||||
if (!res.ok) {
|
||||
setRateError(json?.error?.message || 'Kunde inte hämta växelkursen.')
|
||||
return
|
||||
}
|
||||
if (json?.data) {
|
||||
setEnrichedTx({ ...json.data, ...{
|
||||
potential_invoice: transaction.potential_invoice,
|
||||
potential_supplier_invoice: transaction.potential_supplier_invoice,
|
||||
} })
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setRateError('Kunde inte hämta växelkursen.')
|
||||
} finally {
|
||||
if (!cancelled) setRateLoading(false)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, transaction])
|
||||
|
||||
if (!transaction || !category) return null
|
||||
|
||||
const isIncome = transaction.amount > 0
|
||||
const tx = enrichedTx ?? transaction
|
||||
const isIncome = tx.amount > 0
|
||||
const isCounterpartyTemplate = !!(counterpartyLinePattern && counterpartyLinePattern.length > 0)
|
||||
const isTemplateBooking = !!templateId || isCounterpartyTemplate
|
||||
const isLiabilityAccount = accountOverride.startsWith('2')
|
||||
// For non-SEK transactions, the verifikation and the headline must show
|
||||
// the SEK-converted total — the mall/category booking always posts in SEK.
|
||||
const sekAmount = resolveSekAmount(
|
||||
transaction.amount,
|
||||
transaction.amount_sek,
|
||||
transaction.currency,
|
||||
transaction.exchange_rate
|
||||
tx.amount,
|
||||
tx.amount_sek,
|
||||
tx.currency,
|
||||
tx.exchange_rate
|
||||
)
|
||||
const isForeign = !!(transaction.currency && transaction.currency !== 'SEK')
|
||||
const isForeign = !!(tx.currency && tx.currency !== 'SEK')
|
||||
const sekConversionMissing = isForeign && (tx.amount_sek == null || tx.exchange_rate == null)
|
||||
|
||||
async function handleConfirm() {
|
||||
if (!category || !transaction) return
|
||||
@@ -202,23 +261,43 @@ export default function QuickReviewDialog({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm break-all">{transaction.description}</p>
|
||||
<p className="text-xs text-muted-foreground">{formatDate(transaction.date)}</p>
|
||||
<p className="font-medium text-sm break-all">{tx.description}</p>
|
||||
<p className="text-xs text-muted-foreground">{formatDate(tx.date)}</p>
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<p className={`font-medium text-sm tabular-nums ${isIncome ? 'text-success' : ''}`}>
|
||||
{isIncome ? '+' : ''}
|
||||
{formatCurrency(sekAmount, 'SEK')}
|
||||
</p>
|
||||
{isForeign && (
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{isForeign ? (
|
||||
<>
|
||||
<p className={`font-medium text-sm tabular-nums ${isIncome ? 'text-success' : ''}`}>
|
||||
{isIncome ? '+' : ''}
|
||||
{formatCurrency(tx.amount, tx.currency)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{rateLoading || sekConversionMissing
|
||||
? 'Hämtar växelkurs…'
|
||||
: `≈ ${isIncome ? '+' : ''}${formatCurrency(sekAmount, 'SEK')}`}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p className={`font-medium text-sm tabular-nums ${isIncome ? 'text-success' : ''}`}>
|
||||
{isIncome ? '+' : ''}
|
||||
{formatCurrency(transaction.amount, transaction.currency)}
|
||||
{formatCurrency(sekAmount, 'SEK')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isForeign && tx.exchange_rate != null && tx.exchange_rate_date && !sekConversionMissing && (
|
||||
<p className="text-xs text-muted-foreground -mt-1">
|
||||
Bokförs i SEK med Riksbankens kurs {formatCurrency(tx.exchange_rate, 'SEK')} per {tx.currency} ({formatDate(tx.exchange_rate_date)}).
|
||||
</p>
|
||||
)}
|
||||
|
||||
{rateError && (
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/[0.05] px-3 py-2">
|
||||
<p className="text-xs text-destructive leading-snug">{rateError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Template or Category */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-muted-foreground">
|
||||
@@ -275,23 +354,26 @@ export default function QuickReviewDialog({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Journal entry preview */}
|
||||
<JournalEntryPreview
|
||||
amount={transaction.amount}
|
||||
amountSek={sekAmount}
|
||||
{...(isCounterpartyTemplate
|
||||
? { linePattern: counterpartyLinePattern ?? undefined }
|
||||
: templateId && template
|
||||
? {
|
||||
templateDebitAccount: template.debit_account,
|
||||
templateCreditAccount: template.credit_account,
|
||||
templateVatRate: template.vat_rate,
|
||||
templateVatTreatment: template.vat_treatment,
|
||||
templateSupplierType: template.reverse_charge_supplier_type,
|
||||
}
|
||||
: { category, vatTreatment: isLiabilityAccount ? 'none' : vatTreatment, accountOverride, entityType }
|
||||
)}
|
||||
/>
|
||||
{/* Journal entry preview — hidden until we have a SEK conversion;
|
||||
otherwise we'd render a verifikation in the wrong currency. */}
|
||||
{!sekConversionMissing && !rateLoading && (
|
||||
<JournalEntryPreview
|
||||
amount={tx.amount}
|
||||
amountSek={sekAmount}
|
||||
{...(isCounterpartyTemplate
|
||||
? { linePattern: counterpartyLinePattern ?? undefined }
|
||||
: templateId && template
|
||||
? {
|
||||
templateDebitAccount: template.debit_account,
|
||||
templateCreditAccount: template.credit_account,
|
||||
templateVatRate: template.vat_rate,
|
||||
templateVatTreatment: template.vat_treatment,
|
||||
templateSupplierType: template.reverse_charge_supplier_type,
|
||||
}
|
||||
: { category, vatTreatment: isLiabilityAccount ? 'none' : vatTreatment, accountOverride, entityType }
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Account & VAT — hidden for template bookings (accounts defined by the template) */}
|
||||
{!isTemplateBooking && (
|
||||
@@ -410,10 +492,15 @@ export default function QuickReviewDialog({
|
||||
<Button
|
||||
className="flex-1"
|
||||
onClick={handleConfirm}
|
||||
disabled={isProcessing || (!isTemplateBooking && !accountOverride)}
|
||||
disabled={
|
||||
isProcessing ||
|
||||
(!isTemplateBooking && !accountOverride) ||
|
||||
rateLoading ||
|
||||
sekConversionMissing
|
||||
}
|
||||
>
|
||||
<Check className="mr-2 h-4 w-4" />
|
||||
{isProcessing ? 'Bokför...' : 'Bokför'}
|
||||
{isProcessing ? 'Bokför...' : rateLoading ? 'Hämtar växelkurs…' : 'Bokför'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
Reference in New Issue
Block a user