Files
accounted/app/api/salary/ku/[year]/route.ts
T
MattssonandClaude Opus 4.8 abe9ac9d8c Fix/attributes config (#926)
* fix(git): pin LF on generated extension registry and vitest snapshots

setup:extensions and vitest write these files with LF; with
core.autocrlf=true git expects CRLF and flags them as phantom
modifications on every dev/build run.

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

* fix(security): enforce MFA on mcp-oauth consent and gate viewer storno route

mcp-oauth/authorize renders an HTML consent page and issues 303 redirects that withRouteContext cannot express, so it kept raw getUser() and thereby skipped the AAL2 gate: a password-only (AAL1) session could approve consent that mints a long-lived, MFA-bypassing API key. Add a route-local requireAal2() step-up on GET and POST; AAL1 sessions redirect to /mfa/verify, BankID users are exempt.

Separately, POST /api/reports/vat-declaration/rc-basis-gaps/fix calls correctEntry() (storno of a posted entry) but lacked requireWrite, so viewer-role members could trigger it. Add { requireWrite: true }.

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

* fix(api): route transactions endpoints through withRouteContext

Migrate the transactions routes off hand-rolled supabase.auth.getUser() onto the MFA-enforcing withRouteContext wrapper; add requireWrite on mutating handlers (book, uncategorize, attach-document, ignore, batch-match, create-from-document). Behavior and response shapes preserved; tests updated to the wrapper mock pattern.

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

* fix(api): route SIE import and bank reconciliation through withRouteContext

Migrate import/sie and reconciliation/bank routes onto the MFA-enforcing wrapper; requireWrite on mutations (import execute, create-accounts, mappings write verbs, link/unlink/run/mark-opening-balance). Reads (status, unmatched-entries) stay ungated. Response shapes preserved; tests added/updated to the wrapper mock pattern.

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

* fix(api): route salary endpoints through withRouteContext

Migrate salary employees and runs routes (plus ku, payroll-config, tax-tables) onto the MFA-enforcing wrapper; requireWrite on mutations. Personnummer masking/encryption untouched; file downloads (AGI XML, payslip PDF, payment files) keep their headers. Two payment-file GETs retain requireWrite because they stamp *_file_generated_at and previously gated viewers. Tests added/updated to the wrapper mock pattern.

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

* fix(api): route report endpoints through withRouteContext

Migrate the read-only report routes (trial balance, balansrapport, resultatrapport, income statement, ledgers, KPI, VAT declaration, salary journal, monthly breakdown, journal register, continuity check, full archive, etc.) onto the MFA-enforcing wrapper. All read-only, no requireWrite. JSON/XLSX/PDF/ZIP response bodies and headers preserved byte-for-byte; tests updated to the wrapper mock pattern.

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

* fix(api): route invoices, skatteverket, agent and extension endpoints through withRouteContext

Migrate invoices, supplier-invoices, skatteverket tax-payments, and dynamic extension routes onto the MFA-enforcing wrapper with requireWrite on mutations. The two NDJSON streaming agent routes (invoke, onboarding/stream) use requireAuth() directly (the wrapper can't wrap a streaming response) so MFA is still enforced. skatteverket payment-file GET keeps requireWrite (stamps a generated-at field). Response shapes and file headers preserved; tests added/updated.

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

* fix(api): route documents, events, team and account endpoints through withRouteContext

Migrate documents, events, kpi/preferences, vat/validate, support/contact onto the MFA-enforcing wrapper with requireWrite on mutations. account/password, team/accept and team/members use requireAuth() directly (user-level or pre-membership flows with no active company context) so MFA is still enforced. events keeps its dual API-key-or-session auth. Document retention guard untouched; tests added/updated.

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

* fix(api): route settings and pending-operations endpoints through withRouteContext

Migrate settings (api-keys, oauth-clients, booking-templates, counterparty-templates, logo, company settings) and pending-operations (commit, bulk-commit, reject, edit-before-approve) onto the MFA-enforcing wrapper with requireWrite on mutations. Credential-guarding routes keep their per-user ownership filters. Response shapes preserved; tests added/updated to the wrapper mock pattern.

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

* chore(guards): ratchet raw-route-auth baseline 119->1 after A1 migration

Lock in the withRouteContext migration so the count cannot regress. The single remaining entry, mcp-oauth/authorize, is a documented exception (HTML consent + redirects, MFA enforced via route-local step-up). Record the campaign and requireWrite decisions in DECISIONS.md.

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

* feat(vat): add eSKD momsdeklaration file export for "Deklarera via fil"

Generate the Skatteverket eSKDUpload v6.0 XML file so users can file VAT by
upload instead of typing every ruta into the form. Extract buildFiledAmounts()
as the shared whole-krona source of truth (öre truncated per SFL 22 kap 1 §) so
the XML file and the manual-filing PDF can never disagree. Adds the /eskd API
route, an XML option in the report export menu, and the upload button on the
manual-filing card. Strings in sv + en.

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

* feat(vat): add 'vat_settlement' source type and update related components

* fix(booking): adjust search input layout and enable autofocus

* fix(vat): support 12-digit org numbers and adjust emission order for eSKD file

* fix(migration): add 'vat_settlement' to journal_entries.source_type CHECK

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 09:54:46 +02:00

154 lines
6.1 KiB
TypeScript

import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { generateKU10Xml } from '@/lib/salary/ku/ku10-generator'
import type { KU10EmployeeData, KU10CompanyData } from '@/lib/salary/ku/ku10-generator'
ensureInitialized()
/**
* Generate KU10 (Kontrolluppgift) XML for a calendar year.
*
* Per Skatteförfarandelagen 15 kap: Must be filed by January 31 of the
* following year. Reports total annual income, tax, and benefits per employee.
*
* The XML is räkenskapsinformation per BFL 7 kap, 7-year retention.
*/
export const GET = withRouteContext<{ params: Promise<{ year: string }> }>(
'salary.ku.export',
async (request, { supabase, companyId, user }, { params }) => {
const { year } = await params
const yearNum = parseInt(year)
if (isNaN(yearNum) || yearNum < 2020 || yearNum > 2100) {
return NextResponse.json({ error: 'Ogiltigt år' }, { status: 400 })
}
// Load company
const { data: company } = await supabase
.from('companies')
.select('name, org_number')
.eq('id', companyId)
.single()
if (!company) return NextResponse.json({ error: 'Företag hittades inte' }, { status: 404 })
const { data: settings } = await supabase
.from('company_settings')
.select('company_name, org_number, phone, email')
.eq('company_id', companyId)
.single()
const { data: profile } = await supabase
.from('profiles')
.select('full_name, email')
.eq('id', user.id)
.single()
// Load all booked salary run employees for the year, grouped by employee
const { data: runEmployees, error } = await supabase
.from('salary_run_employees')
.select(`
employee_id, gross_salary, tax_withheld, tax_withheld_override,
avgifter_basis, avgifter_basis_override,
employee:employees(personnummer, specification_number, employment_start, employment_end),
salary_run:salary_runs!inner(period_year, status),
line_items:salary_line_items(item_type, amount)
`)
.eq('company_id', companyId)
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
// Filter to booked runs for the year
const bookedForYear = (runEmployees || []).filter(sre => {
const run = sre.salary_run as unknown as { period_year: number; status: string } | null
return run && run.period_year === yearNum && run.status === 'booked'
})
// Aggregate per employee
const byEmployee = new Map<string, {
personnummer: string
specificationNumber: number
employmentStart: string | null
employmentEnd: string | null
totalGross: number
totalTax: number
totalAvgifterBasis: number
benefitCar: number
benefitHousing: number
benefitMeals: number
benefitOther: number
}>()
for (const sre of bookedForYear) {
const emp = sre.employee as unknown as { personnummer: string; specification_number: number; employment_start: string; employment_end: string | null } | null
if (!emp) continue
const current = byEmployee.get(sre.employee_id) || {
personnummer: emp.personnummer,
specificationNumber: emp.specification_number,
employmentStart: emp.employment_start,
employmentEnd: emp.employment_end,
totalGross: 0, totalTax: 0, totalAvgifterBasis: 0,
benefitCar: 0, benefitHousing: 0, benefitMeals: 0, benefitOther: 0,
}
current.totalGross += sre.gross_salary
// Honor advanced-mode override so KU matches AGI + the ledger.
current.totalTax += sre.tax_withheld_override ?? sre.tax_withheld
current.totalAvgifterBasis += sre.avgifter_basis_override ?? sre.avgifter_basis
// Sum benefits by type from line items
const lineItems = (sre.line_items || []) as Array<{ item_type: string; amount: number }>
for (const li of lineItems) {
if (li.item_type === 'benefit_car') current.benefitCar += li.amount
else if (li.item_type === 'benefit_housing') current.benefitHousing += li.amount
else if (li.item_type === 'benefit_meals') current.benefitMeals += li.amount
else if (['benefit_wellness', 'benefit_other'].includes(li.item_type)) current.benefitOther += li.amount
}
byEmployee.set(sre.employee_id, current)
}
if (byEmployee.size === 0) {
return NextResponse.json({ error: `Inga bokförda lönekörningar för ${yearNum}` }, { status: 404 })
}
// Employer name on the KU10 follows the current company name
// (company_settings.company_name), not the frozen onboarding companies.name.
const companyName = settings?.company_name || company.name
const companyData: KU10CompanyData = {
orgNumber: (settings?.org_number || company.org_number || '').trim(),
companyName,
year: yearNum,
contactName: (profile?.full_name || companyName || '').trim(),
contactPhone: (settings?.phone || '').trim(),
contactEmail: (settings?.email || profile?.email || user.email || '').trim(),
}
const r = (x: number) => Math.round(x * 100) / 100
const employeeData: KU10EmployeeData[] = Array.from(byEmployee.values()).map(emp => ({
personnummer: emp.personnummer,
specificationNumber: emp.specificationNumber,
totalGross: r(emp.totalGross),
totalTax: r(emp.totalTax),
totalAvgifterBasis: r(emp.totalAvgifterBasis),
benefitCar: emp.benefitCar > 0 ? r(emp.benefitCar) : undefined,
benefitHousing: emp.benefitHousing > 0 ? r(emp.benefitHousing) : undefined,
benefitMeals: emp.benefitMeals > 0 ? r(emp.benefitMeals) : undefined,
benefitOther: emp.benefitOther > 0 ? r(emp.benefitOther) : undefined,
employmentStart: emp.employmentStart || undefined,
employmentEnd: emp.employmentEnd || undefined,
}))
const xml = generateKU10Xml(companyData, employeeData)
return new Response(xml, {
headers: {
'Content-Type': 'application/xml; charset=utf-8',
'Content-Disposition': `attachment; filename="KU10_${company.org_number}_${yearNum}.xml"`,
},
})
},
)