feat(rot-rut): overview page, beslutsfil import, avslag reclaim, MCP list + settle (#2397)
* feat(rot-rut): overview page, beslutsfil import, avslag reclaim, MCP list + settle Follow-up to #2239/#2360 for firms whose every invoice carries ROT/RUT. - /invoices/rot-rut: tiles (at Skatteverket on 1513, awaiting beslut, refused to book, ready to request) and one row per begaran with mark uploaded, cancel, download and "Bokfor nekat belopp"; the Fakturor button links here, ?rot-rut=1 still opens the file dialog. - Beslutsfil import from the UI through the existing import route. - Reclaim of the share Skatteverket refused: one voucher debit 1510 / credit 1513 per invoice (source_type rot_rut_reclaim), CAS-attached to the begaran and guarded by a partial unique index; the invoice reopens for the refused share via invoices.deduction_reclaimed_total, with the customer-share formula and its SQL twin gaining the same term. The payment dialog and bank match then settle the reopened remaining as a plain 1510 clearing; a booked kontantmetod invoice is proposed accrual- shaped so revenue is never recognised twice. Unknown per-invoice split of a partial beslut is refused, never allocated. - MCP: gnubok_list_rot_rut_payout_requests (search-only read) and gnubok_settle_rot_rut_payout (staged write, op settle_rot_rut_payout) sharing one pre-flight + settle with the dashboard match route. - Migrations 20260907140000 (reclaim state, source_type, INSERT guard), 20260907140100/140101 (pending_operations op type). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB * chore(rot-rut): renumber migrations after merging main Main already carries 20260907143000 and 20260907150000, so the three rot-rut migrations move to 20260907160000/160100/160101 to keep the applied order monotonic (see memory: migration-version-collisions). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB * fix(rot-rut): close the reclaim gaps found by skeptics, CI and review Skeptic refutations (#2397): - payment-sync recomputes remaining with deduction_reclaimed_total, so a storno of a payment on a reopened invoice no longer strands the refused share (R1). - Reclaim refused while an invoice sits in a later live begäran (ROT_RUT_RECLAIM_INVOICE_REREQUESTED); the overview and the MCP list hide the action for the same case (C2). - A reclaimed invoice is blocked from a new begäran (DEDUCTION_RECLAIMED) until the reclaim voucher is reversed (R2/C3). - Storno of the reclaim voucher syncs the invoices and the begäran back (rot-rut-reclaim-reversal.ts, hooked into reverseEntry) (R3). - A paid invoice with NULL paid_amount counts its customer share as paid (C4). Crediting an invoice with a reclaimed share is refused on the dashboard, v1 and MCP paths (R4). CI and review: - Build: custom-coded MCP errors via Object.assign, not codedError. - pg-real: column default for default_voucher_series_per_source_type re-stated with rot_rut_reclaim (20260907160200); the default test now re-applies the latest default migration. - Checks: accounted-api skill regenerated (journal-entries source types). - CodeRabbit/Superagent: per-item refused shares must reconcile with the request-level beslut; per-invoice reopen through the idempotent RPC apply_rot_rut_reclaim_invoice (20260907160300) with a resume path; update-stage settle failures keep the voucher id (failed_partial); Stockholm calendar date for the booking; existing-voucher tab uses the same proposal method; MCP stage checks bank_line junction rows. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB * fix(rot-rut): carry the voucher id through the match outcome type; date the reclaim on the beslut - The shared match outcome now declares journalEntryId on update-stage errors, matching the settle service (Core Build TS2339 on 2d6cece1a). - The reclaim voucher is dated on the Swedish calendar day of Skatteverkets beslut (decided_at), today only when no decision date is recorded, and the confirm dialog states the date (Swedish accounting review: BFL 5 kap 6-7 §, datum for affarshandelsen). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB * fix(rot-rut): reclaim RPCs validate the share and derive the invoice state; idempotent revert; v1 credit guard reads the column - apply_rot_rut_reclaim_invoice (20260907160400 replaces the 160300 signature) takes only the refused share, validates it against the locked item, request and invoice, and derives remaining_amount and status from the INSERT-guard formula (review: caller-supplied accounting values, CWE-862). revert_rot_rut_reclaim_invoice mirrors it for a reversed reclaim voucher; the request link is cleared only after every leg. - v1 credit route projection includes deduction_reclaimed_total so the reclaim guard actually fires there. - Overview keeps "Bokfor nekat belopp" available while legs are pending (resume after a partial failure). - Match and settle routes attach journal_entry_id on update-stage errors. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
5d735097a1
commit
fdcb7d937e
@@ -2333,9 +2333,23 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
<span className="text-muted-foreground">{t('deduction_row', { kind: deductionKindLabel })}</span>
|
||||
<span>{formatCurrency(-Math.abs(invoice.deduction_total ?? 0), invoice.currency)}</span>
|
||||
</div>
|
||||
{/* Skatteverket refused (part of) the deduction and the reclaim
|
||||
voucher moved it back onto the customer: the printed
|
||||
deduction stands, the refused share is the customer's again. */}
|
||||
{(invoice.deduction_reclaimed_total ?? 0) > 0 && (
|
||||
<div className="flex justify-between gap-4">
|
||||
<span className="text-muted-foreground">{t('deduction_reclaimed_row')}</span>
|
||||
<span>{formatCurrency(Math.abs(invoice.deduction_reclaimed_total ?? 0), invoice.currency)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-baseline justify-between gap-4 border-t border-border pt-2">
|
||||
<span>{t('amount_to_pay')}</span>
|
||||
<span className="font-display text-xl">{formatCurrency(amountToPay.toPay, invoice.currency)}</span>
|
||||
<span className="font-display text-xl">
|
||||
{formatCurrency(
|
||||
Math.round((amountToPay.toPay + Math.abs(invoice.deduction_reclaimed_total ?? 0)) * 100) / 100,
|
||||
invoice.currency,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -355,8 +355,6 @@ export default function InvoicesPage() {
|
||||
)
|
||||
const closeRotRutPayout = () =>
|
||||
router.replace(invoicesUrl((p) => p.delete('rot-rut')), { scroll: false })
|
||||
const openRotRutPayout = () =>
|
||||
router.push(invoicesUrl((p) => p.set('rot-rut', '1')), { scroll: false })
|
||||
|
||||
// Begäran om utbetalning (Lag 2009:194 8 §) only concerns companies selling
|
||||
// ROT/RUT-eligible work to consumers, so the action stays out of the header
|
||||
@@ -771,12 +769,13 @@ export default function InvoicesPage() {
|
||||
<h1 className="font-display text-2xl leading-8 tracking-tight">{t('title')}</h1>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{showRotRutAction && (
|
||||
// The ROT/RUT overview (begäran, beslut, utbetalning, nekat
|
||||
// belopp) has its own page; the file dialog still opens from
|
||||
// ?rot-rut=1 here for existing links and the Att göra rows.
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={openRotRutPayout}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
onClick={() => router.push('/invoices/rot-rut')}
|
||||
>
|
||||
<FileDown className="mr-2 h-4 w-4" />
|
||||
{t('rot_rut_payout_action')}
|
||||
|
||||
@@ -0,0 +1,606 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { AlertTriangle, Download, FileDown, FileUp, Loader2, Receipt } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { TH_CLASS, TD_CLASS, QUIET_LINK_CLASS } from '@/components/ui/dry-table'
|
||||
import {
|
||||
DestructiveConfirmDialog,
|
||||
useDestructiveConfirm,
|
||||
} from '@/components/ui/destructive-confirm-dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { downloadFile } from '@/lib/browser/download-file'
|
||||
import { failureDescription } from '@/lib/browser/action-failure'
|
||||
import {
|
||||
getErrorMessage,
|
||||
getResponseErrorMessage,
|
||||
type ErrorLocale,
|
||||
} from '@/lib/errors/get-error-message'
|
||||
import { computeRefusedShares } from '@/lib/invoices/rot-rut-reclaim'
|
||||
import { expectedRotRutPayoutAmount } from '@/lib/invoices/rot-rut-payout-matching'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { todayIsoStockholm } from '@/lib/dates/iso'
|
||||
|
||||
const RotRutPayoutDialog = dynamic(() => import('@/components/invoices/RotRutPayoutDialog'), {
|
||||
ssr: false,
|
||||
})
|
||||
|
||||
type RequestStatus = 'generated' | 'submitted' | 'paid' | 'partially_paid' | 'rejected' | 'cancelled'
|
||||
|
||||
interface RequestItem {
|
||||
id: string
|
||||
invoice_id: string
|
||||
requested_amount: number | string
|
||||
decided_amount: number | string | null
|
||||
reclaimed_amount: number | string | null
|
||||
invoice: { id: string; invoice_number: string | null; status: string; remaining_amount: number | string } | null
|
||||
}
|
||||
|
||||
interface PayoutRequest {
|
||||
id: string
|
||||
name: string
|
||||
deduction_type: 'rot' | 'rut'
|
||||
status: RequestStatus
|
||||
requested_total: number | string
|
||||
decided_total: number | string | null
|
||||
file_name: string
|
||||
file_document_id: string | null
|
||||
created_at: string
|
||||
submitted_at: string | null
|
||||
decided_at: string | null
|
||||
settlement_journal_entry_id: string | null
|
||||
reclaim_journal_entry_id: string | null
|
||||
reclaimed_at: string | null
|
||||
skv_referensnummer: string | null
|
||||
items: RequestItem[]
|
||||
}
|
||||
|
||||
interface BeslutImportResult {
|
||||
imported: number
|
||||
already_imported: number
|
||||
errors: number
|
||||
results: Array<{ namn: string; status: string; error?: string }>
|
||||
}
|
||||
|
||||
const STATUS_VARIANT: Record<RequestStatus, 'secondary' | 'outline' | 'success' | 'warning' | 'destructive'> = {
|
||||
generated: 'warning',
|
||||
submitted: 'outline',
|
||||
paid: 'success',
|
||||
partially_paid: 'warning',
|
||||
rejected: 'destructive',
|
||||
cancelled: 'secondary',
|
||||
}
|
||||
|
||||
/** Days between an ISO timestamp and now, floored at 0. */
|
||||
function daysSince(iso: string): number {
|
||||
const ms = Date.now() - new Date(iso).getTime()
|
||||
return Math.max(0, Math.floor(ms / 86_400_000))
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Refused share and whether it still needs its reclaim voucher. An invoice
|
||||
* re-requested in a later live begäran (avslag → new file) is being reviewed
|
||||
* again, so its refused share stays at Skatteverket: no reclaim offered, the
|
||||
* same rule the reclaim route enforces.
|
||||
*/
|
||||
function refusedState(
|
||||
request: PayoutRequest,
|
||||
allRequests: PayoutRequest[],
|
||||
): { refused: number; needsReclaim: boolean; splitUnknown: boolean; rerequested: boolean } {
|
||||
const computed = computeRefusedShares(request, request.items)
|
||||
if (!computed.ok) {
|
||||
return {
|
||||
refused: 0,
|
||||
needsReclaim: false,
|
||||
splitUnknown: computed.code === 'ROT_RUT_RECLAIM_SPLIT_UNKNOWN',
|
||||
rerequested: false,
|
||||
}
|
||||
}
|
||||
const ownInvoices = new Set(request.items.map((item) => item.invoice_id))
|
||||
const rerequested = allRequests.some(
|
||||
(other) =>
|
||||
other.id !== request.id &&
|
||||
other.status !== 'cancelled' &&
|
||||
other.status !== 'rejected' &&
|
||||
other.items.some((item) => ownInvoices.has(item.invoice_id)),
|
||||
)
|
||||
// Pending = refused legs whose item marker (reclaimed_amount) is still
|
||||
// unset. Before the voucher that is every refused leg; after a partial
|
||||
// failure it is the legs the service will resume, so the action stays
|
||||
// available until the whole begäran is applied.
|
||||
const pending = computed.shares
|
||||
.filter((share) => share.refused > 0)
|
||||
.filter((share) => request.items.find((item) => item.id === share.itemId)?.reclaimed_amount == null)
|
||||
.reduce((sum, share) => sum + share.refused, 0)
|
||||
return {
|
||||
refused: computed.total,
|
||||
needsReclaim: pending > 0 && !rerequested,
|
||||
splitUnknown: false,
|
||||
rerequested,
|
||||
}
|
||||
}
|
||||
|
||||
export default function RotRutOverviewPage() {
|
||||
const t = useTranslations('rot_rut_overview')
|
||||
const locale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const { dialogProps, confirm } = useDestructiveConfirm()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const loadSequence = useRef(0)
|
||||
|
||||
const [requests, setRequests] = useState<PayoutRequest[]>([])
|
||||
const [eligibleCounts, setEligibleCounts] = useState<{ rot: number; rut: number }>({ rot: 0, rut: 0 })
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [busyId, setBusyId] = useState<string | null>(null)
|
||||
const [importing, setImporting] = useState(false)
|
||||
|
||||
// The file dialog is driven by ?new=1 so the browser back button closes it
|
||||
// (same pattern as /invoices and /invoices/recurring).
|
||||
const showNewRequest = searchParams.has('new')
|
||||
const openNewRequest = () => router.push('/invoices/rot-rut?new=1', { scroll: false })
|
||||
const closeNewRequest = () => router.replace('/invoices/rot-rut', { scroll: false })
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const sequence = ++loadSequence.current
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const [requestsRes, rotRes, rutRes] = await Promise.all([
|
||||
fetch('/api/rot-rut/payout-requests'),
|
||||
fetch('/api/rot-rut/eligible?type=rot'),
|
||||
fetch('/api/rot-rut/eligible?type=rut'),
|
||||
])
|
||||
if (!requestsRes.ok) {
|
||||
const description = await getResponseErrorMessage(requestsRes, 'invoice', locale)
|
||||
if (sequence !== loadSequence.current) return
|
||||
toast({ title: t('load_failed_title'), description, variant: 'destructive' })
|
||||
setRequests([])
|
||||
return
|
||||
}
|
||||
const body = (await requestsRes.json()) as { data: PayoutRequest[] }
|
||||
const rot = rotRes.ok ? ((await rotRes.json()) as { data: { eligible: unknown[] } }).data.eligible.length : 0
|
||||
const rut = rutRes.ok ? ((await rutRes.json()) as { data: { eligible: unknown[] } }).data.eligible.length : 0
|
||||
if (sequence !== loadSequence.current) return
|
||||
setRequests(body.data)
|
||||
setEligibleCounts({ rot, rut })
|
||||
} catch (error) {
|
||||
if (sequence !== loadSequence.current) return
|
||||
toast({
|
||||
title: t('load_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'invoice', locale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
if (sequence === loadSequence.current) setIsLoading(false)
|
||||
}
|
||||
}, [locale, t, toast])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const summary = useMemo(() => {
|
||||
let atSkv = 0
|
||||
let awaitingDecision = 0
|
||||
let refusedOpen = 0
|
||||
let refusedOpenCount = 0
|
||||
for (const request of requests) {
|
||||
if (request.status === 'cancelled') continue
|
||||
const state = refusedState(request, requests)
|
||||
if (state.needsReclaim) {
|
||||
refusedOpen += state.refused
|
||||
refusedOpenCount += 1
|
||||
}
|
||||
if (request.status === 'rejected') continue
|
||||
if (!request.settlement_journal_entry_id) {
|
||||
atSkv += expectedRotRutPayoutAmount(request)
|
||||
if (!request.decided_at) awaitingDecision += 1
|
||||
}
|
||||
}
|
||||
return { atSkv: Math.round(atSkv * 100) / 100, awaitingDecision, refusedOpen: Math.round(refusedOpen * 100) / 100, refusedOpenCount }
|
||||
}, [requests])
|
||||
|
||||
async function patchRequest(request: PayoutRequest, status: 'submitted' | 'cancelled') {
|
||||
if (!canWrite || busyId) return
|
||||
setBusyId(request.id)
|
||||
try {
|
||||
const response = await fetch(`/api/rot-rut/payout-requests/${request.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('update_failed_title'),
|
||||
description: await getResponseErrorMessage(response, 'invoice', locale),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
toast({ title: t(status === 'submitted' ? 'uploaded_title' : 'cancelled_title') })
|
||||
await load()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('update_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'invoice', locale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function reclaim(request: PayoutRequest) {
|
||||
if (!canWrite || busyId) return
|
||||
const state = refusedState(request, requests)
|
||||
// The affärshändelse is Skatteverkets beslut, so the voucher is dated on
|
||||
// the decision day (Swedish calendar date of decided_at), not on the day
|
||||
// the bookkeeper clicks; today only when no decision date is recorded.
|
||||
const bookingDate = request.decided_at
|
||||
? todayIsoStockholm(new Date(request.decided_at))
|
||||
: todayIsoStockholm()
|
||||
const confirmed = await confirm({
|
||||
title: t('reclaim_confirm_title'),
|
||||
description: t('reclaim_confirm_description', {
|
||||
amount: formatCurrency(state.refused),
|
||||
count: request.items.length,
|
||||
name: request.name,
|
||||
date: formatDate(bookingDate),
|
||||
}),
|
||||
confirmLabel: t('reclaim_confirm_action'),
|
||||
variant: 'warning',
|
||||
})
|
||||
if (!confirmed) return
|
||||
setBusyId(request.id)
|
||||
try {
|
||||
const response = await fetch(`/api/rot-rut/payout-requests/${request.id}/reclaim`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ booking_date: bookingDate }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('reclaim_failed_title'),
|
||||
description: await getResponseErrorMessage(response, 'invoice', locale),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
const body = (await response.json()) as {
|
||||
data: { reclaimed_total: number; invoices: Array<{ invoice_id: string }> }
|
||||
}
|
||||
toast({
|
||||
title: t('reclaim_done_title'),
|
||||
description: t('reclaim_done_description', {
|
||||
amount: formatCurrency(body.data.reclaimed_total),
|
||||
count: body.data.invoices.length,
|
||||
}),
|
||||
})
|
||||
await load()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('reclaim_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'invoice', locale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function importBeslut(file: File) {
|
||||
if (!canWrite || importing) return
|
||||
setImporting(true)
|
||||
try {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(await file.text())
|
||||
} catch {
|
||||
toast({ title: t('import_failed_title'), description: t('import_invalid_json'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
const response = await fetch('/api/rot-rut/beslut/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(parsed),
|
||||
})
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('import_failed_title'),
|
||||
description: await getResponseErrorMessage(response, 'invoice', locale),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
const body = (await response.json()) as { data: BeslutImportResult }
|
||||
const failed = body.data.results.filter((r) => r.status === 'error')
|
||||
toast({
|
||||
title: t('import_done_title'),
|
||||
description:
|
||||
t('import_done_description', {
|
||||
imported: body.data.imported,
|
||||
already: body.data.already_imported,
|
||||
errors: body.data.errors,
|
||||
}) + (failed.length > 0 ? ' ' + failed.map((r) => `${r.namn}: ${r.error ?? ''}`).join(' ') : ''),
|
||||
variant: body.data.errors > 0 && body.data.imported === 0 ? 'destructive' : undefined,
|
||||
})
|
||||
await load()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('import_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'invoice', locale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setImporting(false)
|
||||
if (fileInputRef.current) fileInputRef.current.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadArchivedFile(request: PayoutRequest) {
|
||||
if (!request.file_document_id || busyId) return
|
||||
setBusyId(request.id)
|
||||
try {
|
||||
const result = await downloadFile({
|
||||
url: `/api/documents/${request.file_document_id}/inline`,
|
||||
filename: request.file_name,
|
||||
locale,
|
||||
})
|
||||
if (!result.ok) {
|
||||
toast({
|
||||
title: t('download_failed_title'),
|
||||
description: failureDescription(result, {
|
||||
timeout: t('download_timeout'),
|
||||
network: t('download_network'),
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const readyCount = eligibleCounts.rot + eligibleCounts.rut
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title={t('title')}
|
||||
description={t('description')}
|
||||
action={
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
className="hidden"
|
||||
onChange={(event) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (file) void importBeslut(file)
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={!canWrite || importing}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : t('import_beslut_help')}
|
||||
>
|
||||
{importing ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <FileUp className="mr-2 h-4 w-4" />}
|
||||
{t('import_beslut')}
|
||||
</Button>
|
||||
<Button type="button" onClick={openNewRequest} disabled={!canWrite}>
|
||||
<FileDown className="mr-2 h-4 w-4" />
|
||||
{t('new_request')}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Summary tiles: what sits at Skatteverket, what waits, what came back refused. */}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="rounded-lg border p-4">
|
||||
<p className="text-xs text-muted-foreground">{t('tile_at_skv')}</p>
|
||||
<p className="mt-1 font-display text-2xl tabular-nums">{formatCurrency(summary.atSkv)}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t('tile_at_skv_help')}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-4">
|
||||
<p className="text-xs text-muted-foreground">{t('tile_awaiting')}</p>
|
||||
<p className="mt-1 font-display text-2xl tabular-nums">{summary.awaitingDecision}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t('tile_awaiting_help')}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-4">
|
||||
<p className="text-xs text-muted-foreground">{t('tile_refused')}</p>
|
||||
<p className="mt-1 font-display text-2xl tabular-nums">{formatCurrency(summary.refusedOpen)}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{t('tile_refused_help', { count: summary.refusedOpenCount })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-4">
|
||||
<p className="text-xs text-muted-foreground">{t('tile_ready')}</p>
|
||||
<p className="mt-1 font-display text-2xl tabular-nums">{readyCount}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{t('tile_ready_help', { rot: eligibleCounts.rot, rut: eligibleCounts.rut })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-3" role="status" aria-label={t('loading')}>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
) : requests.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Receipt}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_description')}
|
||||
actionLabel={canWrite ? t('new_request') : undefined}
|
||||
onAction={canWrite ? openNewRequest : undefined}
|
||||
/>
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={TH_CLASS}>{t('col_name')}</th>
|
||||
<th className={TH_CLASS}>{t('col_status')}</th>
|
||||
<th className={TH_CLASS}>{t('col_created')}</th>
|
||||
<th className={`${TH_CLASS} text-right`}>{t('col_requested')}</th>
|
||||
<th className={`${TH_CLASS} text-right`}>{t('col_decided')}</th>
|
||||
<th className={`${TH_CLASS} text-right`}>{t('col_refused')}</th>
|
||||
<th className={TH_CLASS}>{t('col_waiting')}</th>
|
||||
<th className={`${TH_CLASS} text-right`}>{t('col_actions')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{requests.map((request) => {
|
||||
const state = refusedState(request, requests)
|
||||
const isBusy = busyId === request.id
|
||||
// Waiting = at Skatteverket without a beslut. A decided begäran
|
||||
// (beslutsfil imported, status may still read submitted) is
|
||||
// waiting for money, not for a decision: no counter.
|
||||
const waitingSince =
|
||||
!request.settlement_journal_entry_id &&
|
||||
!request.decided_at &&
|
||||
request.status !== 'cancelled' &&
|
||||
request.status !== 'rejected'
|
||||
? request.submitted_at ?? request.created_at
|
||||
: null
|
||||
return (
|
||||
<tr key={request.id}>
|
||||
<td className={TD_CLASS}>
|
||||
<details>
|
||||
<summary className="cursor-pointer list-none">
|
||||
<span className="font-medium">{request.name}</span>
|
||||
<span className="ml-2 text-xs text-muted-foreground">
|
||||
{request.deduction_type.toUpperCase()} · {t('cases', { count: request.items.length })}
|
||||
</span>
|
||||
</summary>
|
||||
<ul className="mt-2 space-y-1 text-xs">
|
||||
{request.items.map((item) => (
|
||||
<li key={item.id} className="flex flex-wrap justify-between gap-2">
|
||||
<Link href={`/invoices/${item.invoice_id}`} className={QUIET_LINK_CLASS}>
|
||||
{item.invoice?.invoice_number ?? item.invoice_id.slice(0, 8)}
|
||||
</Link>
|
||||
<span className="tabular-nums text-muted-foreground">
|
||||
{formatCurrency(Number(item.requested_amount))}
|
||||
{item.decided_amount != null && ` · ${t('item_decided', { amount: formatCurrency(Number(item.decided_amount)) })}`}
|
||||
{item.reclaimed_amount != null && Number(item.reclaimed_amount) > 0 && ` · ${t('item_reclaimed', { amount: formatCurrency(Number(item.reclaimed_amount)) })}`}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
</td>
|
||||
<td className={TD_CLASS}>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<Badge variant={STATUS_VARIANT[request.status]} className="font-normal">
|
||||
{t(`status_${request.status}`)}
|
||||
</Badge>
|
||||
{request.settlement_journal_entry_id && (
|
||||
<Link href={`/bookkeeping/${request.settlement_journal_entry_id}`} className={`${QUIET_LINK_CLASS} text-xs`}>
|
||||
{t('settled_link')}
|
||||
</Link>
|
||||
)}
|
||||
{request.reclaim_journal_entry_id && (
|
||||
<Link href={`/bookkeeping/${request.reclaim_journal_entry_id}`} className={`${QUIET_LINK_CLASS} text-xs`}>
|
||||
{t('reclaimed_link')}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className={`${TD_CLASS} whitespace-nowrap`}>{formatDate(request.created_at)}</td>
|
||||
<td className={`${TD_CLASS} text-right tabular-nums`}>{formatCurrency(Number(request.requested_total))}</td>
|
||||
<td className={`${TD_CLASS} text-right tabular-nums`}>
|
||||
{request.decided_total == null ? <span className="text-muted-foreground">-</span> : formatCurrency(Number(request.decided_total))}
|
||||
</td>
|
||||
<td className={`${TD_CLASS} text-right tabular-nums`}>
|
||||
{state.splitUnknown ? (
|
||||
<span className="inline-flex items-center gap-1 text-attn" title={t('split_unknown_hint')}>
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
{t('split_unknown')}
|
||||
</span>
|
||||
) : state.refused > 0 ? (
|
||||
<span
|
||||
className={state.needsReclaim ? 'text-attn' : undefined}
|
||||
title={state.rerequested ? t('rerequested_hint') : undefined}
|
||||
>
|
||||
{formatCurrency(state.refused)}
|
||||
{state.rerequested && (
|
||||
<span className="ml-1 text-xs text-muted-foreground">{t('rerequested')}</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={`${TD_CLASS} whitespace-nowrap`}>
|
||||
{waitingSince ? t('waiting_days', { days: daysSince(waitingSince) }) : <span className="text-muted-foreground">-</span>}
|
||||
</td>
|
||||
<td className={`${TD_CLASS} text-right`}>
|
||||
<div className="flex flex-wrap justify-end gap-1.5">
|
||||
{request.file_document_id && (
|
||||
<Button type="button" size="sm" variant="ghost" disabled={isBusy} onClick={() => void downloadArchivedFile(request)}>
|
||||
<Download className="mr-1.5 h-3.5 w-3.5" />
|
||||
{t('download')}
|
||||
</Button>
|
||||
)}
|
||||
{request.status === 'generated' && canWrite && (
|
||||
<>
|
||||
<Button type="button" size="sm" variant="outline" disabled={isBusy} onClick={() => void patchRequest(request, 'cancelled')}>
|
||||
{t('cancel_request')}
|
||||
</Button>
|
||||
<Button type="button" size="sm" disabled={isBusy} onClick={() => void patchRequest(request, 'submitted')}>
|
||||
{isBusy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||||
{t('mark_uploaded')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{state.needsReclaim && canWrite && (
|
||||
<Button type="button" size="sm" disabled={isBusy} onClick={() => void reclaim(request)}>
|
||||
{isBusy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||||
{t('book_refused')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DestructiveConfirmDialog {...dialogProps} />
|
||||
|
||||
{showNewRequest && (
|
||||
<RotRutPayoutDialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
closeNewRequest()
|
||||
void load()
|
||||
}
|
||||
}}
|
||||
canWrite={canWrite}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -351,6 +351,18 @@ async function createCreditNote(
|
||||
})
|
||||
}
|
||||
|
||||
// A refused ROT/RUT share booked onto the customer (rot_rut_reclaim) moved
|
||||
// kronor from 1513 to 1510 after issue; the credit note reverses the
|
||||
// issue-time split (1510 total minus deduction, 1513 deduction) and would
|
||||
// leave a phantom fordran on 1510 and a phantom liability on 1513. Reverse
|
||||
// the reclaim voucher first; the storno sync closes the invoice again.
|
||||
if (Number((originalInvoice as { deduction_reclaimed_total?: number | null }).deduction_reclaimed_total ?? 0) > 0) {
|
||||
return errorResponseFromCode('INVOICE_CREDIT_ROT_RUT_RECLAIMED', log, {
|
||||
requestId,
|
||||
details: { deduction_reclaimed_total: originalInvoice.deduction_reclaimed_total },
|
||||
})
|
||||
}
|
||||
|
||||
// Self-billed originals have invoice_number null by design (the DB
|
||||
// constraint invoices_self_billed_numbering enforces it); their number
|
||||
// lives in external_invoice_number. Without this fallback the credit note
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
const mockReclaim = vi.fn()
|
||||
vi.mock('@/lib/invoices/rot-rut-reclaim', () => ({
|
||||
reclaimRotRutRefusal: (...args: unknown[]) => mockReclaim(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const REQUEST_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
const routeParams = createMockRouteParams({ id: REQUEST_ID })
|
||||
|
||||
function makeReq(body: unknown = { booking_date: '2026-08-21' }) {
|
||||
return createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/reclaim`, {
|
||||
method: 'POST',
|
||||
body,
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
|
||||
mockReclaim.mockResolvedValue({
|
||||
ok: true,
|
||||
journalEntryId: 'je-reclaim',
|
||||
reclaimedTotal: 2000,
|
||||
invoices: [
|
||||
{ invoice_id: 'inv-1', invoice_number: '2026-002', reclaimed_amount: 2000, remaining_amount: 2000, status: 'partially_paid' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/rot-rut/payout-requests/[id]/reclaim', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const response = await POST(makeReq(), routeParams)
|
||||
expect(response.status).toBe(401)
|
||||
expect(mockReclaim).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 on an invalid body', async () => {
|
||||
const response = await POST(makeReq({ booking_date: 'yesterday' }), routeParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(mockReclaim).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the request is not in the company', async () => {
|
||||
mockReclaim.mockResolvedValue({ ok: false, kind: 'code', code: 'ROT_RUT_REQUEST_NOT_FOUND' })
|
||||
const response = await POST(makeReq(), routeParams)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('ROT_RUT_REQUEST_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('maps service refusals to their structured codes', async () => {
|
||||
mockReclaim.mockResolvedValue({
|
||||
ok: false,
|
||||
kind: 'code',
|
||||
code: 'ROT_RUT_RECLAIM_SPLIT_UNKNOWN',
|
||||
details: { request_id: REQUEST_ID },
|
||||
})
|
||||
const response = await POST(makeReq(), routeParams)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('ROT_RUT_RECLAIM_SPLIT_UNKNOWN')
|
||||
|
||||
mockReclaim.mockResolvedValue({ ok: false, kind: 'code', code: 'ROT_RUT_RECLAIM_ALREADY_DONE' })
|
||||
const conflict = await POST(makeReq(), routeParams)
|
||||
expect(conflict.status).toBe(409)
|
||||
})
|
||||
|
||||
it('books the reclaim with the caller as acting user and the body date', async () => {
|
||||
const response = await POST(makeReq(), routeParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { journal_entry_id: string; reclaimed_total: number; invoices: unknown[] }
|
||||
}>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({
|
||||
journal_entry_id: 'je-reclaim',
|
||||
reclaimed_total: 2000,
|
||||
invoices: [
|
||||
{ invoice_id: 'inv-1', invoice_number: '2026-002', reclaimed_amount: 2000, remaining_amount: 2000, status: 'partially_paid' },
|
||||
],
|
||||
})
|
||||
expect(mockReclaim).toHaveBeenCalledWith(mockSupabase, 'user-1', 'company-1', {
|
||||
requestId: REQUEST_ID,
|
||||
bookingDate: '2026-08-21',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 500 when the engine refuses to book', async () => {
|
||||
mockReclaim.mockResolvedValue({
|
||||
ok: false,
|
||||
kind: 'error',
|
||||
error: new Error('No open fiscal period'),
|
||||
stage: 'book',
|
||||
})
|
||||
const response = await POST(makeReq(), routeParams)
|
||||
expect(response.status).toBeGreaterThanOrEqual(400)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { RotRutReclaimSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { reclaimRotRutRefusal } from '@/lib/invoices/rot-rut-reclaim'
|
||||
|
||||
/**
|
||||
* POST /api/rot-rut/payout-requests/[id]/reclaim
|
||||
*
|
||||
* Books the share of a begäran that Skatteverket refused back onto the
|
||||
* customer(s) and reopens their invoices for it:
|
||||
*
|
||||
* Debit 1510 Kundfordringar [refused share, per invoice]
|
||||
* Credit 1513 Skattereduktion rot/rut [refused share, per invoice]
|
||||
*
|
||||
* The amounts come from the recorded beslut (PATCH or beslutsfil import);
|
||||
* the body carries only the booking date. See lib/invoices/rot-rut-reclaim.ts
|
||||
* for every refusal.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'rot_rut.requests.reclaim',
|
||||
async (request, ctx, { params }) => {
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
const { id } = await params
|
||||
|
||||
const validation = await validateBody(request, RotRutReclaimSchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
const outcome = await reclaimRotRutRefusal(supabase, user.id, companyId!, {
|
||||
requestId: id,
|
||||
bookingDate: validation.data.booking_date,
|
||||
})
|
||||
|
||||
if (!outcome.ok) {
|
||||
if (outcome.kind === 'code') {
|
||||
return errorResponseFromCode(outcome.code, log, { requestId, details: outcome.details })
|
||||
}
|
||||
if (outcome.stage === 'book') {
|
||||
log.error('failed to book rot/rut reclaim entry', outcome.error as Error)
|
||||
} else {
|
||||
log.error('rot/rut reclaim failed', outcome.error as Error, { stage: outcome.stage })
|
||||
}
|
||||
return errorResponse(outcome.error, log, { requestId })
|
||||
}
|
||||
|
||||
log.info('rot/rut refused share reclaimed', {
|
||||
userId: user.id,
|
||||
payoutRequestId: id,
|
||||
journalEntryId: outcome.journalEntryId,
|
||||
reclaimedTotal: outcome.reclaimedTotal,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
journal_entry_id: outcome.journalEntryId,
|
||||
reclaimed_total: outcome.reclaimedTotal,
|
||||
invoices: outcome.invoices,
|
||||
},
|
||||
})
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -50,7 +50,12 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
} else if (outcome.stage === 'book') {
|
||||
log.error('failed to book rot/rut payout entry', outcome.error as Error)
|
||||
}
|
||||
return errorResponse(outcome.error, log, { requestId })
|
||||
// At stage 'update' the voucher is posted: name it so nobody books the
|
||||
// payout twice while repairing the request row.
|
||||
return errorResponse(outcome.error, log, {
|
||||
requestId,
|
||||
...(outcome.journalEntryId ? { details: { journal_entry_id: outcome.journalEntryId } } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
log.info('rot/rut payout settled', {
|
||||
|
||||
@@ -20,8 +20,9 @@ export const GET = withRouteContext('rot_rut.requests.list', async (request, ctx
|
||||
.select(
|
||||
'id, name, deduction_type, status, requested_total, decided_total, file_name, file_document_id, ' +
|
||||
'created_at, submitted_at, decided_at, settlement_journal_entry_id, ' +
|
||||
'items:rot_rut_payout_request_items(id, invoice_id, requested_amount, decided_amount, ' +
|
||||
'invoice:invoices(id, invoice_number))',
|
||||
'reclaim_journal_entry_id, reclaimed_at, skv_referensnummer, ' +
|
||||
'items:rot_rut_payout_request_items(id, invoice_id, requested_amount, decided_amount, reclaimed_amount, ' +
|
||||
'invoice:invoices(id, invoice_number, status, remaining_amount))',
|
||||
)
|
||||
.eq('company_id', companyId!)
|
||||
.order('created_at', { ascending: false })
|
||||
|
||||
@@ -3,13 +3,7 @@ import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { MatchRotRutPayoutSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { resolveSettlementAccount } from '@/lib/bookkeeping/settlement-account'
|
||||
import {
|
||||
settleRotRutPayoutRequest,
|
||||
settleRotRutPayoutRequestSet,
|
||||
} from '@/lib/invoices/rot-rut-settle'
|
||||
import { hasLiveJournalEntryLink } from '@/lib/transactions/link-journal-entry'
|
||||
import { hasBankLineJunctionRow } from '@/lib/transactions/is-booked'
|
||||
import { matchTransactionToRotRutPayout } from '@/lib/invoices/rot-rut-match-transaction'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -31,6 +25,10 @@ ensureInitialized()
|
||||
* body may name several begäran (`request_ids`, #2239): then ONE voucher
|
||||
* carries one 1513 credit per begäran and the row is linked to it, provided
|
||||
* the expected payouts sum to the row exactly.
|
||||
*
|
||||
* The pre-flight and the settle live in lib/invoices/rot-rut-match-transaction
|
||||
* (shared with the MCP settle_rot_rut_payout executor); this route only maps
|
||||
* the outcome to HTTP.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'transaction.match_rot_rut_payout',
|
||||
@@ -49,88 +47,14 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
|
||||
const txLog = log.child({ transactionId, payoutRequestIds })
|
||||
|
||||
// transaction_voucher_links rides along: a row bulk-booked into a
|
||||
// samlingsverifikat carries journal_entry_id = NULL and must still refuse.
|
||||
const { data: transactionRow, error: fetchTxError } = await supabase
|
||||
.from('transactions')
|
||||
.select(
|
||||
'id, date, amount, currency, journal_entry_id, cash_account_id, transaction_voucher_links(journal_entry_id, role)',
|
||||
)
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', companyId!)
|
||||
.single()
|
||||
|
||||
if (fetchTxError || !transactionRow) {
|
||||
return errorResponseFromCode('TX_CATEGORIZE_TX_NOT_FOUND', txLog, { requestId })
|
||||
}
|
||||
const { transaction_voucher_links: junctionLinks, ...transaction } = transactionRow as {
|
||||
id: string
|
||||
date: string
|
||||
amount: number
|
||||
currency: string | null
|
||||
journal_entry_id: string | null
|
||||
cash_account_id: string | null
|
||||
transaction_voucher_links?: Array<{ journal_entry_id: string; role?: string | null }> | null
|
||||
}
|
||||
|
||||
if (!(transaction.amount > 0)) {
|
||||
return errorResponseFromCode('ROT_RUT_MATCH_NOT_INCOME', txLog, {
|
||||
requestId,
|
||||
details: { amount: transaction.amount },
|
||||
})
|
||||
}
|
||||
|
||||
if ((transaction.currency || 'SEK').toUpperCase() !== 'SEK') {
|
||||
return errorResponseFromCode('ROT_RUT_MATCH_CURRENCY', txLog, {
|
||||
requestId,
|
||||
details: { currency: transaction.currency },
|
||||
})
|
||||
}
|
||||
|
||||
// Only a LIVE (posted) pointer or a bank_line junction row blocks: a
|
||||
// pointer left behind by a storno reads as "utan koppling" in the UI and
|
||||
// must stay matchable (same predicate as link-journal-entry, issue #988).
|
||||
if (
|
||||
hasBankLineJunctionRow(junctionLinks) ||
|
||||
(await hasLiveJournalEntryLink(supabase, companyId!, transaction.journal_entry_id))
|
||||
) {
|
||||
return errorResponseFromCode('ROT_RUT_MATCH_TX_ALREADY_LINKED', txLog, {
|
||||
requestId,
|
||||
details: { existingJournalEntryId: transaction.journal_entry_id },
|
||||
})
|
||||
}
|
||||
|
||||
// Debit the cash account THIS transaction belongs to, never a company-wide
|
||||
// default (mirrors match-supplier-invoice).
|
||||
const bankAccount = await resolveSettlementAccount(
|
||||
const outcome = await matchTransactionToRotRutPayout(
|
||||
supabase,
|
||||
user.id,
|
||||
companyId!,
|
||||
transaction.cash_account_id,
|
||||
{ transactionId, requestIds: payoutRequestIds },
|
||||
txLog,
|
||||
)
|
||||
|
||||
// Shared by both shapes: amount, date and account come from the bank row;
|
||||
// the link CAS locks on the pointer read above (null for a free row, or
|
||||
// the stale pointer of a reversed entry the guard let through).
|
||||
const settleParams = {
|
||||
paymentDate: transaction.date,
|
||||
amount: transaction.amount,
|
||||
bankAccount,
|
||||
transactionId,
|
||||
previousJournalEntryId: transaction.journal_entry_id,
|
||||
}
|
||||
|
||||
const outcome =
|
||||
payoutRequestIds.length === 1
|
||||
? await settleRotRutPayoutRequest(supabase, user.id, companyId!, {
|
||||
requestId: payoutRequestIds[0],
|
||||
...settleParams,
|
||||
})
|
||||
: await settleRotRutPayoutRequestSet(supabase, user.id, companyId!, {
|
||||
requestIds: payoutRequestIds,
|
||||
...settleParams,
|
||||
})
|
||||
|
||||
if (!outcome.ok) {
|
||||
if (outcome.kind === 'code') {
|
||||
return errorResponseFromCode(outcome.code, txLog, { requestId, details: outcome.details })
|
||||
@@ -138,20 +62,25 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
if (outcome.stage === 'book') {
|
||||
txLog.error('failed to book rot/rut payout entry', outcome.error as Error)
|
||||
}
|
||||
return errorResponse(outcome.error, txLog, { requestId })
|
||||
// At stage 'update' the voucher is posted: name it so nobody books the
|
||||
// payout twice while repairing the request row.
|
||||
return errorResponse(outcome.error, txLog, {
|
||||
requestId,
|
||||
...(outcome.journalEntryId ? { details: { journal_entry_id: outcome.journalEntryId } } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
txLog.info('rot/rut payout matched from bank transaction', {
|
||||
userId: user.id,
|
||||
journalEntryId: outcome.journalEntryId,
|
||||
amount: outcome.amount,
|
||||
fullyPaid: 'fullyPaid' in outcome ? outcome.fullyPaid : true,
|
||||
fullyPaid: outcome.fullyPaid,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
journal_entry_id: outcome.journalEntryId,
|
||||
...('request' in outcome ? { request: outcome.request } : { requests: outcome.requests }),
|
||||
...(outcome.request ? { request: outcome.request } : { requests: outcome.requests }),
|
||||
category: 'income_other',
|
||||
})
|
||||
},
|
||||
|
||||
@@ -39,7 +39,7 @@ const CreditNoteRequest = z.object({
|
||||
})
|
||||
|
||||
const ORIGINAL_INVOICE_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, invoice_marking, notes, reverse_charge_text, credited_invoice_id, document_type, default_dimensions'
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, invoice_marking, notes, reverse_charge_text, credited_invoice_id, document_type, default_dimensions, deduction_reclaimed_total'
|
||||
|
||||
// default_dimensions stays in this projection: the inserted credit-note row is
|
||||
// handed to createCreditNoteJournalEntry, which reads the bag off the row so
|
||||
@@ -199,6 +199,14 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
requestId: ctx.requestId,
|
||||
})
|
||||
}
|
||||
// Same guard as the dashboard credit route: a reclaimed ROT/RUT share
|
||||
// (rot_rut_reclaim) must be reversed before the issue-time split is credited.
|
||||
if (Number((original as { deduction_reclaimed_total?: number | null }).deduction_reclaimed_total ?? 0) > 0) {
|
||||
return v1ErrorResponseFromCode('INVOICE_CREDIT_ROT_RUT_RECLAIMED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { deduction_reclaimed_total: original.deduction_reclaimed_total },
|
||||
})
|
||||
}
|
||||
if (!['sent', 'paid', 'overdue'].includes(original.status)) {
|
||||
return v1ErrorResponseFromCode('INVOICE_CREDIT_NOT_SENT', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
|
||||
Reference in New Issue
Block a user