Canadian sales tax
BodyTax follows the province of supply, where goods are delivered or the customer is, never the seller's province. HST provinces get one line. BC and SK get GST plus PST, MB GST plus RST, Quebec GST plus QST, and Alberta and the territories GST alone. Each tax is worked on its own base and rounded once, so PST and QST exemptions are honoured. QST is never charged on GST. Rates are effective-dated rows picked by the tax point date, because they change mid-year. The GST/HST number must pass its check digit to be printed, and a seller that is not registered charges none and says so. CRA's $100 and $500 information tiers are applied to the tax-included total, and anything missing is printed as a warning. All of it is one deriver.
npx dxcl add canadian-sales-tax salesTax.supplyProvince Данные предпросмотра
JSON, на котором построен этот предпросмотр{
"salesTax": {
"supplyProvince": "AB",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "BC",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "MB",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "NB",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "NL",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "NS",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "NT",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "NU",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "ON",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "PE",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "QC",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "SK",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} {
"salesTax": {
"supplyProvince": "YT",
"taxPointDate": "2026-11-30",
"paymentTerms": "Net 45 days from invoice date; 2% per month on overdue balances",
"lines": [
{
"description": "Annual preventive maintenance contract for HVAC and building automation systems, Tour Centre-Ville, 1250 boulevard René-Lévesque Ouest, floors 1 to 42",
"amount": 1284750,
"gstCategory": "taxable",
"provincialCategory": "taxable"
},
{
"description": "Printed operating manuals and technical reference books, bilingual edition, 12 volumes",
"amount": 1840,
"gstCategory": "taxable",
"provincialCategory": "exempt"
},
{
"description": "Long-term residential accommodation for relocated caretaker, 1 to 30 November 2026",
"amount": 2450,
"gstCategory": "exempt",
"provincialCategory": "exempt"
},
{
"description": "Emergency out-of-hours call-out, chilled water pump failure, 14 and 15 November",
"amount": 18425.5,
"gstCategory": "taxable",
"provincialCategory": "taxable"
}
]
},
"seller": {
"name": "Groupe Maintenance Technique Saint-Laurent-Outaouais Inc.",
"gstRegistered": true,
"bn": "843219767RT0001",
"provincialRegistered": true,
"qst": "1219876543TQ0001"
},
"customer": {
"name": "Fiducie de placement immobilier Centre-Ville Montréal-Laval S.E.C."
}
} Отрисованный предпросмотр
каждая компоновка, отрисованная сама по себеarrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" Разрешённые узлы
что получает рендерер — узлов: 1canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section canadian-sales-tax section Файлы
что записывает установка; выбранный файл и есть компонентnodes/canadian-sales-tax.node.tsx import { arrange, Section, type Section as SectionComponent, useDeriver, useState } from "docxcelerate/template";
import type { CanadianSalesTaxLines } from "../arrangements/canadian-sales-tax/lines.ts";
import { stacked } from "../arrangements/canadian-sales-tax/stacked.arrangement.tsx";
import { table } from "../arrangements/canadian-sales-tax/table.arrangement.tsx";
import canadianSalesTax from "../derivers/canadian-sales-tax.deriver.ts";
/**
* The sales-tax block of a Canadian invoice: subtotal, each tax on its own
* base, the tax-included total, the registration numbers, and what is missing
* for the customer to claim it.
*
* Decisions already made for you:
* - Tax follows the province of supply — where goods are delivered, where the
* customer is for services — never the seller's province. There is no
* seller-province field to get wrong.
* - HST provinces get one line. BC and SK get GST plus PST, MB GST plus RST,
* QC GST plus QST. Alberta and the territories get GST alone. Never a
* combined 13% or 14.975% on one base.
* - Each tax has its own base, because PST and QST exempt different things
* than GST. QST is charged on the price before GST, as it has been since
* 2013, never tax on tax. Each tax is rounded once on its base, half away
* from zero, not line by line.
* - Rates are effective-dated rows picked by the tax point date, because they
* change mid-year: NS HST went from 15% to 14% on 1 April 2025.
* - A seller not registered for GST/HST charges none, and the block says so.
* - CRA's invoice tiers are applied to the tax-included total (under $100,
* $100 to $499.99, $500 or more; not the old $30 and $150). Whatever the
* tier needs and the data lacks is printed as a warning.
* - A GST/HST number is printed only if it passes the check digit. A wrong
* number is worse than none.
*
* Everything is decided in one deriver, because totals, rounding and date
* comparisons on request data cannot be done at publish time. The node prints
* what it returns.
*
* Installed by `dxcl add canadian-sales-tax`, which also installs its deriver.
*/
/** The thirteen provinces and territories, as Canada Post codes. */
export type CanadianProvince =
| "AB" | "BC" | "MB" | "NB" | "NL" | "NS" | "NT" | "NU" | "ON" | "PE" | "QC" | "SK" | "YT";
/**
* One effective-dated rate. Rows are picked by `salesTax.taxPointDate`;
* exactly one row must cover the date for every tax the province charges.
*/
export interface CanadianTaxRate {
/** Which tax. `GST` is federal; HST is the harmonized rate in one line. */
tax: "GST" | "HST" | "PST" | "RST" | "QST";
/** The province the rate belongs to. Required for HST, PST, RST and QST; ignored for GST. */
province?: CanadianProvince;
/**
* The rate as a percentage: `5`, `9.975`. At most three decimal places;
* more, a negative value, or a value that is not a finite number throws.
*/
rate: number;
/** First day the rate applies, ISO 8601 (`2025-04-01`). Inclusive. */
from: string;
/** Last day it applies, ISO 8601, inclusive. Missing means still in force. */
to?: string;
}
/** What this component reads. Add these fields to your document data type. */
export interface CanadianSalesTaxData {
salesTax: {
/**
* The province of supply: where goods are delivered, or where the
* customer is for services. Not the seller's province. Required; anything
* outside `CanadianProvince` throws.
*/
supplyProvince: CanadianProvince;
/**
* The day tax became payable, ISO 8601: the earlier of the day the
* consideration was paid and the day it fell due — usually the invoice
* date. Picks the rate rows. Anything after the tenth character is
* ignored. Required: missing, not YYYY-MM-DD, or before 2013-04-01 (when
* the current federal/provincial structure began) throws.
*/
taxPointDate: string;
/**
* Every line of the invoice, at its price before any tax, after line
* discounts. Required (an empty array is allowed and prints zeros);
* missing or not an array throws.
*/
lines: Array<{
/**
* What was supplied. Not printed here; read for the $500 tier check and
* named in the "No GST on" note. Missing prints as "line N" in that
* note, and on a $500+ invoice adds a warning.
*/
description?: string;
/**
* The pre-tax amount in Canadian dollars, to the cent. Negative is a
* discount or credit line. Not a finite number throws.
*/
amount: number;
/**
* GST/HST status. Missing means `taxable` — the Excise Tax Act's default.
* Any other string throws.
*/
gstCategory?: "taxable" | "zero-rated" | "exempt";
/**
* PST/RST/QST status, read only in BC, SK, MB and QC. Missing follows
* the GST status: `taxable` if `gstCategory` is taxable, otherwise
* `exempt`. Any other string throws.
*/
provincialCategory?: "taxable" | "exempt";
}>;
/**
* Rate rows. Missing or empty uses the table built into the deriver. When
* given, they replace that table entirely; they are not merged with it.
*/
rates?: CanadianTaxRate[];
/** Payment terms. Not printed; its absence warns on a $500+ invoice. */
paymentTerms?: string;
};
seller: {
/** The seller's name. Not printed here (the letterhead does); missing warns at every tier. */
name?: string;
/**
* Whether the seller is a GST/HST registrant. Missing means not registered
* (a small supplier): no GST/HST line, and the small-supplier note prints.
* Charging GST/HST without being registered is the worse error.
*/
gstRegistered?: boolean;
/**
* The GST/HST number: 9-digit BN, `RT`, 4-digit account, as in
* `843219767RT0001`. Spaces and hyphens are removed and letters upper-cased
* before checking; printed in that normalised form. Read only when
* `gstRegistered` is true. Missing: from $100 a warning prints. Present but
* invalid: a warning prints at every tier and the number is not printed.
*/
bn?: string;
/**
* Whether the seller is registered for the supply province's PST (BC, SK),
* RST (MB) or QST (QC). False means no provincial line. Missing means the
* same, plus a warning that it was not stated. Ignored elsewhere.
*/
provincialRegistered?: boolean;
/**
* The QST number: 10 digits, `TQ`, 4 digits (`1219876543TQ0001`).
* Normalised like `bn`. Read only when QST is charged. Missing: from $100 a
* warning prints. Present but invalid: a warning at every tier, not printed.
*/
qst?: string;
};
/** The customer. The whole object may be missing. */
customer?: {
/** The customer's name. Not printed here; its absence warns on a $500+ invoice. */
name?: string;
};
}
/**
* Where the lines sit.
*
* - `table`: labels on the left, amounts right-aligned beside them. The default.
* - `stacked`: one labelled line under another, for a narrow column or a letter.
*/
export type CanadianSalesTaxArrangement = "table" | "stacked";
/** Props for {@linkcode CanadianSalesTax}. */
export interface CanadianSalesTaxProps {
/** Where the lines sit. Defaults to `"table"`. */
arrangement?: CanadianSalesTaxArrangement;
}
export const CanadianSalesTax: SectionComponent<CanadianSalesTaxProps> = async ({ arrangement }) => {
const [salesTax] = useState((data: CanadianSalesTaxData) => data.salesTax);
const [seller] = useState((data: CanadianSalesTaxData) => data.seller);
const [customer] = useState((data: CanadianSalesTaxData) => data.customer);
const result = await useDeriver(canadianSalesTax, [salesTax, seller, customer]);
const lines: CanadianSalesTaxLines = {
subtotal: result.subtotal,
federalLabel: result.federalLabel,
federalAmount: result.federalAmount,
provincialLabel: result.provincialLabel,
provincialAmount: result.provincialAmount,
total: result.total,
bn: result.bn,
qst: result.qst,
smallSupplierNote: result.smallSupplierNote,
statusNote: result.statusNote,
warning: result.warning,
};
return (
<Section id="canadian-sales-tax" title="Sales tax">
{arrange(arrangement, {
table: () => table(lines),
stacked: () => stacked(lines),
})}
</Section>
);
}; derivers/canadian-sales-tax.deriver.ts import { deriver } from "docxcelerate/template";
/**
* Decides the whole sales-tax block of a Canadian invoice: which taxes the
* province of supply charges, the rate in force on the tax point date, each
* tax on its own base, the registration numbers worth printing, and what is
* missing for the customer to claim input tax credits. Installed by
* `dxcl add canadian-sales-tax`.
*
* 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. The
* province map, the rate table and every helper are declared inside `run`.
*/
export default deriver({
name: "canadianSalesTax",
run: (salesTax: unknown, seller: unknown, customer: unknown) => {
// deno-lint-ignore no-explicit-any
const st = salesTax as any;
// deno-lint-ignore no-explicit-any
const sel = seller as any;
// deno-lint-ignore no-explicit-any
const cus = customer as any;
// Which taxes each province of supply charges: [federal, provincial].
const structure: Record<string, [string, string | null]> = {
ON: ["HST", null], NS: ["HST", null], NB: ["HST", null], NL: ["HST", null], PE: ["HST", null],
BC: ["GST", "PST"], SK: ["GST", "PST"], MB: ["GST", "RST"], QC: ["GST", "QST"],
AB: ["GST", null], NT: ["GST", null], NU: ["GST", null], YT: ["GST", null],
};
const province = st?.supplyProvince;
if (typeof province !== "string" || !Object.hasOwn(structure, province)) {
throw new Error("salesTax.supplyProvince must be one of " + Object.keys(structure).join(", "));
}
if (typeof st.taxPointDate !== "string" || !/^\d{4}-\d{2}-\d{2}/.test(st.taxPointDate)) {
throw new Error("salesTax.taxPointDate must be an ISO 8601 date");
}
const date: string = st.taxPointDate.slice(0, 10);
if (date < "2013-04-01") {
throw new Error("salesTax.taxPointDate must be on or after 2013-04-01");
}
if (!Array.isArray(st.lines)) throw new Error("salesTax.lines must be an array");
// These are the numbers an owner edits. Older rows (NB/NL 13%, PE 14%,
// SK 5%, MB 8%) are left out on purpose: a date they would cover throws
// rather than quietly taxing at today's rate.
const builtIn = [
{ tax: "GST", rate: 5, from: "2008-01-01" },
{ tax: "HST", province: "ON", rate: 13, from: "2010-07-01" },
{ tax: "HST", province: "NS", rate: 15, from: "2010-07-01", to: "2025-03-31" },
{ tax: "HST", province: "NS", rate: 14, from: "2025-04-01" },
{ tax: "HST", province: "NB", rate: 15, from: "2016-07-01" },
{ tax: "HST", province: "NL", rate: 15, from: "2016-07-01" },
{ tax: "HST", province: "PE", rate: 15, from: "2016-10-01" },
{ tax: "PST", province: "BC", rate: 7, from: "2013-04-01" },
{ tax: "PST", province: "SK", rate: 6, from: "2017-03-23" },
{ tax: "RST", province: "MB", rate: 7, from: "2019-07-01" },
{ tax: "QST", province: "QC", rate: 9.975, from: "2013-01-01" },
];
const rates: Array<{ tax: string; province?: string; rate: number; from: string; to?: string }> =
Array.isArray(st.rates) && st.rates.length > 0 ? st.rates : builtIn;
for (const row of rates) {
if (
typeof row?.rate !== "number" || !Number.isFinite(row.rate) || row.rate < 0 ||
Math.abs(row.rate * 1000 - Math.round(row.rate * 1000)) > 1e-6
) {
throw new Error(
"salesTax.rates: " + row?.tax + " " + (row?.province ?? "") + " rate " + row?.rate + " from " + row?.from +
" must be a non-negative number with at most three decimal places",
);
}
}
const pickRate = (tax: string): number => {
const hits = rates.filter((r) =>
r.tax === tax && (tax === "GST" || r.province === province) &&
r.from <= date && (r.to === undefined || date <= r.to)
);
const where = tax === "GST" ? "" : " for " + province;
if (hits.length === 0) {
throw new Error("No " + tax + " rate" + where + " on " + date + "; add a row to salesTax.rates");
}
if (hits.length > 1) {
throw new Error("Overlapping " + tax + " rows" + where + " on " + date + "; fix salesTax.rates");
}
return hits[0].rate;
};
const [federalName, provincialName] = structure[province];
const federalOn = sel?.gstRegistered === true;
const provincialOn = provincialName !== null && sel?.provincialRegistered === true;
const federalRate = federalOn ? pickRate(federalName) : 0;
const provincialRate = provincialOn ? pickRate(provincialName as string) : 0;
const gstStatuses = ["taxable", "zero-rated", "exempt"];
const provStatuses = ["taxable", "exempt"];
let subtotal = 0;
let federalBase = 0;
let provincialBase = 0;
const notFederal: string[] = [];
const notProvincial: string[] = [];
let taxableFederal = 0;
let taxableProvincial = 0;
let undescribed = false;
st.lines.forEach((line: { description?: unknown; amount?: unknown; gstCategory?: unknown; provincialCategory?: unknown }, i: number) => {
const at = "salesTax.lines[" + i + "]";
if (typeof line?.amount !== "number" || !Number.isFinite(line.amount)) {
throw new Error(at + ".amount must be a finite number");
}
const gst = line.gstCategory ?? "taxable";
if (!gstStatuses.includes(gst as string)) {
throw new Error(at + ".gstCategory must be one of " + gstStatuses.join(", "));
}
if (line.provincialCategory !== undefined && !provStatuses.includes(line.provincialCategory as string)) {
throw new Error(at + ".provincialCategory must be one of " + provStatuses.join(", "));
}
const prov = line.provincialCategory ?? (gst === "taxable" ? "taxable" : "exempt");
const cents = Math.round(line.amount * 100);
const blank = typeof line.description !== "string" || line.description.trim() === "";
const name = blank ? "line " + (i + 1) : (line.description as string).trim();
if (blank) undescribed = true;
subtotal += cents;
if (gst === "taxable") {
federalBase += cents;
taxableFederal++;
} else notFederal.push(name);
if (prov === "taxable") {
provincialBase += cents;
taxableProvincial++;
} else notProvincial.push(name);
});
// Half away from zero in integers, so a 9.975% half cent cannot float down.
const taxOn = (base: number, rate: number) =>
Math.sign(base) * Math.floor((Math.abs(base) * Math.round(rate * 1000) + 50000) / 100000);
const federalTax = federalOn ? taxOn(federalBase, federalRate) : 0;
const provincialTax = provincialOn ? taxOn(provincialBase, provincialRate) : 0;
const total = subtotal + federalTax + provincialTax;
const currency = new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" });
// + 0 turns a negative zero into zero, which would print as "-$0.00".
const money = (cents: number) => currency.format(cents / 100 + 0);
const normalise = (value: unknown) => typeof value === "string" ? value.replace(/[\s-]/g, "").toUpperCase() : "";
const blank = (value: unknown) => typeof value !== "string" || value.trim() === "";
const bnRaw = normalise(sel?.bn);
const bnMatch = /^(\d{9})RT(\d{4})$/.exec(bnRaw);
let luhn = 0;
if (bnMatch) {
[...bnMatch[1]].forEach((ch, i) => {
let d = Number(ch);
if (i % 2 === 1) {
d *= 2;
if (d > 9) d -= 9;
}
luhn += d;
});
}
const bnValid = bnMatch !== null && bnMatch[2] !== "0000" && luhn % 10 === 0;
const qstRaw = normalise(sel?.qst);
const qstOn = provincialOn && provincialName === "QST";
const qstValid = /^\d{10}TQ(\d{4})$/.test(qstRaw) && !qstRaw.endsWith("0000");
const notes: string[] = [];
for (
const [charged, taxName, names, taxable] of [
[federalOn, federalName, notFederal, taxableFederal],
[provincialOn, provincialName, notProvincial, taxableProvincial],
] as const
) {
if (charged && taxable > 0 && names.length > 0) notes.push("No " + taxName + " on: " + names.join("; ") + ".");
}
const abs = Math.abs(total);
const tier = abs < 10000 ? 0 : abs < 50000 ? 1 : 2;
const warnings: string[] = [];
if (federalOn && !blank(sel.bn) && !bnValid) {
warnings.push(
sel.bn.trim() +
" is not a valid GST/HST registration number: it must be a nine-digit business number that passes its check digit, then RT and a four-digit account.",
);
}
if (qstOn && !blank(sel.qst) && !qstValid) {
warnings.push(
sel.qst.trim() + " is not a valid QST registration number: it must be ten digits, then TQ and four digits.",
);
}
if (provincialName !== null && sel?.provincialRegistered === undefined) {
warnings.push(
"It is not stated whether the seller is registered for " + provincialName + ", so none has been charged.",
);
}
const missing: string[] = [];
if (blank(sel?.name)) missing.push("seller name");
if (tier >= 1 && federalOn && blank(sel.bn)) missing.push("GST/HST registration number");
if (tier >= 1 && qstOn && blank(sel.qst)) missing.push("QST registration number");
if (tier >= 2) {
if (blank(cus?.name)) missing.push("customer name");
if (blank(st.paymentTerms)) missing.push("payment terms");
if (undescribed) missing.push("a description for every line");
}
if (missing.length > 0) {
warnings.push(
"Missing for an invoice of " + ["under $100", "$100 or more", "$500 or more"][tier] + ": " +
missing.join(", ") + ". Until it is added the customer cannot claim input tax credits on this invoice.",
);
}
return {
subtotal: money(subtotal),
federalLabel: federalOn ? federalName + " " + federalRate + "% on " + money(federalBase) : null,
federalAmount: federalOn ? money(federalTax) : null,
provincialLabel: provincialOn ? provincialName + " " + provincialRate + "% on " + money(provincialBase) : null,
provincialAmount: provincialOn ? money(provincialTax) : null,
total: money(total),
bn: federalOn && bnValid ? bnRaw : null,
qst: qstOn && qstValid ? qstRaw : null,
smallSupplierNote: federalOn
? null
: "Not registered for GST/HST (small supplier), so no " + federalName + " is charged.",
statusNote: notes.length > 0 ? notes.join(" ") : null,
warning: warnings.length > 0 ? warnings.join(" ") : null,
};
},
}); arrangements/canadian-sales-tax/lines.ts /**
* What the sales-tax block 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 invoice does not carry. Test it in the
* JSX, `{lines.federalLabel && …}`, so the test is compiled into a condition
* the engine settles per document.
*
* Installed by `dxcl add canadian-sales-tax`, with the arrangements.
*/
export interface CanadianSalesTaxLines {
/** Sum of all line amounts, formatted: "$1,307,465.50". */
subtotal: string;
/** "GST 5% on $1,305,015.50" or "HST 14% on …"; null when the seller is not GST/HST-registered. */
federalLabel: string | null;
/** That tax, formatted: "$65,250.78". Null with the label. */
federalAmount: string | null;
/** "QST 9.975% on $1,303,175.50", "PST 7% on …", "RST 7% on …"; null when none is charged. */
provincialLabel: string | null;
/** That tax, formatted. Null with the label. */
provincialAmount: string | null;
/** Subtotal plus every charged tax, formatted. */
total: string;
/** Normalised valid GST/HST number, or null. */
bn: string | null;
/** Normalised valid QST number, or null. */
qst: string | null;
/** The small-supplier sentence, or null. */
smallSupplierNote: string | null;
/** "No GST on: …" sentences for mixed-status invoices, or null. */
statusNote: string | null;
/** Every warning sentence joined by a space, or null. */
warning: string | null;
} arrangements/canadian-sales-tax/table.arrangement.tsx import { Cell, Paragraph, Row, Table, type Yield } from "docxcelerate/template";
import type { CanadianSalesTaxLines } from "./lines.ts";
/**
* Labels on the left, amounts right-aligned beside them. The default: this is
* a totals block that sits under line items, and the amounts have to line up.
*/
export const table = (lines: CanadianSalesTaxLines): Yield => (
<>
<Table id="canadian-sales-tax-summary" columns={[{}, { align: "right" }]}>
<Row id="canadian-sales-tax-subtotal">
<Cell>Subtotal</Cell>
<Cell>{lines.subtotal}</Cell>
</Row>
{lines.federalLabel && (
<Row id="canadian-sales-tax-federal">
<Cell>{lines.federalLabel}</Cell>
<Cell>{lines.federalAmount}</Cell>
</Row>
)}
{lines.provincialLabel && (
<Row id="canadian-sales-tax-provincial">
<Cell>{lines.provincialLabel}</Cell>
<Cell>{lines.provincialAmount}</Cell>
</Row>
)}
<Row id="canadian-sales-tax-total">
<Cell>Total including tax</Cell>
<Cell>{lines.total}</Cell>
</Row>
{lines.bn && (
<Row id="canadian-sales-tax-bn">
<Cell>GST/HST registration number</Cell>
<Cell>{lines.bn}</Cell>
</Row>
)}
{lines.qst && (
<Row id="canadian-sales-tax-qst">
<Cell>QST registration number</Cell>
<Cell>{lines.qst}</Cell>
</Row>
)}
</Table>
{lines.smallSupplierNote && <Paragraph id="canadian-sales-tax-small-supplier">{lines.smallSupplierNote}</Paragraph>}
{lines.statusNote && <Paragraph id="canadian-sales-tax-status">{lines.statusNote}</Paragraph>}
{lines.warning && <Paragraph id="canadian-sales-tax-warning">{lines.warning}</Paragraph>}
</>
); arrangements/canadian-sales-tax/stacked.arrangement.tsx import { Paragraph, type Yield } from "docxcelerate/template";
import type { CanadianSalesTaxLines } from "./lines.ts";
/**
* One labelled line under another, for a narrow column or a plain letter:
* nothing has to line up with anything.
*/
export const stacked = (lines: CanadianSalesTaxLines): Yield => (
<>
<Paragraph id="canadian-sales-tax-subtotal">Subtotal: {lines.subtotal}</Paragraph>
{lines.federalLabel && (
<Paragraph id="canadian-sales-tax-federal">{lines.federalLabel}: {lines.federalAmount}</Paragraph>
)}
{lines.provincialLabel && (
<Paragraph id="canadian-sales-tax-provincial">{lines.provincialLabel}: {lines.provincialAmount}</Paragraph>
)}
<Paragraph id="canadian-sales-tax-total">Total including tax: {lines.total}</Paragraph>
{lines.bn && <Paragraph id="canadian-sales-tax-bn">GST/HST registration number: {lines.bn}</Paragraph>}
{lines.qst && <Paragraph id="canadian-sales-tax-qst">QST registration number: {lines.qst}</Paragraph>}
{lines.smallSupplierNote && <Paragraph id="canadian-sales-tax-small-supplier">{lines.smallSupplierNote}</Paragraph>}
{lines.statusNote && <Paragraph id="canadian-sales-tax-status">{lines.statusNote}</Paragraph>}
{lines.warning && <Paragraph id="canadian-sales-tax-warning">{lines.warning}</Paragraph>}
</>
);