Bug/momsdeklaration skv (#449)

* fix(salary): show birthdate in masked personnummer, hide the 4-digit suffix

Flip the personnummer display format from XXXXXXXX-NNNN to YYYYMMDD-XXXX so
the sensitive 4-digit suffix is hidden while the (public) birthdate stays
visible. Affects the employees list/detail, salary run, payslip PDF, payslip
email, and the MCP server tools (list_employees, get_salary_run). Each call
site now decrypts the stored personnummer before masking.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(transactions): allow deleting unbooked transactions from "Alla transaktioner"

The history list only let users delete via the inbox card; once a category or
mall was picked but the verifikation hadn't been created, the row showed
"Ej bokförd" with no way to remove it. The API already permits delete while
journal_entry_id is null, so the gap was purely a missing UI affordance.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(vat): populate ruta 20-24 for reverse charge + dishonest "Validera OK"

Three connected issues caused Skatteverket to reject momsdeklarationer
with FK004 even after our local "Validera"-knapp returned OK.

1. supplier-invoice-entries booked fiktiv moms (2614/2624/2634 + 2645/2647)
   on reverse-charge invoices but never the underlying basbelopp on 44xx/45xx.
   Ruta 30-32 filled up at SKV while ruta 20-24 stayed at 0 — SKV's FK004
   ("silent netting prohibited", ML 13 kap kräver båda sidor).

   Fix: generateReverseChargeBasisLines in vat-entries.ts emits parallel
   45xx/44xx debit + 4598 motkonto credit per rate group. Engine calls it
   from registration, cash, and credit-note paths. Skipped when the user
   booked the expense directly on a basis account to avoid double-counting.
   4598 added to BAS reference (no migration needed; account_number is
   plain text on journal_entry_lines).

2. rutorToMomsuppgift rounded each ruta independently but computed
   summaMoms from the unrounded ruta49. SKV recomputes the sum from
   integer rutor on their side, so fractional öres caused ±1 SEK drift
   and SKV rejected with FK009.

   Fix: derive summaMoms from the already-rounded VAT-amount rutor.

3. "Validera"-knappen only confirmed SKV's internal arithmetic — a
   declaration with ruta 30-32 populated and ruta 20-24 empty validated
   fine until /utkast hit FK004. Users got a false green light.

   Fix: vat-declaration-checks.ts runs locally before the SKV call,
   blocks Validera/Spara when ERROR-level findings exist, and surfaces
   them in a separate "Lokala kontroller"-section. Success message
   reworded so SKV's OK is no longer presented as filing-ready.

Tests: 4535/4536/4531/4425 lines + 4598 motkonto on EU/non-EU/byggtjänster
RC, credit-note reversal, fractional-öres summaMoms, all four pre-flight
codes (RC_BASIS_MISSING, RC_OUTPUT_MISSING, RC_INPUT_VAT_MISMATCH,
SUMMA_MOMS_DRIFT).

Backfill for already-posted entries follows in the next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: add skattekonto matching functionality

- Enhance TransactionInboxCard to display a warning for potential 1930↔1630 transfers.
- Implement match suggestions for skattekonto transactions in the backend.
- Create SkattekontoMatchDialog component for linking skattekonto rows to existing journal entries.
- Develop SkattekontoInboxCard component to handle skattekonto transactions in the inbox.
- Introduce skattekonto-match utility functions for candidate matching and linking.
- Update types to include match suggestions and enriched transaction responses.

* refactor: reorganize skattekonto types and implement bank counterpart matching logic

* docs: update CLAUDE.md to streamline integrations and clarify architecture details

* refactor: enhance reverse charge logic to handle non-basis accounts and prevent double-counting

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-05-12 18:04:48 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent eb77ad50b5
commit 980f29dae8
33 changed files with 3337 additions and 493 deletions
+80 -8
View File
@@ -21,8 +21,12 @@ import {
ShieldAlert,
Trash2,
} from 'lucide-react'
import type { VatPeriodType } from '@/types'
import type { VatDeclarationRutor, VatPeriodType } from '@/types'
import { formatRedovisare, formatRedovisningsperiod } from '@/lib/skatteverket/format'
import {
runVatDeclarationChecks,
type VatDeclarationCheck,
} from '@/lib/reports/vat-declaration-checks'
interface SkatteverketStatus {
connected: boolean
@@ -45,6 +49,13 @@ interface SkatteverketPanelProps {
year: number
period: number
hasData: boolean
/**
* Calculated rutor for the current period. Used to run local pre-flight
* checks before Skatteverket sees the payload — SKV only validates internal
* arithmetic consistency, so we have to catch "ruta 30-32 present but
* 20-24 empty" locally before letting the user submit.
*/
rutor?: VatDeclarationRutor | null
}
function formatAmount(amount: number): string {
@@ -58,7 +69,7 @@ export function SkatteverketPanel(props: SkatteverketPanelProps) {
return <SkatteverketPanelInner {...props} />
}
function SkatteverketPanelInner({ periodType, year, period, hasData }: SkatteverketPanelProps) {
function SkatteverketPanelInner({ periodType, year, period, hasData, rutor }: SkatteverketPanelProps) {
const [status, setStatus] = useState<SkatteverketStatus | null>(null)
const [loading, setLoading] = useState(true)
const [actionLoading, setActionLoading] = useState<string | null>(null)
@@ -71,6 +82,14 @@ function SkatteverketPanelInner({ periodType, year, period, hasData }: Skattever
tidpunkt?: string
} | null>(null)
// Local sanity checks against the calculated declaration, run before any
// SKV call. SKV's "OK" only confirms arithmetic — these checks confirm
// the declaration looks plausible (no orphaned RC output, no missing
// basis, no summaMoms drift).
const localChecks: VatDeclarationCheck[] = rutor ? runVatDeclarationChecks(rutor) : []
const localErrors = localChecks.filter((c) => c.status === 'ERROR')
const localBlocked = localErrors.length > 0
const fetchStatus = useCallback(async () => {
try {
const res = await fetch('/api/extensions/ext/skatteverket/status')
@@ -133,6 +152,13 @@ function SkatteverketPanelInner({ periodType, year, period, hasData }: Skattever
}
const handleValidate = async () => {
if (localBlocked) {
setError(
'Lokala kontroller hittade fel i bokföringen. Åtgärda dessa innan ' +
'du skickar till Skatteverket.',
)
return
}
setActionLoading('validate')
setError(null)
setKontroller([])
@@ -149,13 +175,19 @@ function SkatteverketPanelInner({ periodType, year, period, hasData }: Skattever
const controls: KontrollResult[] = result.data?.kontrollResultat?.resultat || []
setKontroller(controls)
if (controls.length === 0) {
setSuccess('Valideringen godkänd — inga fel eller varningar')
// SKV's OK only confirms arithmetic — it does NOT confirm that the
// declaration is materially correct. We say so explicitly so the
// user doesn't read this as a green light for actual filing.
setSuccess(
'Skatteverket har inga tekniska invändningar mot deklarationen. ' +
'Kontrollera siffrorna i förhandsgranskningen innan du skickar in.',
)
} else {
const errors = controls.filter(k => k.status === 'ERROR')
if (errors.length > 0) {
setError(`${errors.length} valideringsfel hittades`)
} else {
setSuccess('Valideringen godkänd med varningar')
setSuccess('Skatteverket har inga tekniska invändningar (med varningar)')
}
}
}
@@ -167,6 +199,13 @@ function SkatteverketPanelInner({ periodType, year, period, hasData }: Skattever
}
const handleSaveDraft = async () => {
if (localBlocked) {
setError(
'Lokala kontroller hittade fel i bokföringen. Åtgärda dessa innan ' +
'du sparar utkastet hos Skatteverket.',
)
return
}
setActionLoading('draft')
setError(null)
try {
@@ -439,11 +478,42 @@ function SkatteverketPanelInner({ periodType, year, period, hasData }: Skattever
</div>
)}
{/* Validation results */}
{/* Local pre-flight check results — surfaced separately from SKV's
kontroller so the user knows these are gnubok's own sanity checks,
not Skatteverket's. ERRORs block the submit/validate buttons. */}
{localChecks.length > 0 && (
<div className="space-y-1.5">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Lokala kontroller
</p>
{localChecks.map((c, i) => (
<div
key={`${c.code}-${i}`}
className={`flex items-start gap-2 text-sm rounded-lg p-2.5 ${
c.status === 'ERROR'
? 'bg-destructive/5 text-destructive'
: 'bg-amber-50 text-amber-800 dark:bg-amber-950/30 dark:text-amber-200'
}`}
>
{c.status === 'ERROR' ? (
<ShieldAlert className="h-4 w-4 mt-0.5 shrink-0" />
) : (
<AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />
)}
<div>
<span className="font-mono text-xs mr-1.5">{c.code}</span>
{c.message}
</div>
</div>
))}
</div>
)}
{/* Validation results from Skatteverket */}
{kontroller.length > 0 && (
<div className="space-y-1.5">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Valideringsresultat
Skatteverkets valideringsresultat
</p>
{kontroller.map((k, i) => (
<div
@@ -513,8 +583,9 @@ function SkatteverketPanelInner({ periodType, year, period, hasData }: Skattever
variant="outline"
size="sm"
onClick={handleValidate}
disabled={!hasData || actionLoading !== null}
disabled={!hasData || localBlocked || actionLoading !== null}
className="gap-1.5"
title={localBlocked ? 'Åtgärda lokala kontrollfel innan validering' : undefined}
>
{actionLoading === 'validate' ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
@@ -528,8 +599,9 @@ function SkatteverketPanelInner({ periodType, year, period, hasData }: Skattever
variant="outline"
size="sm"
onClick={handleSaveDraft}
disabled={!hasData || actionLoading !== null}
disabled={!hasData || localBlocked || actionLoading !== null}
className="gap-1.5"
title={localBlocked ? 'Åtgärda lokala kontrollfel innan inlämning' : undefined}
>
{actionLoading === 'draft' ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />