* 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>
184 lines
5.7 KiB
TypeScript
184 lines
5.7 KiB
TypeScript
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'crypto'
|
|
import { createLogger } from '@/lib/logger'
|
|
|
|
const ALGORITHM = 'aes-256-gcm'
|
|
const IV_LENGTH = 12
|
|
const TAG_LENGTH = 16
|
|
|
|
const logger = createLogger('salary/personnummer')
|
|
|
|
/**
|
|
* Get the encryption key from environment.
|
|
* Falls back to a dev-only key for local development.
|
|
*/
|
|
function getEncryptionKey(): Buffer {
|
|
const envKey = process.env.PERSONNUMMER_ENCRYPTION_KEY
|
|
if (!envKey) {
|
|
if (process.env.NODE_ENV === 'production') {
|
|
throw new Error('PERSONNUMMER_ENCRYPTION_KEY is required in production')
|
|
}
|
|
// Dev-only deterministic key (NOT safe for production)
|
|
return scryptSync('dev-only-key', 'gnubok-dev-salt', 32)
|
|
}
|
|
// Use scrypt to derive a 32-byte key from the env var
|
|
return scryptSync(envKey, 'gnubok-pnr-salt', 32)
|
|
}
|
|
|
|
/**
|
|
* Encrypt a personnummer for storage.
|
|
* Returns a hex string: iv + ciphertext + authTag
|
|
*/
|
|
export function encryptPersonnummer(personnummer: string): string {
|
|
const key = getEncryptionKey()
|
|
const iv = randomBytes(IV_LENGTH)
|
|
const cipher = createCipheriv(ALGORITHM, key, iv)
|
|
|
|
let encrypted = cipher.update(personnummer, 'utf8', 'hex')
|
|
encrypted += cipher.final('hex')
|
|
const authTag = cipher.getAuthTag()
|
|
|
|
return iv.toString('hex') + encrypted + authTag.toString('hex')
|
|
}
|
|
|
|
/**
|
|
* Decrypt a personnummer from storage.
|
|
*/
|
|
export function decryptPersonnummer(encrypted: string): string {
|
|
// Tolerate legacy/unencrypted rows. A raw 12-digit personnummer (written by
|
|
// a path that skipped encryptPersonnummer, e.g. the v1 REST create route
|
|
// before this fix, or a seed) would otherwise be sliced as iv/ciphertext/tag
|
|
// and throw ERR_CRYPTO_INVALID_AUTH_TAG ("Invalid authentication tag length:
|
|
// 6"), 500-ing every decrypt-on-read path (roster, salary runs, payslips,
|
|
// KU, AGI, MCP). Real ciphertext is 80 hex chars, so a 12-digit match is
|
|
// unambiguously plaintext. Return it as-is and warn so the backfill can find
|
|
// and re-encrypt it. Value is never logged. See DECISIONS.md.
|
|
if (/^\d{12}$/.test(encrypted)) {
|
|
logger.warn('decryptPersonnummer received an unencrypted personnummer; returning as-is (row needs backfill)')
|
|
return encrypted
|
|
}
|
|
|
|
const key = getEncryptionKey()
|
|
const ivHex = encrypted.slice(0, IV_LENGTH * 2)
|
|
const authTagHex = encrypted.slice(-TAG_LENGTH * 2)
|
|
const ciphertext = encrypted.slice(IV_LENGTH * 2, -TAG_LENGTH * 2)
|
|
|
|
const iv = Buffer.from(ivHex, 'hex')
|
|
const authTag = Buffer.from(authTagHex, 'hex')
|
|
|
|
const decipher = createDecipheriv(ALGORITHM, key, iv)
|
|
decipher.setAuthTag(authTag)
|
|
|
|
let decrypted = decipher.update(ciphertext, 'hex', 'utf8')
|
|
decrypted += decipher.final('utf8')
|
|
return decrypted
|
|
}
|
|
|
|
/**
|
|
* Extract the last 4 digits of a personnummer for display.
|
|
*/
|
|
export function extractLast4(personnummer: string): string {
|
|
const digits = personnummer.replace(/\D/g, '')
|
|
return digits.slice(-4)
|
|
}
|
|
|
|
/**
|
|
* Validate a Swedish personnummer (12-digit format: YYYYMMDDNNNN).
|
|
* Checks format + Luhn checksum on last 10 digits.
|
|
*/
|
|
export function validatePersonnummer(personnummer: string): { valid: boolean; error?: string } {
|
|
const digits = personnummer.replace(/\D/g, '')
|
|
|
|
if (digits.length !== 12) {
|
|
return { valid: false, error: 'Personnummer måste vara 12 siffror (ÅÅÅÅMMDDNNNN)' }
|
|
}
|
|
|
|
const year = parseInt(digits.slice(0, 4))
|
|
const month = parseInt(digits.slice(4, 6))
|
|
const day = parseInt(digits.slice(6, 8))
|
|
|
|
if (year < 1900 || year > 2100) {
|
|
return { valid: false, error: 'Ogiltigt år' }
|
|
}
|
|
if (month < 1 || month > 12) {
|
|
return { valid: false, error: 'Ogiltig månad' }
|
|
}
|
|
if (day < 1 || day > 31) {
|
|
return { valid: false, error: 'Ogiltig dag' }
|
|
}
|
|
|
|
// Luhn check on digits 3-12 (YYMMDDNNNN, 10 digits)
|
|
const luhnDigits = digits.slice(2)
|
|
if (!luhnCheck(luhnDigits)) {
|
|
return { valid: false, error: 'Ogiltigt kontrollnummer (Luhn)' }
|
|
}
|
|
|
|
return { valid: true }
|
|
}
|
|
|
|
/**
|
|
* Luhn checksum validation for 10-digit string.
|
|
*/
|
|
function luhnCheck(digits: string): boolean {
|
|
let sum = 0
|
|
for (let i = 0; i < digits.length; i++) {
|
|
let d = parseInt(digits[i])
|
|
// Multiply every other digit by 2, starting from the first
|
|
if (i % 2 === 0) {
|
|
d *= 2
|
|
if (d > 9) d -= 9
|
|
}
|
|
sum += d
|
|
}
|
|
return sum % 10 === 0
|
|
}
|
|
|
|
/**
|
|
* Extract birth date from a 12-digit personnummer.
|
|
*/
|
|
export function extractBirthDate(personnummer: string): { year: number; month: number; day: number } {
|
|
const digits = personnummer.replace(/\D/g, '')
|
|
return {
|
|
year: parseInt(digits.slice(0, 4)),
|
|
month: parseInt(digits.slice(4, 6)),
|
|
day: parseInt(digits.slice(6, 8)),
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Calculate age at a given date from a personnummer.
|
|
*/
|
|
export function calculateAge(personnummer: string, atDate: string): number {
|
|
const birth = extractBirthDate(personnummer)
|
|
const [refYear, refMonth, refDay] = atDate.split('-').map(Number)
|
|
|
|
let age = refYear - birth.year
|
|
if (refMonth < birth.month || (refMonth === birth.month && refDay < birth.day)) {
|
|
age--
|
|
}
|
|
return age
|
|
}
|
|
|
|
/**
|
|
* Calculate age at the start of a given year.
|
|
* Used for avgifter age tier determination.
|
|
*/
|
|
export function calculateAgeAtYearStart(personnummer: string, year: number): number {
|
|
return calculateAge(personnummer, `${year}-01-01`)
|
|
}
|
|
|
|
/**
|
|
* Mask personnummer for display: YYYYMMDD-XXXX (birthdate visible, suffix hidden).
|
|
*/
|
|
export function maskPersonnummer(personnummer: string): string {
|
|
const digits = personnummer.replace(/\D/g, '')
|
|
return `${digits.slice(0, 8)}-XXXX`
|
|
}
|
|
|
|
/**
|
|
* Format personnummer with dash: YYYYMMDD-NNNN
|
|
*/
|
|
export function formatPersonnummer(personnummer: string): string {
|
|
const digits = personnummer.replace(/\D/g, '')
|
|
return `${digits.slice(0, 8)}-${digits.slice(8)}`
|
|
}
|