Finnish virtual bank barcode (virtuaaliviivakoodi)
ClosingBuilds the 54-digit virtual bank barcode from the Finanssiala bank barcode guide, or checks the one the ERP issued against it. The reference decides the version: a viitenumero gives version 4, an RF reference gives version 5, whose RF check digits take the place of version 4's reserved zeros, with the padding after them, not before. Obsolete version 2 is never produced. The code is printed only for a Finnish IBAN that passes mod-97, a euro invoice, a reference whose check digit is right and an RF that is numeric; any failure, or an ERP code that disagrees, withholds it and prints the IBAN and reference on their own. An amount over 999 999,99 or an open amount zero-fills the amount field rather than truncating it, and a missing or on-receipt due date becomes 000000. A credit note or paid invoice prints nothing. The code is one unbroken run, without the drawn barcode's mod-103 check. All of it is one deriver.
npx dxcl add finnish-virtual-barcode Voorbeelddata
de JSON waarmee dit voorbeeld is gebouwd{
"payee": {
"iban": "FI79 4405 2020 0360 82"
},
"invoice": {
"currency": "EUR",
"total": 987654.32,
"dueDate": "2026-12-31"
},
"payment": {
"reference": "RF26 2026 1100 4817 3500 1234 5"
},
"virtualBarcode": "579440520200360829876543226202611004817350012345261231"
} Gerenderd voorbeeld
elke opstelling op zichzelf gerenderdarrangement="stacked" standaard arrangement="table" Opgeloste nodes
wat een renderer krijgt — 4 nodesvirtual-barcode-iban paragraph · static Saajan tilinumero (IBAN): FI79 4405 2020 0360 82 virtual-barcode-reference paragraph · static Viitenumero: RF26 2026 1100 4817 3500 1234 5 virtual-barcode-label paragraph · static Virtuaaliviivakoodi virtual-barcode-code paragraph · static 579440520200360829876543226202611004817350012345261231 De bestanden
wat installeren schrijft; het gekozen bestand is de componentnodes/finnish-virtual-barcode.node.tsx import { arrange, type Nodes, useDeriver, useState } from "docxcelerate/template";
import type { FinnishVirtualBarcodeLines } from "../arrangements/finnish-virtual-barcode/lines.ts";
import { stacked } from "../arrangements/finnish-virtual-barcode/stacked.arrangement.tsx";
import { table } from "../arrangements/finnish-virtual-barcode/table.arrangement.tsx";
import finnishVirtualBarcode from "../derivers/finnish-virtual-barcode.deriver.ts";
/**
* The payee's IBAN, the payment reference and the 54-digit virtual bank
* barcode (virtuaaliviivakoodi) a Finnish payer pastes into a banking app. A
* truncated or mis-versioned code would scan into the wrong account and a
* payer cannot spot that by eye, so the code is printed only when every check
* passes.
*
* The reference decides the version: an RF reference gives version 5, a
* viitenumero version 4. There is no flag, because a flag could disagree with
* the reference. Version 2 is never produced.
*
* Any doubt withholds the code: a bad IBAN, a non-Finnish one, a currency
* other than EUR, a bad reference check, an alphanumeric RF, a bad due date,
* or an ERP code that differs from the rebuilt one. The IBAN and reference
* are still printed, so the invoice can be paid by hand. A total of zero or
* less prints nothing at all.
*
* All of it is one deriver, since it is checksums and string surgery on
* request data, which publishing refuses. The node computes nothing; the
* arrangements guard each line on its string. There is no heading, so it can
* sit under an invoice's totals or giro block.
*
* Installed by `dxcl add finnish-virtual-barcode`, which also installs its deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface FinnishVirtualBarcodeData {
payee: {
/**
* The account to be paid, as an IBAN. Spaces are ignored and letters are
* upper-cased, so "fi79 4405 2020 0360 82" is fine. It must pass the
* IBAN mod-97 check and start with FI: the guide allows a barcode only
* for a Finnish account. A non-Finnish IBAN that is otherwise valid is
* still printed, without a code. An invalid one is printed as given
* (trimmed), without a code; the payer's bank refuses it at payment
* rather than sending money anywhere. Missing or empty withholds the
* code and prints no IBAN line.
*/
iban: string;
};
invoice: {
/**
* ISO 4217 code. Must be "EUR" (compared after trimming and
* upper-casing). Anything else, or missing, withholds the code: the
* barcode's amount field is euros by definition.
*/
currency: string;
/**
* What the payer owes, in euros, to the cent: 4883.15. Zero or less
* (a credit note, an invoice already paid) prints nothing at all. Over
* 999 999,99 the amount field is zero-filled so the payer types it in.
* Not a finite number, or finer than a cent (12.345), withholds the code,
* because a barcode amount a cent off the printed total is a wrong
* barcode. Not read when `openAmount` is true.
*/
total: number;
/**
* The due date, ISO 8601 (YYYY-MM-DD; anything after the tenth character
* is ignored). Written into the code as YYMMDD. Missing or empty gives
* 000000. A value that is not a real date in 2000-2099 withholds the
* code. Ignored when `onReceipt` is true.
*/
dueDate?: string;
/**
* True when the invoice is payable on receipt. The code's due-date field
* becomes 000000 rather than a guessed date. Missing means false.
*/
onReceipt?: boolean;
/**
* True when the payer decides the amount (a donation, an advance). The
* amount field is zero-filled and `total` is not read. Missing means false.
*/
openAmount?: boolean;
};
payment: {
/**
* The payment reference: a Finnish viitenumero ("86851 62596 19897") or
* an ISO 11649 RF reference ("RF09 8685 1625 9619 897"). Spaces are
* ignored. A reference starting with RF (any case) is read as RF and
* gives a version 5 code; anything else is read as a viitenumero and
* gives version 4. A reference that fails its checks is printed as given
* (trimmed), without a code. Missing or empty withholds the code and
* prints no reference line.
*/
reference: string;
};
/**
* The 54-digit code the ERP already issued, if it issues one. Spaces are
* ignored. It is never printed on trust: the code is rebuilt from the
* fields above, and if the two differ the code is withheld, because
* nobody can say which one is wrong, and the wrong one pays the wrong
* account or the wrong amount. Missing or empty means "build it".
*/
virtualBarcode?: string;
}
/**
* Where the lines sit.
*
* - `stacked`: each labelled line under the last, the code on its own line
* under its label. The default.
* - `table`: the IBAN and reference as label/value rows, the code under the
* table at full column width.
*/
export type FinnishVirtualBarcodeArrangement = "stacked" | "table";
/** Props for {@linkcode FinnishVirtualBarcode}. */
export interface FinnishVirtualBarcodeProps {
/** Where the lines sit. Defaults to `"stacked"`. */
arrangement?: FinnishVirtualBarcodeArrangement;
}
export const FinnishVirtualBarcode: Nodes<FinnishVirtualBarcodeProps> = async ({ arrangement }) => {
const [payee] = useState((data: FinnishVirtualBarcodeData) => data.payee);
const [invoice] = useState((data: FinnishVirtualBarcodeData) => data.invoice);
const [payment] = useState((data: FinnishVirtualBarcodeData) => data.payment);
const [virtualBarcode] = useState((data: FinnishVirtualBarcodeData) => data.virtualBarcode);
const v = await useDeriver(finnishVirtualBarcode, [payee, invoice, payment, virtualBarcode]);
const lines: FinnishVirtualBarcodeLines = { iban: v.iban, reference: v.reference, code: v.code };
return <>{arrange(arrangement, { stacked: () => stacked(lines), table: () => table(lines) })}</>;
}; derivers/finnish-virtual-barcode.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Builds the 54-digit Finnish virtual bank barcode, or says why it must not be
* printed. Installed by `dxcl add finnish-virtual-barcode`.
*
* It never throws: every bad input is a withheld code, because the fallback
* (the IBAN and reference on their own) is still a payable invoice.
*
* It is self-contained on purpose: it travels to the engine as source text, so
* a module-level constant or helper would be a ReferenceError there. Every
* helper is declared inside `run`.
*/
export default deriver({
name: "finnishVirtualBarcode",
run: (payee: unknown, invoice: unknown, payment: unknown, virtualBarcode: unknown) => {
const pay = payee as any;
const inv = invoice as any;
const pmt = payment as any;
const iban = String(pay?.iban ?? "").replace(/\s+/g, "").toUpperCase();
const ref = String(pmt?.reference ?? "").replace(/\s+/g, "").toUpperCase();
const erp = String(virtualBarcode ?? "").replace(/\s+/g, "");
const currency = String(inv?.currency ?? "").trim().toUpperCase();
// Folded digit by digit: Number() on the whole string loses precision.
const mod97 = (s: string): boolean => {
const moved = s.slice(4) + s.slice(0, 4);
let r = 0;
for (const ch of moved) {
const n = /[A-Z]/.test(ch) ? String(ch.charCodeAt(0) - 55) : ch;
for (const d of n) r = (r * 10 + Number(d)) % 97;
}
return r === 1;
};
const groups = (s: string, size: number, fromRight: boolean): string => {
const out: string[] = [];
if (fromRight) {
for (let i = s.length; i > 0; i -= size) out.unshift(s.slice(Math.max(0, i - size), i));
} else {
for (let i = 0; i < s.length; i += size) out.push(s.slice(i, i + size));
}
return out.join(" ");
};
const ibanOk = /^[A-Z]{2}\d{2}[A-Z0-9]{1,30}$/.test(iban) && mod97(iban);
// The reference is judged on its own, so it is grouped even when the IBAN
// failed first.
const isRf = ref.startsWith("RF");
const v = ref.replace(/^0+/, "");
let refOk: boolean;
if (isRf) {
refOk = /^RF\d{2}[0-9A-Z]{1,21}$/.test(ref) && mod97(ref);
} else {
refOk = /^\d{4,20}$/.test(v);
if (refOk) {
let sum = 0;
const body = v.slice(0, -1);
for (let i = 0; i < body.length; i++) {
sum += Number(body[body.length - 1 - i]) * [7, 3, 1][i % 3];
}
refOk = (10 - sum % 10) % 10 === Number(v[v.length - 1]);
}
}
const printedIban = ibanOk ? groups(iban, 4, false) : String(pay?.iban ?? "").trim();
const printedRef = !refOk
? String(pmt?.reference ?? "").trim()
: isRf
? groups(ref, 4, false)
: groups(v, 5, true);
const withheld = (reason: string) => ({
outcome: "withheld",
reason,
iban: printedIban,
reference: printedRef,
code: "",
});
// 1. Nothing owed: a credit note or a paid invoice prints nothing at all.
const open = inv?.openAmount === true;
if (!open && typeof inv?.total === "number" && Number.isFinite(inv.total) && inv.total <= 0) {
return { outcome: "none", reason: "", iban: "", reference: "", code: "" };
}
if (!ibanOk) return withheld("iban");
if (!/^FI\d{16}$/.test(iban)) return withheld("not-finnish");
if (currency !== "EUR") return withheld("currency");
let amount8 = "00000000";
if (!open) {
const total = inv?.total;
if (typeof total !== "number" || !Number.isFinite(total)) return withheld("amount");
const cents = Math.round(total * 100);
if (Math.abs(total * 100 - cents) > 1e-6) return withheld("amount");
// Zero-filled past the cap, never truncated: the payer types it in.
if (cents <= 99_999_999) amount8 = String(cents).padStart(8, "0");
}
if (!refOk) return withheld("reference");
if (isRf && !/^\d+$/.test(ref.slice(4))) return withheld("rf-alphanumeric");
let due6 = "000000";
const dueDate = inv?.dueDate;
if (inv?.onReceipt !== true && dueDate !== undefined && dueDate !== null && dueDate !== "") {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dueDate).slice(0, 10));
if (!m) return withheld("due-date");
const y = Number(m[1]), mo = Number(m[2]), d = Number(m[3]);
const t = new Date(Date.UTC(y, mo - 1, d));
if (
y < 2000 || y > 2099 || t.getUTCFullYear() !== y || t.getUTCMonth() !== mo - 1 || t.getUTCDate() !== d
) return withheld("due-date");
due6 = m[1].slice(2) + m[2] + m[3];
}
// The versions differ in field order: version 5 puts the RF check digits
// where version 4 has the reserved 000, and pads after them.
const built = isRf
? "5" + iban.slice(2) + amount8 + ref.slice(2, 4) + ref.slice(4).padStart(21, "0") + due6
: "4" + iban.slice(2) + amount8 + "000" + v.padStart(20, "0") + due6;
if (built.length !== 54) return withheld("reference");
if (erp !== "" && erp !== built) return withheld("mismatch");
return { outcome: "code", reason: "", iban: printedIban, reference: printedRef, code: built };
},
}); arrangements/finnish-virtual-barcode/lines.ts /**
* What the Finnish virtual barcode hands each of its arrangements: every line
* it may print, already decided. An arrangement places these and decides
* nothing, so both print the same lines under the same conditions.
*
* An empty string is a line this document does not carry. Test it in the JSX,
* `{lines.code && …}`, so the test is compiled into a condition the engine
* settles per document.
*
* Installed by `dxcl add finnish-virtual-barcode`, with the arrangements.
*/
export interface FinnishVirtualBarcodeLines {
/** The IBAN as printed (grouped in fours when valid), or "" for no line. */
iban: string;
/** The reference as printed (grouped when valid), or "" for no line. */
reference: string;
/** The 54 digits, unbroken, or "" when the code is withheld or nothing is owed. */
code: string;
} arrangements/finnish-virtual-barcode/stacked.arrangement.tsx import { Paragraph, type Yield } from "docxcelerate/template";
import type { FinnishVirtualBarcodeLines } from "./lines.ts";
/**
* Each labelled line under the last. The code sits on its own paragraph under
* its label: at 11pt its 54 digits need the whole text column, and a soft wrap
* in the middle would make a payer doubt they had copied all of it.
*/
export const stacked = (lines: FinnishVirtualBarcodeLines): Yield => (
<>
{lines.iban && <Paragraph id="virtual-barcode-iban">Saajan tilinumero (IBAN): {lines.iban}</Paragraph>}
{lines.reference && <Paragraph id="virtual-barcode-reference">Viitenumero: {lines.reference}</Paragraph>}
{lines.code && <Paragraph id="virtual-barcode-label">Virtuaaliviivakoodi</Paragraph>}
{lines.code && <Paragraph id="virtual-barcode-code">{lines.code}</Paragraph>}
</>
); arrangements/finnish-virtual-barcode/table.arrangement.tsx import { Cell, Paragraph, Row, Table, type Yield } from "docxcelerate/template";
import type { FinnishVirtualBarcodeLines } from "./lines.ts";
/**
* The IBAN and reference as label/value rows, so their values line up with
* other label/value blocks on the invoice. The code follows under the table.
*/
export const table = (lines: FinnishVirtualBarcodeLines): Yield => (
<>
{(lines.iban || lines.reference) && (
<Table id="virtual-barcode-details" columns={[{ width: 45 }, { width: "auto" }]}>
{lines.iban && (
<Row id="virtual-barcode-iban">
<Cell>Saajan tilinumero (IBAN)</Cell>
<Cell>{lines.iban}</Cell>
</Row>
)}
{lines.reference && (
<Row id="virtual-barcode-reference">
<Cell>Viitenumero</Cell>
<Cell>{lines.reference}</Cell>
</Row>
)}
</Table>
)}
{/* Not a row: beside a 45mm label the value cell is about 115mm less cell padding, too narrow for 54 digits. */}
{lines.code && <Paragraph id="virtual-barcode-label">Virtuaaliviivakoodi</Paragraph>}
{lines.code && <Paragraph id="virtual-barcode-code">{lines.code}</Paragraph>}
</>
);