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:
@@ -0,0 +1,149 @@
|
||||
import { headers } from 'next/headers'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Card, CardHeader, CardContent } from '@/components/ui/card'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { getExtensionDefinition } from '@/lib/extensions/sectors'
|
||||
|
||||
// Mirror of FULLSCREEN_WORKSPACES in ExtensionWorkspaceLoader. loading.tsx
|
||||
// can't read route params, so we inspect the forwarded x-pathname header to
|
||||
// branch the skeleton shape — the parent dashboard loading.tsx renders a
|
||||
// metrics dashboard shape that has nothing to do with extension workspaces.
|
||||
const FULLSCREEN_WORKSPACES = new Set(['general/invoice-inbox'])
|
||||
|
||||
export default async function ExtensionWorkspaceLoading() {
|
||||
const h = await headers()
|
||||
const pathname = h.get('x-pathname') ?? ''
|
||||
const match = pathname.match(/^\/e\/([^/]+)\/([^/]+)/)
|
||||
const sector = match?.[1] ?? ''
|
||||
const slug = match?.[2] ?? ''
|
||||
const key = `${sector}/${slug}`
|
||||
|
||||
if (FULLSCREEN_WORKSPACES.has(key)) {
|
||||
return <FullScreenWorkspaceSkeleton />
|
||||
}
|
||||
|
||||
const definition = sector && slug ? getExtensionDefinition(sector, slug) : undefined
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10 space-y-8">
|
||||
{definition ? (
|
||||
<PageHeader title={definition.name} />
|
||||
) : (
|
||||
<Skeleton className="h-9 md:h-10 w-64" />
|
||||
)}
|
||||
<ShellWorkspaceBody workspaceKey={key} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ShellWorkspaceBody({ workspaceKey }: { workspaceKey: string }) {
|
||||
if (workspaceKey === 'general/tic') {
|
||||
return <TicSkeleton />
|
||||
}
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-32 w-full rounded-lg" />
|
||||
<Skeleton className="h-64 w-full rounded-lg" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TicSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader className="space-y-2">
|
||||
<Skeleton className="h-5 w-48" />
|
||||
<Skeleton className="h-3.5 w-40" />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<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 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) => (
|
||||
<div key={i} className="space-y-1.5">
|
||||
<Skeleton className="h-3 w-20" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FullScreenWorkspaceSkeleton() {
|
||||
return (
|
||||
<div className="h-[calc(100vh-1px)] p-4 md:p-6">
|
||||
<div className="h-full flex flex-col rounded-lg border bg-card overflow-hidden">
|
||||
<header className="flex items-center justify-between gap-4 border-b px-4 py-2.5">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Skeleton className="h-4 w-4 shrink-0" />
|
||||
<Skeleton className="h-4 w-32 shrink-0" />
|
||||
<Skeleton className="hidden md:block h-3 w-56" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-28 shrink-0" />
|
||||
</header>
|
||||
<div className="flex-1 grid grid-cols-1 md:grid-cols-[240px_minmax(0,1fr)_320px] lg:grid-cols-[280px_minmax(0,1fr)_340px] min-h-0">
|
||||
<aside className="border-r overflow-hidden bg-muted/20 pt-3">
|
||||
<div className="px-3 pb-3 space-y-2 border-b">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Skeleton className="h-5 w-10 rounded-full" />
|
||||
<Skeleton className="h-5 w-24 rounded-full" />
|
||||
<Skeleton className="h-5 w-20 rounded-full" />
|
||||
<Skeleton className="h-5 w-8 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
<ul>
|
||||
{Array.from({ length: 7 }).map((_, i) => (
|
||||
<li key={i} className="border-b px-3 py-2 flex flex-col gap-1.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 shrink-0" />
|
||||
<Skeleton className="h-3.5 flex-1 max-w-[180px]" />
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Skeleton className="h-3 w-16" />
|
||||
<Skeleton className="h-3 w-12" />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</aside>
|
||||
<main className="overflow-hidden bg-muted/10 hidden md:block" />
|
||||
<aside className="border-l overflow-hidden hidden md:block" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -40,6 +40,7 @@ interface SaldoEnvelope {
|
||||
interface TransaktionerEnvelope {
|
||||
data: {
|
||||
booked: SkattekontoTransactionWithSuggestion[]
|
||||
overdue: StoredSkattekontoTransaction[]
|
||||
upcoming: StoredSkattekontoTransaction[]
|
||||
}
|
||||
}
|
||||
@@ -267,6 +268,9 @@ export default function SkattekontoPage() {
|
||||
<TabsTrigger value="booked">
|
||||
Genomförda {tx?.booked ? `(${tx.booked.length})` : ''}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="overdue">
|
||||
Förfallna {tx?.overdue ? `(${tx.overdue.length})` : ''}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="upcoming">
|
||||
Kommande {tx?.upcoming ? `(${tx.upcoming.length})` : ''}
|
||||
</TabsTrigger>
|
||||
@@ -280,6 +284,16 @@ export default function SkattekontoPage() {
|
||||
emptyText="Inga genomförda transaktioner än."
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="overdue" className="mt-4">
|
||||
<TransactionTable
|
||||
rows={tx?.overdue ?? []}
|
||||
onBokfor={bokfor}
|
||||
onMatch={openMatch}
|
||||
bookingId={bookingId}
|
||||
emptyText="Inga förfallna transaktioner."
|
||||
showForfallodatum
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="upcoming" className="mt-4">
|
||||
<TransactionTable
|
||||
rows={tx?.upcoming ?? []}
|
||||
@@ -420,7 +434,7 @@ function BalanceHero({
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wide text-muted-foreground">
|
||||
Senast uppdaterad
|
||||
Saldo per
|
||||
</p>
|
||||
<p className="font-medium tabular-nums">
|
||||
{new Date(data.senastUppdaterad).toLocaleString('sv-SE')}
|
||||
@@ -428,6 +442,17 @@ function BalanceHero({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{saldo.lastSyncedAt && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Senast synkad{' '}
|
||||
<span className="tabular-nums">
|
||||
{new Date(saldo.lastSyncedAt).toLocaleString('sv-SE')}
|
||||
</span>
|
||||
. Skatteverket uppdaterar saldot periodvis — datumet ovan ändras
|
||||
inte varje gång du synkroniserar.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{data.informationstext.length > 0 && (
|
||||
<div className="rounded-md border bg-muted/30 p-3">
|
||||
<p className="mb-1 text-xs font-medium uppercase tracking-wide">
|
||||
|
||||
@@ -168,6 +168,7 @@ export default function NewSupplierInvoicePage() {
|
||||
const watchedSupplierId = watch('supplier_id')
|
||||
const watchedCurrency = watch('currency')
|
||||
const watchedPaidPrivately = watch('paid_with_private_funds')
|
||||
const watchedReverseCharge = watch('reverse_charge')
|
||||
|
||||
const isEF = entityType === 'enskild_firma'
|
||||
|
||||
@@ -401,7 +402,11 @@ export default function NewSupplierInvoicePage() {
|
||||
})
|
||||
const subtotal = itemTotals.reduce((sum, t) => sum + t.lineTotal, 0)
|
||||
const totalVat = itemTotals.reduce((sum, t) => sum + t.vatAmount, 0)
|
||||
const total = Math.round((subtotal + totalVat) * 100) / 100
|
||||
// Reverse charge: supplier never invoices VAT, so it doesn't roll into the
|
||||
// payable total. The VAT is still accounted for via 2614 / 2645 in
|
||||
// bookkeeping — the line stays in the breakdown for transparency.
|
||||
const payableVat = watchedReverseCharge ? 0 : totalVat
|
||||
const total = Math.round((subtotal + payableVat) * 100) / 100
|
||||
|
||||
// Show the AI-suggested supplier card when we have an inbox item, the AI
|
||||
// surfaced a supplier name, and we couldn't match it to an existing record.
|
||||
@@ -1251,7 +1256,9 @@ export default function NewSupplierInvoicePage() {
|
||||
<span className="font-mono sm:w-32 text-right">{formatCurrency(subtotal, watchedCurrency)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between sm:justify-end sm:gap-8">
|
||||
<span className="text-muted-foreground">Moms</span>
|
||||
<span className="text-muted-foreground">
|
||||
{watchedReverseCharge ? 'Moms (omvänd, redovisas av köparen)' : 'Moms'}
|
||||
</span>
|
||||
<span className="font-mono sm:w-32 text-right">{formatCurrency(totalVat, watchedCurrency)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between sm:justify-end sm:gap-8 font-bold text-lg">
|
||||
|
||||
@@ -132,7 +132,11 @@ export const POST = withRouteContext(
|
||||
|
||||
const subtotal = items.reduce((sum, i) => sum + i.line_total, 0)
|
||||
const vatAmount = items.reduce((sum, i) => sum + i.vat_amount, 0)
|
||||
const total = Math.round((subtotal + vatAmount) * 100) / 100
|
||||
// Reverse charge: supplier never invoices VAT, so the payable total equals
|
||||
// the net. VAT is still tracked separately (vat_amount) for declarations
|
||||
// and books fiktiv 2614/2645 in the engine, but neither side moves cash.
|
||||
const payableVat = body.reverse_charge ? 0 : vatAmount
|
||||
const total = Math.round((subtotal + payableVat) * 100) / 100
|
||||
|
||||
// Representation (BAS 6070–6079): ingående moms is only deductible up to
|
||||
// 300 SEK base/person per ML 8 kap. 1 §, and the income-tax deduction was
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
|
||||
import type { Currency, Transaction } from '@/types'
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'transaction.refreshExchangeRate',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const { data: transaction, error: fetchError } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single<Transaction>()
|
||||
|
||||
if (fetchError || !transaction) {
|
||||
return errorResponseFromCode('TX_CATEGORIZE_TX_NOT_FOUND', log, { requestId })
|
||||
}
|
||||
|
||||
// No-op for SEK transactions, or when the rate is already cached.
|
||||
if (
|
||||
transaction.currency === 'SEK' ||
|
||||
(transaction.amount_sek != null && transaction.exchange_rate != null)
|
||||
) {
|
||||
return NextResponse.json({ data: transaction })
|
||||
}
|
||||
|
||||
const rate = await fetchExchangeRate(transaction.currency as Currency, new Date(transaction.date))
|
||||
if (!rate) {
|
||||
return errorResponseFromCode('TX_EXCHANGE_RATE_UNAVAILABLE', log, {
|
||||
requestId,
|
||||
details: { currency: transaction.currency, date: transaction.date },
|
||||
})
|
||||
}
|
||||
|
||||
const amountSek = Math.round(transaction.amount * rate.rate * 100) / 100
|
||||
|
||||
const { data: updated, error: updateError } = await supabase
|
||||
.from('transactions')
|
||||
.update({
|
||||
amount_sek: amountSek,
|
||||
exchange_rate: rate.rate,
|
||||
exchange_rate_date: rate.date,
|
||||
})
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.is('journal_entry_id', null)
|
||||
.select('*')
|
||||
.single<Transaction>()
|
||||
|
||||
if (updateError || !updated) {
|
||||
return errorResponse(updateError ?? new Error('Failed to persist exchange rate'), log, {
|
||||
requestId,
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: updated })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { ToastAction } from '@/components/ui/toast'
|
||||
import {
|
||||
Inbox,
|
||||
Upload,
|
||||
@@ -27,17 +26,9 @@ import {
|
||||
X,
|
||||
} from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||
import type { InvoiceExtractionResult } from '@/types'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog'
|
||||
import BookDirectlyDialog from '@/components/extensions/general/BookDirectlyDialog'
|
||||
|
||||
type AccountingMethod = 'accrual' | 'cash'
|
||||
@@ -98,15 +89,51 @@ function pickSupplierName(item: InboxItem): string | null {
|
||||
}
|
||||
|
||||
// ── Skeleton ─────────────────────────────────────────────────
|
||||
// Mirrors the live layout (top bar + 3-pane card) 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 WorkspaceSkeleton() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<div className="grid grid-cols-[280px_minmax(0,1fr)_320px] gap-4 h-[calc(100vh-12rem)]">
|
||||
<Skeleton className="h-full" />
|
||||
<Skeleton className="h-full" />
|
||||
<Skeleton className="h-full" />
|
||||
<div className="h-[calc(100vh-1px)] p-4 md:p-6">
|
||||
<div className="h-full flex flex-col rounded-lg border bg-card overflow-hidden">
|
||||
<header className="flex items-center justify-between gap-4 border-b px-4 py-2.5">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Skeleton className="h-4 w-4 shrink-0" />
|
||||
<Skeleton className="h-4 w-32 shrink-0" />
|
||||
<Skeleton className="hidden md:block h-3 w-56" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-28 shrink-0" />
|
||||
</header>
|
||||
<div className="flex-1 grid grid-cols-1 md:grid-cols-[240px_minmax(0,1fr)_320px] lg:grid-cols-[280px_minmax(0,1fr)_340px] min-h-0">
|
||||
<aside className="border-r overflow-hidden bg-muted/20 pt-3">
|
||||
<div className="px-3 pb-3 space-y-2 border-b">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Skeleton className="h-5 w-10 rounded-full" />
|
||||
<Skeleton className="h-5 w-24 rounded-full" />
|
||||
<Skeleton className="h-5 w-20 rounded-full" />
|
||||
<Skeleton className="h-5 w-8 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
<ul>
|
||||
{Array.from({ length: 7 }).map((_, i) => (
|
||||
<li key={i} className="border-b px-3 py-2 flex flex-col gap-1.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 shrink-0" />
|
||||
<Skeleton className="h-3.5 flex-1 max-w-[180px]" />
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Skeleton className="h-3 w-16" />
|
||||
<Skeleton className="h-3 w-12" />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</aside>
|
||||
<main className="overflow-hidden bg-muted/10 hidden md:block" />
|
||||
<aside className="border-l overflow-hidden hidden md:block" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -116,16 +143,11 @@ function WorkspaceSkeleton() {
|
||||
|
||||
export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
const { toast } = useToast()
|
||||
const router = useRouter()
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
|
||||
const [items, setItems] = useState<InboxItem[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
// Phone-only master-detail toggle. On screens <md the three panes don't
|
||||
// fit side-by-side and stacking them produces a long vertical scroll, so
|
||||
// we show the list xor the detail view, with a back button to return.
|
||||
const [mobileView, setMobileView] = useState<'list' | 'detail'>('list')
|
||||
// List filter + search (client-side over the already-fetched items list).
|
||||
const [filter, setFilter] = useState<'all' | 'needs_action' | 'done' | 'error'>('all')
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -150,7 +172,6 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [isRotating, setIsRotating] = useState(false)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [attachOpen, setAttachOpen] = useState(false)
|
||||
const [bookDirectOpen, setBookDirectOpen] = useState(false)
|
||||
// Cash method users see "Bokför direkt" as the primary CTA; accrual users
|
||||
// see "Skapa leverantörsfaktura". Defaults to 'accrual' until we've read
|
||||
@@ -272,7 +293,10 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
setSelected(null)
|
||||
setDocUrl(null)
|
||||
setDocMime(null)
|
||||
setMobileView('detail')
|
||||
// Intentionally no auto-scroll: in the vertical-stack layout (below xl)
|
||||
// scrolling the preview into view pushes the list off-screen, and the
|
||||
// user has no obvious way back to pick another item. The row-highlight
|
||||
// + the preview content update are enough feedback that the tap took.
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/extensions/ext/invoice-inbox/items/${id}`)
|
||||
@@ -523,7 +547,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="h-[calc(100vh-1px)] p-4 md:p-6"
|
||||
className="min-h-[calc(100vh-1px)] xl:h-[calc(100vh-1px)] p-4 md:p-6"
|
||||
onDragOver={(e) => { e.preventDefault(); if (!isDragging) setIsDragging(true) }}
|
||||
onDragLeave={(e) => {
|
||||
// only clear when leaving the workspace itself, not children
|
||||
@@ -531,7 +555,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
}}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<div className="h-full flex flex-col rounded-lg border bg-card overflow-hidden shadow-sm">
|
||||
<div className="xl:h-full flex flex-col rounded-lg border bg-card xl:overflow-hidden shadow-sm">
|
||||
{/* Top bar */}
|
||||
<header className="flex items-center justify-between gap-4 border-b px-4 py-2.5 flex-wrap">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
@@ -611,16 +635,14 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Three-pane body. On phone (<md) we toggle between list and detail
|
||||
via `mobileView`; at md+ all three panes show side-by-side. */}
|
||||
<div className="flex-1 grid grid-cols-1 md:grid-cols-[240px_minmax(0,1fr)_320px] lg:grid-cols-[280px_minmax(0,1fr)_340px] min-h-0">
|
||||
{/* List */}
|
||||
<aside
|
||||
className={cn(
|
||||
'border-r overflow-y-auto bg-muted/20 pt-3 md:block',
|
||||
mobileView === 'detail' && 'hidden'
|
||||
)}
|
||||
>
|
||||
{/* Three-section body. Below xl (iPad portrait/landscape + phone) the
|
||||
sections stack vertically as a single scrollable feed. With the app
|
||||
sidebar eating ~256px, even iPad landscape (1024–1180px viewport)
|
||||
has only ~570px of workspace — too tight for 3 panes. At xl+ they
|
||||
sit side-by-side as three panes. */}
|
||||
<div className="xl:flex-1 grid grid-cols-1 xl:grid-cols-[280px_minmax(0,1fr)_340px] xl:min-h-0 xl:overflow-hidden">
|
||||
{/* List — flows naturally below xl; bounded with internal scroll at xl+ */}
|
||||
<aside className="border-b xl:border-b-0 xl:border-r bg-muted/20 pt-3 xl:overflow-y-auto xl:block">
|
||||
{items.length > 0 && (
|
||||
<div className="px-3 pb-3 space-y-2 border-b">
|
||||
<div className="relative">
|
||||
@@ -697,7 +719,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
// compact card on mobile only, quiet empty state on desktop.
|
||||
showOnboarding ? (
|
||||
<>
|
||||
<div className="md:hidden">
|
||||
<div className="xl:hidden">
|
||||
<OnboardingCard
|
||||
hasInboxAddress={hasInboxAddress}
|
||||
hasAnyItem={hasAnyItem}
|
||||
@@ -709,7 +731,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
<div className="hidden md:block p-6 text-center text-sm text-muted-foreground">
|
||||
<div className="hidden xl:block p-6 text-center text-sm text-muted-foreground">
|
||||
<Inbox className="h-6 w-6 mx-auto mb-2 opacity-50" />
|
||||
Inkorgen är tom.
|
||||
</div>
|
||||
@@ -743,22 +765,8 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
|
||||
{/* Document preview (hero) */}
|
||||
<main
|
||||
className={cn(
|
||||
'overflow-hidden bg-muted/10 relative md:block',
|
||||
mobileView === 'list' && 'hidden'
|
||||
)}
|
||||
className="xl:overflow-hidden bg-muted/10 relative xl:block min-h-[55vh] xl:min-h-0"
|
||||
>
|
||||
{/* Phone-only back-to-list button */}
|
||||
{selected && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMobileView('list')}
|
||||
className="md:hidden absolute top-2 left-2 z-10 flex items-center gap-1 rounded-md bg-background/90 backdrop-blur px-2 py-1 text-xs text-foreground border shadow-sm"
|
||||
>
|
||||
<ArrowRight className="h-3 w-3 rotate-180" />
|
||||
Inkorg
|
||||
</button>
|
||||
)}
|
||||
{selected ? (
|
||||
<DocumentPreview docUrl={docUrl} docMime={docMime} isProcessing={!!selected.isPlaceholder} />
|
||||
) : showOnboarding ? (
|
||||
@@ -787,20 +795,17 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
)}
|
||||
</main>
|
||||
|
||||
{/* Fields rail. On phone, sits below the preview (same screen as detail);
|
||||
on md+ it's the third pane. */}
|
||||
{/* Fields rail. Below xl it stacks below the preview as part of the
|
||||
single vertical feed (top border for separation). At xl+ it's the
|
||||
third pane with a left border. */}
|
||||
<aside
|
||||
className={cn(
|
||||
'border-l overflow-y-auto pt-4 md:block',
|
||||
mobileView === 'list' && 'hidden'
|
||||
)}
|
||||
className="border-t xl:border-t-0 xl:border-l xl:overflow-y-auto pt-4 xl:block pb-4"
|
||||
>
|
||||
{selected ? (
|
||||
<FieldsRail
|
||||
item={selected}
|
||||
accountingMethod={accountingMethod}
|
||||
onDelete={() => handleDelete(selected.id)}
|
||||
onAttach={() => setAttachOpen(true)}
|
||||
onBookDirect={() => setBookDirectOpen(true)}
|
||||
isDeleting={isDeleting}
|
||||
onRetryRequested={async () => {
|
||||
@@ -832,29 +837,6 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selected && (
|
||||
<AttachToTransactionDialog
|
||||
open={attachOpen}
|
||||
onOpenChange={setAttachOpen}
|
||||
item={selected}
|
||||
onAttached={async (transactionId) => {
|
||||
setAttachOpen(false)
|
||||
await fetchItems()
|
||||
toast({
|
||||
title: 'Bilaga kopplad till transaktion',
|
||||
description: 'Bokför direkt, eller fortsätt med inkorgen och bokför senare.',
|
||||
action: (
|
||||
<ToastAction
|
||||
altText="Bokför nu"
|
||||
onClick={() => router.push(`/transactions?highlight=${transactionId}`)}
|
||||
>
|
||||
Bokför nu
|
||||
</ToastAction>
|
||||
),
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{selected && (
|
||||
<BookDirectlyDialog
|
||||
open={bookDirectOpen}
|
||||
@@ -869,342 +851,6 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
)
|
||||
}
|
||||
|
||||
// ── Attach-to-transaction dialog ─────────────────────────────
|
||||
|
||||
interface PickerTransaction {
|
||||
id: string
|
||||
date: string
|
||||
description: string
|
||||
amount: number
|
||||
currency: string
|
||||
}
|
||||
|
||||
function AttachToTransactionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
item,
|
||||
onAttached,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (v: boolean) => void
|
||||
item: InboxItem
|
||||
onAttached: (transactionId: string) => void | Promise<void>
|
||||
}) {
|
||||
const { toast } = useToast()
|
||||
const [transactions, setTransactions] = useState<PickerTransaction[]>([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [attachingId, setAttachingId] = useState<string | null>(null)
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
|
||||
const targetAmount = pickAmount(item)
|
||||
const targetCurrency = pickCurrency(item)
|
||||
|
||||
// Prefill for "create transaction from this document" — defaults to a
|
||||
// negative amount because the typical inbox item is an expense receipt
|
||||
// (money out). The user can flip the sign in the form if it's an income
|
||||
// document.
|
||||
const defaultDate =
|
||||
item.extracted_data?.invoice?.invoiceDate ||
|
||||
new Date().toISOString().slice(0, 10)
|
||||
const defaultAmount = targetAmount != null ? -Math.abs(targetAmount) : 0
|
||||
const defaultDescription = [
|
||||
pickSupplierName(item),
|
||||
item.extracted_data?.invoice?.invoiceNumber,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ') || 'Manuell transaktion'
|
||||
|
||||
const [formDate, setFormDate] = useState(defaultDate)
|
||||
const [formAmount, setFormAmount] = useState<string>(
|
||||
defaultAmount !== 0 ? String(defaultAmount) : ''
|
||||
)
|
||||
const [formDescription, setFormDescription] = useState(defaultDescription)
|
||||
|
||||
useEffect(() => {
|
||||
setFormDate(defaultDate)
|
||||
setFormAmount(defaultAmount !== 0 ? String(defaultAmount) : '')
|
||||
setFormDescription(defaultDescription)
|
||||
setSearchTerm('')
|
||||
// Reset whenever a different inbox item opens the dialog.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [item.id])
|
||||
|
||||
const filteredTransactions = useMemo(() => {
|
||||
const term = searchTerm.trim().toLowerCase()
|
||||
if (term === '') return transactions
|
||||
return transactions.filter((t) => (t.description || '').toLowerCase().includes(term))
|
||||
}, [transactions, searchTerm])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
let cancelled = false
|
||||
setIsLoading(true)
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/transactions?unmatched=true')
|
||||
const json = await res.json()
|
||||
if (cancelled) return
|
||||
const rows: PickerTransaction[] = (Array.isArray(json.data) ? json.data : [])
|
||||
.map((t: PickerTransaction) => ({
|
||||
id: t.id,
|
||||
date: t.date,
|
||||
description: t.description,
|
||||
amount: t.amount,
|
||||
currency: t.currency || 'SEK',
|
||||
}))
|
||||
setTransactions(rankByAmount(rows, targetAmount, targetCurrency))
|
||||
} catch (err) {
|
||||
console.error('[invoice-inbox/attach] fetch failed:', err)
|
||||
toast({ title: 'Kunde inte ladda transaktioner', variant: 'destructive' })
|
||||
} finally {
|
||||
if (!cancelled) setIsLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => { cancelled = true }
|
||||
}, [open, targetAmount, targetCurrency, toast])
|
||||
|
||||
const handleAttach = async (tx: PickerTransaction) => {
|
||||
if (!item.document_id) return
|
||||
setAttachingId(tx.id)
|
||||
try {
|
||||
const res = await fetch(`/api/transactions/${tx.id}/attach-document`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ document_id: item.document_id }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const json = await res.json().catch(() => ({}))
|
||||
toast({ title: json.error || 'Kunde inte koppla bilaga', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
await onAttached(tx.id)
|
||||
} finally {
|
||||
setAttachingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateTransaction = async () => {
|
||||
const amountNum = Number(formAmount)
|
||||
if (!Number.isFinite(amountNum) || amountNum === 0) {
|
||||
toast({ title: 'Ange ett belopp skilt från noll', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
if (!formDate || !formDescription.trim()) {
|
||||
toast({ title: 'Fyll i datum och beskrivning', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
setIsCreating(true)
|
||||
try {
|
||||
const res = await fetch('/api/transactions/create-from-document', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
inbox_item_id: item.id,
|
||||
amount: amountNum,
|
||||
transaction_date: formDate,
|
||||
description: formDescription.trim(),
|
||||
}),
|
||||
})
|
||||
const json = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: json.error || 'Kunde inte skapa transaktion',
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
const newTxId = json?.data?.transaction_id as string | undefined
|
||||
if (newTxId) {
|
||||
await onAttached(newTxId)
|
||||
} else {
|
||||
// No id back — fall back to closing without the "Bokför nu" CTA.
|
||||
toast({
|
||||
title: 'Transaktion skapad',
|
||||
description: 'Hittas under Transaktioner för kategorisering.',
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
setIsCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Koppla bilaga till transaktion</DialogTitle>
|
||||
<DialogDescription>
|
||||
{targetAmount != null
|
||||
? `Belopp på fakturan: ${formatCurrency(targetAmount, pickCurrency(item))}. Listan är sorterad efter beloppsmatch.`
|
||||
: 'Välj en transaktion att koppla bilagan till.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{!isLoading && transactions.length > 0 && (
|
||||
<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
|
||||
autoFocus
|
||||
placeholder="Sök på beskrivning…"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="max-h-[60vh] overflow-y-auto -mx-6 px-6">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-12 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" /> Laddar transaktioner…
|
||||
</div>
|
||||
) : transactions.length === 0 ? (
|
||||
<div className="py-10">
|
||||
<div className="text-center space-y-1.5 mb-6">
|
||||
<p className="text-sm font-medium">Hittade ingen transaktion</p>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mx-auto">
|
||||
Skapa en manuell transaktion från underlaget och kategorisera
|
||||
den i transaktionsvyn efter att den är skapad.
|
||||
</p>
|
||||
</div>
|
||||
<div className="max-w-sm mx-auto space-y-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1">
|
||||
<label
|
||||
htmlFor="manual-tx-date"
|
||||
className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground"
|
||||
>
|
||||
Datum
|
||||
</label>
|
||||
<Input
|
||||
id="manual-tx-date"
|
||||
type="date"
|
||||
value={formDate}
|
||||
onChange={(e) => setFormDate(e.target.value)}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<label
|
||||
htmlFor="manual-tx-amount"
|
||||
className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground"
|
||||
>
|
||||
Belopp
|
||||
</label>
|
||||
<Input
|
||||
id="manual-tx-amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
inputMode="decimal"
|
||||
value={formAmount}
|
||||
onChange={(e) => setFormAmount(e.target.value)}
|
||||
placeholder="-0.00"
|
||||
className="tabular-nums"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<label
|
||||
htmlFor="manual-tx-description"
|
||||
className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground"
|
||||
>
|
||||
Beskrivning
|
||||
</label>
|
||||
<Input
|
||||
id="manual-tx-description"
|
||||
type="text"
|
||||
value={formDescription}
|
||||
onChange={(e) => setFormDescription(e.target.value)}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Negativt belopp för utgift, positivt för inkomst.
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
className="w-full"
|
||||
onClick={handleCreateTransaction}
|
||||
disabled={isCreating}
|
||||
>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-3.5 w-3.5 mr-2 animate-spin" />
|
||||
Skapar transaktion…
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="h-3.5 w-3.5 mr-2" />
|
||||
Skapa transaktion från underlag
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : filteredTransactions.length === 0 ? (
|
||||
<p className="py-12 text-center text-sm text-muted-foreground">
|
||||
Inga transaktioner matchar “{searchTerm}”.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y">
|
||||
{filteredTransactions.map((tx) => (
|
||||
<li key={tx.id}>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full flex items-center justify-between gap-4 px-1 py-3 text-left hover:bg-accent/40 disabled:opacity-50"
|
||||
onClick={() => handleAttach(tx)}
|
||||
disabled={attachingId !== null}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium truncate">{tx.description}</p>
|
||||
<p className="text-xs text-muted-foreground">{tx.date}</p>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'text-sm tabular-nums whitespace-nowrap',
|
||||
targetAmount != null
|
||||
&& tx.currency === targetCurrency
|
||||
&& Math.abs(Math.abs(tx.amount) - Math.abs(targetAmount)) < 0.01
|
||||
? 'font-semibold'
|
||||
: '',
|
||||
)}
|
||||
>
|
||||
{formatCurrency(tx.amount, tx.currency)}
|
||||
</span>
|
||||
{attachingId === tx.id && <Loader2 className="h-3.5 w-3.5 animate-spin shrink-0" />}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function rankByAmount(
|
||||
rows: PickerTransaction[],
|
||||
target: number | null,
|
||||
targetCurrency: string,
|
||||
): PickerTransaction[] {
|
||||
if (target == null) return rows
|
||||
const t = Math.abs(target)
|
||||
// Same-currency rows rank by amount distance. Cross-currency rows go to
|
||||
// the bottom — comparing a EUR invoice's amount to a SEK transaction's
|
||||
// amount numerically would be misleading and could cause a wrong attachment
|
||||
// (which then becomes verifikation underlag, BFL 5 kap 6 §). The user can
|
||||
// still manually pick a cross-currency match by scrolling down.
|
||||
return [...rows].sort((a, b) => {
|
||||
const aMatch = a.currency === targetCurrency
|
||||
const bMatch = b.currency === targetCurrency
|
||||
if (aMatch !== bMatch) return aMatch ? -1 : 1
|
||||
if (!aMatch) return 0
|
||||
const da = Math.abs(Math.abs(a.amount) - t)
|
||||
const db = Math.abs(Math.abs(b.amount) - t)
|
||||
return da - db
|
||||
})
|
||||
}
|
||||
|
||||
// ── List row ─────────────────────────────────────────────────
|
||||
|
||||
@@ -1593,7 +1239,6 @@ function FieldsRail({
|
||||
item,
|
||||
accountingMethod,
|
||||
onDelete,
|
||||
onAttach,
|
||||
onBookDirect,
|
||||
isDeleting,
|
||||
onFieldsUpdated,
|
||||
@@ -1602,7 +1247,6 @@ function FieldsRail({
|
||||
item: InboxItem
|
||||
accountingMethod: AccountingMethod
|
||||
onDelete: () => void
|
||||
onAttach: () => void
|
||||
onBookDirect: () => void
|
||||
isDeleting: boolean
|
||||
onFieldsUpdated: (data: InvoiceExtractionResult) => void
|
||||
@@ -1850,43 +1494,21 @@ function FieldsRail({
|
||||
>
|
||||
Bokför direkt
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={onAttach}
|
||||
disabled={!item.document_id}
|
||||
title={!item.document_id ? 'Ingen bilaga att koppla' : undefined}
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 mr-1.5" />
|
||||
Koppla till transaktion
|
||||
</Button>
|
||||
<Link href={`/supplier-invoices/new?inbox_item_id=${item.id}`} className="block">
|
||||
<Button variant="ghost" size="sm" className="w-full">
|
||||
<Button variant="outline" size="sm" className="w-full">
|
||||
Skapa leverantörsfaktura
|
||||
</Button>
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={onAttach}
|
||||
disabled={!item.document_id}
|
||||
title={!item.document_id ? 'Ingen bilaga att koppla' : undefined}
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 mr-1.5" />
|
||||
Koppla till transaktion
|
||||
</Button>
|
||||
<Link href={`/supplier-invoices/new?inbox_item_id=${item.id}`} className="block">
|
||||
<Button variant="outline" size="sm" className="w-full">
|
||||
<Button variant="default" size="sm" className="w-full">
|
||||
Skapa leverantörsfaktura
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
variant="ghost"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={onBookDirect}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { splitTransactions } from '../lib/skattekonto-buckets'
|
||||
import type { StoredSkattekontoTransaction } from '../types'
|
||||
|
||||
function makeRow(
|
||||
overrides: Partial<StoredSkattekontoTransaction> = {},
|
||||
): StoredSkattekontoTransaction {
|
||||
return {
|
||||
id: 'row-1',
|
||||
company_id: 'co-1',
|
||||
transaktionsidentitet: null,
|
||||
dedup_key: 'h:abc',
|
||||
transaktionsdatum: '2026-05-12',
|
||||
forfallodatum: null,
|
||||
ranteberakningsdatum: null,
|
||||
transaktionstext: 'Test',
|
||||
belopp_skatteverket: 100,
|
||||
belopp_kronofogden: 0,
|
||||
status: 'upcoming',
|
||||
journal_entry_id: null,
|
||||
imported_at: '2026-05-15T10:00:00Z',
|
||||
updated_at: '2026-05-15T10:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('splitTransactions', () => {
|
||||
const today = '2026-05-15'
|
||||
|
||||
it('routes booked rows to booked regardless of date', () => {
|
||||
const rows = [
|
||||
makeRow({ id: 'a', status: 'booked', transaktionsdatum: '2026-05-12' }),
|
||||
makeRow({ id: 'b', status: 'booked', transaktionsdatum: '2026-06-01' }),
|
||||
]
|
||||
const out = splitTransactions(rows, today)
|
||||
expect(out.booked.map(r => r.id)).toEqual(['a', 'b'])
|
||||
expect(out.overdue).toEqual([])
|
||||
expect(out.upcoming).toEqual([])
|
||||
})
|
||||
|
||||
it('routes upcoming with past forfallodatum to overdue', () => {
|
||||
// The reported bug: SKV still has it in kommande on 2026-05-15
|
||||
// even though forfallodatum was 2026-05-12.
|
||||
const rows = [
|
||||
makeRow({ id: 'a', status: 'upcoming', forfallodatum: '2026-05-12' }),
|
||||
]
|
||||
const out = splitTransactions(rows, today)
|
||||
expect(out.overdue.map(r => r.id)).toEqual(['a'])
|
||||
expect(out.upcoming).toEqual([])
|
||||
})
|
||||
|
||||
it('routes upcoming with future forfallodatum to upcoming', () => {
|
||||
const rows = [
|
||||
makeRow({ id: 'a', status: 'upcoming', forfallodatum: '2026-06-12' }),
|
||||
]
|
||||
const out = splitTransactions(rows, today)
|
||||
expect(out.upcoming.map(r => r.id)).toEqual(['a'])
|
||||
expect(out.overdue).toEqual([])
|
||||
})
|
||||
|
||||
it('treats today as upcoming, not overdue', () => {
|
||||
const rows = [
|
||||
makeRow({ id: 'a', status: 'upcoming', forfallodatum: today }),
|
||||
]
|
||||
const out = splitTransactions(rows, today)
|
||||
expect(out.upcoming.map(r => r.id)).toEqual(['a'])
|
||||
expect(out.overdue).toEqual([])
|
||||
})
|
||||
|
||||
it('falls back to transaktionsdatum when forfallodatum is null', () => {
|
||||
const rows = [
|
||||
makeRow({
|
||||
id: 'past',
|
||||
status: 'upcoming',
|
||||
forfallodatum: null,
|
||||
transaktionsdatum: '2026-05-10',
|
||||
}),
|
||||
makeRow({
|
||||
id: 'future',
|
||||
status: 'upcoming',
|
||||
forfallodatum: null,
|
||||
transaktionsdatum: '2026-05-20',
|
||||
}),
|
||||
]
|
||||
const out = splitTransactions(rows, today)
|
||||
expect(out.overdue.map(r => r.id)).toEqual(['past'])
|
||||
expect(out.upcoming.map(r => r.id)).toEqual(['future'])
|
||||
})
|
||||
|
||||
it('handles a mixed input', () => {
|
||||
const rows = [
|
||||
makeRow({ id: 'b1', status: 'booked' }),
|
||||
makeRow({ id: 'o1', status: 'upcoming', forfallodatum: '2026-05-01' }),
|
||||
makeRow({ id: 'u1', status: 'upcoming', forfallodatum: '2026-05-31' }),
|
||||
makeRow({ id: 'o2', status: 'upcoming', forfallodatum: '2026-05-14' }),
|
||||
]
|
||||
const out = splitTransactions(rows, today)
|
||||
expect(out.booked.map(r => r.id)).toEqual(['b1'])
|
||||
expect(out.overdue.map(r => r.id)).toEqual(['o1', 'o2'])
|
||||
expect(out.upcoming.map(r => r.id)).toEqual(['u1'])
|
||||
})
|
||||
})
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
matchSkattekontoToEntry,
|
||||
SkattekontoMatchError,
|
||||
} from './lib/skattekonto-match'
|
||||
import { splitTransactions } from './lib/skattekonto-buckets'
|
||||
import type { SkattekontoBalanceSnapshot } from './types'
|
||||
import type { VatPeriodType } from '@/types'
|
||||
|
||||
@@ -1387,7 +1388,8 @@ export const skatteverketExtension: Extension = {
|
||||
}
|
||||
|
||||
const rows = data ?? []
|
||||
const booked = rows.filter(r => r.status === 'booked')
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const { booked, overdue, upcoming } = splitTransactions(rows, today)
|
||||
|
||||
// Enrich obokförda rader with a single-best-candidate suggestion.
|
||||
// Only attached when there's exactly one match — avoids the UI
|
||||
@@ -1411,7 +1413,8 @@ export const skatteverketExtension: Extension = {
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
booked: bookedEnriched,
|
||||
upcoming: rows.filter(r => r.status === 'upcoming'),
|
||||
overdue,
|
||||
upcoming,
|
||||
},
|
||||
})
|
||||
},
|
||||
|
||||
@@ -23,7 +23,7 @@ const DEFAULT_OAUTH_BASE_URL = 'https://peroauth2.test.skatteverket.se/oauth2/v1
|
||||
// section 4.1.2.2 — the 403 "Felaktigt access scope" example shows
|
||||
// `"description": "The required scope agd has been requested for that access token."`
|
||||
// The other tokens match the path segments of their respective APIs.
|
||||
const DEFAULT_SCOPES = 'momsdeklaration inkforetag skattekonto agd'
|
||||
const DEFAULT_SCOPES = 'momsdeklaration inkforetag skahmst skattekonto agd'
|
||||
|
||||
function getOAuthBaseUrl(): string {
|
||||
return process.env.SKATTEVERKET_OAUTH_BASE_URL || DEFAULT_OAUTH_BASE_URL
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { StoredSkattekontoTransaction } from '../types'
|
||||
|
||||
export interface SkattekontoBuckets<T extends StoredSkattekontoTransaction> {
|
||||
booked: T[]
|
||||
overdue: T[]
|
||||
upcoming: T[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Split skattekonto rows into UI buckets.
|
||||
*
|
||||
* SKV's `kommandeTransaktioner` includes rows whose due date has passed but
|
||||
* haven't settled yet — labelling them "Kommande" misleads the user. We pull
|
||||
* those into a separate "Förfallna" bucket here. Stored `status` keeps
|
||||
* mirroring SKV.
|
||||
*
|
||||
* `today` is an ISO date string ('YYYY-MM-DD'). Lexicographic compare on
|
||||
* ISO dates is chronological.
|
||||
*/
|
||||
export function splitTransactions<T extends StoredSkattekontoTransaction>(
|
||||
rows: T[],
|
||||
today: string,
|
||||
): SkattekontoBuckets<T> {
|
||||
const booked: T[] = []
|
||||
const overdue: T[] = []
|
||||
const upcoming: T[] = []
|
||||
|
||||
for (const row of rows) {
|
||||
if (row.status === 'booked') {
|
||||
booked.push(row)
|
||||
continue
|
||||
}
|
||||
const dueDate = row.forfallodatum ?? row.transaktionsdatum
|
||||
if (dueDate < today) {
|
||||
overdue.push(row)
|
||||
} else {
|
||||
upcoming.push(row)
|
||||
}
|
||||
}
|
||||
|
||||
return { booked, overdue, upcoming }
|
||||
}
|
||||
@@ -285,6 +285,13 @@ const TRANSACTIONS: Record<string, StructuredErrorEntry> = {
|
||||
message_sv: 'Transaktionen har ingen kopplad verifikation att stornera.',
|
||||
message_en: 'Transaction has no linked journal entry to reverse.',
|
||||
},
|
||||
TX_EXCHANGE_RATE_UNAVAILABLE: {
|
||||
httpStatus: 502,
|
||||
message_sv:
|
||||
'Kunde inte hämta växelkursen från Riksbanken. Försök igen om en stund — verifikationen måste bokföras i SEK.',
|
||||
message_en:
|
||||
'Could not fetch the exchange rate from Riksbanken. The verifikation must be posted in SEK.',
|
||||
},
|
||||
}
|
||||
|
||||
const MATCH_INVOICE: Record<string, StructuredErrorEntry> = {
|
||||
|
||||
Reference in New Issue
Block a user