fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { luhnCheckDigit } from '@/lib/bankgiro/luhn'
|
||||
import {
|
||||
evaluateInvoiceForBatch,
|
||||
PAYABLE_SUPPLIER_INVOICE_STATUSES,
|
||||
type BatchInvoiceFacts,
|
||||
} from '@/lib/payments/batch-eligibility'
|
||||
|
||||
const VALID_OCR = `1234567${luhnCheckDigit('1234567')}`
|
||||
const TODAY = '2026-08-10'
|
||||
|
||||
const supplier = {
|
||||
bankgiro: '5050-1055',
|
||||
plusgiro: null,
|
||||
bank_account: null,
|
||||
clearing_number: null,
|
||||
account_number: null,
|
||||
city: 'Stockholm',
|
||||
}
|
||||
|
||||
function invoice(overrides: Partial<BatchInvoiceFacts> = {}): BatchInvoiceFacts {
|
||||
return {
|
||||
id: 'inv-1',
|
||||
status: 'approved',
|
||||
approved_at: '2026-08-01T10:00:00Z',
|
||||
due_date: '2026-08-20',
|
||||
remaining_amount: 737.5,
|
||||
currency: 'SEK',
|
||||
is_credit_note: false,
|
||||
payment_reference: VALID_OCR,
|
||||
supplier_invoice_number: 'CD3014794407',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('evaluateInvoiceForBatch', () => {
|
||||
it('accepts every payable status and rejects the rest', () => {
|
||||
for (const status of PAYABLE_SUPPLIER_INVOICE_STATUSES) {
|
||||
const result = evaluateInvoiceForBatch(invoice({ status }), supplier, { today: TODAY })
|
||||
expect(result.eligible, status).toBe(true)
|
||||
}
|
||||
for (const status of ['paid', 'disputed', 'credited', 'reversed']) {
|
||||
const result = evaluateInvoiceForBatch(invoice({ status }), supplier, { today: TODAY })
|
||||
expect(result).toEqual({ eligible: false, reason: 'not_payable' })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects credit notes before anything else', () => {
|
||||
const result = evaluateInvoiceForBatch(
|
||||
invoice({ is_credit_note: true, status: 'paid' }),
|
||||
supplier,
|
||||
{ today: TODAY },
|
||||
)
|
||||
expect(result).toEqual({ eligible: false, reason: 'credit_note' })
|
||||
})
|
||||
|
||||
it('rejects a settled remainder at the epsilon boundary', () => {
|
||||
const atEpsilon = evaluateInvoiceForBatch(invoice({ remaining_amount: 0.005 }), supplier, {
|
||||
today: TODAY,
|
||||
})
|
||||
expect(atEpsilon).toEqual({ eligible: false, reason: 'nothing_remaining' })
|
||||
|
||||
const justAbove = evaluateInvoiceForBatch(invoice({ remaining_amount: 0.01 }), supplier, {
|
||||
today: TODAY,
|
||||
})
|
||||
expect(justAbove.eligible).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects foreign currency', () => {
|
||||
const result = evaluateInvoiceForBatch(invoice({ currency: 'EUR' }), supplier, { today: TODAY })
|
||||
expect(result).toEqual({ eligible: false, reason: 'foreign_currency' })
|
||||
})
|
||||
|
||||
it('rejects a supplier without payment details', () => {
|
||||
const result = evaluateInvoiceForBatch(
|
||||
invoice(),
|
||||
{ bankgiro: null, plusgiro: null, bank_account: null },
|
||||
{ today: TODAY },
|
||||
)
|
||||
expect(result).toEqual({ eligible: false, reason: 'payee_missing' })
|
||||
})
|
||||
|
||||
it('rejects a supplier with an invalid bankgiro', () => {
|
||||
const result = evaluateInvoiceForBatch(
|
||||
invoice(),
|
||||
{ ...supplier, bankgiro: '1234-5678' },
|
||||
{ today: TODAY },
|
||||
)
|
||||
expect(result).toEqual({ eligible: false, reason: 'payee_invalid' })
|
||||
})
|
||||
|
||||
it('defaults the payment date to the due date when it is in the future', () => {
|
||||
const result = evaluateInvoiceForBatch(invoice({ due_date: '2026-08-20' }), supplier, {
|
||||
today: TODAY,
|
||||
})
|
||||
expect(result.eligible && result.defaults.payment_date).toBe('2026-08-20')
|
||||
})
|
||||
|
||||
it('defaults the payment date to today when the due date has passed', () => {
|
||||
const result = evaluateInvoiceForBatch(
|
||||
invoice({ due_date: '2026-07-07', status: 'overdue' }),
|
||||
supplier,
|
||||
{ today: TODAY },
|
||||
)
|
||||
expect(result.eligible && result.defaults.payment_date).toBe(TODAY)
|
||||
})
|
||||
|
||||
it('defaults the amount to the rounded remaining amount', () => {
|
||||
const result = evaluateInvoiceForBatch(invoice({ remaining_amount: 199.291 }), supplier, {
|
||||
today: TODAY,
|
||||
})
|
||||
expect(result.eligible && result.defaults.amount).toBe(199.29)
|
||||
})
|
||||
|
||||
it('warns on an un-attested invoice instead of blocking it', () => {
|
||||
const result = evaluateInvoiceForBatch(
|
||||
invoice({ status: 'registered', approved_at: null }),
|
||||
supplier,
|
||||
{ today: TODAY },
|
||||
)
|
||||
expect(result.eligible && result.warnings).toContain('unattested')
|
||||
})
|
||||
|
||||
it('warns when the invoice already sits in an active batch', () => {
|
||||
const result = evaluateInvoiceForBatch(invoice(), supplier, {
|
||||
today: TODAY,
|
||||
activeBatchIdByInvoice: new Map([['inv-1', 'batch-9']]),
|
||||
})
|
||||
expect(result.eligible && result.warnings).toContain('already_batched')
|
||||
expect(result.eligible && result.activeBatchId).toBe('batch-9')
|
||||
})
|
||||
|
||||
it('warns on an invalid OCR and falls back to the invoice number', () => {
|
||||
const result = evaluateInvoiceForBatch(invoice({ payment_reference: '1234568' }), supplier, {
|
||||
today: TODAY,
|
||||
})
|
||||
expect(result.eligible && result.warnings).toContain('ocr_invalid')
|
||||
expect(result.eligible && result.reference).toEqual({
|
||||
type: 'invoice_number',
|
||||
value: 'CD3014794407',
|
||||
})
|
||||
})
|
||||
|
||||
it('warns when the supplier has no town (Swedbank address rules)', () => {
|
||||
const result = evaluateInvoiceForBatch(invoice(), { ...supplier, city: null }, {
|
||||
today: TODAY,
|
||||
})
|
||||
expect(result.eligible && result.warnings).toContain('payee_city_missing')
|
||||
})
|
||||
|
||||
it('carries a clean OCR through as the structured reference', () => {
|
||||
const result = evaluateInvoiceForBatch(invoice(), supplier, { today: TODAY })
|
||||
expect(result.eligible && result.reference).toEqual({ type: 'ocr', value: VALID_OCR })
|
||||
expect(result.eligible && result.warnings).toEqual([])
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,276 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
generateSupplierPain001,
|
||||
type SupplierPain001Payment,
|
||||
} from '@/lib/payments/pain001-supplier'
|
||||
|
||||
const debtor = {
|
||||
name: 'Testbolaget AB',
|
||||
orgNumber: '556677-8899',
|
||||
iban: 'SE3550000000054910000003',
|
||||
bic: 'ESSESESS',
|
||||
}
|
||||
|
||||
const options = {
|
||||
messageId: 'ACCOUNTED-5566778899-B1A2B3C4D',
|
||||
createdAt: '2026-08-10T12:34:56.789Z',
|
||||
}
|
||||
|
||||
function bgPayment(overrides: Partial<SupplierPain001Payment> = {}): SupplierPain001Payment {
|
||||
return {
|
||||
payee: { type: 'bankgiro', bankgiro: '50501055' },
|
||||
payeeName: 'Derome Bygg & Industri AB',
|
||||
amount: 737.5,
|
||||
paymentDate: '2026-08-15',
|
||||
reference: { type: 'ocr', value: '12345678' },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('generateSupplierPain001', () => {
|
||||
it('is byte-identical for identical inputs (deterministic regeneration)', () => {
|
||||
const a = generateSupplierPain001(debtor, [bgPayment()], options)
|
||||
const b = generateSupplierPain001(debtor, [bgPayment()], options)
|
||||
expect(a).toBe(b)
|
||||
})
|
||||
|
||||
it('derives CreDtTm from createdAt, never the clock', () => {
|
||||
const xml = generateSupplierPain001(debtor, [bgPayment()], options)
|
||||
expect(xml).toContain('<CreDtTm>2026-08-10T12:34:56Z</CreDtTm>')
|
||||
})
|
||||
|
||||
it('carries no SvcLvl and no CtgyPurp (domestic NURG supplier transfer)', () => {
|
||||
const xml = generateSupplierPain001(debtor, [bgPayment()], options)
|
||||
expect(xml).not.toContain('<SvcLvl>')
|
||||
expect(xml).not.toContain('<CtgyPurp>')
|
||||
})
|
||||
|
||||
it('addresses a bankgiro payee through Bankgirot (SESBA 9900, BGNR proprietary scheme)', () => {
|
||||
const xml = generateSupplierPain001(debtor, [bgPayment()], options)
|
||||
expect(xml).toContain('<ClrSysId><Cd>SESBA</Cd></ClrSysId>')
|
||||
expect(xml).toContain('<MmbId>9900</MmbId>')
|
||||
expect(xml).toContain('<Id>50501055</Id>')
|
||||
expect(xml).toContain('<SchmeNm><Prtry>BGNR</Prtry></SchmeNm>')
|
||||
})
|
||||
|
||||
it('addresses a plusgiro payee via SESBA 9960 with BBAN scheme', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[bgPayment({ payee: { type: 'plusgiro', plusgiro: '1234567' } })],
|
||||
options,
|
||||
)
|
||||
expect(xml).toContain('<MmbId>9960</MmbId>')
|
||||
expect(xml).toContain('<Id>1234567</Id>')
|
||||
expect(xml).toContain('<SchmeNm><Cd>BBAN</Cd></SchmeNm>')
|
||||
})
|
||||
|
||||
it('addresses a bank-account payee via its clearing with the salary routing rules', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[
|
||||
bgPayment({
|
||||
// Swedbank 5-digit clearing: 5th digit shifts into the account.
|
||||
payee: { type: 'bank_account', clearing: '83279', account: '123456789' },
|
||||
}),
|
||||
],
|
||||
options,
|
||||
)
|
||||
expect(xml).toContain('<MmbId>8327</MmbId>')
|
||||
expect(xml).toContain('<Id>9123456789</Id>')
|
||||
expect(xml).toContain('<SchmeNm><Cd>BBAN</Cd></SchmeNm>')
|
||||
})
|
||||
|
||||
it('renders exactly one structured SCOR reference with the remitted amount', () => {
|
||||
const xml = generateSupplierPain001(debtor, [bgPayment()], options)
|
||||
expect(xml.match(/<CdtrRefInf>/g)).toHaveLength(1)
|
||||
expect(xml).toContain('<CdOrPrtry><Cd>SCOR</Cd></CdOrPrtry>')
|
||||
expect(xml).toContain('<Ref>12345678</Ref>')
|
||||
// Swedbank MIG (Validex PFH_217): Strd must carry RfrdDocAmt.
|
||||
expect(xml).toContain('<RmtdAmt Ccy="SEK">737.50</RmtdAmt>')
|
||||
expect(xml.indexOf('<RfrdDocAmt>')).toBeLessThan(xml.indexOf('<CdtrRefInf>'))
|
||||
expect(xml).not.toContain('<Ustrd>')
|
||||
})
|
||||
|
||||
it('always carries the creditor postal country and the initiator OrgId', () => {
|
||||
const xml = generateSupplierPain001(debtor, [bgPayment()], options)
|
||||
// Swedbank MIG rules 020/237 and 002 (Validex run 2026-08-10).
|
||||
expect(xml).toContain('<PstlAdr>')
|
||||
expect(xml).toContain('<Ctry>SE</Ctry>')
|
||||
expect(xml.match(/<OrgId>/g)!.length).toBeGreaterThanOrEqual(2)
|
||||
expect(xml).toContain('<Othr><Id>5566778899</Id></Othr>')
|
||||
})
|
||||
|
||||
it('refuses a debtor without an organisation number', () => {
|
||||
expect(() =>
|
||||
generateSupplierPain001({ ...debtor, orgNumber: '' }, [bgPayment()], options),
|
||||
).toThrow(/Organisationsnummer/)
|
||||
})
|
||||
|
||||
it('debits the company bankgiro for bankgiro payees and the IBAN for others', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
{ ...debtor, bankgiro: '9912346' },
|
||||
[
|
||||
bgPayment(),
|
||||
bgPayment({ payee: { type: 'plusgiro', plusgiro: '1234567' }, amount: 100 }),
|
||||
],
|
||||
options,
|
||||
)
|
||||
// Same date, two debit forms -> two PmtInf groups (Swedbank rule 219:
|
||||
// BGNR creditors debit the bankgiro; the plusgiro payment debits the IBAN).
|
||||
expect(xml.match(/<PmtInf>/g)).toHaveLength(2)
|
||||
const debtorAccounts = xml.match(/<DbtrAcct>[\s\S]*?<\/DbtrAcct>/g) ?? []
|
||||
expect(debtorAccounts).toHaveLength(2)
|
||||
expect(debtorAccounts.filter((block) => block.includes('BGNR'))).toHaveLength(1)
|
||||
expect(debtorAccounts.find((block) => block.includes('BGNR'))).toContain(
|
||||
'<Id>9912346</Id>',
|
||||
)
|
||||
expect(debtorAccounts.filter((block) => block.includes(debtor.iban))).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps everything on the IBAN when the company has no bankgiro', () => {
|
||||
const xml = generateSupplierPain001(debtor, [bgPayment()], options)
|
||||
const debtorAccounts = xml.match(/<DbtrAcct>[\s\S]*?<\/DbtrAcct>/g) ?? []
|
||||
expect(debtorAccounts).toHaveLength(1)
|
||||
expect(debtorAccounts[0]).toContain(`<IBAN>${debtor.iban}</IBAN>`)
|
||||
expect(debtorAccounts[0]).not.toContain('BGNR')
|
||||
})
|
||||
|
||||
it('carries the creditor address on the BGNR path too (rule 237 is absolute)', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
{ ...debtor, bankgiro: '9912346' },
|
||||
[bgPayment({ payeeCity: 'Veddige' })],
|
||||
options,
|
||||
)
|
||||
const creditor = xml.match(/<Cdtr>[\s\S]*?<\/Cdtr>/)![0]
|
||||
expect(creditor).toContain('<TwnNm>Veddige</TwnNm>')
|
||||
expect(creditor).toContain('<Ctry>SE</Ctry>')
|
||||
})
|
||||
|
||||
it('carries the supplier town on IBAN-debited payments when known', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[bgPayment({ payeeCity: 'Göteborg' })],
|
||||
options,
|
||||
)
|
||||
const creditor = xml.match(/<Cdtr>[\s\S]*?<\/Cdtr>/)![0]
|
||||
expect(creditor).toContain('<TwnNm>Göteborg</TwnNm>')
|
||||
expect(creditor.indexOf('<TwnNm>')).toBeLessThan(creditor.indexOf('<Ctry>'))
|
||||
})
|
||||
|
||||
it('carries the company town on the debtor when known', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
{ ...debtor, city: 'Stockholm' },
|
||||
[bgPayment()],
|
||||
options,
|
||||
)
|
||||
const debtorBlock = xml.match(/<Dbtr>[\s\S]*?<\/Dbtr>/)![0]
|
||||
expect(debtorBlock).toContain('<TwnNm>Stockholm</TwnNm>')
|
||||
expect(debtorBlock.indexOf('<PstlAdr>')).toBeLessThan(debtorBlock.indexOf('<Id>'))
|
||||
})
|
||||
|
||||
it('transliterates disallowed characters in names (MIG character set)', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[bgPayment({ payeeName: 'Demokafé & Crème AB' })],
|
||||
options,
|
||||
)
|
||||
expect(xml).toContain('<Nm>Demokafe + Creme AB</Nm>')
|
||||
})
|
||||
|
||||
it('folds decomposed Unicode before transliterating', () => {
|
||||
// 'e' + combining acute (U+0301) and 'a' + combining ring (U+030A):
|
||||
// NFC folds them to é and å, which then map per the MIG set.
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[bgPayment({ payeeName: 'Café Ångby' })],
|
||||
options,
|
||||
)
|
||||
expect(xml).toContain('<Nm>Cafe Ångby</Nm>')
|
||||
})
|
||||
|
||||
it('renders an invoice-number reference as unstructured text, truncated to 25 chars', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[
|
||||
bgPayment({
|
||||
reference: { type: 'invoice_number', value: 'F-12345678901234567890123456789' },
|
||||
}),
|
||||
],
|
||||
options,
|
||||
)
|
||||
expect(xml).toContain('<Ustrd>F-12345678901234567890123</Ustrd>')
|
||||
expect(xml).not.toContain('<Strd>')
|
||||
})
|
||||
|
||||
it('groups payments into one PmtInf per distinct execution date, dates ascending', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[
|
||||
bgPayment({ paymentDate: '2026-08-20', amount: 100 }),
|
||||
bgPayment({ paymentDate: '2026-08-15', amount: 200 }),
|
||||
bgPayment({ paymentDate: '2026-08-20', amount: 300 }),
|
||||
],
|
||||
options,
|
||||
)
|
||||
expect(xml.match(/<PmtInf>/g)).toHaveLength(2)
|
||||
const first15 = xml.indexOf('<ReqdExctnDt>2026-08-15</ReqdExctnDt>')
|
||||
const first20 = xml.indexOf('<ReqdExctnDt>2026-08-20</ReqdExctnDt>')
|
||||
expect(first15).toBeGreaterThan(-1)
|
||||
expect(first20).toBeGreaterThan(first15)
|
||||
// Group control sums: 200.00 for the 15th, 400.00 for the 20th, 600.00 total.
|
||||
expect(xml).toContain('<CtrlSum>600.00</CtrlSum>')
|
||||
expect(xml).toContain('<CtrlSum>200.00</CtrlSum>')
|
||||
expect(xml).toContain('<CtrlSum>400.00</CtrlSum>')
|
||||
// The tx counter runs across groups so ids stay unique file-wide.
|
||||
expect(xml).toContain('-TX0001')
|
||||
expect(xml).toContain('-TX0002')
|
||||
expect(xml).toContain('-TX0003')
|
||||
expect(xml.match(/<PmtInfId>[^<]*-P1<\/PmtInfId>/)).not.toBeNull()
|
||||
expect(xml.match(/<PmtInfId>[^<]*-P2<\/PmtInfId>/)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('maps ampersands to + per the MIG character set (Swedish å ä ö survive)', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[bgPayment({ payeeName: 'Derome Bygg & Industri Åängö AB' })],
|
||||
options,
|
||||
)
|
||||
expect(xml).toContain('<Nm>Derome Bygg + Industri Åängö AB</Nm>')
|
||||
})
|
||||
|
||||
it('keeps all ids within Max35Text with the suffix intact', () => {
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[bgPayment()],
|
||||
{ ...options, messageId: 'X'.repeat(60) },
|
||||
)
|
||||
const ids = [...xml.matchAll(/<(MsgId|PmtInfId|InstrId|EndToEndId)>([^<]+)<\/\1>/g)].map(
|
||||
(m) => m[2],
|
||||
)
|
||||
expect(ids.length).toBeGreaterThan(0)
|
||||
for (const id of ids) expect(id.length).toBeLessThanOrEqual(35)
|
||||
expect(xml).toContain('-TX0001</InstrId>')
|
||||
})
|
||||
|
||||
it('formats amounts with two decimals and a dot separator', () => {
|
||||
const xml = generateSupplierPain001(debtor, [bgPayment({ amount: 199.291 })], options)
|
||||
expect(xml).toContain('<InstdAmt Ccy="SEK">199.29</InstdAmt>')
|
||||
})
|
||||
|
||||
it('control sums equal the sum of the rendered amounts, not the raw floats', () => {
|
||||
// Raw floats: 0.014 + 0.014 = 0.028 -> rounded once = 0.03, but each
|
||||
// InstdAmt renders as 0.01. Banks reject CtrlSum != sum(InstdAmt).
|
||||
const xml = generateSupplierPain001(
|
||||
debtor,
|
||||
[bgPayment({ amount: 0.014 }), bgPayment({ amount: 0.014 })],
|
||||
options,
|
||||
)
|
||||
expect(xml.match(/<InstdAmt Ccy="SEK">0\.01<\/InstdAmt>/g)).toHaveLength(2)
|
||||
expect(xml).toContain('<CtrlSum>0.02</CtrlSum>')
|
||||
expect(xml).not.toContain('<CtrlSum>0.03</CtrlSum>')
|
||||
})
|
||||
|
||||
it('refuses an empty batch', () => {
|
||||
expect(() => generateSupplierPain001(debtor, [], options)).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { luhnCheckDigit } from '@/lib/bankgiro/luhn'
|
||||
import {
|
||||
formatPayeeLabel,
|
||||
resolvePaymentReference,
|
||||
resolveSupplierPayee,
|
||||
} from '@/lib/payments/supplier-payee'
|
||||
|
||||
// Luhn-valid fixtures built from the same check-digit routine the validators use.
|
||||
const VALID_BG = '5050-1055' // Skatteverket's bankgiro; known Luhn-valid
|
||||
const VALID_PG = `123456${luhnCheckDigit('123456')}`
|
||||
const VALID_OCR = `1234567${luhnCheckDigit('1234567')}`
|
||||
|
||||
const emptySource = {
|
||||
bankgiro: null,
|
||||
plusgiro: null,
|
||||
bank_account: null,
|
||||
clearing_number: null,
|
||||
account_number: null,
|
||||
}
|
||||
|
||||
describe('resolveSupplierPayee', () => {
|
||||
it('resolves a valid bankgiro first', () => {
|
||||
const result = resolveSupplierPayee({
|
||||
...emptySource,
|
||||
bankgiro: VALID_BG,
|
||||
plusgiro: VALID_PG,
|
||||
clearing_number: '3300',
|
||||
account_number: '1234567',
|
||||
})
|
||||
expect(result).toEqual({ ok: true, payee: { type: 'bankgiro', bankgiro: '50501055' } })
|
||||
})
|
||||
|
||||
it('fails on an invalid bankgiro instead of falling through to plusgiro', () => {
|
||||
const result = resolveSupplierPayee({
|
||||
...emptySource,
|
||||
bankgiro: '1234-5678',
|
||||
plusgiro: VALID_PG,
|
||||
})
|
||||
expect(result).toEqual({ ok: false, reason: 'payee_invalid' })
|
||||
})
|
||||
|
||||
it('resolves plusgiro when no bankgiro is set', () => {
|
||||
const result = resolveSupplierPayee({ ...emptySource, plusgiro: VALID_PG })
|
||||
expect(result).toEqual({ ok: true, payee: { type: 'plusgiro', plusgiro: VALID_PG } })
|
||||
})
|
||||
|
||||
it('resolves structured clearing + account columns', () => {
|
||||
const result = resolveSupplierPayee({
|
||||
...emptySource,
|
||||
clearing_number: '3300',
|
||||
account_number: '000123456',
|
||||
})
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
payee: { type: 'bank_account', clearing: '3300', account: '000123456' },
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects an invalid clearing in the structured columns', () => {
|
||||
const result = resolveSupplierPayee({
|
||||
...emptySource,
|
||||
clearing_number: '12',
|
||||
account_number: '1234567',
|
||||
})
|
||||
expect(result).toEqual({ ok: false, reason: 'payee_invalid' })
|
||||
})
|
||||
|
||||
it('parses free-text bank_account with an explicit separator', () => {
|
||||
const result = resolveSupplierPayee({ ...emptySource, bank_account: '3300-123 456 789' })
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
payee: { type: 'bank_account', clearing: '3300', account: '123456789' },
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts a 5-digit Swedbank clearing in free text', () => {
|
||||
const result = resolveSupplierPayee({ ...emptySource, bank_account: '83279 123456789' })
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
payee: { type: 'bank_account', clearing: '83279', account: '123456789' },
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses an ambiguous free-text digit blob', () => {
|
||||
const result = resolveSupplierPayee({ ...emptySource, bank_account: '83279123456789' })
|
||||
expect(result).toEqual({ ok: false, reason: 'payee_invalid' })
|
||||
})
|
||||
|
||||
it('reports payee_missing when nothing is set', () => {
|
||||
expect(resolveSupplierPayee(emptySource)).toEqual({ ok: false, reason: 'payee_missing' })
|
||||
})
|
||||
|
||||
it('treats whitespace-only fields as missing', () => {
|
||||
expect(resolveSupplierPayee({ ...emptySource, bankgiro: ' ' })).toEqual({
|
||||
ok: false,
|
||||
reason: 'payee_missing',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatPayeeLabel', () => {
|
||||
it('formats each payee type', () => {
|
||||
expect(formatPayeeLabel({ type: 'bankgiro', bankgiro: '50501055' })).toBe('BG 5050-1055')
|
||||
expect(formatPayeeLabel({ type: 'plusgiro', plusgiro: '1234567' })).toBe('PG 123456-7')
|
||||
expect(formatPayeeLabel({ type: 'bank_account', clearing: '3300', account: '123456789' })).toBe(
|
||||
'3300 123456789',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolvePaymentReference', () => {
|
||||
it('uses a Luhn-valid OCR as a structured reference', () => {
|
||||
const { reference, ocrInvalid } = resolvePaymentReference({
|
||||
payment_reference: VALID_OCR,
|
||||
supplier_invoice_number: 'F-1001',
|
||||
})
|
||||
expect(reference).toEqual({ type: 'ocr', value: VALID_OCR })
|
||||
expect(ocrInvalid).toBe(false)
|
||||
})
|
||||
|
||||
it('strips formatting from the OCR before validating', () => {
|
||||
const { reference } = resolvePaymentReference({
|
||||
payment_reference: ` ${VALID_OCR.slice(0, 4)} ${VALID_OCR.slice(4)} `,
|
||||
supplier_invoice_number: 'F-1001',
|
||||
})
|
||||
expect(reference).toEqual({ type: 'ocr', value: VALID_OCR })
|
||||
})
|
||||
|
||||
it('falls back to the invoice number with a warning on an invalid OCR', () => {
|
||||
const { reference, ocrInvalid } = resolvePaymentReference({
|
||||
payment_reference: '1234568',
|
||||
supplier_invoice_number: 'F-1001',
|
||||
})
|
||||
expect(reference).toEqual({ type: 'invoice_number', value: 'F-1001' })
|
||||
expect(ocrInvalid).toBe(true)
|
||||
})
|
||||
|
||||
it('falls back to the invoice number without a warning when no OCR is set', () => {
|
||||
const { reference, ocrInvalid } = resolvePaymentReference({
|
||||
payment_reference: null,
|
||||
supplier_invoice_number: 'F-1001',
|
||||
})
|
||||
expect(reference).toEqual({ type: 'invoice_number', value: 'F-1001' })
|
||||
expect(ocrInvalid).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { normaliseSwish, isValidSwish, buildSwishQrPayload } from '../swish'
|
||||
|
||||
describe('normaliseSwish', () => {
|
||||
it('strips whitespace and hyphens', () => {
|
||||
expect(normaliseSwish('123 456 78 90')).toBe('1234567890')
|
||||
expect(normaliseSwish('070-123 45 67')).toBe('0701234567')
|
||||
expect(normaliseSwish(' 1234567890 ')).toBe('1234567890')
|
||||
})
|
||||
|
||||
it('returns empty string for null/undefined/empty', () => {
|
||||
expect(normaliseSwish(null)).toBe('')
|
||||
expect(normaliseSwish(undefined)).toBe('')
|
||||
expect(normaliseSwish('')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isValidSwish', () => {
|
||||
it('accepts Swish Företag numbers (123XXXXXXX)', () => {
|
||||
expect(isValidSwish('1234567890')).toBe(true)
|
||||
expect(isValidSwish('1230000000')).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts Swedish mobile numbers (07XXXXXXXX)', () => {
|
||||
expect(isValidSwish('0701234567')).toBe(true)
|
||||
expect(isValidSwish('0700000000')).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts empty string for clearing the field', () => {
|
||||
expect(isValidSwish('')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects non-conforming numbers', () => {
|
||||
expect(isValidSwish('0123456789')).toBe(false)
|
||||
expect(isValidSwish('1239')).toBe(false)
|
||||
expect(isValidSwish('12345678901')).toBe(false)
|
||||
expect(isValidSwish('123abc4567')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildSwishQrPayload', () => {
|
||||
it('builds a fully-locked Type C payload for a Swish-företag number', () => {
|
||||
expect(buildSwishQrPayload('1234567890', 1250, 'Faktura 100')).toBe('C1234567890;1250.00;Faktura 100;0')
|
||||
})
|
||||
|
||||
it('works for a mobile-number payee with the same syntax', () => {
|
||||
expect(buildSwishQrPayload('0701234567', 99.5, 'F-1')).toBe('C0701234567;99.50;F-1;0')
|
||||
})
|
||||
|
||||
it('normalises spaces/hyphens in the number', () => {
|
||||
expect(buildSwishQrPayload('123 456 78 90', 10, 'x')).toBe('C1234567890;10.00;x;0')
|
||||
})
|
||||
|
||||
it('strips the ; field delimiter from the message and trims it', () => {
|
||||
expect(buildSwishQrPayload('1234567890', 10, ' a;b ')).toBe('C1234567890;10.00;a b;0')
|
||||
})
|
||||
|
||||
it('formats the amount with two decimals', () => {
|
||||
expect(buildSwishQrPayload('1234567890', 100, 'x')).toBe('C1234567890;100.00;x;0')
|
||||
expect(buildSwishQrPayload('1234567890', 1234.5, 'x')).toBe('C1234567890;1234.50;x;0')
|
||||
})
|
||||
|
||||
it('returns null for an invalid or empty number', () => {
|
||||
expect(buildSwishQrPayload('12345', 10, 'x')).toBeNull()
|
||||
expect(buildSwishQrPayload('', 10, 'x')).toBeNull()
|
||||
expect(buildSwishQrPayload(null, 10, 'x')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for a non-positive amount', () => {
|
||||
expect(buildSwishQrPayload('1234567890', 0, 'x')).toBeNull()
|
||||
expect(buildSwishQrPayload('1234567890', -5, 'x')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Eligibility rules for including a supplier invoice in a payment batch.
|
||||
*
|
||||
* Single source of truth used by BOTH the preview route and the create route:
|
||||
* create re-evaluates every invoice against the same rules, so a row that
|
||||
* changed between preview and create (paid meanwhile, due date moved, supplier
|
||||
* details edited) is rejected instead of silently paid on stale terms.
|
||||
*
|
||||
* Warnings never block; exclusions always do. An un-attested invoice is a
|
||||
* warning (mark-paid pays registered invoices today, and sjalvbokforare have
|
||||
* no attest step), while a missing payee is an exclusion (there is nothing to
|
||||
* route the payment to).
|
||||
*/
|
||||
|
||||
import { ORE_TOLERANCE, roundOre } from '@/lib/money'
|
||||
import {
|
||||
resolvePaymentReference,
|
||||
resolveSupplierPayee,
|
||||
type PaymentReference,
|
||||
type SupplierPayee,
|
||||
type SupplierPayeeSource,
|
||||
} from './supplier-payee'
|
||||
|
||||
/**
|
||||
* Statuses a payment instruction may be created for: exactly the set the
|
||||
* mark-paid route accepts, so the batch can never contain an invoice the
|
||||
* settlement path would refuse.
|
||||
*/
|
||||
export const PAYABLE_SUPPLIER_INVOICE_STATUSES = [
|
||||
'registered',
|
||||
'approved',
|
||||
'partially_paid',
|
||||
'overdue',
|
||||
] as const
|
||||
|
||||
|
||||
export type BatchExclusionReason =
|
||||
| 'not_payable'
|
||||
| 'nothing_remaining'
|
||||
| 'credit_note'
|
||||
| 'foreign_currency'
|
||||
| 'payee_missing'
|
||||
| 'payee_invalid'
|
||||
|
||||
export type BatchItemWarning =
|
||||
| 'unattested'
|
||||
| 'already_batched'
|
||||
| 'ocr_invalid'
|
||||
// Swedbank rejects a creditor address without a town (Validex rules
|
||||
// 237 + 222), and the address itself is mandatory; warn so the user fills
|
||||
// in the supplier's city before the bank bounces the file.
|
||||
| 'payee_city_missing'
|
||||
|
||||
export interface BatchInvoiceFacts {
|
||||
id: string
|
||||
status: string
|
||||
approved_at: string | null
|
||||
due_date: string
|
||||
remaining_amount: number
|
||||
currency: string
|
||||
is_credit_note: boolean
|
||||
payment_reference: string | null
|
||||
supplier_invoice_number: string
|
||||
}
|
||||
|
||||
export interface BatchEvaluationOptions {
|
||||
/** ISO yyyy-MM-dd. Passed in so preview and create agree within a request. */
|
||||
today: string
|
||||
/** invoice id -> active (created, not cancelled) batch id it already sits in. */
|
||||
activeBatchIdByInvoice?: ReadonlyMap<string, string>
|
||||
}
|
||||
|
||||
export type BatchInvoiceEvaluation =
|
||||
| {
|
||||
eligible: true
|
||||
defaults: { amount: number; payment_date: string }
|
||||
payee: SupplierPayee
|
||||
reference: PaymentReference
|
||||
warnings: BatchItemWarning[]
|
||||
activeBatchId: string | null
|
||||
}
|
||||
| { eligible: false; reason: BatchExclusionReason }
|
||||
|
||||
export function evaluateInvoiceForBatch(
|
||||
invoice: BatchInvoiceFacts,
|
||||
supplier: SupplierPayeeSource & { city?: string | null },
|
||||
options: BatchEvaluationOptions,
|
||||
): BatchInvoiceEvaluation {
|
||||
if (invoice.is_credit_note) return { eligible: false, reason: 'credit_note' }
|
||||
if (!(PAYABLE_SUPPLIER_INVOICE_STATUSES as readonly string[]).includes(invoice.status)) {
|
||||
return { eligible: false, reason: 'not_payable' }
|
||||
}
|
||||
if (invoice.remaining_amount <= ORE_TOLERANCE) {
|
||||
return { eligible: false, reason: 'nothing_remaining' }
|
||||
}
|
||||
if (invoice.currency !== 'SEK') return { eligible: false, reason: 'foreign_currency' }
|
||||
|
||||
const resolution = resolveSupplierPayee(supplier)
|
||||
if (!resolution.ok) return { eligible: false, reason: resolution.reason }
|
||||
|
||||
const { reference, ocrInvalid } = resolvePaymentReference(invoice)
|
||||
|
||||
const warnings: BatchItemWarning[] = []
|
||||
if (!invoice.approved_at) warnings.push('unattested')
|
||||
const activeBatchId = options.activeBatchIdByInvoice?.get(invoice.id) ?? null
|
||||
if (activeBatchId) warnings.push('already_batched')
|
||||
if (ocrInvalid) warnings.push('ocr_invalid')
|
||||
if (!supplier.city?.trim()) warnings.push('payee_city_missing')
|
||||
|
||||
return {
|
||||
eligible: true,
|
||||
defaults: {
|
||||
amount: roundOre(invoice.remaining_amount),
|
||||
// A due date in the future is honored; a passed one pays as soon as the
|
||||
// bank can execute.
|
||||
payment_date: invoice.due_date > options.today ? invoice.due_date : options.today,
|
||||
},
|
||||
payee: resolution.payee,
|
||||
reference,
|
||||
warnings,
|
||||
activeBatchId,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
/**
|
||||
* Supplier payment batch orchestration: preview, create, render.
|
||||
*
|
||||
* A batch is an immutable snapshot of payment instructions. Preview and create
|
||||
* share evaluateInvoiceForBatch so nothing can be created that the preview
|
||||
* would not have shown; create re-reads and re-evaluates every invoice so a
|
||||
* row that changed since the preview (settled meanwhile, supplier edited) is
|
||||
* rejected rather than paid on stale terms.
|
||||
*
|
||||
* The write itself is one transactional RPC (create_supplier_payment_batch):
|
||||
* it locks the selected invoices, re-checks active batches inside the
|
||||
* transaction, and inserts header + items atomically, so two concurrent
|
||||
* creates can never both land an active batch for the same invoice and a
|
||||
* header can never outlive its items (#1503).
|
||||
*
|
||||
* The file is rendered deterministically from the stored batch + item rows
|
||||
* alone: msg_id and created_at are fixed at creation, so every download of a
|
||||
* batch is byte-identical and bank-side duplicate detection (keyed on MsgId)
|
||||
* works. Generating or downloading a file books nothing and settles nothing.
|
||||
*/
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { getSwedishLocalDate } from '@/lib/bookkeeping/engine'
|
||||
import { ORE_TOLERANCE, roundOre, sumOre } from '@/lib/money'
|
||||
import { validateBankgiroNumber } from '@/lib/bankgiro/luhn'
|
||||
import {
|
||||
lookupBicByClearing,
|
||||
lookupBicByBankName,
|
||||
normalizeBankNumber,
|
||||
} from '@/lib/salary/payment/bank-account'
|
||||
import {
|
||||
evaluateInvoiceForBatch,
|
||||
type BatchExclusionReason,
|
||||
type BatchInvoiceFacts,
|
||||
type BatchItemWarning,
|
||||
} from './batch-eligibility'
|
||||
import { formatPayeeLabel, type SupplierPayeeSource } from './supplier-payee'
|
||||
import { generateSupplierPain001, type SupplierPain001Payment } from './pain001-supplier'
|
||||
import type { SupplierPaymentBatch, SupplierPaymentBatchItem } from '@/types'
|
||||
|
||||
const log = createLogger('payments/batch-service')
|
||||
|
||||
type InvoiceRow = BatchInvoiceFacts & {
|
||||
supplier: (SupplierPayeeSource & { id: string; name: string; city: string | null }) | null
|
||||
}
|
||||
|
||||
const INVOICE_SELECT =
|
||||
'id, status, approved_at, due_date, remaining_amount, currency, is_credit_note, ' +
|
||||
'payment_reference, supplier_invoice_number, ' +
|
||||
'supplier:suppliers(id, name, city, bankgiro, plusgiro, bank_account, clearing_number, account_number)'
|
||||
|
||||
export interface BatchDebtor {
|
||||
name: string
|
||||
org_number: string
|
||||
iban: string
|
||||
bic: string
|
||||
/** Company bankgiro digits; enables the BGNR-to-BGNR debit Swedbank wants. */
|
||||
bankgiro: string | null
|
||||
/** Company town; Dbtr/PstlAdr/TwnNm (mandatory from Nov 2026 when present). */
|
||||
city: string | null
|
||||
}
|
||||
|
||||
export type DebtorResolution =
|
||||
| { ok: true; debtor: BatchDebtor }
|
||||
| { ok: false; missing: 'iban' | 'bic' | 'org_number' }
|
||||
|
||||
/**
|
||||
* Resolve the paying company (pain.001 debtor) from settings, mirroring the
|
||||
* salary pain001 route: saved BIC first, then derivation from the clearing
|
||||
* number or bank name the company already entered, so most users only ever
|
||||
* fill in the IBAN. The org number is required: InitgPty must carry an OrgId
|
||||
* (Swedbank Validex PFH_002). The bankgiro rides along when valid so
|
||||
* bankgiro payees can be debited BGNR-to-BGNR.
|
||||
*/
|
||||
export async function resolveBatchDebtor(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<DebtorResolution> {
|
||||
const [{ data: company }, { data: settings }] = await Promise.all([
|
||||
supabase.from('companies').select('name, org_number').eq('id', companyId).single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name, org_number, city, iban, bic, bankgiro, clearing_number, bank_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
const iban = (settings?.iban ?? '').replace(/\s/g, '').toUpperCase()
|
||||
if (!iban) return { ok: false, missing: 'iban' }
|
||||
|
||||
const bic =
|
||||
settings?.bic?.trim() ||
|
||||
lookupBicByClearing(normalizeBankNumber(settings?.clearing_number)) ||
|
||||
lookupBicByBankName(settings?.bank_name)
|
||||
if (!bic) return { ok: false, missing: 'bic' }
|
||||
|
||||
// Settings first: it is the maintained value; companies.org_number is the
|
||||
// write-once onboarding snapshot and may be empty.
|
||||
const orgNumber = settings?.org_number?.trim() || company?.org_number?.trim() || ''
|
||||
if (!orgNumber.replace(/\D/g, '')) return { ok: false, missing: 'org_number' }
|
||||
|
||||
const bankgiroRaw = settings?.bankgiro ?? ''
|
||||
const bankgiro = validateBankgiroNumber(bankgiroRaw) ? bankgiroRaw.replace(/\D/g, '') : null
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
debtor: {
|
||||
name: settings?.company_name || company?.name || '',
|
||||
org_number: orgNumber,
|
||||
iban,
|
||||
bic,
|
||||
bankgiro,
|
||||
city: settings?.city?.trim() || null,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* invoice id -> id of the active (created) batch it already sits in.
|
||||
*
|
||||
* Fails CLOSED: a lookup error must abort the caller, because treating it as
|
||||
* "no active batches" would silently disable the duplicate-batch guard and
|
||||
* let a second payable file be created without confirm_already_batched.
|
||||
*/
|
||||
export async function loadActiveBatchMap(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<Map<string, string>> {
|
||||
const { data, error } = await supabase
|
||||
.from('supplier_payment_batch_items')
|
||||
.select('supplier_invoice_id, batch:supplier_payment_batches!inner(id, status)')
|
||||
.eq('company_id', companyId)
|
||||
.eq('batch.status', 'created')
|
||||
|
||||
if (error) throw error
|
||||
|
||||
const map = new Map<string, string>()
|
||||
for (const row of data ?? []) {
|
||||
const batch = row.batch as unknown as { id: string }
|
||||
if (!map.has(row.supplier_invoice_id)) map.set(row.supplier_invoice_id, batch.id)
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
export interface BatchPreviewLine {
|
||||
id: string
|
||||
supplier_name: string
|
||||
invoice_number: string
|
||||
amount: number
|
||||
payment_date: string
|
||||
payee: { type: string; label: string }
|
||||
reference: { type: 'ocr' | 'invoice_number'; value: string }
|
||||
warnings: BatchItemWarning[]
|
||||
active_batch_id: string | null
|
||||
}
|
||||
|
||||
export interface BatchPreview {
|
||||
eligible: BatchPreviewLine[]
|
||||
excluded: Array<{ id: string; reason: BatchExclusionReason | 'not_found' }>
|
||||
total: number
|
||||
debtor_ok: boolean
|
||||
debtor_missing?: 'iban' | 'bic' | 'org_number'
|
||||
}
|
||||
|
||||
export async function previewSupplierPaymentBatch(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
input: { ids: string[] },
|
||||
): Promise<BatchPreview> {
|
||||
// Swedish calendar date, not UTC: between 00:00 and 01:59 Swedish summer
|
||||
// time a UTC slice is still yesterday, and "pay today" would produce an
|
||||
// execution date the bank rejects as passed.
|
||||
const today = getSwedishLocalDate()
|
||||
|
||||
const [{ data: invoices }, activeBatchIdByInvoice, debtorResolution] = await Promise.all([
|
||||
supabase
|
||||
.from('supplier_invoices')
|
||||
.select(INVOICE_SELECT)
|
||||
.eq('company_id', companyId)
|
||||
.in('id', input.ids),
|
||||
loadActiveBatchMap(supabase, companyId),
|
||||
resolveBatchDebtor(supabase, companyId),
|
||||
])
|
||||
|
||||
const rows = (invoices ?? []) as unknown as InvoiceRow[]
|
||||
const byId = new Map(rows.map((row) => [row.id, row]))
|
||||
|
||||
const eligible: BatchPreviewLine[] = []
|
||||
const excluded: BatchPreview['excluded'] = []
|
||||
|
||||
for (const id of input.ids) {
|
||||
const invoice = byId.get(id)
|
||||
if (!invoice || !invoice.supplier) {
|
||||
excluded.push({ id, reason: invoice ? 'payee_missing' : 'not_found' })
|
||||
continue
|
||||
}
|
||||
const evaluation = evaluateInvoiceForBatch(invoice, invoice.supplier, {
|
||||
today,
|
||||
activeBatchIdByInvoice,
|
||||
})
|
||||
if (!evaluation.eligible) {
|
||||
excluded.push({ id, reason: evaluation.reason })
|
||||
continue
|
||||
}
|
||||
eligible.push({
|
||||
id,
|
||||
supplier_name: invoice.supplier.name,
|
||||
invoice_number: invoice.supplier_invoice_number,
|
||||
amount: evaluation.defaults.amount,
|
||||
payment_date: evaluation.defaults.payment_date,
|
||||
payee: { type: evaluation.payee.type, label: formatPayeeLabel(evaluation.payee) },
|
||||
reference: evaluation.reference,
|
||||
warnings: evaluation.warnings,
|
||||
active_batch_id: evaluation.activeBatchId,
|
||||
})
|
||||
}
|
||||
|
||||
const total = sumOre(eligible.map((line) => line.amount))
|
||||
|
||||
return {
|
||||
eligible,
|
||||
excluded,
|
||||
total,
|
||||
debtor_ok: debtorResolution.ok,
|
||||
...(debtorResolution.ok ? {} : { debtor_missing: debtorResolution.missing }),
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreateBatchItemInput {
|
||||
supplier_invoice_id: string
|
||||
amount?: number
|
||||
payment_date?: string
|
||||
}
|
||||
|
||||
export interface CreateBatchInput {
|
||||
format: 'pain001'
|
||||
items: CreateBatchItemInput[]
|
||||
confirm_already_batched?: boolean
|
||||
}
|
||||
|
||||
export type CreateBatchResult =
|
||||
| { ok: true; batch: SupplierPaymentBatch }
|
||||
| { ok: false; code: 'debtor_incomplete'; missing: 'iban' | 'bic' | 'org_number' }
|
||||
| { ok: false; code: 'ineligible'; details: Array<{ id: string; reason: string }> }
|
||||
| { ok: false; code: 'amount_exceeds_remaining'; details: Array<{ id: string }> }
|
||||
| { ok: false; code: 'invalid_amount'; details: Array<{ id: string }> }
|
||||
| { ok: false; code: 'already_batched'; details: Array<{ id: string; batch_id: string }> }
|
||||
| { ok: false; code: 'create_failed' }
|
||||
|
||||
/** Shape returned by the create_supplier_payment_batch RPC. */
|
||||
type CreateBatchRpcResult =
|
||||
| { ok: true; batch: SupplierPaymentBatch }
|
||||
| { ok: false; code: string; details?: unknown }
|
||||
|
||||
export async function createSupplierPaymentBatch(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
input: CreateBatchInput,
|
||||
): Promise<CreateBatchResult> {
|
||||
const today = getSwedishLocalDate()
|
||||
const ids = input.items.map((item) => item.supplier_invoice_id)
|
||||
|
||||
const debtorResolution = await resolveBatchDebtor(supabase, companyId)
|
||||
if (!debtorResolution.ok) {
|
||||
return { ok: false, code: 'debtor_incomplete', missing: debtorResolution.missing }
|
||||
}
|
||||
const { debtor } = debtorResolution
|
||||
|
||||
const [{ data: invoices }, activeBatchIdByInvoice] = await Promise.all([
|
||||
supabase
|
||||
.from('supplier_invoices')
|
||||
.select(INVOICE_SELECT)
|
||||
.eq('company_id', companyId)
|
||||
.in('id', ids),
|
||||
loadActiveBatchMap(supabase, companyId),
|
||||
])
|
||||
const rows = (invoices ?? []) as unknown as InvoiceRow[]
|
||||
const byId = new Map(rows.map((row) => [row.id, row]))
|
||||
|
||||
const ineligible: Array<{ id: string; reason: string }> = []
|
||||
const excessive: Array<{ id: string }> = []
|
||||
const invalidAmount: Array<{ id: string }> = []
|
||||
const alreadyBatched: Array<{ id: string; batch_id: string }> = []
|
||||
const itemRows: Array<Omit<SupplierPaymentBatchItem, 'id' | 'batch_id' | 'created_at'>> = []
|
||||
|
||||
for (const item of input.items) {
|
||||
const invoice = byId.get(item.supplier_invoice_id)
|
||||
if (!invoice || !invoice.supplier) {
|
||||
ineligible.push({ id: item.supplier_invoice_id, reason: invoice ? 'payee_missing' : 'not_found' })
|
||||
continue
|
||||
}
|
||||
const evaluation = evaluateInvoiceForBatch(invoice, invoice.supplier, {
|
||||
today,
|
||||
activeBatchIdByInvoice,
|
||||
})
|
||||
if (!evaluation.eligible) {
|
||||
ineligible.push({ id: invoice.id, reason: evaluation.reason })
|
||||
continue
|
||||
}
|
||||
if (evaluation.activeBatchId && !input.confirm_already_batched) {
|
||||
alreadyBatched.push({ id: invoice.id, batch_id: evaluation.activeBatchId })
|
||||
continue
|
||||
}
|
||||
|
||||
const amount = item.amount !== undefined ? roundOre(item.amount) : evaluation.defaults.amount
|
||||
if (amount <= 0) {
|
||||
invalidAmount.push({ id: invoice.id })
|
||||
continue
|
||||
}
|
||||
if (amount > invoice.remaining_amount + ORE_TOLERANCE) {
|
||||
excessive.push({ id: invoice.id })
|
||||
continue
|
||||
}
|
||||
|
||||
// A payment date in the past is normalized to today: banks reject passed
|
||||
// execution dates, and "pay now" is what an overdue due date means.
|
||||
const requestedDate = item.payment_date ?? evaluation.defaults.payment_date
|
||||
const paymentDate = requestedDate > today ? requestedDate : today
|
||||
|
||||
const { payee } = evaluation
|
||||
itemRows.push({
|
||||
company_id: companyId,
|
||||
supplier_invoice_id: invoice.id,
|
||||
amount,
|
||||
payment_date: paymentDate,
|
||||
payee_type: payee.type,
|
||||
payee_bankgiro: payee.type === 'bankgiro' ? payee.bankgiro : null,
|
||||
payee_plusgiro: payee.type === 'plusgiro' ? payee.plusgiro : null,
|
||||
payee_clearing: payee.type === 'bank_account' ? payee.clearing : null,
|
||||
payee_account: payee.type === 'bank_account' ? payee.account : null,
|
||||
payee_name: invoice.supplier.name,
|
||||
payee_city: invoice.supplier.city?.trim() || null,
|
||||
reference_type: evaluation.reference.type,
|
||||
reference: evaluation.reference.value,
|
||||
})
|
||||
}
|
||||
|
||||
if (ineligible.length > 0) return { ok: false, code: 'ineligible', details: ineligible }
|
||||
if (invalidAmount.length > 0) return { ok: false, code: 'invalid_amount', details: invalidAmount }
|
||||
if (excessive.length > 0) return { ok: false, code: 'amount_exceeds_remaining', details: excessive }
|
||||
if (alreadyBatched.length > 0) return { ok: false, code: 'already_batched', details: alreadyBatched }
|
||||
if (itemRows.length === 0) return { ok: false, code: 'create_failed' }
|
||||
|
||||
// The id is minted here (not by the DB default) because msg_id derives from
|
||||
// it and both must land in the same transaction.
|
||||
const batchId = crypto.randomUUID()
|
||||
const orgDigits = debtor.org_number.replace(/\D/g, '')
|
||||
const msgId = `${getBranding().appName.toUpperCase()}-${orgDigits}-B${batchId.replace(/-/g, '').slice(0, 8).toUpperCase()}`.slice(0, 35)
|
||||
|
||||
// The RPC is the authority: it locks the invoices, re-runs the active-batch
|
||||
// check inside the transaction (the loadActiveBatchMap pass above is the
|
||||
// friendly fast path, not the guarantee), and writes header + items
|
||||
// atomically. company_id rides in p_company_id, so it is stripped from the
|
||||
// item rows. Domain refusals come back as { ok: false, code }; constraint
|
||||
// violations and the tenant guard surface as an error.
|
||||
const { data, error } = await supabase.rpc('create_supplier_payment_batch', {
|
||||
p_company_id: companyId,
|
||||
p_batch_id: batchId,
|
||||
p_format: input.format,
|
||||
p_msg_id: msgId,
|
||||
p_debtor_snapshot: debtor,
|
||||
p_items: itemRows.map(({ company_id: _companyId, ...row }) => row),
|
||||
p_confirm_already_batched: input.confirm_already_batched ?? false,
|
||||
p_user_id: userId,
|
||||
})
|
||||
// The client only ever sees create_failed. What tells the RPC's tenant
|
||||
// guard (42501), a constraint violation inside the SECURITY DEFINER body
|
||||
// and a PostgREST schema-cache miss right after a deploy (PGRST202) apart
|
||||
// is the SQLSTATE plus the message (the RPC's own RAISE text, "violates
|
||||
// check constraint <name>", "duplicate key value violates unique
|
||||
// constraint <name>"), so those two go to the log (#2060). `details` is
|
||||
// where Postgres quotes row data ("Failing row contains (...)",
|
||||
// "Key (...)=(...)") and `hint` adds nothing operational: neither is
|
||||
// logged, so payee and account data cannot reach a log line through them.
|
||||
// debtor_snapshot and the item rows are not logged either; companyId,
|
||||
// batchId and the item count make the line greppable.
|
||||
if (error) {
|
||||
log.error('create_supplier_payment_batch RPC failed', {
|
||||
companyId,
|
||||
batchId,
|
||||
itemCount: itemRows.length,
|
||||
rpcError: { code: error.code, message: error.message },
|
||||
})
|
||||
return { ok: false, code: 'create_failed' }
|
||||
}
|
||||
|
||||
const result = data as CreateBatchRpcResult | null
|
||||
if (!result) {
|
||||
log.error('create_supplier_payment_batch RPC returned no payload', {
|
||||
companyId,
|
||||
batchId,
|
||||
itemCount: itemRows.length,
|
||||
})
|
||||
return { ok: false, code: 'create_failed' }
|
||||
}
|
||||
if (!result.ok) {
|
||||
switch (result.code) {
|
||||
case 'already_batched':
|
||||
return {
|
||||
ok: false,
|
||||
code: 'already_batched',
|
||||
details: result.details as Array<{ id: string; batch_id: string }>,
|
||||
}
|
||||
case 'amount_exceeds_remaining':
|
||||
return {
|
||||
ok: false,
|
||||
code: 'amount_exceeds_remaining',
|
||||
details: result.details as Array<{ id: string }>,
|
||||
}
|
||||
case 'ineligible':
|
||||
return {
|
||||
ok: false,
|
||||
code: 'ineligible',
|
||||
details: result.details as Array<{ id: string; reason: string }>,
|
||||
}
|
||||
default:
|
||||
// An RPC refusal code with no client mapping (a code added in SQL
|
||||
// without this switch learning it, or the RPC's own payload-shape
|
||||
// refusals) must stay visible rather than vanish behind create_failed.
|
||||
log.error('create_supplier_payment_batch RPC refused with an unmapped code', {
|
||||
companyId,
|
||||
batchId,
|
||||
itemCount: itemRows.length,
|
||||
rpcCode: result.code,
|
||||
rpcDetails: result.details,
|
||||
})
|
||||
return { ok: false, code: 'create_failed' }
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, batch: result.batch }
|
||||
}
|
||||
|
||||
export interface RenderedBatchFile {
|
||||
content: string
|
||||
contentType: string
|
||||
filename: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the payment file for a stored batch. Deterministic: same rows, same
|
||||
* bytes, on every call.
|
||||
*/
|
||||
export function renderSupplierPaymentBatchFile(
|
||||
batch: Pick<SupplierPaymentBatch, 'id' | 'format' | 'msg_id' | 'debtor_snapshot' | 'created_at'>,
|
||||
items: SupplierPaymentBatchItem[],
|
||||
): RenderedBatchFile {
|
||||
if (batch.format !== 'pain001') {
|
||||
throw new Error(`Filformatet stöds inte: ${batch.format}`)
|
||||
}
|
||||
|
||||
const payments: SupplierPain001Payment[] = items.map((item) => ({
|
||||
payee:
|
||||
item.payee_type === 'bankgiro'
|
||||
? { type: 'bankgiro', bankgiro: item.payee_bankgiro ?? '' }
|
||||
: item.payee_type === 'plusgiro'
|
||||
? { type: 'plusgiro', plusgiro: item.payee_plusgiro ?? '' }
|
||||
: {
|
||||
type: 'bank_account',
|
||||
clearing: item.payee_clearing ?? '',
|
||||
account: item.payee_account ?? '',
|
||||
},
|
||||
payeeName: item.payee_name,
|
||||
payeeCity: item.payee_city ?? null,
|
||||
amount: item.amount,
|
||||
paymentDate: item.payment_date,
|
||||
reference: { type: item.reference_type, value: item.reference },
|
||||
}))
|
||||
|
||||
const debtor = batch.debtor_snapshot
|
||||
const content = generateSupplierPain001(
|
||||
{
|
||||
name: debtor.name,
|
||||
orgNumber: debtor.org_number,
|
||||
iban: debtor.iban,
|
||||
bic: debtor.bic,
|
||||
bankgiro: debtor.bankgiro ?? null,
|
||||
city: debtor.city ?? null,
|
||||
},
|
||||
payments,
|
||||
{ messageId: batch.msg_id, createdAt: batch.created_at },
|
||||
)
|
||||
|
||||
const datePart = batch.created_at.slice(0, 10).replace(/-/g, '')
|
||||
const shortId = batch.id.replace(/-/g, '').slice(0, 8)
|
||||
return {
|
||||
content,
|
||||
contentType: 'application/xml; charset=utf-8',
|
||||
filename: `betalfil_${datePart}_${shortId}.xml`,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
/**
|
||||
* pain.001 (ISO 20022) payment file generator for supplier payments
|
||||
* (leverantorsbetalningar).
|
||||
*
|
||||
* Dialect: Swedish DOMESTIC giro credit transfers per the Swedish Common
|
||||
* Interpretation of ISO 20022 payment messages (Svenska Bankforeningen,
|
||||
* "Common Payment Types in Sweden", Appendix 1), cross-checked against
|
||||
* Nordea Corporate Access Payables pain.001 examples v2.6 (2026-06-22) and
|
||||
* validated against Swedbank Validex (eken.validex.net, Swedbank MIG 1.0,
|
||||
* run 2026-08-10). Target banks: Swedbank, SEB, Handelsbanken, Nordea
|
||||
* (pain.001.001.03 uploaded in the corporate portal).
|
||||
*
|
||||
* Wire-format constraints this file encodes (do not "improve" without a
|
||||
* bank implementation guide in hand):
|
||||
*
|
||||
* - No SvcLvl element: SvcLvl SEPA means a SEPA credit transfer (EUR-only);
|
||||
* the domestic default (NURG) applies when SvcLvl is omitted. No CtgyPurp:
|
||||
* SALA/PENS mark salary rails; supplier giro payments are plain transfers.
|
||||
* - Bankgiro payees are addressed through Bankgirot: CdtrAgt ClrSysMmbId
|
||||
* SESBA member 9900, CdtrAcct/Id/Othr with the bare BG digits and
|
||||
* SchmeNm/Prtry BGNR. Plusgiro payees route SESBA member 9960 with
|
||||
* SchmeNm/Cd BBAN. Bank-account payees use the clearing number as the
|
||||
* SESBA member and the account (without clearing) as BBAN, through the
|
||||
* same splitDomesticBankAccount used by the salary generator so the two
|
||||
* files can never route an account differently.
|
||||
* - Swedbank MIG (Validex PFH_pain_001_001_03_219): a BGNR creditor demands
|
||||
* a BGNR debtor. When the company has a bankgiro, bankgiro-payee payments
|
||||
* are grouped into their own PmtInf debited from the company bankgiro
|
||||
* (DbtrAcct Othr/BGNR); other payees are debited from the IBAN.
|
||||
* - Creditor postal address ALWAYS (Validex round 3, rule PFH_237 fires on
|
||||
* the BGNR path too, overriding what rule 020's phrasing suggested), and
|
||||
* a present PstlAdr must carry TwnNm (rule PFH_222, enforced now): the
|
||||
* supplier's town when known, plus Ctry SE (v1 is domestic-only). A payee
|
||||
* without a town yields a Ctry-only address that Swedbank rejects, so the
|
||||
* preview warns when the supplier register lacks a city. The debtor
|
||||
* address rides along the same way from company settings.
|
||||
* - InitgPty and Dbtr always carry OrgId (Validex PFH_002: InitgPty
|
||||
* other/Id must be stated); the batch service refuses to create a batch
|
||||
* for a company without an organisationsnummer.
|
||||
* - A Luhn-valid OCR reference rides RmtInf/Strd with the amount repeated
|
||||
* as RfrdDocAmt/RmtdAmt (Validex PFH_217) and CdtrRefInf type SCOR,
|
||||
* exactly one per transaction. Anything else is an unstructured
|
||||
* RmtInf/Ustrd message (the giro "meddelande" field).
|
||||
* - Free text is restricted to the MIG character set (Validex PFH_214):
|
||||
* Swedish letters survive, other accented letters transliterate (e for
|
||||
* e-acute, u for u-umlaut), anything else becomes '?'. Identifiers and
|
||||
* references are ASCII digits by construction.
|
||||
* - MsgId, PmtInfId, InstrId and EndToEndId are Max35Text.
|
||||
* - ReqdExctnDt sits on PmtInf, so payments are grouped into one PmtInf per
|
||||
* distinct (payment date, debtor account form).
|
||||
* - Determinism: CreDtTm comes from the caller (the batch row's created_at),
|
||||
* never from the clock, so re-generating a stored batch is byte-identical
|
||||
* for the same generator version and bank-side duplicate detection (keyed
|
||||
* on MsgId) stays meaningful.
|
||||
*
|
||||
* Per BFL: the generated file is rakenskapsinformation (underlag) for the
|
||||
* payments it initiates. Subject to 7-year retention.
|
||||
*/
|
||||
|
||||
import { escapeXml } from '@/lib/xml/escape'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { splitDomesticBankAccount } from '@/lib/salary/payment/bank-account'
|
||||
import type { PaymentReference, SupplierPayee } from './supplier-payee'
|
||||
|
||||
export interface SupplierPain001Debtor {
|
||||
name: string
|
||||
orgNumber: string
|
||||
iban: string
|
||||
bic: string
|
||||
/** Company bankgiro (digits); enables the BGNR-to-BGNR debit Swedbank wants. */
|
||||
bankgiro?: string | null
|
||||
/** Company town; emitted as Dbtr/PstlAdr/TwnNm when present. */
|
||||
city?: string | null
|
||||
}
|
||||
|
||||
export interface SupplierPain001Payment {
|
||||
payee: SupplierPayee
|
||||
payeeName: string
|
||||
/** Supplier town; Cdtr/PstlAdr/TwnNm on IBAN-debited payments when known. */
|
||||
payeeCity?: string | null
|
||||
amount: number
|
||||
/** YYYY-MM-DD requested execution date. */
|
||||
paymentDate: string
|
||||
reference: PaymentReference
|
||||
}
|
||||
|
||||
export interface SupplierPain001Options {
|
||||
/** Stored batch msg_id; reused verbatim on regeneration. */
|
||||
messageId: string
|
||||
/** Batch created_at (ISO timestamp): becomes CreDtTm, NOT the clock. */
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/** The receiver-side giro message field is 25 positions; keep Ustrd within it. */
|
||||
const USTRD_MAX = 25
|
||||
|
||||
export function generateSupplierPain001(
|
||||
debtor: SupplierPain001Debtor,
|
||||
payments: SupplierPain001Payment[],
|
||||
options: SupplierPain001Options,
|
||||
): string {
|
||||
if (payments.length === 0) {
|
||||
throw new Error('Betalfilen måste innehålla minst en betalning')
|
||||
}
|
||||
|
||||
const creDtTm = new Date(options.createdAt).toISOString().replace(/\.\d{3}Z$/, 'Z')
|
||||
const msgId = max35(options.messageId)
|
||||
const orgDigits = debtor.orgNumber.replace(/\D/g, '')
|
||||
if (!orgDigits) {
|
||||
// Validex PFH_002: InitgPty other/Id must be stated. The batch service
|
||||
// guarantees this; a missing org number here is a programming error.
|
||||
throw new Error('Organisationsnummer saknas för betalfilens avsändare')
|
||||
}
|
||||
const debtorBankgiro = (debtor.bankgiro ?? '').replace(/\D/g, '')
|
||||
const debtorName = sanitizeText(debtor.name)
|
||||
// Sum the per-transaction amounts exactly as they are rendered (rounded to
|
||||
// ore): CtrlSum must equal the sum of the InstdAmt values or banks reject
|
||||
// the file, and summing raw floats then rounding once can differ by an ore.
|
||||
const totalAmount = sumRendered(payments)
|
||||
|
||||
// One PmtInf per distinct (execution date, debtor account form): a BGNR
|
||||
// creditor must debit the company bankgiro (Swedbank rule 219), everything
|
||||
// else debits the IBAN, and ReqdExctnDt is PmtInf-level. Original order is
|
||||
// preserved within a group so the file reads like the batch it came from.
|
||||
const byGroup = new Map<string, SupplierPain001Payment[]>()
|
||||
for (const payment of payments) {
|
||||
const bgnrDebit = debtorBankgiro !== '' && payment.payee.type === 'bankgiro'
|
||||
const key = `${payment.paymentDate}|${bgnrDebit ? 'bgnr' : 'acct'}`
|
||||
const group = byGroup.get(key)
|
||||
if (group) group.push(payment)
|
||||
else byGroup.set(key, [payment])
|
||||
}
|
||||
const groupKeys = [...byGroup.keys()].sort()
|
||||
|
||||
const lines: string[] = []
|
||||
lines.push('<?xml version="1.0" encoding="UTF-8"?>')
|
||||
lines.push('<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"')
|
||||
lines.push(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">')
|
||||
lines.push(' <CstmrCdtTrfInitn>')
|
||||
|
||||
lines.push(' <GrpHdr>')
|
||||
lines.push(` <MsgId>${escapeXml(msgId)}</MsgId>`)
|
||||
lines.push(` <CreDtTm>${creDtTm}</CreDtTm>`)
|
||||
lines.push(` <NbOfTxs>${payments.length}</NbOfTxs>`)
|
||||
lines.push(` <CtrlSum>${formatDecimal(totalAmount)}</CtrlSum>`)
|
||||
lines.push(' <InitgPty>')
|
||||
lines.push(` <Nm>${escapeXml(debtorName)}</Nm>`)
|
||||
lines.push(' <Id>')
|
||||
lines.push(' <OrgId>')
|
||||
lines.push(` <Othr><Id>${escapeXml(orgDigits)}</Id></Othr>`)
|
||||
lines.push(' </OrgId>')
|
||||
lines.push(' </Id>')
|
||||
lines.push(' </InitgPty>')
|
||||
lines.push(' </GrpHdr>')
|
||||
|
||||
let txCounter = 0
|
||||
for (let g = 0; g < groupKeys.length; g++) {
|
||||
const key = groupKeys[g]
|
||||
const [date, form] = key.split('|')
|
||||
const group = byGroup.get(key) as SupplierPain001Payment[]
|
||||
const groupTotal = sumRendered(group)
|
||||
const bgnrDebit = form === 'bgnr'
|
||||
|
||||
lines.push(' <PmtInf>')
|
||||
lines.push(` <PmtInfId>${escapeXml(suffixId(msgId, `-P${g + 1}`))}</PmtInfId>`)
|
||||
lines.push(' <PmtMtd>TRF</PmtMtd>')
|
||||
lines.push(' <BtchBookg>true</BtchBookg>')
|
||||
lines.push(` <NbOfTxs>${group.length}</NbOfTxs>`)
|
||||
lines.push(` <CtrlSum>${formatDecimal(groupTotal)}</CtrlSum>`)
|
||||
lines.push(` <ReqdExctnDt>${date}</ReqdExctnDt>`)
|
||||
lines.push(' <Dbtr>')
|
||||
lines.push(` <Nm>${escapeXml(debtorName)}</Nm>`)
|
||||
// XSD order in PostalAddress6: TwnNm before Ctry; PstlAdr before Id.
|
||||
if (debtor.city?.trim()) {
|
||||
lines.push(' <PstlAdr>')
|
||||
lines.push(` <TwnNm>${escapeXml(sanitizeText(debtor.city.trim()))}</TwnNm>`)
|
||||
lines.push(' <Ctry>SE</Ctry>')
|
||||
lines.push(' </PstlAdr>')
|
||||
}
|
||||
lines.push(' <Id>')
|
||||
lines.push(' <OrgId>')
|
||||
lines.push(` <Othr><Id>${escapeXml(orgDigits)}</Id></Othr>`)
|
||||
lines.push(' </OrgId>')
|
||||
lines.push(' </Id>')
|
||||
lines.push(' </Dbtr>')
|
||||
lines.push(' <DbtrAcct>')
|
||||
lines.push(' <Id>')
|
||||
if (bgnrDebit) {
|
||||
lines.push(' <Othr>')
|
||||
lines.push(` <Id>${escapeXml(debtorBankgiro)}</Id>`)
|
||||
lines.push(' <SchmeNm><Prtry>BGNR</Prtry></SchmeNm>')
|
||||
lines.push(' </Othr>')
|
||||
} else {
|
||||
lines.push(` <IBAN>${escapeXml(debtor.iban)}</IBAN>`)
|
||||
}
|
||||
lines.push(' </Id>')
|
||||
lines.push(' <Ccy>SEK</Ccy>')
|
||||
lines.push(' </DbtrAcct>')
|
||||
lines.push(' <DbtrAgt>')
|
||||
lines.push(' <FinInstnId>')
|
||||
lines.push(` <BIC>${escapeXml(debtor.bic)}</BIC>`)
|
||||
lines.push(' </FinInstnId>')
|
||||
lines.push(' </DbtrAgt>')
|
||||
|
||||
for (const payment of group) {
|
||||
txCounter += 1
|
||||
const txId = suffixId(msgId, `-TX${String(txCounter).padStart(4, '0')}`)
|
||||
|
||||
lines.push(' <CdtTrfTxInf>')
|
||||
lines.push(' <PmtId>')
|
||||
lines.push(` <InstrId>${escapeXml(txId)}</InstrId>`)
|
||||
lines.push(` <EndToEndId>${escapeXml(txId)}</EndToEndId>`)
|
||||
lines.push(' </PmtId>')
|
||||
lines.push(' <Amt>')
|
||||
lines.push(` <InstdAmt Ccy="SEK">${formatDecimal(payment.amount)}</InstdAmt>`)
|
||||
lines.push(' </Amt>')
|
||||
pushCreditor(lines, payment)
|
||||
pushRemittance(lines, payment.reference, payment.amount)
|
||||
lines.push(' </CdtTrfTxInf>')
|
||||
}
|
||||
|
||||
lines.push(' </PmtInf>')
|
||||
}
|
||||
|
||||
lines.push(' </CstmrCdtTrfInitn>')
|
||||
lines.push('</Document>')
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
/** XSD order within CdtTrfTxInf: CdtrAgt before Cdtr before CdtrAcct. */
|
||||
function pushCreditor(lines: string[], payment: SupplierPain001Payment): void {
|
||||
const { payee } = payment
|
||||
|
||||
let memberId: string
|
||||
let accountId: string
|
||||
let scheme: string
|
||||
switch (payee.type) {
|
||||
case 'bankgiro':
|
||||
memberId = '9900'
|
||||
accountId = payee.bankgiro
|
||||
scheme = '<SchmeNm><Prtry>BGNR</Prtry></SchmeNm>'
|
||||
break
|
||||
case 'plusgiro':
|
||||
memberId = '9960'
|
||||
accountId = payee.plusgiro
|
||||
scheme = '<SchmeNm><Cd>BBAN</Cd></SchmeNm>'
|
||||
break
|
||||
case 'bank_account': {
|
||||
const { clearing4, accountDigits } = splitDomesticBankAccount(payee.clearing, payee.account)
|
||||
memberId = clearing4
|
||||
accountId = accountDigits
|
||||
scheme = '<SchmeNm><Cd>BBAN</Cd></SchmeNm>'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(' <CdtrAgt>')
|
||||
lines.push(' <FinInstnId>')
|
||||
lines.push(' <ClrSysMmbId>')
|
||||
lines.push(' <ClrSysId><Cd>SESBA</Cd></ClrSysId>')
|
||||
lines.push(` <MmbId>${memberId}</MmbId>`)
|
||||
lines.push(' </ClrSysMmbId>')
|
||||
lines.push(' </FinInstnId>')
|
||||
lines.push(' </CdtrAgt>')
|
||||
lines.push(' <Cdtr>')
|
||||
lines.push(` <Nm>${escapeXml(sanitizeText(payment.payeeName))}</Nm>`)
|
||||
// Always (Validex round 3, rule 237 fires on every path): the supplier's
|
||||
// town when known and country SE (v1 scope). XSD order: TwnNm before Ctry.
|
||||
lines.push(' <PstlAdr>')
|
||||
if (payment.payeeCity?.trim()) {
|
||||
lines.push(` <TwnNm>${escapeXml(sanitizeText(payment.payeeCity.trim()))}</TwnNm>`)
|
||||
}
|
||||
lines.push(' <Ctry>SE</Ctry>')
|
||||
lines.push(' </PstlAdr>')
|
||||
lines.push(' </Cdtr>')
|
||||
lines.push(' <CdtrAcct>')
|
||||
lines.push(' <Id>')
|
||||
lines.push(' <Othr>')
|
||||
lines.push(` <Id>${escapeXml(accountId)}</Id>`)
|
||||
lines.push(` ${scheme}`)
|
||||
lines.push(' </Othr>')
|
||||
lines.push(' </Id>')
|
||||
lines.push(' </CdtrAcct>')
|
||||
}
|
||||
|
||||
function pushRemittance(lines: string[], reference: PaymentReference, amount: number): void {
|
||||
lines.push(' <RmtInf>')
|
||||
if (reference.type === 'ocr') {
|
||||
lines.push(' <Strd>')
|
||||
// Validex PFH_217: RfrdDocAmt must be stated when Strd is provided. The
|
||||
// remitted amount equals the instructed amount for a full-line payment.
|
||||
lines.push(' <RfrdDocAmt>')
|
||||
lines.push(` <RmtdAmt Ccy="SEK">${formatDecimal(amount)}</RmtdAmt>`)
|
||||
lines.push(' </RfrdDocAmt>')
|
||||
lines.push(' <CdtrRefInf>')
|
||||
lines.push(' <Tp>')
|
||||
lines.push(' <CdOrPrtry><Cd>SCOR</Cd></CdOrPrtry>')
|
||||
lines.push(' </Tp>')
|
||||
lines.push(` <Ref>${escapeXml(reference.value)}</Ref>`)
|
||||
lines.push(' </CdtrRefInf>')
|
||||
lines.push(' </Strd>')
|
||||
} else {
|
||||
lines.push(` <Ustrd>${escapeXml(sanitizeText(reference.value).slice(0, USTRD_MAX))}</Ustrd>`)
|
||||
}
|
||||
lines.push(' </RmtInf>')
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helpers (deliberately duplicated from the salary generator: that dialect is
|
||||
// production-hardened and stays untouched; see DECISIONS.md 2026-08-10)
|
||||
// ============================================================
|
||||
|
||||
/** Control sums add the amounts AS RENDERED: each rounded to öre first. */
|
||||
function sumRendered(payments: readonly SupplierPain001Payment[]): number {
|
||||
return payments.reduce((sum, p) => sum + roundOre(p.amount), 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* MIG character-set restriction (Validex PFH_pain_001_001_03_214): Swedish
|
||||
* letters pass through, other accented Latin letters transliterate to their
|
||||
* base letter, and anything still outside the allowed set becomes '?', the
|
||||
* same substitution the Bankgirot LB generator uses. Sanitize BEFORE
|
||||
* escapeXml so entity-encoded characters are never mangled.
|
||||
*/
|
||||
const TRANSLITERATIONS: Record<string, string> = {
|
||||
'é': 'e', 'è': 'e', 'ê': 'e', 'ë': 'e', 'É': 'E', 'È': 'E', 'Ê': 'E', 'Ë': 'E',
|
||||
'á': 'a', 'à': 'a', 'â': 'a', 'ã': 'a', 'Á': 'A', 'À': 'A', 'Â': 'A', 'Ã': 'A',
|
||||
'í': 'i', 'ì': 'i', 'î': 'i', 'ï': 'i', 'Í': 'I', 'Ì': 'I', 'Î': 'I', 'Ï': 'I',
|
||||
'ó': 'o', 'ò': 'o', 'ô': 'o', 'õ': 'o', 'Ó': 'O', 'Ò': 'O', 'Ô': 'O', 'Õ': 'O',
|
||||
'ú': 'u', 'ù': 'u', 'û': 'u', 'ü': 'u', 'Ú': 'U', 'Ù': 'U', 'Û': 'U', 'Ü': 'U',
|
||||
'ý': 'y', 'ÿ': 'y', 'Ý': 'Y', 'ñ': 'n', 'Ñ': 'N', 'ç': 'c', 'Ç': 'C',
|
||||
'ø': 'o', 'Ø': 'O', 'æ': 'a', 'Æ': 'A', 'ß': 'ss',
|
||||
'š': 's', 'Š': 'S', 'ž': 'z', 'Ž': 'Z', 'đ': 'd', 'Đ': 'D',
|
||||
// '+' is in the allowed set and reads naturally where Swedish names use '&'.
|
||||
'&': '+',
|
||||
}
|
||||
|
||||
const DISALLOWED_TEXT = /[^0-9A-Za-zåäöÅÄÖ/\-?:().,'+ ]/g
|
||||
|
||||
function sanitizeText(value: string): string {
|
||||
// NFC first: decomposed input (base letter + combining mark, common in text
|
||||
// pasted from PDFs) must fold to the precomposed forms the map knows.
|
||||
let transliterated = ''
|
||||
for (const ch of value.normalize('NFC')) transliterated += TRANSLITERATIONS[ch] ?? ch
|
||||
return transliterated.replace(DISALLOWED_TEXT, '?')
|
||||
}
|
||||
|
||||
function formatDecimal(amount: number): string {
|
||||
return roundOre(amount).toFixed(2)
|
||||
}
|
||||
|
||||
function max35(value: string): string {
|
||||
return value.slice(0, 35)
|
||||
}
|
||||
|
||||
function suffixId(base: string, suffix: string): string {
|
||||
return base.slice(0, Math.max(1, 35 - suffix.length)) + suffix
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Payee and payment-reference resolution for supplier payment files.
|
||||
*
|
||||
* A payee is the routing target a payment instruction addresses. Suppliers
|
||||
* store their payment details across five columns of mixed quality
|
||||
* (bankgiro, plusgiro, structured clearing_number + account_number, and the
|
||||
* legacy free-text bank_account); this module is the single place that turns
|
||||
* them into a validated, discriminated payee or an explicit failure. Nothing
|
||||
* downstream may guess: an ambiguous digit blob must become 'payee_invalid',
|
||||
* never a payment to the wrong account.
|
||||
*
|
||||
* Priority mirrors the suppliers list page (bankgiro before plusgiro before
|
||||
* bank account) minus IBAN, which v1 does not pay to (SEK domestic only).
|
||||
*/
|
||||
|
||||
import { validateBankgiroNumber, validatePlusgiroNumber, validateOcrReference } from '@/lib/bankgiro/luhn'
|
||||
import { isValidAccount, isValidClearing } from '@/lib/salary/payment/bank-account'
|
||||
|
||||
export type SupplierPayee =
|
||||
| { type: 'bankgiro'; bankgiro: string }
|
||||
| { type: 'plusgiro'; plusgiro: string }
|
||||
| { type: 'bank_account'; clearing: string; account: string }
|
||||
|
||||
export type PayeeResolution =
|
||||
| { ok: true; payee: SupplierPayee }
|
||||
| { ok: false; reason: 'payee_missing' | 'payee_invalid' }
|
||||
|
||||
export interface SupplierPayeeSource {
|
||||
bankgiro: string | null
|
||||
plusgiro: string | null
|
||||
bank_account: string | null
|
||||
clearing_number?: string | null
|
||||
account_number?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Free-text bank_account values are accepted only when they carry an explicit
|
||||
* clearing/account separator: "8327-9 123456789", "3300-1234567". A bare digit
|
||||
* blob cannot be split safely (is 83279123456789 clearing 8327 or 8327-9?),
|
||||
* so it resolves to payee_invalid.
|
||||
*/
|
||||
const FREE_TEXT_BANK_ACCOUNT = /^(\d{4}|8\d{4})[-\s]+([\d\s-]{5,15})$/
|
||||
|
||||
function digits(value: string | null | undefined): string {
|
||||
return (value ?? '').replace(/\D/g, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the payee a supplier payment should be routed to, or an explicit
|
||||
* failure. A present-but-invalid value in a higher-priority field fails the
|
||||
* resolution rather than falling through: silently paying a supplier's
|
||||
* plusgiro because its bankgiro has a typo hides the typo forever.
|
||||
*/
|
||||
export function resolveSupplierPayee(supplier: SupplierPayeeSource): PayeeResolution {
|
||||
if (supplier.bankgiro?.trim()) {
|
||||
if (!validateBankgiroNumber(supplier.bankgiro)) return { ok: false, reason: 'payee_invalid' }
|
||||
return { ok: true, payee: { type: 'bankgiro', bankgiro: digits(supplier.bankgiro) } }
|
||||
}
|
||||
|
||||
if (supplier.plusgiro?.trim()) {
|
||||
if (!validatePlusgiroNumber(supplier.plusgiro)) return { ok: false, reason: 'payee_invalid' }
|
||||
return { ok: true, payee: { type: 'plusgiro', plusgiro: digits(supplier.plusgiro) } }
|
||||
}
|
||||
|
||||
const clearing = digits(supplier.clearing_number)
|
||||
const account = digits(supplier.account_number)
|
||||
if (clearing || account) {
|
||||
if (!isValidClearing(clearing) || !isValidAccount(account)) {
|
||||
return { ok: false, reason: 'payee_invalid' }
|
||||
}
|
||||
return { ok: true, payee: { type: 'bank_account', clearing, account } }
|
||||
}
|
||||
|
||||
const freeText = supplier.bank_account?.trim()
|
||||
if (freeText) {
|
||||
const match = FREE_TEXT_BANK_ACCOUNT.exec(freeText)
|
||||
if (!match) return { ok: false, reason: 'payee_invalid' }
|
||||
const ftClearing = match[1]
|
||||
const ftAccount = digits(match[2])
|
||||
if (!isValidClearing(ftClearing) || !isValidAccount(ftAccount)) {
|
||||
return { ok: false, reason: 'payee_invalid' }
|
||||
}
|
||||
return { ok: true, payee: { type: 'bank_account', clearing: ftClearing, account: ftAccount } }
|
||||
}
|
||||
|
||||
return { ok: false, reason: 'payee_missing' }
|
||||
}
|
||||
|
||||
/** Human-readable payee label for previews and batch views: "BG 5050-1055". */
|
||||
export function formatPayeeLabel(payee: SupplierPayee): string {
|
||||
switch (payee.type) {
|
||||
case 'bankgiro': {
|
||||
const bg = payee.bankgiro
|
||||
return `BG ${bg.slice(0, bg.length - 4)}-${bg.slice(-4)}`
|
||||
}
|
||||
case 'plusgiro': {
|
||||
const pg = payee.plusgiro
|
||||
return `PG ${pg.slice(0, pg.length - 1)}-${pg.slice(-1)}`
|
||||
}
|
||||
case 'bank_account':
|
||||
return `${payee.clearing} ${payee.account}`
|
||||
}
|
||||
}
|
||||
|
||||
export type PaymentReference =
|
||||
| { type: 'ocr'; value: string }
|
||||
| { type: 'invoice_number'; value: string }
|
||||
|
||||
export interface PaymentReferenceSource {
|
||||
payment_reference: string | null
|
||||
supplier_invoice_number: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference the receiver uses to match the payment to the invoice.
|
||||
*
|
||||
* A Luhn-valid payment_reference is a real OCR number and rides the structured
|
||||
* rail (pain.001 CdtrRefInf SCOR). Anything else falls back to the supplier's
|
||||
* invoice number as a plain message: a mistyped OCR still reaches the supplier
|
||||
* as text a human can match, whereas a structured SCOR reference that fails
|
||||
* the receiver's OCR check can bounce the whole payment. Callers surface the
|
||||
* fallback-on-invalid case as a warning (ocrInvalid) so the typo gets fixed.
|
||||
*/
|
||||
export function resolvePaymentReference(invoice: PaymentReferenceSource): {
|
||||
reference: PaymentReference
|
||||
ocrInvalid: boolean
|
||||
} {
|
||||
const raw = invoice.payment_reference?.trim()
|
||||
if (raw) {
|
||||
const ocr = digits(raw)
|
||||
if (validateOcrReference(ocr)) {
|
||||
return { reference: { type: 'ocr', value: ocr }, ocrInvalid: false }
|
||||
}
|
||||
return {
|
||||
reference: { type: 'invoice_number', value: invoice.supplier_invoice_number },
|
||||
ocrInvalid: true,
|
||||
}
|
||||
}
|
||||
return {
|
||||
reference: { type: 'invoice_number', value: invoice.supplier_invoice_number },
|
||||
ocrInvalid: false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Swish number normalisation + validation.
|
||||
*
|
||||
* Two accepted shapes:
|
||||
* - Swish Företag: `123XXXXXXX` (10 digits starting with `123`)
|
||||
* - Swedish mobile: `07XXXXXXXX` (10 digits starting with `07`)
|
||||
*
|
||||
* Whitespace and hyphens are stripped before validation so users can paste
|
||||
* formatted numbers (`123 456 78 90` or `070-123 45 67`) and have them
|
||||
* canonicalised.
|
||||
*/
|
||||
|
||||
import { roundOre } from '@/lib/money'
|
||||
|
||||
const SWISH_FORETAG = /^123\d{7}$/
|
||||
const SWEDISH_MOBILE = /^07\d{8}$/
|
||||
|
||||
export function normaliseSwish(value: string | null | undefined): string {
|
||||
if (!value) return ''
|
||||
return value.replace(/[\s-]/g, '')
|
||||
}
|
||||
|
||||
export function isValidSwish(normalised: string): boolean {
|
||||
return normalised === '' || SWISH_FORETAG.test(normalised) || SWEDISH_MOBILE.test(normalised)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the Swish "Type C" QR payload: `C<payee>;<amount>;<message>;<editmask>`.
|
||||
*
|
||||
* editmask 0 locks payee, amount and message, so the Swish app opens prefilled
|
||||
* and uneditable. This is the documented format the Swish app scans directly,
|
||||
* so the QR can be generated entirely offline (no call to Swish's QR API).
|
||||
* Works for both Swish-företag (123XXXXXXX) and mobile (07XXXXXXXX) payees.
|
||||
*
|
||||
* Returns null when the number is missing/invalid or the amount is not positive.
|
||||
* Spec: Swish QR Code Design Specification (Getswish AB).
|
||||
*/
|
||||
export function buildSwishQrPayload(
|
||||
swishNumber: string | null | undefined,
|
||||
amount: number,
|
||||
message: string,
|
||||
): string | null {
|
||||
const number = normaliseSwish(swishNumber)
|
||||
if (!number || !isValidSwish(number)) return null
|
||||
if (!(amount > 0)) return null
|
||||
// Amount uses a dot decimal with at most two decimals. The message must not
|
||||
// contain the ';' field delimiter; cap its length to keep the QR scannable.
|
||||
const amt = roundOre(amount).toFixed(2)
|
||||
const msg = (message ?? '').replace(/;/g, ' ').trim().slice(0, 50)
|
||||
return `C${number};${amt};${msg};0`
|
||||
}
|
||||
Reference in New Issue
Block a user