Files
accounted/extensions/general/skatteverket/lib/declaration-prep.ts
T
MattssonandClaude Fable 5 288915c152 Fix/fdb fr usrs (#1125)
* fix(invoices): return attachment filename in delivery history summaries

The 20260723003000 hardening dropped attachment_filename from
list_invoice_delivery_summaries, so the delivery history UI always fell
back to the generic "faktura.pdf" label. Recreate the RPC with the
filename included: it is derived from company name, customer name,
invoice number, and date, all already visible to every company member,
so the minimization boundary is unchanged. Addresses stay masked and
message content, BCC, and checksums stay server-side.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(reconciliation): surface own-account transfer legs in match-to-voucher by default

The second (incoming) leg of a transfer between two of the company's own
bank accounts was hidden in the 'Matcha mot befintlig verifikation' dialog
because the voucher counted as 'already matched' once its outgoing leg was
linked, even though the incoming account's line had no settling transaction.
Users read the empty default list as 'the app won't let me link this'.

get_account_gl_lines_for_matching now counts links per settlement account:
a transaction provably on another cash account no longer marks the voucher
as matched for the requested account, so the unsettled transfer leg surfaces
by default (and auto-selects on an exact match). Same-account N:1 stays
behind the 'Visa aven matchade verifikationer' opt-in, and transactions
without a resolvable cash account conservatively keep counting everywhere.
get_unlinked_gl_lines is deliberately untouched (feeds auto-reconcile).

Companion guard: mark_entry_as_opening_balance now refuses entries with
linked bank transactions, since half-settled transfer vouchers became
reachable in the reconciliation view's unmatched table where 'Mark som IB'
renders; re-tagging one would strand its transaction against a movement-
excluded entry. getReconciliationStatus counts unmatched GL lines with the
account-scoped RPC so the status card agrees with the table.

Fixes #1026

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf(api): cut prod p95 latency via local JWT auth, single-RT company resolution, and report aggregate RPCs

Baseline 2026-07-23 (487 prod samples): p50 160ms, p95 480ms, 13% of
requests over 300ms. Target: p95 under 300ms.

- requireAuth: verify JWTs locally via getClaims (ES256/JWKS) instead of
  a second network getUser per request; getUser fallback keeps HS256
  self-hosted and existing test mocks working; middleware still
  revocation-checks every /api request
- resolve_active_company RPC (20260723161000): one round trip replaces
  2-3 queries in getActiveCompanyId and middleware; PGRST202/42501 fall
  back to the legacy query path
- arsredovisning build-data: ~33 sequential round trips down to ~7,
  output byte-identical (snapshot-proven)
- currency rate route: stop bypassing the exchange_rates cache (missing
  supabase arg caused an external Riksbanken call on every request)
- document.get: parallelize row fetch, signed URL and audit event
- list_company_accounts RPC (20260723170000): accounts list in one round
  trip instead of paging past PostgREST's 1000-row cap
- vat-declaration route: drop a dead sequential company_settings query
- get_kpi_report_aggregates RPC (20260723180000): KPI report's three
  full-period line scans collapsed into one aggregate call; dimension-
  filtered path unchanged
- lint: fix 9 baseline errors, downgrade 4 react-hooks compiler rules to
  warn, zero the eslint baseline ratchet

All four gates green: lint 0 errors, 9163 tests, check:guards, build.
Migrations applied idempotently to staging only; prod receives them via
Supabase branching on merge.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): resolve PR review findings across auth, VAT declaration, and IB retag

- requireAuth getClaims fast path: pin iss (project URL) and aud
  ('authenticated'), log every fallback to getUser (ASVS V9.1 finding)
- remove the ignored accountingMethod parameter from calculateVatDeclaration
  and the dead company_settings.accounting_method reads in xlsx/pdf/eskd
  routes; v1 API keeps accepting the query param but documents it as a no-op
- close the mark_entry_as_opening_balance TOCTOU race with a transactions
  trigger (20260723190000, FOR KEY SHARE on journal_entries) + pg tests;
  applied to staging and smoke-verified both directions
- re-add the 42501 tenant guard to branch-local migration 20260723160000
  (function body had silently reverted to the pre-20260619130100 definition)
- document the buildK3Noter tbFullRows full-TB contract (uppskjuten skatt
  opening balance per BFNAR 2012:1 ch.29)
- add KPI VAT-liability test covering reduced-rate output accounts 2621/2631

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): use NULL-safe caller_is_company_member in opening-balance retag guard

The re-added tenant guard carried the pre-20260703180000 raw
NOT IN (SELECT user_company_ids()) pattern, which the
null-safe-tenant-guards ratchet blocks. Staging re-synced.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:16:55 +02:00

