Payment method surcharge
BodyCharges a payment-method surcharge only where it is lawful, and says why when it is not. No UK consumer is surcharged for any method; no consumer card (credit, debit or prepaid) is surcharged in the UK or EU, and no SEPA transfer in the EU; in the US only credit cards are, never debit or prepaid, and never in a state that bans it. What is allowed is capped at the cost of acceptance, and in the US at the network's and the state's cap too. Every percentage is applied to the net total, the smallest base a cap could mean, so it holds whichever one a rule intends. In the UK and EU the surcharge is taxed as part of the main supply, spread across the invoice's VAT rates so a zero-rated share carries no VAT, never as a flat 20% line or as exempt. The disclosure prints with the rate actually charged. All of it is one deriver.
npx dxcl add payment-surcharge-line surcharge.jurisdiction Данные предпросмотра
JSON, на котором построен этот предпросмотр{
"surcharge": {
"jurisdiction": "GB",
"customer": "business",
"method": {
"kind": "commercial-card",
"network": "mastercard"
},
"percent": 2.5,
"costOfAcceptance": 1.95,
"currency": "GBP",
"bands": [
{
"ratePercent": 20,
"net": 1184250,
"vat": 236850
},
{
"ratePercent": 5,
"net": 96400,
"vat": 4820
},
{
"ratePercent": 0,
"net": 48975.5,
"vat": 0
}
]
}
} {
"surcharge": {
"jurisdiction": "EU",
"customer": "business",
"method": {
"kind": "commercial-card",
"network": "mastercard"
},
"percent": 2.5,
"costOfAcceptance": 1.95,
"currency": "GBP",
"bands": [
{
"ratePercent": 20,
"net": 1184250,
"vat": 236850
},
{
"ratePercent": 5,
"net": 96400,
"vat": 4820
},
{
"ratePercent": 0,
"net": 48975.5,
"vat": 0
}
]
}
} {
"surcharge": {
"jurisdiction": "US",
"customer": "business",
"method": {
"kind": "commercial-card",
"network": "mastercard"
},
"percent": 2.5,
"costOfAcceptance": 1.95,
"currency": "GBP",
"bands": [
{
"ratePercent": 20,
"net": 1184250,
"vat": 236850
},
{
"ratePercent": 5,
"net": 96400,
"vat": 4820
},
{
"ratePercent": 0,
"net": 48975.5,
"vat": 0
}
]
}
} Отрисованный предпросмотр
каждая компоновка, отрисованная сама по себеarrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" arrangement="table" по умолчанию arrangement="stacked" Разрешённые узлы
что получает рендерер — узлов: 3surcharge-table table surcharge-tax-note paragraph · static The surcharge is split across the invoice's VAT rates in proportion to their net: £23,092.87 at 20%, £1,879.80 at 5%, £955.02 at 0%. surcharge-disclosure paragraph · static A surcharge of 1.95% has been added for payment by commercial card. It is no more than the cost to us of accepting that payment method. surcharge-table table surcharge-tax-note paragraph · static The surcharge is split across the invoice's VAT rates in proportion to their net: £23,092.87 at 20%, £1,879.80 at 5%, £955.02 at 0%. surcharge-disclosure paragraph · static A surcharge of 1.95% has been added for payment by commercial card. It is no more than the cost to us of accepting that payment method. surcharge-warning paragraph · static Surcharge not applied: the US state decides whether a surcharge is allowed, and no usState was given. Remove the surcharge or correct the data before this document is issued. Файлы
что записывает установка; выбранный файл и есть компонентnodes/payment-surcharge-line.node.tsx import { arrange, type Nodes, useDeriver, useState } from "docxcelerate/template";
import type { PaymentSurchargeLineLines } from "../arrangements/payment-surcharge-line/lines.ts";
import { stacked } from "../arrangements/payment-surcharge-line/stacked.arrangement.tsx";
import { table } from "../arrangements/payment-surcharge-line/table.arrangement.tsx";
import paymentSurchargeLine from "../derivers/payment-surcharge-line.deriver.ts";
/**
* The surcharge for the customer's chosen payment method, printed only where
* charging it is lawful, never above a cap, taxed the way the main supply is
* taxed, and with the disclosure the rules require. Otherwise no surcharge
* and a warning for whoever issues the document. No heading, so it can sit
* straight under the invoice totals.
*
* Decisions already made for you:
*
* - Banned cases print nothing but the warning: no UK consumer for any method;
* no consumer card in the UK or EU; no SEPA transfer in the EU; in the US
* only credit cards (commercial included), and never in a state that bans it.
* - Every regime caps the surcharge at the cost of acceptance; with no cost
* given, nothing is charged. The US adds the network's and the state's cap.
* - Every percentage, the request and each cap, is applied to the net total.
* That is the smallest base any of these rules could mean, so a cap stated
* as a share of "the transaction" holds whichever base a regulator reads.
* - Rounded once, in minor units, and down at a cap so the cap is never
* exceeded.
* - In the UK and EU the surcharge is further consideration for the main
* supply (Bookit, C-607/14): not exempt, and not a flat 20% line. It is
* spread across the invoice's VAT bands in proportion to their net, by
* largest remainder, and taxed at each band's rate, so a zero-rated band's
* share carries no VAT. In the US it is part of the sales price unless
* `usTaxable` says the state excludes it.
* - A reduced rate after capping gets no warning: the label and the
* disclosure print the rate actually charged.
*
* Every rule is arithmetic or comparison on request data, which cannot be
* written inline in a published document, so all of it is one deriver. This
* node and its arrangements only place what the deriver returns.
*
* Not modelled: member-state bans beyond the EU defaults, other US states,
* card-network rules other than the percentage cap, fixed-fee surcharges,
* credit notes. The warning prints in the document, to recipients as well as
* the issuer, because the framework has no author-only output: send `percent`
* only for customers you mean to surcharge.
*
* Installed by `dxcl add payment-surcharge-line`, which also installs its
* deriver and arrangements.
*/
/** What this component reads. Add these fields to your document data type. */
export interface PaymentSurchargeLineData {
surcharge: {
/**
* Whose surcharging rules apply. `EU` means the Directive and Regulation
* defaults; a member state that bans more is not modelled. Required:
* anything else throws.
*/
jurisdiction: "GB" | "EU" | "US";
/**
* The US state the sale is made in, as a two-letter postal code: `"NY"`.
* Trimmed and upper-cased before it is compared. Read only for `US`.
* Missing or empty there prints the "not applied" warning, because the
* state decides whether a surcharge is allowed at all.
*/
usState?: string;
/**
* Who is paying. Read only for `GB`, where any consumer surcharge is
* banned; in the EU and US the method decides. Missing means `consumer`,
* the reading that bans more. Any other value throws.
*/
customer?: "consumer" | "business";
/** How the customer is paying. Required. */
method: {
/**
* The payment method. `credit-card`, `debit-card` and `prepaid-card`
* are consumer cards; `commercial-card` is a business card. In `GB`,
* `sepa` is treated as `bank-transfer`. Required: anything else throws.
*/
kind: "credit-card" | "debit-card" | "prepaid-card" | "commercial-card" | "sepa" | "bank-transfer";
/**
* The card network, lower case: `"visa"`, `"mastercard"`. Read only in
* the US, for the network cap. Missing or unknown gets the lowest cap
* in the table (3%).
*/
network?: string;
};
/**
* The surcharge rate the seller asks for, as a percentage of the net
* total: `2.5` means 2.5%. Rounded to 3 decimal places. Missing or 0
* prints nothing at all and no warning. Negative or not a finite number
* throws.
*/
percent?: number;
/**
* What accepting this method costs the seller, as a percentage of the
* transaction: the merchant service charge rate, such as `1.95`. Every
* regime caps the surcharge here. Missing, when a surcharge would
* otherwise be charged, prints the "not applied" warning. Negative or not
* finite throws.
*/
costOfAcceptance?: number;
/**
* US only: whether the state taxes the surcharge as part of the sales
* price. Missing means true, because most states' definition of sales
* price includes charges needed to complete the sale. False prints no
* tax on the surcharge.
*/
usTaxable?: boolean;
/**
* ISO 4217 code: `"GBP"`. Sets the minor units (JPY has none) and how
* amounts print. Required: missing or unknown throws.
*/
currency: string;
/**
* The invoice's totals by tax rate, before any surcharge, as the totals
* section already shows them. One entry per rate. The surcharge is
* spread across these by net. An empty list gives a zero base and prints
* nothing.
*/
bands: Array<{
/**
* The VAT or sales-tax rate, as a percentage: `20`, `5`, `0`, `8.875`.
* An exempt or zero-rated band is `0`. Negative or not finite throws.
*/
ratePercent: number;
/**
* The band's net amount, in major units. Negative or not finite throws:
* a credit note is never surcharged.
*/
net: number;
/**
* The tax already charged on that net, in major units. Read only to
* work out the pre-surcharge gross for the total line, and never
* recomputed. Missing counts as 0. Negative or not finite throws.
*/
vat?: number;
}>;
};
}
/**
* Where the lines sit.
*
* - `table`: the surcharge, its tax and the new total in a label/amount table
* under the invoice totals, then the notes. The default.
* - `stacked`: each line as a sentence, one under another, down the text column.
*/
export type PaymentSurchargeLineArrangement = "table" | "stacked";
/** Props for {@linkcode PaymentSurchargeLine}. */
export interface PaymentSurchargeLineProps {
/** Where the lines sit. Defaults to `"table"`. */
arrangement?: PaymentSurchargeLineArrangement;
}
/** The payment surcharge line for an invoice, as a table row or a stacked sentence. */
export const PaymentSurchargeLine: Nodes<PaymentSurchargeLineProps> = async ({ arrangement }) => {
const [surcharge] = useState((data: PaymentSurchargeLineData) => data.surcharge);
const out = await useDeriver(paymentSurchargeLine, [surcharge]);
const lines: PaymentSurchargeLineLines = {
surchargeLabel: out.surchargeLabel,
surchargeAmount: out.surchargeAmount,
taxLabel: out.taxLabel,
taxAmount: out.taxAmount,
taxNote: out.taxNote,
totalLabel: out.totalLabel,
totalAmount: out.totalAmount,
disclosure: out.disclosure,
warning: out.warning,
};
return <>{arrange(arrangement, { table: () => table(lines), stacked: () => stacked(lines) })}</>;
}; derivers/payment-surcharge-line.deriver.ts import { deriver } from "docxcelerate/template";
/**
* Decides whether a payment-method surcharge may be charged, how much, and
* what it is taxed at. Installed by `dxcl add payment-surcharge-line`.
*
* 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 rule
* tables, the formatter and the integer helpers are all declared inside it.
*/
export default deriver({
name: "paymentSurchargeLine",
run: (surcharge: unknown) => {
// deno-lint-ignore no-explicit-any
const s = surcharge as any;
const bad = (field: string, why: string) => new Error("surcharge." + field + " " + why);
const present = (v: unknown) => v !== undefined && v !== null;
const nonNegative = (v: unknown) => typeof v === "number" && Number.isFinite(v) && v >= 0;
const jurisdictions = ["GB", "EU", "US"];
const kinds = ["credit-card", "debit-card", "prepaid-card", "commercial-card", "sepa", "bank-transfer"];
if (!jurisdictions.includes(s?.jurisdiction)) {
throw bad("jurisdiction", "must be one of " + jurisdictions.join(", "));
}
if (present(s.customer) && s.customer !== "consumer" && s.customer !== "business") {
throw bad("customer", "must be consumer or business");
}
if (!kinds.includes(s.method?.kind)) throw bad("method.kind", "must be one of " + kinds.join(", "));
if (present(s.percent) && !nonNegative(s.percent)) throw bad("percent", "must be a non-negative number");
if (present(s.costOfAcceptance) && !nonNegative(s.costOfAcceptance)) {
throw bad("costOfAcceptance", "must be a non-negative number");
}
if (typeof s.currency !== "string" || s.currency === "") throw bad("currency", "is required");
if (!Array.isArray(s.bands)) throw bad("bands", "must be an array");
for (const band of s.bands) {
if (!nonNegative(band?.ratePercent)) throw bad("bands.ratePercent", "must be a non-negative number");
if (!nonNegative(band.net)) throw bad("bands.net", "must be a non-negative number");
if (present(band.vat) && !nonNegative(band.vat)) throw bad("bands.vat", "must be a non-negative number");
}
const jurisdiction: string = s.jurisdiction;
const us = jurisdiction === "US";
const locale = us ? "en-US" : "en-GB";
const currencyFormat = (() => {
try {
return new Intl.NumberFormat(locale, { style: "currency", currency: s.currency });
} catch {
throw bad("currency", "is not an ISO 4217 code: " + s.currency);
}
})();
const d: number = currencyFormat.resolvedOptions().maximumFractionDigits ?? 2;
const scale = 10 ** d;
// Integer arithmetic only: a float product rounded for money is wrong at
// exactly the halves these rules turn on.
const floorDiv = (a: number, b: number) => (a - a % b) / b;
const roundHalfUp = (a: number, b: number) => floorDiv(2 * a + b, 2 * b);
const milli = (percent: number) => Math.round(percent * 1000);
const bands = (s.bands as Array<{ ratePercent: number; net: number; vat?: number }>).map((band) => ({
netMinor: Math.round(band.net * scale),
vatMinor: Math.round((band.vat ?? 0) * scale),
rateMilli: milli(band.ratePercent),
}));
const base = bands.reduce((sum, band) => sum + band.netMinor, 0);
const preGross = base + bands.reduce((sum, band) => sum + band.vatMinor, 0);
const pMilli = present(s.percent) ? milli(s.percent) : 0;
const none = {
surchargeLabel: null,
surchargeAmount: null,
taxLabel: null,
taxAmount: null,
taxNote: null,
totalLabel: null,
totalAmount: null,
disclosure: null,
warning: null,
};
if (pMilli === 0 || base === 0) return none;
const refuse = (why: string) => ({
...none,
warning: "Surcharge not applied: " + why +
" Remove the surcharge or correct the data before this document is issued.",
});
const kind: string = s.method.kind;
const state = typeof s.usState === "string" ? s.usState.trim().toUpperCase() : "";
// The numbers an owner checks and edits. Percent of the net total.
// Banned: Connecticut and Massachusetts forbid card surcharges outright.
const banned = ["CT", "MA"];
// Colorado caps a surcharge at 2%.
const stateCap: Record<string, number> = { CO: 2 };
// Visa 3%, Mastercard 4%. An unknown network gets the lowest.
const networkCap: Record<string, number> = { visa: 3, mastercard: 4 };
if (jurisdiction === "GB" && s.customer !== "business") {
return refuse(
"surcharging a consumer for any payment method is banned in the UK " +
"(Consumer Rights (Payment Surcharges) Regulations 2012, as amended from 13 January 2018).",
);
}
if (!us && ["credit-card", "debit-card", "prepaid-card"].includes(kind)) {
return refuse(
"consumer cards (credit, debit and prepaid) may not be surcharged in the UK or EU, " +
"whoever is paying (PSD2 Art. 62(4) and the UK equivalent).",
);
}
if (jurisdiction === "EU" && kind === "sepa") {
return refuse("SEPA credit transfers and direct debits may not be surcharged (PSD2 Art. 62(4)).");
}
if (us && (kind === "debit-card" || kind === "prepaid-card")) {
return refuse("debit and prepaid cards may never be surcharged in the US.");
}
if (us && (kind === "sepa" || kind === "bank-transfer")) {
return refuse("only credit cards, commercial cards included, may be surcharged in the US.");
}
if (us && state === "") {
return refuse("the US state decides whether a surcharge is allowed, and no usState was given.");
}
if (us && banned.includes(state)) return refuse("surcharges are banned in " + state + ".");
if (!present(s.costOfAcceptance)) {
return refuse("every rule that allows a surcharge caps it at the cost of acceptance, and no costOfAcceptance was given.");
}
// Every regime caps at the cost of acceptance; the US adds the network's
// and the state's.
let capMilli = milli(s.costOfAcceptance);
if (us) {
const network = typeof s.method.network === "string" ? s.method.network.trim().toLowerCase() : "";
const networkMilli = milli(
Object.prototype.hasOwnProperty.call(networkCap, network)
? networkCap[network]
: Math.min(...Object.values(networkCap)),
);
capMilli = Math.min(capMilli, networkMilli);
if (Object.prototype.hasOwnProperty.call(stateCap, state)) capMilli = Math.min(capMilli, milli(stateCap[state]));
}
const appliedMilli = Math.min(pMilli, capMilli);
// Rounded once, and down at the cap so the cap is never exceeded.
const S = Math.min(roundHalfUp(base * pMilli, 100000), floorDiv(base * capMilli, 100000));
if (S === 0) return none;
// Largest remainder: shares sum to exactly S, ties to the earlier band.
// BigInt: S * netMinor passes 2^53 on a base of a few million pounds.
const products = bands.map((band) => BigInt(S) * BigInt(band.netMinor));
const shares = products.map((product) => Number(product / BigInt(base)));
const order = bands.map((_, i) => ({ i, rem: products[i] % BigInt(base) }))
.sort((a, b) => (a.rem === b.rem ? a.i - b.i : a.rem > b.rem ? -1 : 1));
let leftover = S - shares.reduce((sum, share) => sum + share, 0);
for (const { i } of order) {
if (leftover === 0) break;
shares[i] += 1;
leftover -= 1;
}
const taxApplies = !us || s.usTaxable !== false;
const T = taxApplies
? bands.reduce((sum, band, i) => sum + roundHalfUp(shares[i] * band.rateMilli, 100000), 0)
: 0;
const fmt = (minor: number) => currencyFormat.format(minor / scale);
const percentFormat = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 });
const pct = (m: number) => percentFormat.format(m / 1000) + "%";
const methods: Record<string, string> = {
"credit-card": "credit card",
"commercial-card": "commercial card",
"bank-transfer": "bank transfer",
sepa: jurisdiction === "GB" ? "bank transfer" : "SEPA transfer",
};
const taxName = us ? "tax" : "VAT";
const split = bands.map((band, i) => ({ share: shares[i], rateMilli: band.rateMilli })).filter((x) => x.share > 0);
return {
surchargeLabel: "Surcharge for payment by " + methods[kind] + " (" + pct(appliedMilli) + ")",
surchargeAmount: fmt(S),
taxLabel: T > 0 ? (us ? "Sales tax on surcharge" : "VAT on surcharge") : null,
taxAmount: T > 0 ? fmt(T) : null,
taxNote: T > 0 && split.length >= 2
? "The surcharge is split across the invoice's " + taxName + " rates in proportion to their net: " +
split.map((x) => fmt(x.share) + " at " + pct(x.rateMilli)).join(", ") + "."
: null,
totalLabel: "Total including surcharge",
totalAmount: fmt(preGross + S + T),
disclosure: us
? "We impose a surcharge of " + pct(appliedMilli) +
" on credit card payments, which is not greater than our cost of acceptance. " +
"No surcharge applies to debit card payments."
: "A surcharge of " + pct(appliedMilli) + " has been added for payment by " + methods[kind] +
". It is no more than the cost to us of accepting that payment method.",
warning: null,
};
},
}); arrangements/payment-surcharge-line/lines.ts /**
* What the payment surcharge line hands each of its arrangements: every line
* it may print, already decided. An arrangement places these and decides
* nothing. A `null` is a line this document does not carry; test it in the
* JSX (`{lines.taxAmount && …}`) so it compiles to a condition the engine
* settles per document.
*
* Installed by `dxcl add payment-surcharge-line`, with the arrangements.
*/
export interface PaymentSurchargeLineLines {
/** "Surcharge for payment by commercial card (1.95%)", or null when none is charged. */
surchargeLabel: string | null;
/** The surcharge, formatted in the currency, or null when none is charged. */
surchargeAmount: string | null;
/** "VAT on surcharge" or "Sales tax on surcharge", or null when no tax is due on it. */
taxLabel: string | null;
/** The tax on the surcharge, formatted, or null when no tax is due on it. */
taxAmount: string | null;
/** How the surcharge was split across tax rates, when it touched more than one; else null. */
taxNote: string | null;
/** "Total including surcharge", or null when none is charged. */
totalLabel: string | null;
/** Pre-surcharge gross + surcharge + its tax, formatted, or null when none is charged. */
totalAmount: string | null;
/** The disclosure the rules require, with the rate charged, or null when none is charged. */
disclosure: string | null;
/** Why a requested surcharge was not applied, or null. Never set together with `surchargeAmount`. */
warning: string | null;
} arrangements/payment-surcharge-line/table.arrangement.tsx import { Cell, Paragraph, Row, Table, type Yield } from "docxcelerate/template";
import type { PaymentSurchargeLineLines } from "./lines.ts";
/**
* The surcharge, its tax and the new total as label and amount rows, the
* amounts in the second column so they line up with an invoice totals table
* above. The notes follow beneath, full width.
*/
export const table = (lines: PaymentSurchargeLineLines): Yield => (
<>
{lines.surchargeAmount && (
<Table id="surcharge-table" columns={[{ width: "auto" }, { width: 40, align: "right" }]}>
<Row id="surcharge-amount">
<Cell>{lines.surchargeLabel}</Cell>
<Cell>{lines.surchargeAmount}</Cell>
</Row>
{lines.taxAmount && (
<Row id="surcharge-tax">
<Cell>{lines.taxLabel}</Cell>
<Cell>{lines.taxAmount}</Cell>
</Row>
)}
<Row id="surcharge-total">
<Cell>{lines.totalLabel}</Cell>
<Cell>{lines.totalAmount}</Cell>
</Row>
</Table>
)}
{lines.taxNote && <Paragraph id="surcharge-tax-note">{lines.taxNote}</Paragraph>}
{lines.disclosure && <Paragraph id="surcharge-disclosure">{lines.disclosure}</Paragraph>}
{lines.warning && <Paragraph id="surcharge-warning">{lines.warning}</Paragraph>}
</>
); arrangements/payment-surcharge-line/stacked.arrangement.tsx import { Paragraph, type Yield } from "docxcelerate/template";
import type { PaymentSurchargeLineLines } from "./lines.ts";
/** Each line as a sentence, one under another, down the text column. */
export const stacked = (lines: PaymentSurchargeLineLines): Yield => (
<>
{lines.surchargeAmount && (
<Paragraph id="surcharge-amount">{lines.surchargeLabel}: {lines.surchargeAmount}</Paragraph>
)}
{lines.taxAmount && <Paragraph id="surcharge-tax">{lines.taxLabel}: {lines.taxAmount}</Paragraph>}
{lines.totalAmount && <Paragraph id="surcharge-total">{lines.totalLabel}: {lines.totalAmount}</Paragraph>}
{lines.taxNote && <Paragraph id="surcharge-tax-note">{lines.taxNote}</Paragraph>}
{lines.disclosure && <Paragraph id="surcharge-disclosure">{lines.disclosure}</Paragraph>}
{lines.warning && <Paragraph id="surcharge-warning">{lines.warning}</Paragraph>}
</>
);