Files
accounted/lib/reports/avgifter-basis.ts
T
Mattsson 04dbb31d7e Salary module (#245)
* 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
2026-04-15 11:17:39 +02:00

133 lines
3.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { SupabaseClient } from '@supabase/supabase-js'
/**
* Arbetsgivaravgiftsunderlag — Employer contribution basis report.
*
* Monthly breakdown by avgifter rate category:
* - Standard (31.42%)
* - Reduced 65+ (10.21%)
* - Youth (20.81%, Apr 2026Sep 2027)
* - Växa-stöd (10.21%)
*
* Used for reconciling against AGI filings (Ruta 060-062)
* and verifying correct avgifter calculations per social-charges.md.
*
* Per BFL: Part of räkenskapsinformation, 7-year retention.
*/
export interface AvgifterBasisRow {
periodYear: number
periodMonth: number
category: string
categoryLabel: string
rate: number
basis: number // Underlag (sum of avgifter_basis for employees in this category)
amount: number // Avgift (basis × rate)
employeeCount: number
}
export interface AvgifterBasisReport {
rows: AvgifterBasisRow[]
totals: {
totalBasis: number
totalAmount: number
}
year: number
}
const CATEGORY_LABELS: Record<string, string> = {
standard: 'Standard (31,42%)',
reduced_65plus: 'Reducerad 67+ (10,21%)',
youth: 'Ungdomsrabatt (20,81%)',
vaxa_stod: 'Växa-stöd (10,21%)',
exempt: 'Undantagen (0%)',
}
/**
* Generate avgifter basis report for a year.
*/
export async function generateAvgifterBasis(
supabase: SupabaseClient,
companyId: string,
year: number
): Promise<AvgifterBasisReport> {
const r = (x: number) => Math.round(x * 100) / 100
// Load all salary run employees for booked runs this year
const { data: runEmployees, error } = await supabase
.from('salary_run_employees')
.select(`
avgifter_basis,
avgifter_amount,
avgifter_rate,
salary_run:salary_runs!inner(period_year, period_month, status)
`)
.eq('company_id', companyId)
if (error) throw new Error(`Failed to load avgifter data: ${error.message}`)
// Filter to booked runs for the year
const bookedForYear = (runEmployees || []).filter(sre => {
const run = sre.salary_run as unknown as { period_year: number; period_month: number; status: string } | null
return run && run.period_year === year && run.status === 'booked'
})
// Group by month + rate category
const grouped = new Map<string, {
periodYear: number
periodMonth: number
category: string
rate: number
basis: number
amount: number
count: number
}>()
for (const sre of bookedForYear) {
const run = sre.salary_run as unknown as { period_year: number; period_month: number }
const category = rateToCategory(sre.avgifter_rate)
const key = `${run.period_month}-${category}`
const current = grouped.get(key) || {
periodYear: year,
periodMonth: run.period_month,
category,
rate: sre.avgifter_rate,
basis: 0,
amount: 0,
count: 0,
}
current.basis += sre.avgifter_basis
current.amount += sre.avgifter_amount
current.count++
grouped.set(key, current)
}
const rows: AvgifterBasisRow[] = Array.from(grouped.values())
.map(g => ({
periodYear: g.periodYear,
periodMonth: g.periodMonth,
category: g.category,
categoryLabel: CATEGORY_LABELS[g.category] || g.category,
rate: g.rate,
basis: r(g.basis),
amount: r(g.amount),
employeeCount: g.count,
}))
.sort((a, b) => a.periodMonth - b.periodMonth || a.category.localeCompare(b.category))
const totals = {
totalBasis: r(rows.reduce((s, row) => s + row.basis, 0)),
totalAmount: r(rows.reduce((s, row) => s + row.amount, 0)),
}
return { rows, totals, year }
}
function rateToCategory(rate: number): string {
if (rate === 0) return 'exempt'
if (rate <= 0.1022) return 'reduced_65plus' // 10.21% ± rounding
if (rate <= 0.2082) return 'youth' // 20.81%
return 'standard' // 31.42%
}