Files
accounted/extensions/general/skatteverket/lib/agi-mappers.ts
T
Mattssonandgreptile-apps[bot] bb0db7a588 Salary module improvements (#250)
* feat: implement salary module with personnummer encryption, salary entries, tax tables, and AGI tracking

- Added personnummer encryption and decryption functions for secure storage.
- Created salary entries handling for journal entries including gross salary, tax withholding, and employer contributions.
- Implemented tax table lookup functionality for calculating tax amounts based on monthly income.
- Developed SQL migration for salary module including tables for payroll configuration, tax rates, employees, salary runs, salary run employees, salary line items, and AGI declarations.
- Established row-level security policies for all new tables to ensure company-scoped access.

* feat: add salary calculation modules for 2026

- Implemented engångsskatt calculation for one-time payments with tax brackets.
- Added löneväxling functionality for salary sacrifice to pension, including employer savings and warnings.
- Created pain.001 generator for salary batch payments in compliance with Swedish banking standards.
- Developed PDF template for payslips, including detailed breakdowns and employer costs.
- Generated seed data for Swedish tax tables for 2026, including SQL insert statements.
- Implemented traktamente calculations for per diem and mileage allowances, adhering to Skatteverket regulations.
- Added seed script for populating tax tables in the database.

* feat: Update meal reduction percentages in traktamente calculation

fix: Remove obsolete seed script for 2026 tax tables

feat: Extend SalaryRunStatus type to include 'corrected' status

feat: Implement KU10 XML generation endpoint for annual employee income statements

feat: Add endpoint for creating corrections to booked salary runs

feat: Implement endpoint for sending payslip PDFs to employees

feat: Create KU10 XML generator for annual reporting

feat: Add salary transaction matcher for auto-linking bank transactions to salary entries

chore: Add database migration for salary correction support

* feat: replace select elements with custom Select component for employment and salary types

* feat: enhance salary calculations with pension entry and avgifter category support

* feat: enhance employee management with salary type, tax status, and validation improvements

* feat: Implement AGI submission flow to Skatteverket

- Added AGI submission route to handle the submission process.
- Created AGI client for interacting with Skatteverket's API.
- Introduced AGI mappers to convert salary run data into the required AGI JSON payload format.
- Enhanced API client to support custom base URLs for Skatteverket API requests.
- Added types for AGI submission payload and validation results.
- Implemented tests for AGI mappers to ensure correct payload structure and data handling.

* feat: enhance salary module with Skatteverket integration and update dashboard navigation

* Update app/api/salary/runs/[id]/agi/submit/route.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update app/api/salary/runs/[id]/approve/route.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* feat: integrate write permission check and remove Skatteverket extension

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-04-15 20:55:29 +02:00

94 lines
3.8 KiB
TypeScript

import type { AGIEmployeeData, AGITotals } from '@/lib/salary/agi/xml-generator'
import type { SkatteverketAGIInlamning, SkatteverketHuvuduppgift, SkatteverketIndividuppgift } from '../types'
import { decryptPersonnummer } from '@/lib/salary/personnummer'
// Re-export shared formatting utilities
export { formatRedovisare, formatRedovisningsperiod } from '@/lib/skatteverket/format'
/**
* Convert gnubok salary run data to Skatteverket AGI JSON payload.
*
* JSON property names are derived from Skatteverket's XML element names,
* following the same camelCase convention as the Momsdeklaration API.
* The exact names should be verified against the RAML spec on Utvecklarportalen.
*
* CRITICAL: FK570 (specifikationsnummer) must stay consistent per employee.
* Using a different number creates a new record instead of a correction.
*/
export function buildAGIPayload(
employees: AGIEmployeeData[],
totals: AGITotals,
isCorrection: boolean = false
): SkatteverketAGIInlamning {
const huvuduppgift = buildHuvuduppgift(totals)
const individuppgifter = employees.map(emp => buildIndividuppgift(emp))
return {
rattelse: isCorrection,
huvuduppgift,
individuppgifter,
}
}
function buildHuvuduppgift(totals: AGITotals): SkatteverketHuvuduppgift {
const result: SkatteverketHuvuduppgift = {}
if (totals.totalTax > 0) {
result.avdragenSkatt = Math.round(totals.totalTax)
}
if (totals.totalAvgifterBasis > 0) {
result.summaArbetsgivaravgifterUnderlag = Math.round(totals.totalAvgifterBasis)
}
// Avgifter by category (rutor 060-062)
if (totals.avgifterByCategory.standard) {
result.avgifterUnderlagStandard = Math.round(totals.avgifterByCategory.standard.basis)
}
if (totals.avgifterByCategory.reduced65plus) {
result.avgifterUnderlagAlderspension = Math.round(totals.avgifterByCategory.reduced65plus.basis)
}
if (totals.avgifterByCategory.youth) {
result.avgifterUnderlagUngdom = Math.round(totals.avgifterByCategory.youth.basis)
}
return result
}
function buildIndividuppgift(emp: AGIEmployeeData): SkatteverketIndividuppgift {
// Decrypt personnummer — must be plaintext for Skatteverket
let personnummer: string
try {
personnummer = decryptPersonnummer(emp.personnummer)
} catch {
throw new Error(
`Kunde inte dekryptera personnummer för anställd med FK570=${emp.specificationNumber}. ` +
'AGI kan inte skickas utan giltigt personnummer.'
)
}
const result: SkatteverketIndividuppgift = {
personnummer,
specifikationsnummer: emp.specificationNumber,
}
// Only include non-zero values (Skatteverket treats absent fields as 0)
if (emp.grossSalary > 0) result.kontantBruttoloen = Math.round(emp.grossSalary)
if (emp.taxWithheld > 0) result.avdragenSkatt = Math.round(emp.taxWithheld)
if (emp.avgifterBasis > 0) result.underlagArbetsgivaravgifter = Math.round(emp.avgifterBasis)
if (emp.fSkattPayment && emp.fSkattPayment > 0) result.ersattningFSkatt = Math.round(emp.fSkattPayment)
// Benefits (rutor 012-019)
if (emp.benefitCar && emp.benefitCar > 0) result.formanBil = Math.round(emp.benefitCar)
if (emp.benefitFuel && emp.benefitFuel > 0) result.formanDrivmedel = Math.round(emp.benefitFuel)
if (emp.benefitHousing && emp.benefitHousing > 0) result.formanBostad = Math.round(emp.benefitHousing)
if (emp.benefitMeals && emp.benefitMeals > 0) result.formanKost = Math.round(emp.benefitMeals)
if (emp.benefitOther && emp.benefitOther > 0) result.formanOvrigt = Math.round(emp.benefitOther)
// Absence fields (from 2025)
if (emp.sickDays && emp.sickDays > 0) result.sjukfranvaroDagar = Math.round(emp.sickDays)
if (emp.vabDays && emp.vabDays > 0) result.vabDagar = Math.round(emp.vabDays)
if (emp.parentalDays && emp.parentalDays > 0) result.foraldraledigDagar = Math.round(emp.parentalDays)
return result
}