166 lines
5.7 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import type { VatPeriodType } from '@/types'
import { calculateVatDeclaration, resolvePeriodDates } from '@/lib/reports/vat-declaration'
import { rutorToMomsuppgift, formatRedovisare, formatRedovisningsperiod } from './mappers'
import type { SkatteverketMomsuppgift } from '../types'
/**
* Request-free Skatteverket declaration prep.
*
* These functions are the single source of truth for what gets filed to
* Skatteverket. They are shared by the HTTP route handlers
* (parseDeclarationRequest / loadAGIXml) and the commit-side services
* (commitSubmitVatDeclaration / commitSubmitAgi) so the numbers and XML
* computed at preview time match exactly what is filed at commit time.
*
* Compliance-critical: drift between the two paths would mean different
* figures filed to SKV than the user reviewed. Keep these the only place that
* computes momsuppgift / loads AGI XML.
*/
export interface VatDeclarationPrep {
redovisare: string
redovisningsperiod: string
momsuppgift: SkatteverketMomsuppgift
}
export interface AgiUnderlagPrep {
arbetsgivare: string
period: string // YYYYMM
salaryRunId: string
xml: string
periodYear: number
periodMonth: number
}
/**
* Resolve a company's 12-digit "redovisare" string from company_settings.
* Shared by the VAT and AGI paths and by the status tools that only need the
* identifier (no momsuppgift / XML compute).
*/
export async function resolveRedovisare(
supabase: SupabaseClient,
companyId: string,
): Promise<string> {
const { data: settings } = await supabase
.from('company_settings')
.select('org_number, entity_type')
.eq('company_id', companyId)
.single()
if (!settings?.org_number) {
throw new Error('Organisationsnummer saknas i företagsinställningar')
}
return formatRedovisare(settings.org_number, settings.entity_type)
}
/**
* Compute the momsuppgift filed to SKV for a period, from the general ledger.
* Body lifted verbatim from the former parseDeclarationRequest so route and
* commit paths produce identical payloads.
*/
export async function buildMomsuppgift(
supabase: SupabaseClient,
companyId: string,
input: { periodType: VatPeriodType; year: number; period: number; fiscalPeriodId?: string },
): Promise<VatDeclarationPrep> {
const { periodType, year, period, fiscalPeriodId } = input
const redovisare = await resolveRedovisare(supabase, companyId)
// Helårsmoms is filed per räkenskapsår (SFL 26 kap 10-11 §§): the SKV
// redovisningsperiod is the FY-end month, which for a broken fiscal year is
// not December. Resolve the fiscal period's actual bounds so the period
// identifier and the figures below always describe the same räkenskapsår.
let fiscalYearEnd: { year: number; month: number } | undefined
if (periodType === 'yearly') {
const { end } = await resolvePeriodDates(
supabase, companyId, periodType, year, period, fiscalPeriodId,
)
fiscalYearEnd = { year: Number(end.slice(0, 4)), month: Number(end.slice(5, 7)) }
}
const redovisningsperiod = formatRedovisningsperiod(periodType, year, period, fiscalYearEnd)
// Calculate VAT declaration from the general ledger
const declaration = await calculateVatDeclaration(
supabase,
companyId,
periodType,
year,
period,
{ fiscalPeriodId },
)
const momsuppgift = rutorToMomsuppgift(declaration.rutor)
return { redovisare, redovisningsperiod, momsuppgift }
}
/**
* Load the AGI XML for a salary run from agi_declarations.xml_content
* (built by app/api/salary/runs/[id]/agi/xml/route.ts via generateAGIXml),
* alongside the formatted arbetsgivare/period strings used downstream by the
* granskningsunderlag and kvittenser calls.
*
* Body lifted verbatim from the former loadAGIXml: including the salary-run
* status guard (per BFL 5 kap and SFL 26 kap, AGI must reflect finalised
* payroll data; submitting from a draft/cancelled run would emit incorrect
* figures and require a costly rättelse).
*/
export async function buildAgiUnderlag(
supabase: SupabaseClient,
companyId: string,
salaryRunId: string,
): Promise<AgiUnderlagPrep> {
if (!salaryRunId) {
throw new Error('Saknar obligatoriskt fält: salaryRunId')
}
const { data: run, error: runError } = await supabase
.from('salary_runs')
.select('status')
.eq('id', salaryRunId)
.eq('company_id', companyId)
.single()
if (runError || !run) {
throw new Error('Lönekörning hittades inte')
}
if (!['review', 'approved', 'paid', 'booked'].includes(run.status)) {
throw new Error('AGI kan bara skickas till Skatteverket efter granskning')
}
const arbetsgivare = await resolveRedovisare(supabase, companyId)
// Use the most recent agi_declarations row for this salary run: covers
// both new declarations and corrections (which overwrite xml_content
// in place per the existing /api/salary/runs/[id]/agi/xml route).
const { data: declaration, error: declarationError } = await supabase
.from('agi_declarations')
.select('xml_content, period_year, period_month')
.eq('company_id', companyId)
.eq('salary_run_id', salaryRunId)
.order('created_at', { ascending: false })
.limit(1)
.maybeSingle()
if (declarationError || !declaration?.xml_content) {
throw new Error(
'AGI-XML saknas. Generera AGI-filen först: knappen "Lämna in till Skatteverket" på lönekörningen gör det automatiskt, eller klicka "Ladda ner AGI-fil".',
)
}
const period = formatRedovisningsperiod('monthly', declaration.period_year, declaration.period_month)
return {
arbetsgivare,
period,
salaryRunId,
xml: declaration.xml_content,
periodYear: declaration.period_year,
periodMonth: declaration.period_month,
}
}