Bug/customer invoice bug (#628)
* fix(supplier-invoices): self-assess reverse-charge VAT + link payments to vouchers Reverse-charge supplier invoices now carry a per-item reverse_charge_rate (0.06/0.12/0.25). Under omvänd skattskyldighet the supplier charges 0% VAT, so the line vat_rate stays 0 and the buyer self-assesses fiktiv moms at the statutory rate. Centralizes rate resolution (resolveReverseChargeRate) and the ruta 20-24 basis-account guard (isReverseChargeBasisAccount) in vat-entries so the booking engine and review-dialog preview can no longer drift. Adds the link_supplier_invoice_voucher pending operation: mark a leverantorsfaktura paid by linking an existing posted verifikat that debits 2440, with no new journal entry. Exposes find-candidates/link MCP tools and the bulk-reconcile helper, scoped under suppliers:read/write. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(vat): report yearly VAT over the rakenskapsar, not the calendar year Annual VAT (helarsmoms) is filed per beskattningsar/rakenskapsar (SFL 26 kap), which can be extended or shortened up to 18 months. The previous Jan-Dec calendar span silently dropped part of an extended first year. calculateVatDeclaration now accepts a fiscalPeriodId and resolves the period's actual bounds for yearly; monthly/quarterly stay calendar. The reports UI passes the selected fiscal period, defaults the periodicity from the company's moms_period setting, and carries the period into the ruta drill-down. full-archive export threads the period id through too. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(migration): resolve supplier invoice status from payment amounts The provider's lifecycle status and its payment status are computed independently upstream and can contradict each other (e.g. a Fortnox invoice marked booked but fully paid). Both the arcim entity-mapper and the Fortnox mapper now let payment state win: fully paid -> paid, partial -> partially_paid, otherwise the mapped lifecycle status, with credit notes forced terminal. Balance is compared numerically (never strict === 0) so float drift or a residual ore resolves cleanly, and an absent Balance is treated as unpaid. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(enable-banking): only ingest booked transactions to stop re-import drift Pending entries are skipped during sync: a pending row is unstable across syncs (a later 'synka nu' returns it still pending or finally booked, often with a different effective date). Because both the dedup external_id and the content-dedup key are date-derived, that drift minted a new id and re-imported a transaction that already existed - observed in production as the same amount+description landing twice with different dates. Gating the import set on a stable booking_date removes the drift at the source and leaves booked rows' ids byte-identical. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(gitignore): ignore local SIE test fixtures tests/fixtures/sie/ may contain real or scrubbed company data and must never be committed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(invoice): handle errors during registration journal entry creation and ensure invoice rollback feat(tests): add test for reverse charge rate handling on supplier invoice line items feat(fortnox): ensure paid status reflects zero balance for fully paid invoices chore(migrations): add reverse_charge_rate to supplier_invoice_items and backfill link_supplier_invoice_voucher --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
358c25094d
commit
f6ee0c2a82
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import React, { useState, useEffect, useCallback } from 'react'
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
@@ -15,6 +15,7 @@ import { formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { FiscalYearSelector } from '@/components/common/FiscalYearSelector'
|
||||
import { ReportDateRange, type DateRangeValue } from '@/components/common/ReportDateRange'
|
||||
import { ReportsNav } from '@/components/reports/ReportsNav'
|
||||
@@ -171,14 +172,6 @@ export default function ReportsPage() {
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('sie_moved_hint')}{' '}
|
||||
<Link href="/import?view=export#sie-export" className="text-foreground underline underline-offset-4 decoration-muted-foreground/40 hover:decoration-foreground">
|
||||
{t('sie_moved_link')}
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
|
||||
{isLoadingInit ? (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
@@ -247,7 +240,12 @@ export default function ReportsPage() {
|
||||
{activeTab === 'balance-sheet' && (
|
||||
<BalanceSheetView periodId={selectedPeriod} dateRange={dateRange} onNavigateToAccount={navigateToAccount} />
|
||||
)}
|
||||
{activeTab === 'vat-declaration' && <VatDeclarationView />}
|
||||
{activeTab === 'vat-declaration' && (
|
||||
<VatDeclarationView
|
||||
fiscalPeriodId={selectedPeriod}
|
||||
fiscalPeriodBounds={selectedPeriodBounds}
|
||||
/>
|
||||
)}
|
||||
{activeTab === 'periodisk-sammanstallning' && <PeriodiskSammanstallningView />}
|
||||
{isEnskildFirma && activeTab === 'ne-declaration' && (
|
||||
<NEDeclarationView periodId={selectedPeriod} />
|
||||
@@ -1273,7 +1271,18 @@ function ReportSectionTable({
|
||||
)
|
||||
}
|
||||
|
||||
function VatDeclarationView() {
|
||||
// Carries the selected fiscal period into the ruta drill-down rows so their
|
||||
// source-verifikat query matches the report's period. Only set for yearly
|
||||
// (räkenskapsår); undefined for monthly/quarterly (calendar periods).
|
||||
const VatDrillContext = React.createContext<{ fiscalPeriodId?: string }>({})
|
||||
|
||||
function VatDeclarationView({
|
||||
fiscalPeriodId,
|
||||
fiscalPeriodBounds,
|
||||
}: {
|
||||
fiscalPeriodId: string
|
||||
fiscalPeriodBounds: { start: string; end: string } | null
|
||||
}) {
|
||||
const currentYear = new Date().getFullYear()
|
||||
const currentMonth = new Date().getMonth() + 1
|
||||
const currentQuarter = Math.ceil(currentMonth / 3)
|
||||
@@ -1285,6 +1294,25 @@ function VatDeclarationView() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// Default the periodicity to the company's configured VAT reporting period
|
||||
// (moms_period in Inställningar) so the picker mirrors the setting instead of
|
||||
// always starting on quarterly. Applied once per company the first time its
|
||||
// settings load; a later manual change to the picker is preserved, and a
|
||||
// company switch re-applies the new company's setting. `useSettings` only
|
||||
// refetches when the active company changes, so this never clobbers a manual
|
||||
// selection mid-session.
|
||||
const { settings } = useSettings()
|
||||
const appliedForCompany = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
const momsPeriod = settings?.moms_period
|
||||
const companyId = settings?.company_id
|
||||
if (!momsPeriod || !companyId) return
|
||||
if (appliedForCompany.current === companyId) return
|
||||
appliedForCompany.current = companyId
|
||||
setPeriodType(momsPeriod)
|
||||
// `period` is reset to a sensible value by the periodType effect below.
|
||||
}, [settings])
|
||||
|
||||
// Generate year options (last 5 years)
|
||||
const yearOptions = Array.from({ length: 5 }, (_, i) => currentYear - i)
|
||||
|
||||
@@ -1331,12 +1359,26 @@ function VatDeclarationView() {
|
||||
}
|
||||
}, [periodType, currentMonth, currentQuarter])
|
||||
|
||||
// Annual VAT (helårsmoms) is reported per räkenskapsår, not per calendar year.
|
||||
// For yearly we pass the selected fiscal period so the API uses its actual
|
||||
// bounds (handles extended/shortened years); monthly/quarterly stay calendar.
|
||||
const isYearly = periodType === 'yearly'
|
||||
const vatQueryString = () => {
|
||||
const params = new URLSearchParams({
|
||||
periodType,
|
||||
year: String(year),
|
||||
period: String(period),
|
||||
})
|
||||
if (isYearly && fiscalPeriodId) params.set('fiscal_period_id', fiscalPeriodId)
|
||||
return params.toString()
|
||||
}
|
||||
|
||||
const fetchDeclaration = async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/reports/vat-declaration?periodType=${periodType}&year=${year}&period=${period}`
|
||||
`/api/reports/vat-declaration?${vatQueryString()}`
|
||||
)
|
||||
const result = await res.json()
|
||||
if (result.error) {
|
||||
@@ -1352,12 +1394,13 @@ function VatDeclarationView() {
|
||||
}
|
||||
|
||||
return (
|
||||
<VatDrillContext.Provider value={{ fiscalPeriodId: isYearly ? fiscalPeriodId : undefined }}>
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/vat-declaration/xlsx?periodType=${periodType}&year=${year}&period=${period}`, '_blank')}
|
||||
onClick={() => window.open(`/api/reports/vat-declaration/xlsx?${vatQueryString()}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
@@ -1387,34 +1430,49 @@ function VatDeclarationView() {
|
||||
<option value="yearly">Årsvis</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>År</Label>
|
||||
<select
|
||||
value={year}
|
||||
onChange={(e) => setYear(parseInt(e.target.value))}
|
||||
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
{yearOptions.map((y) => (
|
||||
<option key={y} value={y}>
|
||||
{y}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Period</Label>
|
||||
<select
|
||||
value={period}
|
||||
onChange={(e) => setPeriod(parseInt(e.target.value))}
|
||||
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
{getPeriodOptions().map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{isYearly ? (
|
||||
// Annual VAT covers the selected räkenskapsår — driven by the
|
||||
// fiscal-year picker at the top of the page, not a calendar year.
|
||||
<div>
|
||||
<Label>Räkenskapsår</Label>
|
||||
<div className="mt-1 rounded-md border border-input bg-muted/40 px-3 py-2 text-sm tabular-nums">
|
||||
{fiscalPeriodBounds
|
||||
? `${formatDate(fiscalPeriodBounds.start)} – ${formatDate(fiscalPeriodBounds.end)}`
|
||||
: '—'}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<Label>År</Label>
|
||||
<select
|
||||
value={year}
|
||||
onChange={(e) => setYear(parseInt(e.target.value))}
|
||||
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
{yearOptions.map((y) => (
|
||||
<option key={y} value={y}>
|
||||
{y}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Period</Label>
|
||||
<select
|
||||
value={period}
|
||||
onChange={(e) => setPeriod(parseInt(e.target.value))}
|
||||
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
{getPeriodOptions().map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<Button onClick={fetchDeclaration} disabled={loading}>
|
||||
{loading ? 'Laddar...' : 'Hämta'}
|
||||
</Button>
|
||||
@@ -1646,13 +1704,29 @@ function VatDeclarationView() {
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</VatDrillContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function makeVatFetcher(ruta: string, periodType: VatPeriodType, year: number, period: number): ReportSourceFetcher {
|
||||
function makeVatFetcher(
|
||||
ruta: string,
|
||||
periodType: VatPeriodType,
|
||||
year: number,
|
||||
period: number,
|
||||
fiscalPeriodId?: string,
|
||||
): ReportSourceFetcher {
|
||||
return async () => {
|
||||
const params = new URLSearchParams({
|
||||
periodType,
|
||||
year: String(year),
|
||||
period: String(period),
|
||||
})
|
||||
// Yearly drill-down resolves against the räkenskapsår, matching the report.
|
||||
if (periodType === 'yearly' && fiscalPeriodId) {
|
||||
params.set('fiscal_period_id', fiscalPeriodId)
|
||||
}
|
||||
const res = await fetch(
|
||||
`/api/reports/vat-declaration/ruta/${encodeURIComponent(ruta)}/sources?periodType=${periodType}&year=${year}&period=${period}`
|
||||
`/api/reports/vat-declaration/ruta/${encodeURIComponent(ruta)}/sources?${params.toString()}`
|
||||
)
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error || 'Kunde inte hämta verifikat')
|
||||
@@ -1680,10 +1754,11 @@ function VatRutaRow({
|
||||
year?: number
|
||||
period?: number
|
||||
}) {
|
||||
const { fiscalPeriodId } = React.useContext(VatDrillContext)
|
||||
const canDrill = periodType !== undefined && year !== undefined && period !== undefined
|
||||
const fetcher = React.useMemo(
|
||||
() => (canDrill ? makeVatFetcher(ruta, periodType!, year!, period!) : null),
|
||||
[canDrill, ruta, periodType, year, period]
|
||||
() => (canDrill ? makeVatFetcher(ruta, periodType!, year!, period!, fiscalPeriodId) : null),
|
||||
[canDrill, ruta, periodType, year, period, fiscalPeriodId]
|
||||
)
|
||||
// Hooks must be called unconditionally — provide a noop fetcher when drill
|
||||
// is disabled. The early-return for zero rows lives below the hooks.
|
||||
|
||||
@@ -24,8 +24,7 @@ import { cn, formatCurrency } from '@/lib/utils'
|
||||
import { useUnsavedChanges } from '@/lib/hooks/use-unsaved-changes'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import BankTransactionPicker from '@/components/transactions/BankTransactionPicker'
|
||||
import CreatePeriodDialog from '@/components/bookkeeping/CreatePeriodDialog'
|
||||
import { ArrowLeft, Plus, Trash2, ChevronDown, Loader2, Lock, AlertCircle, AlertTriangle, CalendarPlus, MessageCircle, Link2 } from 'lucide-react'
|
||||
import { ArrowLeft, Plus, Trash2, ChevronDown, Loader2, Lock, AlertCircle, MessageCircle, Link2 } from 'lucide-react'
|
||||
import type { Supplier, BASAccount, VatTreatment, EntityType, InvoiceExtractionResult, FiscalPeriod } from '@/types'
|
||||
|
||||
interface LineItem {
|
||||
@@ -33,6 +32,9 @@ interface LineItem {
|
||||
amount: number
|
||||
account_number: string
|
||||
vat_rate: number
|
||||
// Self-assessed VAT rate for omvänd skattskyldighet (0.25/0.12/0.06). Only
|
||||
// meaningful when reverse_charge is on; the line's vat_rate is then 0.
|
||||
reverse_charge_rate?: number
|
||||
}
|
||||
|
||||
interface FormData {
|
||||
@@ -184,6 +186,26 @@ function VatRateCell({ value, onChange }: { value: number; onChange: (v: number)
|
||||
)
|
||||
}
|
||||
|
||||
// Self-assessment rate picker shown in place of the Momssats cell when an
|
||||
// invoice is reverse charge. The supplier charges no VAT (the line vat_rate is
|
||||
// 0); this is the Swedish statutory rate the buyer self-assesses at — 25%
|
||||
// huvudregeln for EU services, 12%/6% for reduced-rated services (ML 6 kap 34 §).
|
||||
function RcRateSelect({ value, onChange }: { value: number; onChange: (v: number) => void }) {
|
||||
const t = useTranslations('supplier_invoice_editor')
|
||||
return (
|
||||
<Select value={String(value ?? 0.25)} onValueChange={(v) => onChange(parseFloat(v))}>
|
||||
<SelectTrigger className="h-9 tabular-nums" aria-label={t('col_rc_vat_rate')}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0.25" className="tabular-nums">25 %</SelectItem>
|
||||
<SelectItem value="0.12" className="tabular-nums">12 %</SelectItem>
|
||||
<SelectItem value="0.06" className="tabular-nums">6 %</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
const EMPTY_NEW_SUPPLIER: NewSupplierForm = {
|
||||
name: '',
|
||||
supplier_type: 'swedish_business',
|
||||
@@ -221,7 +243,6 @@ export default function NewSupplierInvoicePage() {
|
||||
const [accountingMethod, setAccountingMethod] = useState<'accrual' | 'cash'>('accrual')
|
||||
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
|
||||
const [periodsLoaded, setPeriodsLoaded] = useState(false)
|
||||
const [showCreatePeriod, setShowCreatePeriod] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [showReview, setShowReview] = useState(false)
|
||||
const [pendingData, setPendingData] = useState<FormData | null>(null)
|
||||
@@ -268,7 +289,7 @@ export default function NewSupplierInvoicePage() {
|
||||
payment_reference: '',
|
||||
notes: '',
|
||||
paid_with_private_funds: false,
|
||||
items: [{ description: '', amount: 0, account_number: '5010', vat_rate: 0.25 }],
|
||||
items: [{ description: '', amount: 0, account_number: '5010', vat_rate: 0.25, reverse_charge_rate: 0.25 }],
|
||||
},
|
||||
})
|
||||
|
||||
@@ -559,7 +580,10 @@ export default function NewSupplierInvoicePage() {
|
||||
|
||||
const itemTotals = (watchedItems || []).map((item) => {
|
||||
const lineTotal = Math.round((item.amount || 0) * 100) / 100
|
||||
const vatAmount = Math.round(lineTotal * (item.vat_rate || 0) * 100) / 100
|
||||
// Reverse charge: VAT is self-assessed at reverse_charge_rate (25% default),
|
||||
// not the line's vat_rate (which is 0 — the supplier charged nothing).
|
||||
const effectiveRate = watchedReverseCharge ? (item.reverse_charge_rate ?? 0.25) : (item.vat_rate || 0)
|
||||
const vatAmount = Math.round(lineTotal * effectiveRate * 100) / 100
|
||||
return { lineTotal, vatAmount }
|
||||
})
|
||||
const subtotal = itemTotals.reduce((sum, t) => sum + t.lineTotal, 0)
|
||||
@@ -660,7 +684,10 @@ export default function NewSupplierInvoicePage() {
|
||||
description: item.description,
|
||||
amount: item.amount,
|
||||
account_number: item.account_number,
|
||||
vat_rate: item.vat_rate,
|
||||
// Reverse charge: the supplier charges no VAT, so the line rate is 0 and
|
||||
// the self-assessed rate travels on reverse_charge_rate (25% default).
|
||||
vat_rate: data.reverse_charge ? 0 : item.vat_rate,
|
||||
reverse_charge_rate: data.reverse_charge ? (item.reverse_charge_rate ?? 0.25) : undefined,
|
||||
})),
|
||||
}
|
||||
}
|
||||
@@ -731,6 +758,20 @@ export default function NewSupplierInvoicePage() {
|
||||
}
|
||||
|
||||
function onSubmit(data: FormData) {
|
||||
// Hard block: under faktureringsmetoden (and for privately-paid kvitton) a
|
||||
// verifikation is posted at registration, and BFL 5 kap kräver att
|
||||
// verifikationsnumret ligger i en obruten serie inom ett räkenskapsår. No
|
||||
// räkenskapsår for the invoice date → no compliant voucher can exist, so we
|
||||
// refuse rather than register an unbooked invoice. Kontantmetoden books at
|
||||
// payment, so it is intentionally not blocked here (see showNoPeriodWarning).
|
||||
if (showNoPeriodWarning) {
|
||||
toast({
|
||||
title: t('warning_title'),
|
||||
description: t('no_period_warning', { date: data.invoice_date }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
if (!data.supplier_id) {
|
||||
toast({ title: t('supplier_missing_title'), description: t('supplier_missing_description'), variant: 'destructive' })
|
||||
return
|
||||
@@ -1166,22 +1207,15 @@ export default function NewSupplierInvoicePage() {
|
||||
</div>
|
||||
|
||||
{showNoPeriodWarning && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-warning/30 bg-warning/10 p-3">
|
||||
<AlertTriangle className="h-5 w-5 text-warning-foreground mt-0.5 shrink-0" />
|
||||
<div className="flex-1 text-sm text-warning-foreground">
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 p-3"
|
||||
>
|
||||
<AlertCircle className="h-5 w-5 text-destructive mt-0.5 shrink-0" />
|
||||
<div className="flex-1 text-sm text-destructive">
|
||||
<p className="font-medium">{t('no_period_warning', { date: watchedInvoiceDate })}</p>
|
||||
<p className="mt-0.5">{t('no_period_help')}</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowCreatePeriod(true)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<CalendarPlus className="h-3.5 w-3.5 mr-1.5" />
|
||||
{t('create_period')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
@@ -1197,7 +1231,7 @@ export default function NewSupplierInvoicePage() {
|
||||
size="sm"
|
||||
className="w-full sm:w-auto"
|
||||
onClick={() =>
|
||||
append({ description: '', amount: 0, account_number: '', vat_rate: 0.25 })
|
||||
append({ description: '', amount: 0, account_number: '', vat_rate: 0.25, reverse_charge_rate: 0.25 })
|
||||
}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
@@ -1282,8 +1316,8 @@ export default function NewSupplierInvoicePage() {
|
||||
<th className="pb-2 w-28">{t('col_account')}</th>
|
||||
<th className="pb-2">{t('col_description')}</th>
|
||||
<th className="pb-2 w-32">{t('col_amount_excl')}</th>
|
||||
<th className="pb-2 w-36">{t('col_vat_rate')}</th>
|
||||
<th className="pb-2 w-24 text-right">{t('col_vat')}</th>
|
||||
<th className="pb-2 w-36">{watchedReverseCharge ? t('col_rc_vat_rate') : t('col_vat_rate')}</th>
|
||||
<th className="pb-2 w-24 text-right">{watchedReverseCharge ? t('col_rc_vat') : t('col_vat')}</th>
|
||||
<th className="pb-2 w-8"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -1336,13 +1370,23 @@ export default function NewSupplierInvoicePage() {
|
||||
/>
|
||||
</td>
|
||||
<td className="py-2 pr-2">
|
||||
<Controller
|
||||
name={`items.${index}.vat_rate`}
|
||||
control={control}
|
||||
render={({ field: f }) => (
|
||||
<VatRateCell value={f.value} onChange={f.onChange} />
|
||||
)}
|
||||
/>
|
||||
{watchedReverseCharge ? (
|
||||
<Controller
|
||||
name={`items.${index}.reverse_charge_rate`}
|
||||
control={control}
|
||||
render={({ field: f }) => (
|
||||
<RcRateSelect value={f.value ?? 0.25} onChange={f.onChange} />
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<Controller
|
||||
name={`items.${index}.vat_rate`}
|
||||
control={control}
|
||||
render={({ field: f }) => (
|
||||
<VatRateCell value={f.value} onChange={f.onChange} />
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-2 pr-2 text-right tabular-nums text-muted-foreground">
|
||||
{formatAmount(itemTotals[index]?.vatAmount ?? 0)}
|
||||
@@ -1418,18 +1462,28 @@ export default function NewSupplierInvoicePage() {
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">{t('col_vat_rate')}</Label>
|
||||
<Controller
|
||||
name={`items.${index}.vat_rate`}
|
||||
control={control}
|
||||
render={({ field: f }) => (
|
||||
<VatRateCell value={f.value} onChange={f.onChange} />
|
||||
)}
|
||||
/>
|
||||
<Label className="text-xs text-muted-foreground">{watchedReverseCharge ? t('col_rc_vat_rate') : t('col_vat_rate')}</Label>
|
||||
{watchedReverseCharge ? (
|
||||
<Controller
|
||||
name={`items.${index}.reverse_charge_rate`}
|
||||
control={control}
|
||||
render={({ field: f }) => (
|
||||
<RcRateSelect value={f.value ?? 0.25} onChange={f.onChange} />
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<Controller
|
||||
name={`items.${index}.vat_rate`}
|
||||
control={control}
|
||||
render={({ field: f }) => (
|
||||
<VatRateCell value={f.value} onChange={f.onChange} />
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="pt-1 border-t flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">{t('col_vat')}</span>
|
||||
<span className="text-xs text-muted-foreground">{watchedReverseCharge ? t('col_rc_vat') : t('col_vat')}</span>
|
||||
<span className="tabular-nums text-muted-foreground">
|
||||
{formatAmount(itemTotals[index]?.vatAmount ?? 0)}
|
||||
</span>
|
||||
@@ -1515,7 +1569,7 @@ export default function NewSupplierInvoicePage() {
|
||||
type="submit"
|
||||
variant="outline"
|
||||
className="w-full sm:w-auto"
|
||||
disabled={isSubmitting || !canWrite}
|
||||
disabled={isSubmitting || !canWrite || showNoPeriodWarning}
|
||||
onClick={() => { submitModeRef.current = 'register_and_match' }}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
@@ -1525,7 +1579,7 @@ export default function NewSupplierInvoicePage() {
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || !canWrite}
|
||||
disabled={isSubmitting || !canWrite || showNoPeriodWarning}
|
||||
className="w-full sm:w-auto"
|
||||
onClick={() => { submitModeRef.current = 'register' }}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
@@ -1733,14 +1787,6 @@ export default function NewSupplierInvoicePage() {
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<CreatePeriodDialog
|
||||
open={showCreatePeriod}
|
||||
onOpenChange={setShowCreatePeriod}
|
||||
entryDate={watchedInvoiceDate}
|
||||
periods={periods}
|
||||
onCreated={fetchPeriods}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,10 @@ export const GET = withRouteContext(
|
||||
const periodType = searchParams.get('periodType') as VatPeriodType | null
|
||||
const yearStr = searchParams.get('year')
|
||||
const periodStr = searchParams.get('period')
|
||||
// For yearly (helårsmoms) the period is the räkenskapsår, not the calendar
|
||||
// year; the client passes the selected fiscal period so an extended year is
|
||||
// covered in full. Ignored for monthly/quarterly (calendar periods).
|
||||
const fiscalPeriodId = searchParams.get('fiscal_period_id') ?? undefined
|
||||
|
||||
if (!periodType || !yearStr || !periodStr) {
|
||||
return errorResponseFromCode('VAT_REPORT_MISSING_PARAMS', log, { requestId })
|
||||
@@ -83,11 +87,14 @@ export const GET = withRouteContext(
|
||||
try {
|
||||
const declaration = await calculateVatDeclaration(
|
||||
supabase, companyId!, periodType, year, period, accountingMethod,
|
||||
{ fiscalPeriodId },
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
...declaration,
|
||||
// For yearly the authoritative span is declaration.period.start/end
|
||||
// (the räkenskapsår). The label stays a coarse "Helår {year}".
|
||||
periodLabel: formatPeriodLabel(periodType, year, period),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -38,6 +38,8 @@ export async function GET(request: Request) {
|
||||
const periodType = searchParams.get('periodType') as VatPeriodType | null
|
||||
const yearStr = searchParams.get('year')
|
||||
const periodStr = searchParams.get('period')
|
||||
// Yearly = räkenskapsår (see main route); ignored for monthly/quarterly.
|
||||
const fiscalPeriodId = searchParams.get('fiscal_period_id') ?? undefined
|
||||
|
||||
if (!periodType || !yearStr || !periodStr) {
|
||||
return NextResponse.json(
|
||||
@@ -73,6 +75,7 @@ export async function GET(request: Request) {
|
||||
try {
|
||||
const declaration = await calculateVatDeclaration(
|
||||
supabase, companyId, periodType, year, period, accountingMethod,
|
||||
{ fiscalPeriodId },
|
||||
)
|
||||
|
||||
const rows: RutaRow[] = (Object.keys(declaration.rutor) as (keyof VatDeclarationRutor)[]).map(
|
||||
|
||||
@@ -82,6 +82,9 @@ export const POST = withRouteContext(
|
||||
vat_code: item.vat_code,
|
||||
vat_rate: item.vat_rate,
|
||||
vat_amount: item.vat_amount,
|
||||
// Preserve the self-assessed RC rate so the credit-note verifikat
|
||||
// reverses fiktiv moms at the same rate the original was booked at.
|
||||
reverse_charge_rate: item.reverse_charge_rate,
|
||||
}))
|
||||
|
||||
await supabase.from('supplier_invoice_items').insert(creditItems)
|
||||
|
||||
@@ -208,6 +208,7 @@ describe('POST /api/supplier-invoices/[id]/mark-paid', () => {
|
||||
vat_code: null,
|
||||
vat_rate: 0.25,
|
||||
vat_amount: 2000,
|
||||
reverse_charge_rate: null,
|
||||
created_at: '2024-06-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
|
||||
@@ -132,6 +132,10 @@ export const POST = withRouteContext(
|
||||
vat_code: item.vat_code || null,
|
||||
vat_rate: vatRate,
|
||||
vat_amount: vatAmount,
|
||||
// Self-assessed RC rate (0.06/0.12/0.25) or null. For reverse charge the
|
||||
// supplier charges no VAT (vat_rate stays 0); the engine self-assesses
|
||||
// at this rate, defaulting to 25% huvudregeln when null.
|
||||
reverse_charge_rate: body.reverse_charge ? (item.reverse_charge_rate ?? null) : null,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ const SI_FULL_COLUMNS = `
|
||||
vat_treatment, reverse_charge, remaining_amount,
|
||||
is_credit_note, credited_invoice_id, arrival_number,
|
||||
supplier:suppliers(id, name, supplier_type),
|
||||
items:supplier_invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount)
|
||||
items:supplier_invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount, reverse_charge_rate)
|
||||
`
|
||||
|
||||
const SupplierInvoiceCredited = z.object({
|
||||
@@ -166,6 +166,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
vat_code: string | null
|
||||
vat_rate: number
|
||||
vat_amount: number
|
||||
reverse_charge_rate: number | null
|
||||
}>
|
||||
} & Record<string, unknown>
|
||||
|
||||
@@ -215,6 +216,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
vat_code: item.vat_code,
|
||||
vat_rate: item.vat_rate,
|
||||
vat_amount: item.vat_amount,
|
||||
reverse_charge_rate: item.reverse_charge_rate,
|
||||
}))
|
||||
return dryRunPreview(
|
||||
{
|
||||
@@ -306,6 +308,9 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
vat_code: item.vat_code,
|
||||
vat_rate: item.vat_rate,
|
||||
vat_amount: item.vat_amount,
|
||||
// Preserve the self-assessed RC rate so the credit note reverses fiktiv
|
||||
// moms at the same rate the original was booked at.
|
||||
reverse_charge_rate: item.reverse_charge_rate,
|
||||
}))
|
||||
if (creditItems.length > 0) {
|
||||
const { error: itemsErr } = await ctx.supabase
|
||||
|
||||
@@ -169,7 +169,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
subtotal, subtotal_sek, vat_amount, vat_amount_sek, total_sek, due_date, received_date,
|
||||
is_credit_note, credited_invoice_id, payment_journal_entry_id,
|
||||
supplier:suppliers(id, name, supplier_type),
|
||||
items:supplier_invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount)
|
||||
items:supplier_invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount, reverse_charge_rate)
|
||||
`)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.eq('id', invoiceId)
|
||||
|
||||
@@ -34,7 +34,7 @@ const SI_DETAIL_COLUMNS =
|
||||
'id, supplier_id, arrival_number, supplier_invoice_number, invoice_date, due_date, received_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, reverse_charge, payment_reference, paid_at, paid_amount, remaining_amount, is_credit_note, credited_invoice_id, registration_journal_entry_id, payment_journal_entry_id, transaction_id, document_id, notes, reversed_at, created_at, updated_at'
|
||||
|
||||
const SI_ITEM_COLUMNS =
|
||||
'id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount'
|
||||
'id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount, reverse_charge_rate'
|
||||
|
||||
const SI_PAYMENT_COLUMNS =
|
||||
'id, payment_date, amount, currency, exchange_rate, exchange_rate_difference, journal_entry_id, transaction_id, notes, created_at'
|
||||
|
||||
@@ -264,7 +264,7 @@ const SI_RESPONSE_COLUMNS =
|
||||
'id, supplier_id, arrival_number, supplier_invoice_number, invoice_date, due_date, received_date, delivery_date, status, currency, exchange_rate, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, reverse_charge, payment_reference, paid_amount, remaining_amount, is_credit_note, credited_invoice_id, registration_journal_entry_id, payment_journal_entry_id, notes, created_at, updated_at'
|
||||
|
||||
const SI_ITEMS_RESPONSE_COLUMNS =
|
||||
'id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount'
|
||||
'id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount, reverse_charge_rate'
|
||||
|
||||
const SupplierInvoiceCreated = z.object({
|
||||
id: z.string().uuid(),
|
||||
@@ -345,6 +345,7 @@ interface ComputedItem {
|
||||
vat_code: string | null
|
||||
vat_rate: number
|
||||
vat_amount: number
|
||||
reverse_charge_rate: number | null
|
||||
}
|
||||
|
||||
// Swedish VAT rates per ML 2 kap 1 § + Skatteverket's 2026 satser. Allow
|
||||
@@ -385,6 +386,10 @@ function computeItemsAndTotals(input: z.infer<typeof CreateSupplierInvoiceSchema
|
||||
vat_code: item.vat_code || null,
|
||||
vat_rate: vatRate,
|
||||
vat_amount: vatAmount,
|
||||
// Self-assessed RC rate (0.06/0.12/0.25) or null. For reverse charge the
|
||||
// line vat_rate is 0 (validated below); the engine self-assesses at this
|
||||
// rate, defaulting to 25% huvudregeln when null.
|
||||
reverse_charge_rate: item.reverse_charge_rate ?? null,
|
||||
})
|
||||
}
|
||||
const subtotal = items.reduce((sum, i) => sum + i.line_total, 0)
|
||||
|
||||
Reference in New Issue
Block a user