* feat(salary): validate employee clearing/kontonummer at entry Bank details on the "Anställda" form had no structural validation, so a typo in clearing/kontonummer was saved silently and only surfaced at Bankgirot LB generation (or never, on the SEPA path). Adds a shared validator (lib/salary/payment/bank-account.ts) wired into the create dialog, edit page, CreateEmployeeSchema, and the PATCH route: 4-digit clearing or 5-digit Swedbank (8xxxx), 5-11 digit account, both-or-neither. Mirrors encodeReceiverAccount so entry-time validation matches what the payout layer can encode. Update validates only when a bank field actually changes, so legacy free-text data stays editable. Includes a conservative clearing to bank-name hint (null for unknown ranges). Per-bank mod10/mod11 checksum deferred to a soft-warning follow-up. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(chart-of-accounts): styled delete warnings and bulk select-all Replace the native window.confirm() on single-account delete with the styled DestructiveConfirmDialog, and add to the prune dialog a master 'select all unused accounts' checkbox plus an explicit confirmation step before bulk deletion. New sv/en strings for the confirm titles and actions. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(salary): encrypt personnummer on v1 employee create; tolerate legacy plaintext on read The v1 REST create route stored personnummer unencrypted, which then threw ERR_CRYPTO_INVALID_AUTH_TAG on every decrypt-on-read path and 500'd the employees roster. Encrypt on write in v1 create, decrypt on read in the v1 list/detail/patch responses, and make decryptPersonnummer pass a raw 12-digit value through with a warn so a legacy plaintext row can't take the roster down. Encrypt seeded personnummer. Add a gated, idempotent backfill for existing rows. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): save a manual entry as a reusable template Add a "Spara som mall" action to the manual journal-entry form next to the existing "Anvand mall" picker, so users can capture a booking pattern the moment they work it out. Opens the shared TemplateForm (create mode) pre-seeded from the current lines via deriveTemplateLinesFromBooking, and saves through the existing POST /api/settings/booking-templates. Rendered in both the mobile and desktop layouts and in create + edit modes. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(pending): label all staged operation types The Granskning list rendered the raw snake_case operation_type (e.g. create_supplier_invoice_from_inbox) for any type missing from the label map, which hogs the meta row and wraps awkwardly on mobile. Add short sv/en labels for all operation types in OPERATION_RISK_TIERS, plus a humanized fallback for future ones, and simplify the label map to a plain operation_type -> i18n-key record (the icon/variant fields were dead). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(reports): let users file moms without a Skatteverket connection The momsdeklaration was never gated on the Skatteverket connection (it renders from the bookkeeping), but the not-connected "Anslut med BankID" card read as a wall. Make manual filing a first-class path: - Add a "Lämna in din momsdeklaration" card under the report with a PDF download (SKV 4700 layout, hela kronor) and a skatteverket.se link. - Add a momsdeklaration PDF route + template; buildManualFilingRows() rounds each ruta to whole kronor and recomputes ruta 49 per the SKV 4700 formula so it ties out. The PDF is a read/record copy, not a submission file (moms has no upload channel). - Offer PDF alongside Excel in the report's export menu. - Reframe the not-connected SkatteverketPanel to "Skicka direkt till Skatteverket (valfritt)". Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(salary): compact new-employee dialog and warn on bad account check digit Redesign NewEmployeeDialog into a compact layout: borderless sections split by hairline dividers (no per-section cards), a fixed header + scrolling body + solid footer (fixes content showing through the old sticky bar), and denser grids. EmployeeTaxCard gains a `flat` variant so the dialog can host it without card chrome; the edit page keeps the boxed version. Add non-blocking Swedish account check-digit validation (lib/bankgiro/account-number.ts): mod10 (reuses luhn) + mod11, with a clearing->method table from the Bankgirot "Bankernas kontonummeruppbyggnad" spec, cross-checked against jop-io/kontonummer.js and verified against a real account (Forex 9420/4172385). Surfaced as a soft warning in both employee forms; unrecognised clearings return 'unknown' so we never warn on a valid but unmapped account. Never blocks saving. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(invoices): configurable send time + editing for recurring invoices Re-register the accidentally-removed recurring cron (now hourly) and add a per-schedule send hour (Europe/Stockholm, DST-aware). The cron never sends for a past date, and the enabling migration pauses every existing schedule on deploy so nothing auto-sends behind a user's back; users reactivate consciously (with a confirm) or click "Skapa faktura nu" to send this month on demand. Automatic sending now requires a customer email. Adds a full edit flow (row click opens the prefilled form, PATCH), fixing the row-click 404. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): configure självfaktura via the invoice API Add an optional is_self_billed flag (plus external_invoice_number, self_billing_agreement_ref, received_date) to the public invoice-create endpoint so callers can register a received self-billing invoice (mottagen självfaktura, ML 17 kap 15§) via the API. It was previously only reachable from the internal dashboard route, so it was missing from the API docs. Extract the booking into a shared service (lib/invoices/self-billed-sale.ts) and refactor the internal /api/invoices/self-billed route to a thin wrapper over it, so the dashboard and the API cannot drift. Books as a sale (Debit 1510 / Credit 30xx+26xx) with the counterparty's number; no own number is consumed. Fields are plain optionals (no schema refine) so UpdateInvoiceSchema.omit() keeps working; required-when-self-billed is enforced in the route. Documented in the endpoint registry. No migration (columns already exist). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(settings): allow a partial voucher-series-per-source-type map In Zod 4 an enum-keyed z.record is exhaustive (every source_type required), so saving a default_voucher_series_per_source_type map that omits a source type (e.g. the newly added result_appropriation) failed with "expected string, received undefined". Use partialRecord so the map can be sparse; the engine falls back to series 'A' for any unmapped key. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(salary): resolve employer name via getCompanyDisplayName Payslip PDFs, the payslip email, AGI, KU10, and the BG/LB + SEPA payment files now resolve the employer name through getCompanyDisplayName (company_settings.company_name, falling back to companies.name), matching how invoices already display it. Read-side coalesce, so no migration or backfill: companies.name is write-once at onboarding and not authoritative for these surfaces. The sidebar company switcher uses the same coalesce for the non-active companies in the list. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * perf(kontoplan): index-only account usage counts + lighter reference load Add a covering index on journal_entry_lines (journal_entry_id, account_number) so get_account_usage_counts becomes an index-only scan (prod worst case ~440ms). Slim /api/bookkeeping/accounts/reference to return only the company's activation rows and merge against the client-bundled BAS_REFERENCE instead of re-sending the full ~1,300-account catalog every load, and defer the BAS catalog + usage counts off the first-paint critical path in ChartOfAccountsManager. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * i18n(salary): add bank-account checksum warning string sv/en strings for the employee bank-account (clearing/kontonummer) soft checksum warning shown by the create/edit forms. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs: update decision log Append the 2026-07-06/07 decision entries (salary employer-name coalesce, sidebar switcher, employees API personnummer fix, kontoplan load optimization, momsdeklaration manual filing, recurring invoices resend + reactivation + editing, "spara som mall", voucher-series partial map, and självfaktura via the invoice API). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: address compliance-review findings on recurring invoices + moms filing - recurring cron: close the double-send window with an atomic compare-and-set claim on last_run_at (release-on-failure) so two overlapping hourly runs can't both spawn from the same stale batch row - recurring edit dialog: force auto_send=false whenever the effective customer has no email, so a disabled-but-checked box can't PATCH auto_send=true after the async customer load - momsdeklaration manual-filing: truncate rutor to whole kronor (öretal faller bort per SFL 22 kap 1 §) instead of round-to-nearest, matching the SRU path Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
127 lines
5.5 KiB
TypeScript
127 lines
5.5 KiB
TypeScript
/**
|
|
* Swedish bank account check-digit validation ("kontrollsiffra"), per the
|
|
* Bankgirot manual "Bankernas kontonummeruppbyggnad".
|
|
*
|
|
* Used ONLY as a non-blocking hint: a passing check digit does not prove the
|
|
* account exists at the bank, and a clearing we don't recognise returns
|
|
* 'unknown' (no opinion) rather than a guess. It covers the major, high-volume
|
|
* banks; everything else falls through to 'unknown' so we never warn on a
|
|
* valid-but-unmapped account.
|
|
*
|
|
* The clearing -> (type, comment) mapping and the two algorithms are
|
|
* cross-checked against the public jop-io/kontonummer.js reference (MIT) and
|
|
* verified against a real example account (Forex 9420 / 4172385) in the tests.
|
|
*
|
|
* Account structure recap:
|
|
* Type 1: 4-digit clearing + up to 7-digit account, mod11 check digit last.
|
|
* comment 1: mod11 over the last 10 digits of clearing+account.
|
|
* comment 2: mod11 over the full clearing+account (11 digits).
|
|
* Type 2: check digit lives in the account alone.
|
|
* comment 1: mod10 over a 10-digit account.
|
|
* comment 2: mod11 over a 9-digit account (Handelsbanken).
|
|
* comment 3: mod10 over a 6-10 digit account; the 5-digit 8xxxx clearing
|
|
* carries its own mod10 check digit too (Swedbank/Sparbanken).
|
|
*/
|
|
import { luhnValidate } from './luhn'
|
|
|
|
export type AccountChecksumResult = 'valid' | 'invalid' | 'unknown'
|
|
|
|
// Swedish "11-modulen" weights. For an N-digit input the last N weights are
|
|
// used, applied left-to-right, so the rightmost (check) digit gets weight 1.
|
|
// Valid when the weighted sum is non-zero and divisible by 11.
|
|
const MOD11_WEIGHTS = [1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
|
|
|
|
function mod11Valid(digits: string): boolean {
|
|
if (digits.length === 0 || digits.length > MOD11_WEIGHTS.length) return false
|
|
const weights = MOD11_WEIGHTS.slice(MOD11_WEIGHTS.length - digits.length)
|
|
let sum = 0
|
|
for (let i = 0; i < digits.length; i++) {
|
|
sum += Number(digits[i]) * weights[i]
|
|
}
|
|
return sum !== 0 && sum % 11 === 0
|
|
}
|
|
|
|
interface ClearingRule {
|
|
type: 1 | 2
|
|
comment: 1 | 2 | 3
|
|
}
|
|
|
|
// Ordered resolution: exact-clearing exceptions win over ranges. Only the
|
|
// major banks are mapped; anything else returns null -> 'unknown'. The bank
|
|
// names in the comments are for reference; the display name comes from
|
|
// lookupBankByClearing in lib/salary/payment/bank-account.ts.
|
|
function resolveClearingRule(clearing4: number): ClearingRule | null {
|
|
// Nordea personkonto (10-digit mod10 account): exceptions inside the 3xxx range.
|
|
if (clearing4 === 3300 || clearing4 === 3782) return { type: 2, comment: 1 }
|
|
|
|
const inRange = (lo: number, hi: number) => clearing4 >= lo && clearing4 <= hi
|
|
|
|
// Type 1, comment 1 (mod11 over the last 10 digits of clearing+account).
|
|
if (inRange(1100, 1199)) return { type: 1, comment: 1 } // Nordea
|
|
if (inRange(1200, 1399)) return { type: 1, comment: 1 } // Danske Bank
|
|
if (inRange(1400, 2099)) return { type: 1, comment: 1 } // Nordea
|
|
if (inRange(2400, 2499)) return { type: 1, comment: 1 } // Danske Bank
|
|
if (inRange(3000, 3299)) return { type: 1, comment: 1 } // Nordea
|
|
if (inRange(3410, 3999)) return { type: 1, comment: 1 } // Nordea
|
|
if (inRange(5000, 5999)) return { type: 1, comment: 1 } // SEB
|
|
if (inRange(7000, 7999)) return { type: 1, comment: 1 } // Swedbank
|
|
if (inRange(9400, 9449)) return { type: 1, comment: 1 } // Forex Bank
|
|
|
|
// Type 1, comment 2 (mod11 over the full clearing+account).
|
|
if (inRange(4000, 4999)) return { type: 1, comment: 2 } // Nordea
|
|
|
|
// Type 2, comment 2 (mod11 over a 9-digit account).
|
|
if (inRange(6000, 6999)) return { type: 2, comment: 2 } // Handelsbanken
|
|
|
|
// Type 2, comment 3 (mod10 over the account; 5-digit clearing also mod10).
|
|
if (inRange(8000, 8999)) return { type: 2, comment: 3 } // Swedbank/Sparbanken
|
|
|
|
return null
|
|
}
|
|
|
|
function digitsOnly(s: string | null | undefined): string {
|
|
return (s ?? '').replace(/\D/g, '')
|
|
}
|
|
|
|
/**
|
|
* Validate the check digit(s) of a Swedish clearing/account pair.
|
|
* - 'valid' the check digit is consistent with the bank's rule
|
|
* - 'invalid' the clearing is recognised but the check digit does not match
|
|
* - 'unknown' clearing not in the table, or the length is implausible for the
|
|
* bank (so we stay silent instead of guessing)
|
|
*/
|
|
export function validateSwedishAccountChecksum(
|
|
clearingRaw: string | null | undefined,
|
|
accountRaw: string | null | undefined,
|
|
): AccountChecksumResult {
|
|
const clearing = digitsOnly(clearingRaw)
|
|
const account = digitsOnly(accountRaw)
|
|
if (clearing.length < 4 || account.length === 0) return 'unknown'
|
|
|
|
const rule = resolveClearingRule(Number(clearing.slice(0, 4)))
|
|
if (!rule) return 'unknown'
|
|
|
|
if (rule.type === 1) {
|
|
if (account.length > 7) return 'unknown'
|
|
const full = clearing.slice(0, 4) + account.padStart(7, '0') // 11 digits
|
|
const input = rule.comment === 1 ? full.slice(-10) : full
|
|
return mod11Valid(input) ? 'valid' : 'invalid'
|
|
}
|
|
|
|
// Type 2: the check digit lives in the account.
|
|
if (rule.comment === 1) {
|
|
if (account.length > 10) return 'unknown'
|
|
return luhnValidate(account.padStart(10, '0')) ? 'valid' : 'invalid'
|
|
}
|
|
if (rule.comment === 2) {
|
|
if (account.length > 9) return 'unknown'
|
|
return mod11Valid(account.padStart(9, '0')) ? 'valid' : 'invalid'
|
|
}
|
|
// comment 3: Swedbank/Sparbanken. Account is 6-10 digits (mod10); a 5-digit
|
|
// 8xxxx clearing carries its own mod10 check digit.
|
|
if (account.length < 6 || account.length > 10) return 'unknown'
|
|
const accountOk = luhnValidate(account)
|
|
const clearingOk = clearing.length === 5 ? luhnValidate(clearing) : true
|
|
return accountOk && clearingOk ? 'valid' : 'invalid'
|
|
}
|