Boleto typeable line (Brazil)
ClosingBuilds the linha digitável from the bank code, the due date, the amount and the bank's 25-digit free field, or checks the line the bank returned digit for digit. If that line disagrees with the invoice's due date or amount, the document fails, because the bank collects what its line says. The due-date factor handles the 2025 rollover: it reached 9999 on 2025-02-21 and restarted at 1000. The general check digit is modulus 11 over the barcode order and the field checks are modulus 10 over the line order. A line it cannot build is withheld with the reason: an invoice not in reais, a free field of the wrong length, a due date before 2000-07-03, or nothing to pay. It does not draw the ITF barcode. It is one deriver, so it publishes.
npx dxcl add boleto-linha-digitavel Datos de vista previa
el JSON con el que se construyó esta vista previa{
"boleto": {
"bankCode": "341",
"freeField": "1090000012345678901234561",
"line": "34191.09008 00012.345674 89012.345610 4 16610875043219"
},
"invoice": {
"total": 8750432.19,
"dueDate": "2026-12-15",
"currency": "BRL"
}
} Vista previa renderizada
cada disposición renderizada por su cuentaarrangement="stacked" predeterminada arrangement="table" Nodos resueltos
lo que recibe un renderizador — 1 nodosboleto section Los archivos
lo que escribe la instalación; el archivo seleccionado es el componentenodes/boleto-linha-digitavel.node.tsx import { arrange, Section, type Section as SectionComponent, useDeriver, useState } from "docxcelerate/template";
import type { BoletoLinhaDigitavelLines } from "../arrangements/boleto-linha-digitavel/lines.ts";
import { stacked } from "../arrangements/boleto-linha-digitavel/stacked.arrangement.tsx";
import { table } from "../arrangements/boleto-linha-digitavel/table.arrangement.tsx";
import boletoLinhaDigitavel from "../derivers/boleto-linha-digitavel.deriver.ts";
/**
* The typeable line of a Brazilian boleto, built from the invoice or checked
* against the one the bank returned.
*
* The due-date factor rolled over on 2025-02-22. It counts days from
* 1997-10-07 up to 9999 on 2025-02-21, then restarts at 1000, so it is never
* "days since 1997". The general check digit is modulus 11 over the barcode
* order. The three field check digits are modulus 10 over the line order.
* Those two orders are not the same, and mixing them up is the classic bug.
*
* If the bank's line disagrees with the invoice in any digit, the document
* fails. The bank collects what its line says, so printing a line for a
* different amount or date is worse than printing none. If a line cannot be
* built at all, it is withheld with a visible reason, never approximated. This
* happens for an invoice not in reais, a bank code or free field of the wrong
* length, a due date before the factor window, or nothing to pay.
*
* The drawn ITF barcode is not produced. A payer can pay by the typeable line
* alone. Labels are Portuguese because a boleto is paid through a Brazilian
* bank; thrown errors are English because they are for the developer.
*
* All of it is one deriver: dates and amounts from request data cannot be
* computed at publish time.
*
* Arrangement: where the lines sit is chosen with the `arrangement` prop. This
* file decides every line. Each arrangement in
* `arrangements/boleto-linha-digitavel/` only places the lines.
*
* Installed by `dxcl add boleto-linha-digitavel`, which also installs its deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface BoletoData {
boleto: {
/**
* The issuing bank's three-digit FEBRABAN code: "001" Banco do Brasil,
* "237" Bradesco, "341" Itaú. Trimmed, then it must be exactly three
* digits. Missing or anything else withholds the line.
*/
bankCode: string;
/**
* The bank-specific 25-digit free field (campo livre), as your bank's
* layout assembles it from the nosso número, agency, account and wallet.
* Trimmed, then it must be exactly 25 digits, with no dots, spaces or
* hyphens inside. Missing or any other length withholds the line. This
* component does not assemble it: every bank lays it out differently.
*/
freeField: string;
/**
* The linha digitável the bank returned when the boleto was registered.
* Spaces and dots are ignored, then it must be 47 digits, or the
* document fails. When given, it is checked against the line built from
* the invoice. Any difference fails the document, naming what differs.
* Missing or empty means the line is built from the invoice and not
* cross-checked. It is ignored (not checked) when the line is withheld.
*/
line?: string;
};
invoice: {
/**
* The amount to collect, in reais. Rounded half up to whole centavos as
* written (1.005 becomes R$ 1,01). Not a finite number, below one
* centavo after rounding, or over R$ 99.999.999,99 withholds the line.
*/
total: number;
/**
* The due date, as an ISO 8601 date: `2026-12-15`. Anything after the
* tenth character is ignored. Missing or empty means no due date: factor
* 0000, printed "Contra apresentação". A date before 2000-07-03 withholds
* the line. A value that is not a real YYYY-MM-DD date (`2026-02-30`,
* `15/12/2026`) fails the document.
*/
dueDate?: string;
/**
* Must be "BRL": a boleto is payable in reais only. Missing or anything
* else withholds the line; it is never defaulted.
*/
currency: "BRL";
};
}
/**
* Where the lines sit.
*
* - `stacked`: paragraphs down the column. The default.
* - `table`: due date and amount in a label/value table, the typeable line
* full width beneath it.
*/
export type BoletoLinhaDigitavelArrangement = "stacked" | "table";
/** Props for {@linkcode BoletoLinhaDigitavel}. */
export interface BoletoLinhaDigitavelProps {
/** Where the lines sit. Defaults to `"stacked"`. */
arrangement?: BoletoLinhaDigitavelArrangement;
}
export const BoletoLinhaDigitavel: SectionComponent<BoletoLinhaDigitavelProps> = async ({ arrangement }) => {
const [boleto] = useState((data: BoletoData) => data.boleto);
const [invoice] = useState((data: BoletoData) => data.invoice);
const result = await useDeriver(boletoLinhaDigitavel, [boleto, invoice]);
const lines: BoletoLinhaDigitavelLines = {
line: result.line,
dueDate: result.dueDate,
amount: result.amount,
withheld: result.withheld,
};
return (
<Section id="boleto" title="Boleto bancário">
{arrange(arrangement, {
stacked: () => stacked(lines),
table: () => table(lines),
})}
</Section>
);
}; derivers/boleto-linha-digitavel.deriver.ts // deno-lint-ignore-file no-explicit-any -- the inputs are request data nobody has checked.
import { deriver } from "docxcelerate/template";
/**
* The typeable line of a boleto, built from the invoice and, when the bank
* returned one, checked against it digit for digit. Installed by
* `dxcl add boleto-linha-digitavel`.
*
* Self-contained on purpose: it travels to the engine as source text, so a
* module-level helper or constant would be a ReferenceError there. Every
* helper is declared inside `run`.
*
* The first rule that applies decides: a malformed due date or bank line
* throws, a line that cannot be built is withheld with its reason, and
* otherwise the line is built and, if given, cross-checked.
*/
export default deriver({
name: "boletoLinhaDigitavel",
run: (boleto: unknown, invoice: unknown) => {
const b = boleto as any;
const inv = invoice as any;
// Weights run from the rightmost digit leftwards. Modulus 11 is the
// general check digit, over the barcode order; 0, 10 and 11 become 1.
const mod11 = (digits: string): number => {
let sum = 0;
for (let i = 0; i < digits.length; i++) {
sum += Number(digits[digits.length - 1 - i]) * (2 + (i % 8));
}
const dv = 11 - (sum % 11);
return dv > 9 ? 1 : dv;
};
// Modulus 10 is the field check digit, over the line order.
const mod10 = (digits: string): number => {
let sum = 0;
for (let i = 0; i < digits.length; i++) {
const product = Number(digits[digits.length - 1 - i]) * (i % 2 === 0 ? 2 : 1);
sum += product > 9 ? product - 9 : product;
}
return (10 - (sum % 10)) % 10;
};
const money = (cents: number): string =>
new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(cents / 100);
const brDate = (iso: string): string => iso.slice(8, 10) + "/" + iso.slice(5, 7) + "/" + iso.slice(0, 4);
const epoch = Date.UTC(1997, 9, 7);
const dayMs = 86400000;
const withheldOutput = (reason: string) => ({
line: null,
barcode: null,
dueDate: null,
amount: null,
withheld: "Linha digitável indisponível: " + reason + ". Solicite o boleto ao beneficiário.",
});
// 1. The due date, when there is one, must be a real date.
const rawDue = inv?.dueDate;
const hasDue = rawDue !== undefined && rawDue !== null && rawDue !== "";
let dueIso = "";
let days = 0;
if (hasDue) {
dueIso = String(rawDue).slice(0, 10);
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dueIso);
const t = m ? Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) : NaN;
if (!m || new Date(t).toISOString().slice(0, 10) !== dueIso) {
throw new Error("invoice.dueDate must be an ISO 8601 date");
}
days = Math.round((t - epoch) / dayMs);
}
// 2. The bank's line, when given, must be 47 digits.
const given = b?.line === undefined || b?.line === null ? "" : String(b.line);
let L = "";
if (given !== "") {
L = given.replace(/[ .]/g, "");
if (!/^\d{47}$/.test(L)) throw new Error("boleto.line must be 47 digits");
}
// 3. Withhold, first reason wins.
const bank = typeof b?.bankCode === "string" ? b.bankCode.trim() : "";
const free = typeof b?.freeField === "string" ? b.freeField.trim() : "";
const total = inv?.total;
if (inv?.currency !== "BRL") return withheldOutput("a fatura não está em reais (BRL)");
if (!/^\d{3}$/.test(bank)) return withheldOutput("o código do banco não tem 3 dígitos");
if (!/^\d{25}$/.test(free)) return withheldOutput("o campo livre não tem 25 dígitos");
if (hasDue && days < 1000) {
return withheldOutput(
"o vencimento é anterior a 03/07/2000, a primeira data que o fator de vencimento representa",
);
}
if (typeof total !== "number" || !Number.isFinite(total)) {
return withheldOutput("o total da fatura não é um valor");
}
// Scaling through the string avoids 1.005 * 100 = 100.49999999999999.
const cents = Math.round(Number(String(total) + "e2"));
if (!(cents >= 1)) return withheldOutput("não há valor a pagar");
if (cents > 9999999999) {
return withheldOutput("o valor passa de R$ 99.999.999,99, o máximo que a linha comporta");
}
// 4. Build. The factor restarts at 1000 every 9000 days, from 2025-02-22.
const factor = hasDue ? String(((days - 1000) % 9000) + 1000).padStart(4, "0") : "0000";
const amountField = String(cents).padStart(10, "0");
const dv = mod11(bank + "9" + factor + amountField + free);
const barcode = bank + "9" + dv + factor + amountField + free;
const f1 = bank + "9" + free.slice(0, 5);
const f2 = free.slice(5, 15);
const f3 = free.slice(15, 25);
const digits = f1 + mod10(f1) + f2 + mod10(f2) + f3 + mod10(f3) + dv + factor + amountField;
// 5. Cross-check the bank's line. It collects what its line says.
if (L !== "") {
for (const [n, from, to] of [[1, 0, 9], [2, 10, 20], [3, 21, 31]] as const) {
if (mod10(L.slice(from, to)) !== Number(L[to])) {
throw new Error("boleto.line fails the check digit of field " + n + "; it is mistyped or corrupt");
}
}
const lineFree = L.slice(4, 9) + L.slice(10, 20) + L.slice(21, 31);
const lineBarcode = L.slice(0, 4) + L[32] + L.slice(33) + lineFree;
if (mod11(lineBarcode.slice(0, 4) + lineBarcode.slice(5)) !== Number(L[32])) {
throw new Error("boleto.line fails its general check digit");
}
if (L.slice(0, 3) !== bank) {
throw new Error("boleto.line is for bank " + L.slice(0, 3) + "; the invoice is for bank " + bank);
}
if (L[3] !== "9") throw new Error("boleto.line is not in reais (currency code " + L[3] + ")");
if (lineFree !== free) throw new Error("boleto.line belongs to a different boleto (free field differs)");
const lineFactor = L.slice(33, 37);
if (lineFactor !== factor) {
const describe = (f: string, target: number | null): string => {
if (f === "0000") return "has no due date";
const k = target === null ? 1 : Math.max(0, Math.round((target - Number(f)) / 9000));
return "is due " + brDate(new Date(epoch + (Number(f) + 9000 * k) * dayMs).toISOString().slice(0, 10));
};
throw new Error(
"boleto.line " + describe(lineFactor, hasDue ? days : null) + "; the invoice " +
describe(factor, hasDue ? days : null),
);
}
const lineAmount = L.slice(37);
if (lineAmount !== amountField) {
const describe = (a: string): string =>
Number(a) === 0 ? "no amount (a variable-amount boleto)" : money(Number(a));
throw new Error("boleto.line is for " + describe(lineAmount) + "; the invoice is for " + describe(amountField));
}
if (L !== digits) throw new Error("boleto.line does not match the invoice");
}
return {
line: digits.slice(0, 5) + "." + digits.slice(5, 10) + " " + digits.slice(10, 15) + "." +
digits.slice(15, 21) + " " + digits.slice(21, 26) + "." + digits.slice(26, 32) + " " + digits[32] + " " +
digits.slice(33),
barcode,
dueDate: hasDue ? brDate(dueIso) : "Contra apresentação",
amount: money(cents),
withheld: null,
};
},
}); arrangements/boleto-linha-digitavel/lines.ts /**
* What the boleto component 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.
*
* A field that is `null` is a line this document does not carry. Test it in
* the JSX, `{lines.line && …}`, so the test is compiled into a condition the
* engine settles per document.
*
* Installed by `dxcl add boleto-linha-digitavel`, with the arrangements.
*/
export interface BoletoLinhaDigitavelLines {
/** The grouped 54-character line, or null when withheld. */
line: string | null;
/** "15/12/2026", or "Contra apresentação"; null when withheld. */
dueDate: string | null;
/** "R$ 8.750.432,19"; null when withheld. */
amount: string | null;
/** The whole "unavailable" sentence, or null when a line is printed. */
withheld: string | null;
} arrangements/boleto-linha-digitavel/stacked.arrangement.tsx import { Paragraph, type Yield } from "docxcelerate/template";
import type { BoletoLinhaDigitavelLines } from "./lines.ts";
/**
* Paragraphs down the column, the typeable line on its own beneath the
* labelled due date and amount. The default: it reads in any width.
*/
export const stacked = (lines: BoletoLinhaDigitavelLines): Yield => (
<>
{lines.withheld && <Paragraph id="boleto-withheld">{lines.withheld}</Paragraph>}
{lines.dueDate && <Paragraph id="boleto-due-date">Vencimento: {lines.dueDate}</Paragraph>}
{lines.amount && <Paragraph id="boleto-amount">Valor do documento: {lines.amount}</Paragraph>}
{lines.line && <Paragraph id="boleto-line-label">Linha digitável</Paragraph>}
{lines.line && <Paragraph id="boleto-line">{lines.line}</Paragraph>}
</>
); arrangements/boleto-linha-digitavel/table.arrangement.tsx import { Cell, Paragraph, Row, Table, type Yield } from "docxcelerate/template";
import type { BoletoLinhaDigitavelLines } from "./lines.ts";
/**
* Due date and amount in a label/value table. The typeable line stays out of
* it: its 54 characters do not fit beside a label column at 11pt without
* wrapping, and a wrapped line is the one a payer mistypes.
*/
export const table = (lines: BoletoLinhaDigitavelLines): Yield => (
<>
{lines.withheld && <Paragraph id="boleto-withheld">{lines.withheld}</Paragraph>}
{/* 40mm holds "Valor do documento" at 11pt. */}
{lines.line && (
<Table id="boleto-details" columns={[{ width: 40 }, { width: "auto" }]}>
{lines.dueDate && (
<Row id="boleto-due-date">
<Cell>Vencimento</Cell>
<Cell>{lines.dueDate}</Cell>
</Row>
)}
{lines.amount && (
<Row id="boleto-amount">
<Cell>Valor do documento</Cell>
<Cell>{lines.amount}</Cell>
</Row>
)}
</Table>
)}
{lines.line && <Paragraph id="boleto-line-label">Linha digitável</Paragraph>}
{lines.line && <Paragraph id="boleto-line">{lines.line}</Paragraph>}
</>
);