diff --git a/DECISIONS.md b/DECISIONS.md
index 6d632175..4436c50f 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -645,6 +645,18 @@ One line per decision: `[YYYY-MM-DD] : `. Appended by agents and
[2026-07-28] The "senaste bokförda verifikat" line in the balans-/resultatrapport header (#1267) reads MAX(voucher_number) over posted entries, never voucher_sequences.last_number. The sequence counter is an allocation high-water mark that provably drifts from the books in both directions: next_voucher_number burns a number when the follow-up insert fails (the reversal path in engine.ts does exactly that), delete_last_voucher decrements blindly by one instead of resetting to the new MAX, and pre-RPC SIE imports left it behind MAX. Since the whole point of the line is avstämning, printing an allocated number would send a reconciler chasing a gap that does not exist, so the label states plainly that the number is the last posted one. Scoped to the report's own date range rather than the fiscal year, so a Q1 report printed in November says something true about Q1; the balansrapport keeps the fiscal-year start as its lower bound because it accumulates. Skipped entirely on a dimension-filtered resultatrapport: that report already discloses it is partial, and an unfiltered voucher range beside a filtered result invites the wrong conclusion. No new i18n keys: both report views and the PDF template are hard-coded Swedish, per the "stays Swedish" report surfaces in .claude/rules/i18n.md, so the issue's acceptance criterion asking for sv+en strings does not apply here.
+[2026-07-29] FX revaluation population fixed as-of-balansdagen + per-row booked gate: the revaluation queried LIVE open invoices with no date scoping, so rows issued after balansdagen (or never booked) were revalued into the closed year, fabricating 1510/2440 write-downs. Chose reconstruction via the existing reskontra-payments helpers over snapshotting live status. First attempt gated on accounting_method (cash -> skip the company entirely); adversarial review overturned that: BFL 5 kap 2 § 3 st requires kontantmetoden companies to book outstanding fordringar/skulder at balansdagen, so a company-level skip would leave real 1510 exposure unvalued. The predicate is therefore per row (is this invoice booked?) not per company. The invoice_date ceiling is unconditional, not historical-only, because post-dated invoices make the bug reachable for a current period too. The year-end readiness WARNING is deliberately left ungated: an unbooked FX row still has a remedy (/book posts at invoice_date, into the year being closed) that lockPeriod/closePeriod then destroys forever. fetchFxExposureScope never throws, preserving previewCurrencyRevaluation's read-only render-always contract. ROT/RUT 1513 overstatement and splitting the close into two staged approval runs deliberately left out (own fixes).
+
+[2026-07-29] Parallel issue work runs in three permanent lane worktrees (erp-lanes/lane-1..3, dev ports 3001-3003) with one GitHub issue per branch per PR, rather than per-issue worktree provisioning inside /fix (tried and removed 2026-07-28 as too heavy) or several issues stacked on one shared branch (which corrupted commits across sessions the same day: swept files, a 33-file amend, HEAD moving mid-task). Lanes are one-time infrastructure so no install/port cost is paid per issue, /fix stays issue -> steps -> 'it works' -> commit and only gains a branch step, and small single-issue PRs keep each CI cycle and each origin/main re-sync short. npm ci only in lanes: bun-isolated trees rendered a wrong settings UI on 2026-07-28 and pnpm ignores the npm overrides.
+
+[2026-07-29] Semesteravsattning under sammaloneregeln: the tillagg is now valued on the MONTHLY salary per vacation day (Semesterlagen 16a §) and accrues one month's earned share (dagar/12) per run, replacing dagslon x rate x hela arets dagar in both calculation-engine call sites. Two errors that partly cancelled, which is why the monthly figure looked plausible. Decisive evidence that the old base was wrong: absence-calculator.ts already paid the tillagg out of 2920 on the monthly base, so provision and payout disagreed and the liability drifted negative on every taken day; a regression test now pins accrual-per-day == payout-per-day. Deliberately forward-only: posted runs are not re-touched (BFL 5 kap 5 §, and correcting them is not the sanctioned path), and semesterberedning.ts already books a 7290/2920 drift adjustment against the actual booked balance at vacation-year close, so history self-corrects through existing sanctioned mechanics rather than a migration. dailyDivisor dropped from calculateVacationAccrual entirely: semestertillagg does not vary with workdays per week, and the old signature invited exactly that error.
+
+[2026-07-29] Betalda semesterdagar pro-rated per Semesterlagen 7 § (anstallningsdagar / dagar i intjanandearet x semesterdagar, rounded UP) applied ONLY on the statutory Apr-Mar basis; sammanfallande calendar-year companies keep the flat entitlement. Under sammanfallande the employee earns and takes in the same year, commonly with forskottssemester, so how a mid-year hire is treated is a collective-agreement question rather than a statutory one, and guessing there would understate a real entitlement. Two terms of 7 § left unmodelled and documented at the call site: unpaid full-day absence (no day source in the ledger) and the 4 § five-day cap (which bounds semesterledighet, a different quantity from paid days). Both omissions can only overstate, never understate, so neither can silently deny an employee a paid day. A cutover opening balance still outranks the computation.
+
+[2026-07-29] pain.001 to SEB: shipped an honest warning plus corrected per-bank instructions instead of a SEB CSV generator. SEB Business Arena rejects .xml on upload and its SEPA-CSV is EUR-only, so the previous copy walked the user into a failure discovered on the pay date. Declined to build the bank-specific CSV without SEB's actual file specification: a guessed payment format either fails at the bank or, worse, pays the wrong amounts, and no primary spec was available in-session. Bankgirot LB is the working path for inrikes SEK today and the corrected copy points there, but it is a bridge, not a fix: the banks sunset LB during 2026 (Swedbank 1 Aug 2026), so the CSV generator is still owed once the spec is in hand.
+
+[2026-07-29] Konto 8022 in a verifikat rattelse: made the account reachable instead of adding it to the shared BAS catalog. Verified against the official bas.se BAS 2026 v1.1 kontoplan that 8022 appears nowhere in it (kontogrupp 80 is exactly the 13 accounts lib/bookkeeping/bas-data already ships, and the full catalog matches BAS 2026 1:1 at 1290 vs 1286 accounts); it existed in BAS 2018 together with 8013, 8014, 8019, 8023 and 8073, all since retired. Seeding a retired account into the reference would push it onto every company's picker, so the fix instead wires the existing "Skapa konto" affordance into StrikeLinesDialog and CorrectionEntryDialog, which were the only account pickers in the app without it. BAS permits company-specific underkonton and correct_entry_lines_inline validates chart membership rather than BAS membership, so an own 8022 posts and exports to SIE unchanged. Separately noted, not fixed here: .claude/skills/modifier/holding-ab/SKILL.md still names 8022 as a bas_account_signal and instructs booking dotterbolagsforsaljning on "8020 / 8022", so our own domain skill points agents at an account the catalog lacks.
+
[2026-07-28] Recurring-schedule dims PR ships API/MCP/generator only, no schedule-dialog pickers: UI needs visual sign-off per house rule; substrate stops the cron-spawned-invoices-born-untagged leak now.
[2026-07-29] Retired the generic design skills now that emilkowalski/skills is installed globally (animation-vocabulary, apple-design, emil-design-eng, find-animation-opportunities, improve-animations, pick-ui-library, prototype, review-animations in ~/.claude/skills). Deleted .claude/skills/mobile-ux-core (52 lines of universal mobile UX whose file triggers are *.dart/*.swift/*Activity.kt, paths that do not exist in this repo; superseded by design.md's accessibility section plus apple-design) and .claude/skills/scout-design (a design scan that filed Linear tickets via mcp__claude_ai_Linear__save_issue, while this project files GitHub issues and loop-design-scan is the same scan with the right output; loop-design-scan's sibling reference updated). Kept web-design-guidelines: it is a Vercel-plugin symlink, cheap to keep, and may regenerate anyway. Also removed the global ui-ux-pro-max skill, a 67-style/96-palette catalogue that pulls against a locked editorial-monochrome system.
diff --git a/components/bookkeeping/AccountCombobox.tsx b/components/bookkeeping/AccountCombobox.tsx
index 6453b954..dbf93397 100644
--- a/components/bookkeeping/AccountCombobox.tsx
+++ b/components/bookkeeping/AccountCombobox.tsx
@@ -216,9 +216,20 @@ export default function AccountCombobox({ value, accounts, onChange, onCommit, o
// editing an already-committed number doesn't keep stealing focus. On
// commit, close the dropdown too: focus advances to the amount field, so
// a lingering open list would just cover the rows below.
+ //
+ // Unless the number matches nothing. Then the dropdown is showing the
+ // empty state, which carries the only way forward for a number outside
+ // BAS (a retired account such as 8022, or a company-specific
+ // underkonto): the "Skapa konto" affordance. Closing on the fourth
+ // keystroke used to hide it before it was ever painted, which made the
+ // affordance unreachable for exactly the numbers that need it.
if (newValue !== value) {
onCommit?.(newValue)
- setIsOpen(false)
+ if (searchAccounts(accountIndex, newValue).length > 0) {
+ setIsOpen(false)
+ return
+ }
+ setIsOpen(true)
return
}
}
diff --git a/components/bookkeeping/CorrectionEntryDialog.tsx b/components/bookkeeping/CorrectionEntryDialog.tsx
index 89afb4d6..115d2053 100644
--- a/components/bookkeeping/CorrectionEntryDialog.tsx
+++ b/components/bookkeeping/CorrectionEntryDialog.tsx
@@ -14,6 +14,7 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
+import { AddAccountDialog } from '@/components/bookkeeping/AddAccountDialog'
import CorrectionPreview from '@/components/bookkeeping/CorrectionPreview'
import {
autoCorrectionDescription,
@@ -29,6 +30,7 @@ import {
changeCorrectionLineAccount,
getSelectableCorrectionCatalog,
} from '@/lib/bookkeeping/correction-line-account'
+import { splitCreateAccountPrefill } from '@/lib/bookkeeping/create-account-prefill'
import { loadBasCatalog, type CatalogAccount } from '@/lib/bookkeeping/bas-catalog-client'
import type { JournalEntry, JournalEntryLine, BASAccount } from '@/types'
@@ -56,6 +58,10 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
const [lines, setLines] = useState([])
const [description, setDescription] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
+ // Index of the line whose combobox opened the create dialog, and the search
+ // string it was showing. Null index = the dialog is closed.
+ const [creatingAccountForLine, setCreatingAccountForLine] = useState(null)
+ const [createAccountPrefill, setCreateAccountPrefill] = useState('')
const activeAccounts = useMemo(
() => accounts.filter((account) => account.is_active),
@@ -149,6 +155,34 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
setLines((prev) => prev.filter((_, i) => i !== index))
}
+ const closeCreateAccount = () => {
+ setCreatingAccountForLine(null)
+ setCreateAccountPrefill('')
+ }
+
+ // A number that is neither in the company chart nor in BAS 2026 (a retired
+ // account such as 8022, or a company-specific underkonto) would otherwise be
+ // a dead end here: the rättelse can only post to accounts that exist in the
+ // chart. Creating it inline keeps the half-finished rättelse intact.
+ const handleAccountCreated = async (account: { account_number: string; account_name?: string }) => {
+ await fetchAccounts()
+ if (creatingAccountForLine != null) {
+ // fetchAccounts' state update is not visible in this closure, so the
+ // fresh account's own name is passed alongside the stale sources. The
+ // reactivate path reports no name, but that account is already in
+ // `accounts` (the fetch includes deactivated rows).
+ const created = account.account_name
+ ? [{ account_number: account.account_number, account_name: account.account_name }]
+ : []
+ setLines((prev) => prev.map((line, index) => (
+ index === creatingAccountForLine
+ ? changeCorrectionLineAccount(line, account.account_number, [...accountNameSources, ...created])
+ : line
+ )))
+ }
+ closeCreateAccount()
+ }
+
const totalDebit = lines.reduce((sum, l) => sum + (parseFloat(l.debit_amount) || 0), 0)
const totalCredit = lines.reduce((sum, l) => sum + (parseFloat(l.credit_amount) || 0), 0)
const roundedDebit = Math.round(totalDebit * 100) / 100
@@ -298,6 +332,10 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
accounts={activeAccounts}
catalog={selectableCatalog}
onChange={(v) => updateLineAccount(index, v)}
+ onCreateAccount={(prefill) => {
+ setCreatingAccountForLine(index)
+ setCreateAccountPrefill(prefill)
+ }}
disabled={accountsStatus !== 'ready'}
/>
+ {/* The flow looked clean all the way until the bank said no: the
+ file downloads fine and only fails at upload, on the pay date.
+ Say the delivery precondition up front instead. */}
+ {format === 'pain001' && (
+
+
+ {t('pain001_agreement_warning')}
+
+ )}
+
{format === 'bg_lb' && (
diff --git a/lib/bookkeeping/__tests__/create-account-prefill.test.ts b/lib/bookkeeping/__tests__/create-account-prefill.test.ts
new file mode 100644
index 00000000..61d407d2
--- /dev/null
+++ b/lib/bookkeeping/__tests__/create-account-prefill.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect } from 'vitest'
+import { splitCreateAccountPrefill } from '../create-account-prefill'
+
+describe('splitCreateAccountPrefill', () => {
+ it('routes a full account number to the number field', () => {
+ // The support case: 8022 is a retired BAS account, so the picker finds
+ // nothing and the user reaches for "Skapa konto" with the number typed.
+ expect(splitCreateAccountPrefill('8022')).toEqual({ initialAccountNumber: '8022' })
+ })
+
+ it('routes a partial account number to the number field', () => {
+ expect(splitCreateAccountPrefill('80')).toEqual({ initialAccountNumber: '80' })
+ })
+
+ it('routes a name fragment to the name field', () => {
+ expect(splitCreateAccountPrefill('andelar i dotterföretag')).toEqual({
+ initialAccountName: 'andelar i dotterföretag',
+ })
+ })
+
+ it('treats a number longer than four digits as a name, not a number', () => {
+ // The dialog would silently truncate it to four digits; keeping it in the
+ // name field makes the mistake visible instead.
+ expect(splitCreateAccountPrefill('80221')).toEqual({ initialAccountName: '80221' })
+ })
+
+ it('treats a mixed string as a name', () => {
+ expect(splitCreateAccountPrefill('8022 dotter')).toEqual({ initialAccountName: '8022 dotter' })
+ })
+
+ it('trims surrounding whitespace before deciding', () => {
+ expect(splitCreateAccountPrefill(' 8022 ')).toEqual({ initialAccountNumber: '8022' })
+ })
+
+ it('returns neither prefill for an empty or blank string', () => {
+ // Spreading {} leaves both props undefined, so the dialog opens blank
+ // rather than with an empty-string name.
+ expect(splitCreateAccountPrefill('')).toEqual({})
+ expect(splitCreateAccountPrefill(' ')).toEqual({})
+ })
+})
diff --git a/lib/bookkeeping/__tests__/currency-revaluation.test.ts b/lib/bookkeeping/__tests__/currency-revaluation.test.ts
index 2b984f1b..62cfe566 100644
--- a/lib/bookkeeping/__tests__/currency-revaluation.test.ts
+++ b/lib/bookkeeping/__tests__/currency-revaluation.test.ts
@@ -63,16 +63,33 @@ function mockRates(rates: Partial>) {
})
}
-// Helper to build mock supabase
-function createMockSupabase(config: {
+/**
+ * Extra tables the preview reads besides the two invoice ledgers:
+ * company_settings decides the FX exposure scope (cash/deferred/accrual) and
+ * the payment tables feed the as-of-balansdagen outstanding reconstruction.
+ */
+interface MockTablesConfig {
invoices?: ReturnType[]
supplierInvoices?: ReturnType[]
+ settings?: Record
+ invoicePayments?: Record[]
+ supplierInvoicePayments?: Record[]
existingRevaluation?: boolean
-}) {
- const fromMap: Record = {
+}
+
+function buildFromMap(config: MockTablesConfig): Record {
+ return {
invoices: config.invoices || [],
supplier_invoices: config.supplierInvoices || [],
+ company_settings: config.settings ? [config.settings] : [],
+ invoice_payments: config.invoicePayments || [],
+ supplier_invoice_payments: config.supplierInvoicePayments || [],
}
+}
+
+// Helper to build mock supabase
+function createMockSupabase(config: MockTablesConfig) {
+ const fromMap = buildFromMap(config)
const supabase = {
from: vi.fn().mockImplementation((table: string) => {
@@ -143,6 +160,20 @@ function buildFilterChain(data: unknown[]) {
return chain
})
+ // ISO date strings compare correctly as strings, matching PostgREST lte.
+ chain.lte = vi.fn().mockImplementation((col: string, val: string) => {
+ filtered = filtered.filter((row) => {
+ const v = (row as Record)[col]
+ return v != null && String(v) <= val
+ })
+ return chain
+ })
+
+ // Terminal used by fetchFxExposureScope's company_settings read.
+ chain.maybeSingle = vi.fn().mockImplementation(() =>
+ Promise.resolve({ data: filtered[0] ?? null, error: null })
+ )
+
// Paging stability order: no-op in the mock (data is already deterministic).
chain.order = vi.fn().mockImplementation(() => chain)
@@ -162,11 +193,7 @@ function buildFilterChain(data: unknown[]) {
}
// Better mock for supabase that supports journal_entries idempotency check
-function createFullMockSupabase(config: {
- invoices?: ReturnType[]
- supplierInvoices?: ReturnType[]
- existingRevaluation?: boolean
-}) {
+function createFullMockSupabase(config: MockTablesConfig) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const supabase: any = {
from: vi.fn().mockImplementation((table: string) => {
@@ -184,10 +211,7 @@ function createFullMockSupabase(config: {
return journalChain
}
- const fromMap: Record = {
- invoices: config.invoices || [],
- supplier_invoices: config.supplierInvoices || [],
- }
+ const fromMap = buildFromMap(config)
return buildFilterChain(fromMap[table] || [])
}),
}
@@ -1074,4 +1098,381 @@ describe('currency-revaluation', () => {
expect(result!.preview.totalGain).toBe(1000) // 1000 * (12 - 11)
})
})
+
+ // Regression: a year-end close revalued FX invoices that were NOT on the
+ // balance sheet on balansdagen (issued later, settled earlier, or never
+ // booked at all), writing down a 1510 that stood at zero. The population
+ // must be measured AS OF the closing date, gated by the company's booking
+ // mode, exactly like countOpenFxItemsAtBalansdagen in year-end-service.
+ describe('as-of balansdagen population', () => {
+ it('excludes an invoice issued after balansdagen', async () => {
+ const laterInvoice = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ invoice_date: '2025-03-10',
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({ invoices: [laterInvoice] })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ expect(preview.items).toHaveLength(0)
+ expect(preview.lines).toHaveLength(0)
+ expect(preview.unconvertedFxCount).toBe(0)
+ })
+
+ it('includes an invoice settled after balansdagen at its as-of outstanding', async () => {
+ // Paid in full in February 2025: on 2024-12-31 the whole amount was
+ // still an open monetary item and must be valued (ÅRL 4 kap. 13 §).
+ const settledLater = makeInvoice({
+ id: 'inv-settled-later',
+ status: 'paid',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ paid_amount: 1000,
+ remaining_amount: 0,
+ paid_at: '2025-02-01',
+ invoice_date: '2024-11-15',
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({
+ invoices: [settledLater],
+ invoicePayments: [
+ {
+ company_id: 'company-1',
+ invoice_id: 'inv-settled-later',
+ amount: 1000,
+ payment_date: '2025-02-01',
+ },
+ ],
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ expect(preview.items).toHaveLength(1)
+ expect(preview.items[0].amount_in_currency).toBe(1000)
+ expect(preview.totalGain).toBe(1000) // 1000 * (12 - 11)
+ })
+
+ it('excludes the part of an invoice that was already paid on balansdagen', async () => {
+ const partiallySettled = makeInvoice({
+ id: 'inv-partial-asof',
+ status: 'paid',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ paid_amount: 1000,
+ remaining_amount: 0,
+ paid_at: '2025-01-20',
+ invoice_date: '2024-11-15',
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({
+ invoices: [partiallySettled],
+ invoicePayments: [
+ // 600 paid before balansdagen, 400 after: only 400 was open.
+ {
+ company_id: 'company-1',
+ invoice_id: 'inv-partial-asof',
+ amount: 600,
+ payment_date: '2024-12-10',
+ },
+ {
+ company_id: 'company-1',
+ invoice_id: 'inv-partial-asof',
+ amount: 400,
+ payment_date: '2025-01-20',
+ },
+ ],
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ expect(preview.items).toHaveLength(1)
+ expect(preview.items[0].amount_in_currency).toBe(400)
+ expect(preview.totalGain).toBe(400) // 400 * (12 - 11)
+ })
+
+ it('excludes an unbooked row for a kontantmetoden company', async () => {
+ // A registered-but-unbooked invoice is not on 1510, so revaluing it
+ // fabricated a write-down of an account that stood at zero.
+ const eurInvoice = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ invoice_date: '2024-11-15',
+ journal_entry_id: null,
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({
+ invoices: [eurInvoice],
+ settings: { company_id: 'company-1', accounting_method: 'cash' },
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ expect(preview.items).toHaveLength(0)
+ expect(preview.lines).toHaveLength(0)
+ })
+
+ it('still revalues a kontantmetoden company row booked at balansdagen', async () => {
+ // BFL 5 kap 2 § 3 st: kontantmetoden companies must book their
+ // outstanding fordringar/skulder at year-end. Those converted rows ARE
+ // on 1510 and must be valued at balansdagskurs (ÅRL 4 kap. 13 §), so
+ // gating on accounting_method rather than on the row would drop them.
+ const bookedEur = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ invoice_date: '2024-11-15',
+ journal_entry_id: 'je-yearend-conversion',
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({
+ invoices: [bookedEur],
+ settings: { company_id: 'company-1', accounting_method: 'cash' },
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ expect(preview.items).toHaveLength(1)
+ expect(preview.totalGain).toBe(1000) // 1000 * (12 - 11)
+ })
+
+ it('excludes a post-dated invoice even when balansdagen is not historical', async () => {
+ // The date ceiling is unconditional: an invoice issued after the
+ // balансdagen is not on the balance sheet being valued, whether or not
+ // that date happens to be in the past.
+ const future = new Date(Date.now() + 90 * 86400000).toISOString().slice(0, 10)
+ const postDated = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10)
+ const beforeToday = new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10)
+
+ const openNow = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ invoice_date: beforeToday,
+ })
+ const laterInvoice = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 500,
+ invoice_date: future,
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({ invoices: [openNow, laterInvoice] })
+ // Balansdagen between the two invoice dates, still in the future.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', postDated)
+
+ expect(preview.items).toHaveLength(1)
+ expect(preview.items[0].amount_in_currency).toBe(1000)
+ })
+
+ it('values a still-open invoice at what it owed on balansdagen', async () => {
+ // The common straddling case: the row is 'partially_paid' today, so the
+ // OLD status list already fetched it, but its live paid_amount reflects
+ // payments made after balansdagen.
+ const straddling = makeInvoice({
+ id: 'inv-straddle',
+ status: 'partially_paid',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ paid_amount: 900,
+ remaining_amount: 100,
+ invoice_date: '2024-10-01',
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({
+ invoices: [straddling],
+ invoicePayments: [
+ { company_id: 'company-1', invoice_id: 'inv-straddle', amount: 300, payment_date: '2024-11-05' },
+ { company_id: 'company-1', invoice_id: 'inv-straddle', amount: 600, payment_date: '2025-02-11' },
+ ],
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ // 700 was open on balansdagen, not the live 100.
+ expect(preview.items).toHaveLength(1)
+ expect(preview.items[0].amount_in_currency).toBe(700)
+ expect(preview.totalGain).toBe(700)
+ })
+
+ it('applies the same as-of reconstruction to payables', async () => {
+ const straddlingPayable = makeSupplierInvoice({
+ id: 'si-straddle',
+ status: 'partially_paid',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 2000,
+ remaining_amount: 200,
+ invoice_date: '2024-10-01',
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({
+ supplierInvoices: [straddlingPayable],
+ supplierInvoicePayments: [
+ { company_id: 'company-1', supplier_invoice_id: 'si-straddle', amount: 500, payment_date: '2024-12-01' },
+ { company_id: 'company-1', supplier_invoice_id: 'si-straddle', amount: 1300, payment_date: '2025-03-04' },
+ ],
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ // 1500 was owed on balansdagen; a rising rate is a LOSS on a payable.
+ expect(preview.items).toHaveLength(1)
+ expect(preview.items[0].amount_in_currency).toBe(1500)
+ expect(preview.totalLoss).toBe(1500)
+ expect(preview.totalGain).toBe(0)
+ })
+
+ it('excludes an unbooked payable under deferred booking', async () => {
+ const bookedSi = makeSupplierInvoice({
+ status: 'registered',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ remaining_amount: 1000,
+ invoice_date: '2024-11-01',
+ registration_journal_entry_id: 'je-si-1',
+ })
+ const unbookedSi = makeSupplierInvoice({
+ status: 'registered',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 400,
+ remaining_amount: 400,
+ invoice_date: '2024-11-02',
+ registration_journal_entry_id: null,
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({
+ supplierInvoices: [bookedSi, unbookedSi],
+ settings: {
+ company_id: 'company-1',
+ accounting_method: 'accrual',
+ defer_invoice_booking: true,
+ },
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ expect(preview.items).toHaveLength(1)
+ expect(preview.items[0].amount_in_currency).toBe(1000)
+ expect(preview.totalLoss).toBe(1000)
+ })
+
+ it('renders a preview instead of throwing when settings cannot be read', async () => {
+ // previewCurrencyRevaluation is the read-only surface: the year-end
+ // preview must still render (same contract as the missing-rate path).
+ const eurInvoice = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ invoice_date: '2024-11-15',
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({ invoices: [eurInvoice] })
+ const original = supabase.from
+ supabase.from = vi.fn().mockImplementation((table: string) => {
+ if (table === 'company_settings') {
+ return {
+ select: vi.fn().mockReturnValue({
+ eq: vi.fn().mockReturnValue({
+ maybeSingle: vi.fn().mockResolvedValue({
+ data: null,
+ error: { message: 'connection reset' },
+ }),
+ }),
+ }),
+ }
+ }
+ return original(table)
+ })
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ expect(preview.items).toHaveLength(1)
+ expect(preview.totalGain).toBe(1000)
+ })
+
+ it('under deferred booking only revalues rows whose registration is booked', async () => {
+ const bookedInvoice = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ invoice_date: '2024-11-15',
+ journal_entry_id: 'je-1',
+ })
+ const unbookedInvoice = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 500,
+ invoice_date: '2024-11-20',
+ journal_entry_id: null,
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createMockSupabase({
+ invoices: [bookedInvoice, unbookedInvoice],
+ settings: {
+ company_id: 'company-1',
+ accounting_method: 'accrual',
+ defer_invoice_booking: true,
+ },
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
+
+ expect(preview.items).toHaveLength(1)
+ expect(preview.items[0].amount_in_currency).toBe(1000)
+ expect(preview.totalGain).toBe(1000) // only the booked 1000 EUR row
+ })
+
+ it('executeCurrencyRevaluation posts nothing when nothing was open on balansdagen', async () => {
+ // The Oppy case end to end: only a post-balansdagen invoice exists, so
+ // the year-end run must not create any verifikat at all.
+ const laterInvoice = makeInvoice({
+ status: 'sent',
+ currency: 'EUR',
+ exchange_rate: 11.0,
+ total: 1000,
+ invoice_date: '2025-03-10',
+ })
+
+ mockRates({ EUR: 12.0 })
+ const supabase = createFullMockSupabase({
+ invoices: [laterInvoice],
+ existingRevaluation: false,
+ })
+
+ const result = await executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
+
+ expect(result).toBeNull()
+ expect(mockedCreateEntry).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/lib/bookkeeping/create-account-prefill.ts b/lib/bookkeeping/create-account-prefill.ts
new file mode 100644
index 00000000..2e2b9e0b
--- /dev/null
+++ b/lib/bookkeeping/create-account-prefill.ts
@@ -0,0 +1,22 @@
+/**
+ * Split the search string an account picker was showing when the user reached
+ * for "Skapa konto" into AddAccountDialog's two prefill props.
+ *
+ * The combobox hands over whatever was typed, which is either a partial/full
+ * account number ("8022") or a name fragment ("andelar i dotterföretag").
+ * Feeding a name into initialAccountNumber would be silently dropped by the
+ * dialog's digits-only filter, and feeding a number into initialAccountName
+ * would put "8022" in the name field.
+ */
+export interface CreateAccountPrefill {
+ initialAccountNumber?: string
+ initialAccountName?: string
+}
+
+export function splitCreateAccountPrefill(prefill: string): CreateAccountPrefill {
+ const trimmed = prefill.trim()
+ if (!trimmed) return {}
+ return /^\d{1,4}$/.test(trimmed)
+ ? { initialAccountNumber: trimmed }
+ : { initialAccountName: trimmed }
+}
diff --git a/lib/bookkeeping/currency-revaluation.ts b/lib/bookkeeping/currency-revaluation.ts
index 42c37fbb..24632d96 100644
--- a/lib/bookkeeping/currency-revaluation.ts
+++ b/lib/bookkeeping/currency-revaluation.ts
@@ -2,6 +2,12 @@ import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
+import {
+ fetchPaymentsAsOf,
+ outstandingAsOf,
+ todayIsoDate,
+ type PaymentsAsOf,
+} from '@/lib/reports/reskontra-payments'
import {
BookkeepingDatabaseError,
CurrencyRevaluationAlreadyExistsError,
@@ -80,6 +86,59 @@ function hasUsableRate(rate: number | null | undefined): boolean {
return rate != null && Number(rate) > 0
}
+/**
+ * Which invoice rows can carry balance-sheet FX exposure for this company.
+ *
+ * ÅRL 4 kap. 13 § revalues MONETARY ITEMS ON THE BALANCE SHEET, and an invoice
+ * row only puts anything on 1510/2440 once its registration is booked. Under
+ * #967 "Registrera men bokför inte" (and under kontantmetoden) a registered
+ * invoice can sit in the reskontra with nothing on the balance sheet at all;
+ * revaluing those fabricated a write-down of an account standing at zero.
+ *
+ * NOT keyed on accounting_method: kontantmetoden companies must still book
+ * their outstanding fordringar/skulder at balansdagen (BFL 5 kap 2 § 3 st), and
+ * those year-end-converted rows are genuine FX exposure that has to be valued.
+ * The predicate is therefore per row ("is this one booked?"), never per company
+ * ("does this company use the cash method?"):
+ * - 'booked_only': only rows carrying a registration entry are on the balance
+ * sheet (kontantmetoden, or faktureringsmetoden with defer_invoice_booking)
+ * - 'all': inline booking at issue, the historical default. Every open row is
+ * booked, including legacy/SIE-imported rows that predate the entry links,
+ * so requiring a link there would silently drop real exposure.
+ */
+export type FxExposureScope = 'all' | 'booked_only'
+
+export function fxExposureScope(
+ settings:
+ | { accounting_method?: string | null; defer_invoice_booking?: boolean | null }
+ | null
+ | undefined
+): FxExposureScope {
+ // No settings row: historical default (accrual, book at issue).
+ if (!settings) return 'all'
+ if ((settings.accounting_method || 'accrual') !== 'accrual') return 'booked_only'
+ return settings.defer_invoice_booking ? 'booked_only' : 'all'
+}
+
+/**
+ * Never throws: `previewCurrencyRevaluation` is the read-only surface and the
+ * year-end preview must still render (same contract as the missing-rate path).
+ * A settings row that cannot be read falls back to the historical default,
+ * which is also what a missing row means.
+ */
+export async function fetchFxExposureScope(
+ supabase: SupabaseClient,
+ companyId: string
+): Promise {
+ const { data, error } = await supabase
+ .from('company_settings')
+ .select('accounting_method, defer_invoice_booking')
+ .eq('company_id', companyId)
+ .maybeSingle()
+ if (error) return 'all'
+ return fxExposureScope(data)
+}
+
/**
* Fetch open foreign-currency receivables (invoices).
* Returns invoices with status 'sent', 'overdue' or 'partially_paid' and
@@ -92,24 +151,44 @@ function hasUsableRate(rate: number | null | undefined): boolean {
* monetary item that ÅRL 4 kap. 13 § values at balansdagen. Omitting it made
* partially paid foreign receivables entirely invisible to the revaluation
* (the payables side has always included it).
+ *
+ * When `asOfDate` is given the population is measured AS OF that date, not as
+ * of now. Two independent adjustments:
+ * - the date ceiling (`invoice_date <= asOfDate`) is UNCONDITIONAL: an invoice
+ * issued after the balансdagen was not on the balance sheet being valued,
+ * whether or not that date happens to be in the past. Post-dated invoices
+ * make this reachable for a current period too.
+ * - the status widening to 'paid' applies only to a historical date, where an
+ * invoice settled since (in March, say) was still open on 31 December. For
+ * today or the future the stored open state IS the as-of state.
+ * The caller recomputes each row's outstanding from the payment history (see
+ * previewCurrencyRevaluation). Same reconstruction contract as
+ * countOpenFxItemsAtBalansdagen in year-end-service and the reskontra reports.
*/
export async function getOpenForeignCurrencyReceivables(
supabase: SupabaseClient,
- companyId: string
+ companyId: string,
+ asOfDate?: string
): Promise {
+ const historical = asOfDate != null && asOfDate < todayIsoDate()
try {
// Paginated with a stable id order so a company with >1000 open FX invoices
// is fully revalued rather than silently truncated at 1000 rows.
- return await fetchAllRows(({ from, to }) =>
- supabase
+ return await fetchAllRows(({ from, to }) => {
+ const base = supabase
.from('invoices')
.select('*')
.eq('company_id', companyId)
- .in('status', ['sent', 'overdue', 'partially_paid'])
.neq('currency', 'SEK')
- .order('id', { ascending: true })
- .range(from, to)
- , { dedupeBy: (i) => i.id })
+ .in(
+ 'status',
+ historical
+ ? ['sent', 'overdue', 'partially_paid', 'paid']
+ : ['sent', 'overdue', 'partially_paid']
+ )
+ const scoped = asOfDate != null ? base.lte('invoice_date', asOfDate) : base
+ return scoped.order('id', { ascending: true }).range(from, to)
+ }, { dedupeBy: (i) => i.id })
} catch (err) {
throw new BookkeepingDatabaseError(
'fetch_currency_receivables',
@@ -123,24 +202,34 @@ export async function getOpenForeignCurrencyReceivables(
* Returns supplier invoices with open statuses and non-SEK currency,
* INCLUDING ones with no `exchange_rate` (see the receivables note above).
* Uses remaining_amount for partial payments.
+ *
+ * `asOfDate` behaves as on the receivables side: the date ceiling is
+ * unconditional, the widening to 'paid' applies only to a historical date.
*/
export async function getOpenForeignCurrencyPayables(
supabase: SupabaseClient,
- companyId: string
+ companyId: string,
+ asOfDate?: string
): Promise {
+ const historical = asOfDate != null && asOfDate < todayIsoDate()
try {
// Paginated with a stable id order so a company with >1000 open FX payables
// is fully revalued rather than silently truncated at 1000 rows.
- return await fetchAllRows(({ from, to }) =>
- supabase
+ return await fetchAllRows(({ from, to }) => {
+ const base = supabase
.from('supplier_invoices')
.select('*')
.eq('company_id', companyId)
- .in('status', ['registered', 'approved', 'overdue', 'partially_paid'])
.neq('currency', 'SEK')
- .order('id', { ascending: true })
- .range(from, to)
- , { dedupeBy: (i) => i.id })
+ .in(
+ 'status',
+ historical
+ ? ['registered', 'approved', 'overdue', 'partially_paid', 'paid']
+ : ['registered', 'approved', 'overdue', 'partially_paid']
+ )
+ const scoped = asOfDate != null ? base.lte('invoice_date', asOfDate) : base
+ return scoped.order('id', { ascending: true }).range(from, to)
+ }, { dedupeBy: (i) => i.id })
} catch (err) {
throw new BookkeepingDatabaseError(
'fetch_currency_payables',
@@ -171,26 +260,67 @@ export async function previewCurrencyRevaluation(
companyId: string,
closingDate: string
): Promise {
+ const emptyPreview: CurrencyRevaluationPreviewWithExclusions = {
+ items: [],
+ lines: [],
+ closingRates: {},
+ totalGain: 0,
+ totalLoss: 0,
+ netEffect: 0,
+ unconvertedFx: [],
+ unconvertedFxCount: 0,
+ missingClosingRates: [],
+ }
+
+ const scope = await fetchFxExposureScope(supabase, companyId)
+
const [receivables, payables] = await Promise.all([
- getOpenForeignCurrencyReceivables(supabase, companyId),
- getOpenForeignCurrencyPayables(supabase, companyId),
+ getOpenForeignCurrencyReceivables(supabase, companyId, closingDate),
+ getOpenForeignCurrencyPayables(supabase, companyId, closingDate),
])
+ // For a historical balansdagen the live status/paid_amount columns describe
+ // today, not the balance sheet being valued: reconstruct each row's
+ // outstanding from the payment history, the same walk-back the reskontra
+ // reports and countOpenFxItemsAtBalansdagen use.
+ const isHistorical = closingDate < todayIsoDate()
+ const [receivablePayments, payablePayments]: [PaymentsAsOf | null, PaymentsAsOf | null] =
+ await Promise.all([
+ isHistorical && receivables.length > 0
+ ? fetchPaymentsAsOf(supabase, 'invoice_payments', 'invoice_id', companyId, closingDate)
+ : null,
+ isHistorical && payables.length > 0
+ ? fetchPaymentsAsOf(
+ supabase,
+ 'supplier_invoice_payments',
+ 'supplier_invoice_id',
+ companyId,
+ closingDate
+ )
+ : null,
+ ])
+
// Partition into rows we can revalue and rows with no original rate, and
// collect the distinct currencies of the revaluable rows.
const currencies = new Set()
const unconvertedFx: UnconvertedFxItem[] = []
const revaluableReceivables: Array<{ inv: Invoice; outstanding: number }> = []
- const revaluablePayables: SupplierInvoice[] = []
+ const revaluablePayables: Array<{ si: SupplierInvoice; outstanding: number }> = []
for (const inv of receivables) {
+ // Deferred booking: an unbooked registration is not on 1510, so it is not
+ // a monetary item to revalue (nor unmeasured exposure to report).
+ if (scope === 'booked_only' && !inv.journal_entry_id) continue
// Only the OUTSTANDING amount is a monetary item at balansdagen: the paid
// part has already been settled at its own realized rate. Kundreskontran
// derives outstanding from total - paid_amount (see year-end-service),
// so the same definition is used here, öre-rounded.
- const outstanding =
- Math.round(((Number(inv.total) || 0) - (Number(inv.paid_amount) || 0)) * 100) / 100
- // Nothing outstanding: nothing to revalue, and no exposure to report.
+ const total = Number(inv.total) || 0
+ const live = Math.round((total - (Number(inv.paid_amount) || 0)) * 100) / 100
+ const outstanding = receivablePayments
+ ? outstandingAsOf(inv, total, live, receivablePayments, closingDate)
+ : live
+ // Nothing outstanding on balansdagen: nothing to revalue, no exposure.
if (outstanding <= 0) continue
if (!hasUsableRate(inv.exchange_rate)) {
unconvertedFx.push({
@@ -207,34 +337,31 @@ export async function previewCurrencyRevaluation(
}
for (const si of payables) {
- // Nothing outstanding: nothing to revalue, and no exposure to report.
- if (Number(si.remaining_amount) <= 0) continue
+ // See the receivables note: unbooked registrations carry no 2440 balance.
+ if (scope === 'booked_only' && !si.registration_journal_entry_id) continue
+ const total = Number(si.total) || 0
+ const live = Number(si.remaining_amount) || 0
+ const outstanding = payablePayments
+ ? outstandingAsOf(si, total, live, payablePayments, closingDate)
+ : live
+ // Nothing outstanding on balansdagen: nothing to revalue, no exposure.
+ if (outstanding <= 0) continue
if (!hasUsableRate(si.exchange_rate)) {
unconvertedFx.push({
type: 'payable',
source_id: si.id,
reference: si.supplier_invoice_number,
currency: si.currency as Currency,
- amount_in_currency: si.remaining_amount,
+ amount_in_currency: outstanding,
})
continue
}
currencies.add(si.currency as Currency)
- revaluablePayables.push(si)
+ revaluablePayables.push({ si, outstanding })
}
if (currencies.size === 0) {
- return {
- items: [],
- lines: [],
- closingRates: {},
- totalGain: 0,
- totalLoss: 0,
- netEffect: 0,
- unconvertedFx,
- unconvertedFxCount: unconvertedFx.length,
- missingClosingRates: [],
- }
+ return { ...emptyPreview, unconvertedFx, unconvertedFxCount: unconvertedFx.length }
}
// Fetch closing rates one currency at a time through fetchExchangeRate: it
@@ -294,12 +421,12 @@ export async function previewCurrencyRevaluation(
})
}
- // Process payables (use remaining_amount for partial payments)
- for (const si of revaluablePayables) {
+ // Process payables (outstanding as of balansdagen, mirroring receivables)
+ for (const { si, outstanding } of revaluablePayables) {
const closingRate = rateMap.get(si.currency as Currency)
if (!closingRate || !si.exchange_rate) continue
- const amountInCurrency = si.remaining_amount
+ const amountInCurrency = outstanding
const originalSek = Math.round(amountInCurrency * si.exchange_rate * 100) / 100
const closingSek = Math.round(amountInCurrency * closingRate * 100) / 100
diff --git a/lib/core/bookkeeping/year-end-service.ts b/lib/core/bookkeeping/year-end-service.ts
index 599ed700..a7d860be 100644
--- a/lib/core/bookkeeping/year-end-service.ts
+++ b/lib/core/bookkeeping/year-end-service.ts
@@ -884,9 +884,17 @@ function hasUsableFxRate(rate: number | string | null | undefined): boolean {
* cannot be dated, so its live outstanding is assumed to have stood at
* balansdagen; and an invoice cancelled or credited since is treated as never
* having been open, because neither event carries a reliable date. The status
- * population is kept identical to what the revaluation engine actually acts on
- * (`getOpenForeignCurrencyReceivables` / `...Payables`), so the warning never
- * points at rows for which no remedy exists.
+ * population, date scoping and outstanding reconstruction are kept identical
+ * to what the revaluation engine acts on (`getOpenForeignCurrencyReceivables`
+ * / `...Payables` with the same as-of date).
+ *
+ * Deliberately NOT gated by `fxExposureScope`, unlike the revaluation itself.
+ * An unbooked FX row is exactly the case worth warning about: it is not on
+ * 1510/2440 yet, so the revaluation skips it, but POST /api/invoices/[id]/book
+ * still books it at its own invoice_date, i.e. into the year about to close.
+ * Once step 7/8 lock and close the period that remedy is gone for good, so
+ * suppressing the warning here would convert a recoverable state into a
+ * permanent misstatement.
*/
async function countOpenFxItemsAtBalansdagen(
supabase: SupabaseClient,
diff --git a/lib/salary/__tests__/calculation-engine.test.ts b/lib/salary/__tests__/calculation-engine.test.ts
index caf74760..78f8cb47 100644
--- a/lib/salary/__tests__/calculation-engine.test.ts
+++ b/lib/salary/__tests__/calculation-engine.test.ts
@@ -7,6 +7,7 @@ import {
calculateVacationAccrual,
prorateBaseSalaryForPeriod,
} from '../calculation-engine'
+import { calculateVacationPay } from '../absence-calculator'
import type { PayrollConfig } from '../payroll-config'
import type { TaxTableRate } from '../tax-tables'
@@ -641,8 +642,8 @@ describe('hardening: vacation rule contract', () => {
)
expect(r.grossSalary).toBe(40000)
expect(r.vacationCompensation).toBe(0)
- // dagslön 40000/21 × 0.43% × 25 ≈ 204.76
- expect(r.vacationAccrual).toBeCloseTo(204.76, 1)
+ // månadslön 40000 × 0.43% × 25/12 ≈ 358.33
+ expect(r.vacationAccrual).toBeCloseTo(358.33, 1)
})
it('none: nothing accrued, nothing paid out', () => {
@@ -755,8 +756,48 @@ describe('hardening: sammalöneregeln', () => {
}),
config2026, emptyTaxRates
)
- // 40000/21 × 0.8% × 25 ≈ 380.95
- expect(r.vacationAccrual).toBeCloseTo(380.95, 1)
+ // 40000 × 0.8% × 25/12 ≈ 666.67
+ expect(r.vacationAccrual).toBeCloseTo(666.67, 1)
+ })
+
+ it('values the tillägg on the monthly salary, not the dagslön', () => {
+ const r = calculateSalary(
+ makeBasicInput({
+ vacationRule: 'sammaloneregeln', monthlySalary: 36000,
+ lineItems: [baseLineItem(36000)],
+ }),
+ config2026, emptyTaxRates
+ )
+ // Semesterlagen 16a §: the tillägg is a share of the MONTHLY salary per
+ // vacation day (154.80/day here), and only the month's earned share
+ // (25/12 days) accrues. Valuing it off a dagslön (36000/21) and booking
+ // all 25 days every run produced 184.29, under-provisioning 2920 by ~43%.
+ expect(r.vacationAccrual).toBeCloseTo(322.5, 1)
+ })
+
+ it('accrues a day at exactly what absence-calculator later pays out for it', () => {
+ const monthlySalary = 36000
+ const semestertillaggRate = 0.0043
+ const run = calculateSalary(
+ makeBasicInput({
+ vacationRule: 'sammaloneregeln', monthlySalary, semestertillaggRate,
+ lineItems: [baseLineItem(monthlySalary)],
+ }),
+ config2026, emptyTaxRates
+ )
+ const accrualPerDay = run.vacationAccrual / (25 / 12)
+ const payoutPerDay = calculateVacationPay({
+ monthlySalary,
+ vacationDaysTaken: 1,
+ vacationRule: 'sammaloneregeln',
+ semestertillaggRate,
+ vacationDaysPerYear: 25,
+ }).tillagg
+
+ // 2920 is credited here and relieved there. When the two bases disagreed
+ // the liability drifted negative on every taken day, which is the defect
+ // this pins: provision and payout must value a day identically.
+ expect(accrualPerDay).toBeCloseTo(payoutPerDay, 2)
})
})
@@ -945,8 +986,8 @@ describe('calculateVacationAccrual (standalone export)', () => {
vacationBasis: 40000,
})
expect(partTime.accrual).toBeCloseTo(fullTime.accrual / 2, 1)
- // Independent check: 20000/21 × 0.43% × 25 ≈ 102.38
- expect(partTime.accrual).toBeCloseTo(102.38, 1)
+ // Independent check: 20000 × 0.43% × 25/12 ≈ 179.17
+ expect(partTime.accrual).toBeCloseTo(179.17, 1)
})
it('semesterersattning: 0 accrual with the correct step label', () => {
diff --git a/lib/salary/__tests__/vacation-ledger.test.ts b/lib/salary/__tests__/vacation-ledger.test.ts
index 7bdc48da..be1b238e 100644
--- a/lib/salary/__tests__/vacation-ledger.test.ts
+++ b/lib/salary/__tests__/vacation-ledger.test.ts
@@ -65,6 +65,7 @@ describe('syncVacationLedgerForEmployees', () => {
openRows?: Array>
opening?: Array>
savedLegacy?: number
+ employmentStart?: string
}) => {
mock.enqueue({ data: { salary_vacation_year_basis: over.basis ?? 'calendar' } }) // company_settings
mock.enqueue({
@@ -74,6 +75,8 @@ describe('syncVacationLedgerForEmployees', () => {
vacation_days_per_year: 25,
vacation_days_saved: over.savedLegacy ?? 0,
vacation_rule: 'procentregeln',
+ // Long-tenured by default so the pro-rating cases stay opt-in.
+ employment_start: over.employmentStart ?? '2015-01-01',
},
],
}) // employees
@@ -104,6 +107,49 @@ describe('syncVacationLedgerForEmployees', () => {
expect(row.accrued_days).toBe(0)
})
+ it('pro-rates entitled days for a mid-intjänandeår hire (Semesterlagen 7 §)', async () => {
+ // Hired 2025-05-19. For semesteråret starting 2026-04-01 the intjänandeår
+ // is 2025-04-01 to 2026-04-01 (365 days), of which 317 were employed:
+ // 317/365 x 25 = 21.71, rounded UP to 22. Reporting a flat 25 told the
+ // employee they had three paid days they had not earned.
+ queueBase({ basis: 'statutory_apr_mar', employmentStart: '2025-05-19' })
+
+ const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
+ expect(result.ok).toBe(true)
+ const row = upserted![0]
+ expect(row.vacation_year_start).toBe('2026-04-01')
+ expect(row.entitled_days).toBe(22)
+ })
+
+ it('gives a full entitlement to someone employed the whole intjänandeår', async () => {
+ queueBase({ basis: 'statutory_apr_mar', employmentStart: '2015-01-01' })
+
+ const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
+ expect(result.ok).toBe(true)
+ expect(upserted![0].entitled_days).toBe(25)
+ })
+
+ it('accrues from the employment date, not the vacation-year boundary', async () => {
+ // Hired 2026-07-01, three whole months into the year starting 2026-04-01
+ // as of 2026-10-15: 3/12 x 25 = 6.25, held to half days = 6.5. Counting
+ // from the year boundary instead would credit 12.5.
+ queueBase({ basis: 'statutory_apr_mar', employmentStart: '2026-07-01' })
+
+ const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-10-15')
+ expect(result.ok).toBe(true)
+ expect(upserted![0].accrued_days).toBe(6.5)
+ })
+
+ it('keeps the flat entitlement on a sammanfallande calendar year', async () => {
+ // Earning and taking share the year there, commonly with förskottssemester,
+ // so mid-year hires are a CBA question rather than a statutory one.
+ queueBase({ basis: 'calendar', employmentStart: '2026-05-19' })
+
+ const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
+ expect(result.ok).toBe(true)
+ expect(upserted![0].entitled_days).toBe(25)
+ })
+
it('seeds entitled + saved days from the cutover opening row', async () => {
queueBase({
opening: [
diff --git a/lib/salary/__tests__/work-schedule-threading.test.ts b/lib/salary/__tests__/work-schedule-threading.test.ts
index e8398717..e7f0f221 100644
--- a/lib/salary/__tests__/work-schedule-threading.test.ts
+++ b/lib/salary/__tests__/work-schedule-threading.test.ts
@@ -81,24 +81,20 @@ describe('non-default schedule: 4-day week (divisor 17.33)', () => {
expect(unpaid.amount).toBe(-1731.1)
})
- it('sammalöneregeln accrual values days by the schedule divisor', () => {
- const fourDay = calculateVacationAccrual({
- monthlySalary: 30000,
- vacationRule: 'sammaloneregeln',
- vacationDaysPerYear: 25,
- semestertillaggRate: 0.0043,
- vacationBasis: 30000,
- dailyDivisor: divisor,
- })
- const fiveDay = calculateVacationAccrual({
+ it('sammalöneregeln accrual does NOT take the schedule divisor', () => {
+ const accrual = calculateVacationAccrual({
monthlySalary: 30000,
vacationRule: 'sammaloneregeln',
vacationDaysPerYear: 25,
semestertillaggRate: 0.0043,
vacationBasis: 30000,
})
- // dailyRate 1731.1 vs 1428.57; tillägg = dailyRate x 0.43% x 25 days.
- expect(fourDay.accrual).toBe(186.09)
- expect(fiveDay.accrual).toBe(153.57)
+ // Semestertillägg is a share of the MONTHLY salary per vacation day, so a
+ // 4-day week earns the same tillägg as a 5-day week on the same monthly
+ // salary: 30000 x 0.43% x 25/12. The function deliberately exposes no
+ // divisor parameter; part-time is carried by vacationBasis instead.
+ // Previously this valued a day at monthly/divisor, which made the accrual
+ // vary with workdays per week and under-provisioned 2920 in every case.
+ expect(accrual.accrual).toBeCloseTo(268.75, 2)
})
})
diff --git a/lib/salary/calculation-engine.ts b/lib/salary/calculation-engine.ts
index 8b503571..e4a7d082 100644
--- a/lib/salary/calculation-engine.ts
+++ b/lib/salary/calculation-engine.ts
@@ -36,8 +36,10 @@ export interface SalaryCalculationInput {
semestertillaggRate: number
/** Work-schedule daily-rate divisor (arbetsschema-lite). Defaults to the
* legacy 21 (5-day week); callers with a part-time schedule pass
- * dailyDivisor(workdays_per_week) from lib/salary/work-schedule. Used by
- * the sammalöneregeln day valuation. */
+ * dailyDivisor(workdays_per_week) from lib/salary/work-schedule. Feeds the
+ * daily-rate absence paths only. Deliberately NOT the sammalöneregeln
+ * accrual: semestertillägg is a share of the monthly salary per vacation
+ * day and does not vary with workdays per week. */
dailyDivisor?: number
/** Växa-stöd */
@@ -545,19 +547,36 @@ export function calculateSalary(
})
} else {
// Sammalöneregeln (§16a): employee keeps regular salary during vacation
- // + semestertillägg per day (min 0.43%, often 0.8% per CBA)
+ // + semestertillägg per vacation day (min 0.43%, often 0.8% per CBA)
// Accrual = tillägg only (salary cost is already in normal monthly expense)
// The liability (2920) for sammalöneregeln is the tillägg portion,
// since the base salary is expensed monthly regardless of vacation.
+ //
+ // The tillägg is a share of the MONTHLY salary per vacation day, never of
+ // the dagslön. Valuing it off a daily rate under-provisioned 2920 by the
+ // whole divisor, while absence-calculator.ts relieves that same 2920 at
+ // the correct monthly base when a day is taken, so the liability drifted
+ // further negative with every taken day.
+ //
+ // Only the month's earned share accrues. The full annual entitlement used
+ // to be booked in every single run; the two errors partly cancelled, which
+ // is why the monthly total looked plausible while both halves were wrong.
+ //
// Use baseSalary (degree-adjusted): a 50% part-timer's tillägg should be
- // half a full-timer's, not the same.
- const dailyRate = r(baseSalary / (input.dailyDivisor ?? 21))
- const tillagg = r(dailyRate * input.semestertillaggRate * input.vacationDaysPerYear)
+ // half a full-timer's, not the same. The schedule divisor deliberately
+ // plays no part: semestertillägg does not depend on workdays per week.
+ const daysEarnedThisMonth = input.vacationDaysPerYear / 12
+ const tillagg = r(baseSalary * input.semestertillaggRate * daysEarnedThisMonth)
vacationAccrual = tillagg
steps.push({
label: `Semesteravsättning (sammalöneregeln, tillägg ${fmtPct(input.semestertillaggRate)})`,
- formula: `dagslön × ${fmtPct(input.semestertillaggRate)} × semesterdagar`,
- input: { daily_rate: dailyRate, semestertillagg_rate: input.semestertillaggRate, vacation_days: input.vacationDaysPerYear },
+ formula: `månadslön × ${fmtPct(input.semestertillaggRate)} × semesterdagar / 12`,
+ input: {
+ monthly_base: baseSalary,
+ semestertillagg_rate: input.semestertillaggRate,
+ vacation_days_per_year: input.vacationDaysPerYear,
+ days_earned_this_month: r(daysEarnedThisMonth),
+ },
output: vacationAccrual,
})
}
@@ -775,8 +794,6 @@ export function calculateVacationAccrual(params: {
vacationDaysPerYear: number
semestertillaggRate: number
vacationBasis: number
- /** Arbetsschema-lite daily-rate divisor; legacy 21 when omitted. */
- dailyDivisor?: number
}): { accrual: number; steps: CalculationStep[] } {
const steps: CalculationStep[] = []
@@ -811,15 +828,23 @@ export function calculateVacationAccrual(params: {
})
return { accrual, steps }
} else {
- // Sammalöneregeln: tillägg per vacation day. Use vacationBasis as the
- // degree-adjusted reference: callers must pass the part-time-adjusted
- // monthly amount, never the raw full-time monthlySalary.
- const dailyRate = r(params.vacationBasis / (params.dailyDivisor ?? 21))
- const accrual = r(dailyRate * params.semestertillaggRate * params.vacationDaysPerYear)
+ // Sammalöneregeln: tillägg per vacation day, valued on the MONTHLY salary
+ // and accrued one month's earned share at a time. See the mirrored branch
+ // in calculateSalary for why neither a dagslön base nor the full annual
+ // entitlement belongs here. Use vacationBasis as the degree-adjusted
+ // reference: callers must pass the part-time-adjusted monthly amount,
+ // never the raw full-time monthlySalary.
+ const daysEarnedThisMonth = params.vacationDaysPerYear / 12
+ const accrual = r(params.vacationBasis * params.semestertillaggRate * daysEarnedThisMonth)
steps.push({
label: `Semesteravsättning (sammalöneregeln ${fmtPct(params.semestertillaggRate)})`,
- formula: `dagslön × ${fmtPct(params.semestertillaggRate)} × semesterdagar`,
- input: { daily_rate: dailyRate, rate: params.semestertillaggRate, days: params.vacationDaysPerYear },
+ formula: `månadslön × ${fmtPct(params.semestertillaggRate)} × semesterdagar / 12`,
+ input: {
+ monthly_base: params.vacationBasis,
+ rate: params.semestertillaggRate,
+ vacation_days_per_year: params.vacationDaysPerYear,
+ days_earned_this_month: r(daysEarnedThisMonth),
+ },
output: accrual,
})
return { accrual, steps }
diff --git a/lib/salary/vacation-ledger.ts b/lib/salary/vacation-ledger.ts
index fefe2765..a3985a1b 100644
--- a/lib/salary/vacation-ledger.ts
+++ b/lib/salary/vacation-ledger.ts
@@ -73,7 +73,7 @@ export async function syncVacationLedgerForEmployees(
const { data: employees, error: empErr } = await supabase
.from('employees')
- .select('id, vacation_days_per_year, vacation_days_saved, vacation_rule')
+ .select('id, vacation_days_per_year, vacation_days_saved, vacation_rule, employment_start')
.eq('company_id', companyId)
.in('id', employeeIds)
if (empErr) return { ok: false, message: empErr.message }
@@ -83,6 +83,7 @@ export async function syncVacationLedgerForEmployees(
vacation_days_per_year: number
vacation_days_saved: number
vacation_rule: string
+ employment_start: string
}>).map((e) => [e.id, e]),
)
@@ -156,7 +157,7 @@ export async function syncVacationLedgerForEmployees(
employee_id: employeeId,
vacation_year_start: row.vacation_year_start,
entitled_days: row.entitled_days,
- accrued_days: computeAccruedDays(basis, row.vacation_year_start, asOfDate, employee.vacation_days_per_year),
+ accrued_days: computeAccruedDays(basis, row.vacation_year_start, asOfDate, employee.vacation_days_per_year, employee.employment_start),
taken_days: takenInYear(employeeId, row.vacation_year_start),
saved_days: row.saved_days ?? {},
forced_payout_days: row.forced_payout_days ?? 0,
@@ -189,11 +190,18 @@ export async function syncVacationLedgerForEmployees(
company_id: companyId,
employee_id: employeeId,
vacation_year_start: currentYearStart,
+ // A cutover opening balance is the migrated truth from the previous
+ // system and outranks any recomputation.
entitled_days:
cutoverInThisYear && opening
? opening.vacation_paid_days_remaining
- : employee.vacation_days_per_year,
- accrued_days: computeAccruedDays(basis, currentYearStart, asOfDate, employee.vacation_days_per_year),
+ : computeEntitledDays(
+ basis,
+ currentYearStart,
+ employee.vacation_days_per_year,
+ employee.employment_start,
+ ),
+ accrued_days: computeAccruedDays(basis, currentYearStart, asOfDate, employee.vacation_days_per_year, employee.employment_start),
taken_days: takenInYear(employeeId, currentYearStart),
saved_days: savedDays,
forced_payout_days: 0,
@@ -220,24 +228,93 @@ export async function syncVacationLedgerForEmployees(
* Apr-Mar basis, where intjänandeår (this year) and semesterår (next year)
* are split. Sammanfallande calendar years earn and take in the same year,
* so the live number is entitled - taken and accrued stays 0.
+ *
+ * Earning starts on the employment date, not on the year boundary: a mid-year
+ * hire has not earned the months before their first day, and showing them the
+ * full year's accrual overstates what they may take.
*/
function computeAccruedDays(
basis: VacationYearBasis,
yearStart: string,
asOfDate: string,
vacationDaysPerYear: number,
+ employmentStart: string,
): number {
if (basis !== 'statutory_apr_mar') return 0
const bounds = getVacationYearBounds(yearStart)
if (asOfDate < bounds.start) return 0
- if (asOfDate >= bounds.end) return vacationDaysPerYear
- const startYear = Number(yearStart.slice(0, 4))
- const startMonth = Number(yearStart.slice(5, 7))
- const asOfYear = Number(asOfDate.slice(0, 4))
- const asOfMonth = Number(asOfDate.slice(5, 7))
- const elapsedMonths = (asOfYear - startYear) * 12 + (asOfMonth - startMonth)
+ // Employed only after this earning year closed: nothing earned in it.
+ if (employmentStart >= bounds.end) return 0
+ const earningStart = employmentStart > bounds.start ? employmentStart : bounds.start
+ const effectiveAsOf = asOfDate >= bounds.end ? bounds.end : asOfDate
+ const elapsedMonths = wholeMonthsBetween(earningStart, effectiveAsOf)
// Whole elapsed months / 12, rounded to half days (Semesterlagen 3a §
// rounds UP to whole days at payout; the running accrual view keeps halves
// for transparency).
return Math.round(((elapsedMonths / 12) * vacationDaysPerYear) * 2) / 2
}
+
+/** Whole calendar months from `from` to `to`, day-of-month ignored (the
+ * pre-existing convention of this view). */
+function wholeMonthsBetween(from: string, to: string): number {
+ const months =
+ (Number(to.slice(0, 4)) - Number(from.slice(0, 4))) * 12 +
+ (Number(to.slice(5, 7)) - Number(from.slice(5, 7)))
+ return months > 0 ? months : 0
+}
+
+/**
+ * Betalda semesterdagar for a semesterår, per Semesterlagen 7 §:
+ *
+ * anställningsdagar under intjänandeåret / dagar under intjänandeåret
+ * x semesterdagar, and "om ett brutet tal då uppstår, avrundas detta till
+ * närmast högre hela tal" (round UP, always).
+ *
+ * The intjänandeår is the twelve months immediately preceding the semesterår
+ * (3 §), so someone hired part-way through it earns proportionally fewer PAID
+ * days while keeping the right to take unpaid ones.
+ *
+ * Two deliberate omissions, both of which can only overstate entitlement and
+ * never understate it, so neither can silently deny an employee a paid day:
+ *
+ * - 7 § also subtracts days of unpaid full-day absence. The ledger has no
+ * unpaid-absence day source, so that term is not modelled.
+ * - 4 § second sentence caps semesterLEDIGHET at five days when employment
+ * starts after 31 August of the semesterår. That is a cap on days off,
+ * paid or unpaid, which is a different quantity from the paid days 7 §
+ * computes, so it does not belong in this number.
+ *
+ * Only applied on the statutory basis. Under sammanfallande semesterår the
+ * employee earns and takes in the same year, commonly with förskottssemester,
+ * and how a mid-year hire is treated is a collective-agreement question rather
+ * than a statutory one. Those companies keep the flat entitlement until that
+ * is decided.
+ */
+export function computeEntitledDays(
+ basis: VacationYearBasis,
+ yearStart: string,
+ vacationDaysPerYear: number,
+ employmentStart: string,
+): number {
+ if (basis !== 'statutory_apr_mar') return vacationDaysPerYear
+ // The intjänandeår is the year immediately BEFORE this semesterår.
+ const semesterBounds = getVacationYearBounds(yearStart)
+ const earningStart = shiftYear(semesterBounds.start, -1)
+ const earningEnd = semesterBounds.start
+ if (employmentStart >= earningEnd) return 0
+ const totalDays = daysBetween(earningStart, earningEnd)
+ if (totalDays <= 0) return vacationDaysPerYear
+ const employedFrom = employmentStart > earningStart ? employmentStart : earningStart
+ const employedDays = daysBetween(employedFrom, earningEnd)
+ const quota = (employedDays / totalDays) * vacationDaysPerYear
+ return Math.min(vacationDaysPerYear, Math.ceil(quota))
+}
+
+function shiftYear(iso: string, delta: number): string {
+ return `${Number(iso.slice(0, 4)) + delta}${iso.slice(4)}`
+}
+
+function daysBetween(from: string, to: string): number {
+ const ms = Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)
+ return Math.round(ms / 86_400_000)
+}
diff --git a/messages/en.json b/messages/en.json
index d1989a9d..5af4073e 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -1604,7 +1604,8 @@
"format_bg_lb": "Bankgirot LB file",
"format_pain001": "ISO 20022 pain.001 (XML)",
"format_description_bg_lb": "Legacy Bankgirot format. Being retired by the banks during 2026 — use pain.001 if your bank supports it.",
- "format_description_pain001": "ISO 20022 — the new payment file standard at Swedbank, SEB, Handelsbanken and Nordea.",
+ "format_description_pain001": "ISO 20022, the payment file standard. Usually requires a file transfer agreement with your bank: several online banks do not accept pain.001 through ordinary file upload.",
+ "pain001_agreement_warning": "pain.001 is normally delivered through a file transfer agreement or a bankgiro connection, not by uploading it in your online bank. Check that your bank accepts the file that way well before the pay date.",
"sunset_warning": "Swedish banks are retiring Bankgirot Lön during 2026 — Swedbank stops accepting LB salary files on 1 August 2026, other banks during the autumn. Switch to pain.001 in good time.",
"sunset_link": "Change in payroll settings",
"download": "Download payment file",
@@ -1622,7 +1623,7 @@
"steps_bg_lb_handelsbanken": "Betala → Filimport → choose LB → verify totals → sign. Note: Handelsbanken no longer accepts salary files via Bankgirot.",
"steps_bg_lb_nordea": "Filimport → Bankgiro LB → upload → approve the payment.",
"steps_pain001_swedbank": "Betala och överföra → Filtjänster → Upload file (ISO 20022 pain.001) → sign with BankID.",
- "steps_pain001_seb": "Betalningar → Import SEPA / ISO 20022 (pain.001) → upload and sign. The file must be received no later than 10:30 the day before the pay date.",
+ "steps_pain001_seb": "SEB Business Arena does not accept pain.001 through file upload, only CSV, and SEB's SEPA CSV covers EUR payments only. pain.001 to SEB requires a file transfer agreement. Without one, choose the Bankgirot LB file instead for domestic salaries in SEK.",
"steps_pain001_handelsbanken": "Betala → Filimport → ISO 20022 → choose pain.001 → sign.",
"steps_pain001_nordea": "Filimport in Nordea Business → Format pain.001 → upload → approve.",
"tax_title": "Payment to your skattekonto",
diff --git a/messages/sv.json b/messages/sv.json
index 7004c105..76a41dec 100644
--- a/messages/sv.json
+++ b/messages/sv.json
@@ -1604,7 +1604,8 @@
"format_bg_lb": "Bankgirot LB-fil",
"format_pain001": "ISO 20022 pain.001 (XML)",
"format_description_bg_lb": "Äldre Bankgirot-format. Avvecklas av bankerna under 2026 — använd pain.001 om din bank stöder det.",
- "format_description_pain001": "ISO 20022 — den nya standarden för betalfiler hos Swedbank, SEB, Handelsbanken och Nordea.",
+ "format_description_pain001": "ISO 20022, standarden för betalfiler. Kräver oftast filkommunikationsavtal med banken: flera internetbanker tar inte emot pain.001 via vanlig filuppladdning.",
+ "pain001_agreement_warning": "pain.001 skickas normalt via filkommunikationsavtal eller bankgirokoppling, inte genom att laddas upp i internetbanken. Kontrollera att din bank tar emot filen den vägen i god tid före utbetalningsdagen.",
"sunset_warning": "Bankerna avvecklar Bankgirot Lön under 2026 — Swedbank slutar ta emot LB-lönefiler 1 augusti 2026, övriga banker under hösten. Byt till pain.001 i god tid.",
"sunset_link": "Ändra i löneinställningarna",
"download": "Ladda ner betalfil",
@@ -1622,7 +1623,7 @@
"steps_bg_lb_handelsbanken": "Betala → Filimport → välj LB → kontrollera summor → signera. OBS: Handelsbanken tar inte längre emot lönefiler via Bankgirot.",
"steps_bg_lb_nordea": "Filimport → Bankgiro LB → ladda upp → attestera betalningen.",
"steps_pain001_swedbank": "Betala och överföra → Filtjänster → Ladda upp fil (ISO 20022 pain.001) → signera med BankID.",
- "steps_pain001_seb": "Betalningar → Importera SEPA / ISO 20022 (pain.001) → ladda upp och signera. Filen ska vara inne senast 10:30 dagen före utbetalningsdagen.",
+ "steps_pain001_seb": "SEB Business Arena tar inte emot pain.001 via filuppladdning, där godkänns bara CSV, och SEB:s SEPA-CSV gäller enbart betalningar i EUR. pain.001 till SEB kräver filkommunikationsavtal. Utan ett sådant avtal: välj Bankgirot LB-filen i stället för inrikes löner i SEK.",
"steps_pain001_handelsbanken": "Betala → Filimport → ISO 20022 → välj pain.001 → signera.",
"steps_pain001_nordea": "Filimport i Nordea Business → Format pain.001 → ladda upp → attestera.",
"tax_title": "Inbetalning till Skattekontot",