VAT in local currency
BodyAn invoice in one currency for VAT owed in another restates its VAT analysis in that currency. Each rate band converts its net and its VAT separately, rounded once in the target currency's minor units, and the local totals are the band sums, never a converted gross. The rate carries its direction, so an inverse quote divides instead of multiplying, and is worked in exact integers. It is checked against the tax point under the jurisdiction's rule: the UK market selling, HMRC period or agreed rate; the EU selling or ECB rate; the German BMF monthly average; the Polish NBP or ECB rate of the last working day before the tax point; Bulgaria's fixed euro rate, unrounded and never inverted. A wrong source or date prints a check-before-issuing line. On a final invoice each advance keeps the rate it was declared at. The rate, its source and its date print beside the figures.
npx dxcl add vat-in-local-currency vatConversion.jurisdiction Datos de vista previa
el JSON con el que se construyó esta vista previa{
"vatConversion": {
"jurisdiction": "EU",
"invoiceCurrency": "EUR",
"vatCurrency": "PLN",
"taxPointDate": "2026-03-31",
"issueDate": "2026-03-31",
"bands": [
{
"ratePercent": "23",
"net": "1284750.00",
"vat": "295492.50"
},
{
"ratePercent": "8",
"net": "48210.40",
"vat": "3856.83"
},
{
"ratePercent": "0",
"net": "12500.00",
"vat": "0.00"
}
],
"rate": {
"value": "4.2725",
"base": "EUR",
"quote": "PLN",
"source": "nbp",
"rateDate": "2026-03-30"
},
"advances": [
{
"invoiceNumber": "FV/ZAL/2026/02/0147",
"chargeableDate": "2026-02-16",
"bands": [
{
"ratePercent": "23",
"net": "400000.00",
"vat": "92000.00"
}
],
"rate": {
"value": "4.2187",
"base": "EUR",
"quote": "PLN",
"source": "nbp",
"rateDate": "2026-02-13"
}
}
]
}
} {
"vatConversion": {
"jurisdiction": "PL",
"invoiceCurrency": "EUR",
"vatCurrency": "PLN",
"taxPointDate": "2026-03-31",
"issueDate": "2026-03-31",
"bands": [
{
"ratePercent": "23",
"net": "1284750.00",
"vat": "295492.50"
},
{
"ratePercent": "8",
"net": "48210.40",
"vat": "3856.83"
},
{
"ratePercent": "0",
"net": "12500.00",
"vat": "0.00"
}
],
"rate": {
"value": "4.2725",
"base": "EUR",
"quote": "PLN",
"source": "nbp",
"rateDate": "2026-03-30"
},
"advances": [
{
"invoiceNumber": "FV/ZAL/2026/02/0147",
"chargeableDate": "2026-02-16",
"bands": [
{
"ratePercent": "23",
"net": "400000.00",
"vat": "92000.00"
}
],
"rate": {
"value": "4.2187",
"base": "EUR",
"quote": "PLN",
"source": "nbp",
"rateDate": "2026-02-13"
}
}
]
}
} Vista previa renderizada
cada disposición renderizada por su cuentaarrangement="columns" predeterminada arrangement="block" arrangement="columns" predeterminada arrangement="block" Nodos resueltos
lo que recibe un renderizador — 1 nodosvat-in-local-currency section vat-in-local-currency section Los archivos
lo que escribe la instalación; el archivo seleccionado es el componentenodes/vat-in-local-currency.node.tsx import { arrange, Paragraph, Section, type Section as SectionComponent, useDeriver, useState } from "docxcelerate/template";
import { block } from "../arrangements/vat-in-local-currency/block.arrangement.tsx";
import { columns } from "../arrangements/vat-in-local-currency/columns.arrangement.tsx";
import type { VatInLocalCurrencyLines } from "../arrangements/vat-in-local-currency/lines.ts";
import vatInLocalCurrency from "../derivers/vat-in-local-currency.deriver.ts";
/**
* An invoice issued in one currency for VAT owed in another has to state the
* VAT analysis in the currency the VAT is owed in. The rules are Art. 230 of
* the VAT Directive and, in the UK, HMRC Notice 700 s.16: net per rate and VAT
* per rate in sterling. This component restates the invoice's own VAT bands in
* that currency.
*
* Decisions already made for you:
*
* - Every band is converted on its own. Net and VAT are converted separately
* and each is rounded once, to the minor units of the VAT currency. The
* local totals are the sums of those bands. They are never worked out by
* converting the gross total and backing VAT out of it, and never by adding
* up line-by-line conversions. Those methods drift a penny away from the
* figure an accounting system recomputes.
* - The rate carries its direction. "1 EUR = 0.8571 GBP" multiplies and
* "1 GBP = 1.1667 EUR" divides, so a feed that quotes the inverse cannot
* turn the conversion upside down.
* - The rate is checked against the tax point, not the invoice date, using
* the rule of the jurisdiction: in the UK the market selling rate, an HMRC
* period rate for the month of the tax point, or a rate agreed with HMRC; in
* the EU the latest selling rate or the ECB rate (Art. 91); in Germany the
* BMF monthly average; in Poland the NBP or ECB rate of the last working day
* before the tax point; in Bulgaria the fixed euro rate, used unrounded and
* never inverted.
* - Advances keep their own rate. On a final invoice each advance is restated
* at the rate of its own chargeable event, so VAT already declared in local
* currency is not re-converted at today's rate.
* - The rate, its direction, its source and its date are printed beside the
* figures. A wrong source or date is printed as a "Check before issuing"
* line. It is not silently accepted.
*
* All of this is decided in one deriver, because arithmetic on request data
* cannot be published. This node only interpolates, loops and chooses between
* the same-currency sentence and the figures.
*
* Installed by `dxcl add vat-in-local-currency`, which also installs its deriver and arrangements.
*/
/** One VAT rate band, in the currency of the document it belongs to. */
export interface VatBand {
/**
* The VAT rate as a percentage, a decimal string: "20", "5", "0", "7.7". A
* number is accepted and read with String(n). At most 4 decimal places, and
* it must not be negative. Required: missing or malformed throws, naming the
* field (`vatConversion.bands[1].ratePercent`). Two bands with the same rate
* ("20" and "20.0" count as the same) throw.
*/
ratePercent: string | number;
/**
* The net at this rate, in major units of the invoice currency, a decimal
* string: "1234.56". A number is accepted and read with String(n), so
* 0.1 + 0.2 throws instead of being rounded. Negative for a credit note.
* Zero is allowed. More decimal places than the currency has, or anything
* that is not a plain decimal, throws, naming the field. Required.
*/
net: string | number;
/** The VAT at this rate, as the invoice states it. The same rules as `net`. Required. It is never recomputed from `net`. */
vat: string | number;
}
/** An exchange rate with its direction stated: 1 `base` = `value` `quote`. */
export interface VatExchangeRate {
/**
* The rate as a decimal string, "0.8571". A number is accepted and read with
* String(n). Must be greater than zero, with at most 10 decimal places.
* Required. Printed exactly as given (trimmed).
*/
value: string | number;
/**
* ISO 4217 code of the unit side. Together with `quote` it must be exactly
* the invoice currency and the VAT currency, in either order. Anything else
* throws, naming both currencies it expected. Base = invoice currency
* multiplies. Base = VAT currency divides.
*/
base: string;
/** ISO 4217 code of the priced side. See `base`. Required. */
quote: string;
/**
* Where the rate comes from. Required: anything outside the union throws. A
* source the jurisdiction does not accept is still used, and a warning is
* printed. `fixed-euro` is allowed only for the EUR/BGN pair (it throws
* otherwise). That pair must use `fixed-euro`, with base EUR and value
* exactly "1.95583". Anything else for that pair throws.
*/
source: "market-selling" | "hmrc-period" | "ecb" | "nbp" | "bmf-monthly" | "fixed-euro" | "agreed";
/**
* The date the rate applies to, ISO 8601 (characters after the tenth are
* ignored). For a period rate (`hmrc-period`, `bmf-monthly`) this is any day
* in the month the rate was published for. Required except for `fixed-euro`,
* where it is ignored. Missing or malformed throws.
*/
rateDate?: string;
}
/** An advance invoiced earlier and deducted on this, the final invoice. */
export interface VatAdvance {
/** The advance invoice's number, printed as given (trimmed). Required: missing or blank throws. */
invoiceNumber: string;
/**
* When VAT on the advance became chargeable (the payment was received), ISO
* 8601. Required. Missing or malformed throws, and so does a date after
* `vatConversion.taxPointDate`. The advance's rate is checked against this
* date, never against the final tax point.
*/
chargeableDate: string;
/**
* The advance's VAT bands in the invoice currency, with the same rules as
* `vatConversion.bands`. At least one entry. Every rate must also appear in
* `vatConversion.bands`, or it throws.
*/
bands: VatBand[];
/** The rate the advance was declared at. The same rules as `vatConversion.rate`. Required. */
rate: VatExchangeRate;
}
/** What this component reads. Add these fields to your document data type. */
export interface VatInLocalCurrencyData {
vatConversion: {
/**
* Whose conversion rules apply. `EU` is a member state with no rules of
* its own here, so the Directive's defaults (Art. 91) apply. Required:
* anything else throws.
*/
jurisdiction: "UK" | "EU" | "DE" | "PL" | "BG";
/** ISO 4217 code the invoice is issued in. Required. A code Intl rejects throws. */
invoiceCurrency: string;
/**
* ISO 4217 code the VAT is owed in. Required. It must fit the
* jurisdiction, or it throws: UK is GBP, DE is EUR, PL is PLN, BG is BGN
* for a tax point before 2026-01-01 and EUR from then on. EU accepts any
* valid code. When it equals `invoiceCurrency`, nothing is converted and
* the component prints one sentence saying so.
*/
vatCurrency: string;
/** The tax point (time of supply, chargeable event), ISO 8601. Required. Missing or malformed throws. */
taxPointDate: string;
/**
* The date of issue, ISO 8601. Read only in PL: an invoice issued before
* its tax point takes the rate from before the issue date (art. 31a(2)).
* Required when jurisdiction is PL (missing throws). Elsewhere it is
* optional, and validated when present.
*/
issueDate?: string;
/**
* The invoice's VAT analysis, one band per rate, in the invoice currency,
* printed in the order given. With `advances` these are the whole supply,
* as a final invoice lists it. At least one band, or it throws.
*/
bands: VatBand[];
/** The rate for this invoice's tax point. Required. */
rate: VatExchangeRate;
/**
* Advances already invoiced and deducted here. Missing or empty means
* none. When given, every band must be zero or positive (it throws
* otherwise). After the advances are subtracted, every band's remainder
* must be zero or positive, or it throws, naming the rate.
*/
advances?: VatAdvance[];
};
}
/** Where the local-currency figures sit: beside each band, or in a statement of their own. */
export type VatInLocalCurrencyArrangement = "columns" | "block";
/** Props for {@linkcode VatInLocalCurrency}. */
export interface VatInLocalCurrencyProps {
/** Where the local figures sit. Defaults to `"columns"`. */
arrangement?: VatInLocalCurrencyArrangement;
}
export const VatInLocalCurrency: SectionComponent<VatInLocalCurrencyProps> = async ({ arrangement }) => {
const [conversion] = useState((data: VatInLocalCurrencyData) => data.vatConversion);
const local = await useDeriver(vatInLocalCurrency, [conversion]);
// Built before the decision: the compiler publishes an early return only when
// a lone `return` follows it.
const lines: VatInLocalCurrencyLines = {
invoiceCurrency: local.invoiceCurrency,
vatCurrency: local.vatCurrency,
bands: local.bands,
total: local.total,
hasAdvances: local.hasAdvances,
advances: local.advances,
};
if (!local.converted) {
// Its own id: a published document cannot carry two nodes with the same one.
return (
<Section id="vat-in-local-currency-same-currency" title={`VAT in ${local.vatCurrency}`}>
<Paragraph id="vat-local-same-currency">
VAT on this invoice is charged in {local.sameCurrency}, the currency it is issued in, so no conversion is
needed.
</Paragraph>
</Section>
);
}
return (
<Section id="vat-in-local-currency" title={`VAT in ${local.vatCurrency}`}>
<Paragraph id="vat-local-statement">{local.statement}</Paragraph>
{arrange(arrangement, { columns: () => columns(lines), block: () => block(lines) })}
{local.warnings.map((warning) => (
<Paragraph id="vat-local-warning">Check before issuing: {warning.text}</Paragraph>
))}
</Section>
);
}; derivers/vat-in-local-currency.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Restates an invoice's VAT bands in the currency the VAT is owed in, checks
* the rate against the jurisdiction's rule, and words the check. Installed by
* `dxcl add vat-in-local-currency`.
*
* Money is BigInt minor units and the rate is a BigInt over a power of ten, so
* no float is ever multiplied and a credit note is the exact mirror of its
* invoice. It is self-contained on purpose: it travels to the engine as source
* text, so every helper and table lives inside `run`.
*/
export default deriver({
name: "vatInLocalCurrency",
run: (input: unknown) => {
const conv = input as any;
const fail = (message: string): never => {
throw new Error("vatInLocalCurrency: " + message);
};
const currencyOf = (value: unknown, field: string) => {
if (typeof value !== "string") fail(field + " is required");
let money: Intl.NumberFormat;
try {
money = new Intl.NumberFormat("en-GB", { style: "currency", currency: value as string });
} catch {
fail(field + " must be an ISO 4217 code");
}
return { code: value as string, money: money!, exponent: money!.resolvedOptions().maximumFractionDigits as number };
};
// UTC day indexes, so the engine's time zone never shifts a day.
const isoDay = (value: unknown, field: string): number => {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}/.test(value)) {
fail(field + " must be an ISO 8601 date");
}
const text = (value as string).slice(0, 10);
const [y, m, d] = text.split("-").map(Number);
const day = Date.UTC(y, m - 1, d) / 86_400_000;
if (new Date(day * 86_400_000).toISOString().slice(0, 10) !== text) fail(field + " is not a real date: " + text);
return day;
};
const dates = new Intl.DateTimeFormat("en-GB", { dateStyle: "long", timeZone: "UTC" });
const months = new Intl.DateTimeFormat("en-GB", { month: "long", year: "numeric", timeZone: "UTC" });
const fmt = (day: number) => dates.format(new Date(day * 86_400_000));
const fmtMonth = (day: number) => months.format(new Date(day * 86_400_000));
const monthKey = (day: number) => new Date(day * 86_400_000).toISOString().slice(0, 7);
// Half away from zero on exact integers, so +x and -x round to mirror images.
const roundHalfAway = (n: bigint, d: bigint) => {
const abs = n < 0n ? -n : n;
const q = (2n * abs + d) / (2n * d);
return n < 0n ? -q : q;
};
const JURISDICTIONS = ["UK", "EU", "DE", "PL", "BG"];
const jurisdiction = conv?.jurisdiction;
if (!JURISDICTIONS.includes(jurisdiction)) fail("vatConversion.jurisdiction must be one of " + JURISDICTIONS.join(", "));
const inv = currencyOf(conv?.invoiceCurrency, "vatConversion.invoiceCurrency");
const loc = currencyOf(conv?.vatCurrency, "vatConversion.vatCurrency");
const taxPoint = isoDay(conv?.taxPointDate, "vatConversion.taxPointDate");
if (jurisdiction === "PL" && conv?.issueDate == null) fail("vatConversion.issueDate is required in PL");
const issue = conv?.issueDate == null ? null : isoDay(conv.issueDate, "vatConversion.issueDate");
// The currency each jurisdiction owes VAT in; an owner edits it here.
const owed: Record<string, string> = {
UK: "GBP",
DE: "EUR",
PL: "PLN",
BG: taxPoint < Date.UTC(2026, 0, 1) / 86_400_000 ? "BGN" : "EUR",
};
if (jurisdiction !== "EU" && loc.code !== owed[jurisdiction]) {
fail(
"vatConversion.vatCurrency must be " + owed[jurisdiction] + " in " + jurisdiction + " at this tax point, got " +
loc.code,
);
}
const same = inv.code === loc.code;
const text = (n: bigint, c: { money: Intl.NumberFormat; exponent: number }) => {
const abs = n < 0n ? -n : n;
const scale = 10n ** BigInt(c.exponent);
const frac = c.exponent === 0 ? "" : "." + (abs % scale).toString().padStart(c.exponent, "0");
return c.money.format(Number((n < 0n ? "-" : "") + (abs / scale).toString() + frac));
};
if (same) {
return {
converted: false,
sameCurrency: loc.code,
vatCurrency: loc.code,
invoiceCurrency: inv.code,
statement: "",
bands: [] as any[],
total: { net: "", vat: "", localNet: "", localVat: "" },
hasAdvances: false,
advances: [] as any[],
warnings: [] as any[],
};
}
const minorOf = (value: unknown, field: string): bigint => {
const t = String(value).trim();
const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(t);
if (!m || (m[3] ?? "").length > inv.exponent) {
fail(field + " must be a decimal with at most " + inv.exponent + " decimal places, got " + t);
}
const minor = BigInt(m![2] + (m![3] ?? "").padEnd(inv.exponent, "0"));
return m![1] ? -minor : minor;
};
const bandsOf = (list: unknown, path: string) => {
if (!Array.isArray(list) || list.length === 0) fail(path + " must be a non-empty array");
const seen = new Set<string>();
return (list as any[]).map((b, i) => {
const at = path + "[" + i + "]";
const t = String(b?.ratePercent).trim();
const m = /^(\d+)(?:\.(\d{1,4}))?$/.exec(t);
if (!m) fail(at + ".ratePercent must be a percentage with at most 4 decimal places, got " + t);
const frac = (m![2] ?? "").replace(/0+$/, "");
const rate = m![1].replace(/^0+(?=\d)/, "") + (frac ? "." + frac : "");
if (seen.has(rate)) fail(at + ".ratePercent repeats the " + rate + "% band");
seen.add(rate);
return { rate, net: minorOf(b?.net, at + ".net"), vat: minorOf(b?.vat, at + ".vat") };
});
};
const rateOf = (r: any, path: string) => {
const t = String(r?.value).trim();
const m = /^(\d+)(?:\.(\d{1,10}))?$/.exec(t);
if (!m) fail(path + ".value must be a decimal with at most 10 decimal places, got " + t);
const R = BigInt(m![1] + (m![2] ?? ""));
if (R === 0n) fail(path + ".value must be greater than zero");
const scale = 10n ** BigInt((m![2] ?? "").length);
let multiply: boolean;
if (r.base === inv.code && r.quote === loc.code) multiply = true;
else if (r.base === loc.code && r.quote === inv.code) multiply = false;
else fail(path + " must be a pair of " + inv.code + " and " + loc.code + ", got " + r.base + "/" + r.quote);
const SOURCES = ["market-selling", "hmrc-period", "ecb", "nbp", "bmf-monthly", "fixed-euro", "agreed"];
if (!SOURCES.includes(r.source)) fail(path + ".source must be one of " + SOURCES.join(", "));
const euroBgn = [inv.code, loc.code].sort().join("/") === "BGN/EUR";
if (r.source === "fixed-euro" && !euroBgn) fail(path + ".source fixed-euro is only for the EUR/BGN pair");
if (euroBgn) {
if (r.source !== "fixed-euro") fail(path + ".source must be fixed-euro for the EUR/BGN pair");
if (r.base !== "EUR" || t !== "1.95583") fail(path + " must be 1 EUR = 1.95583 BGN, never rounded or inverted");
}
const day = r.source === "fixed-euro" ? null : isoDay(r.rateDate, path + ".rateDate");
return { R, scale, multiply: multiply!, text: t, base: r.base as string, quote: r.quote as string, source: r.source as string, day };
};
type Rate = ReturnType<typeof rateOf>;
// One rounding, in the VAT currency's minor units, on exact integers.
const convert = (a: bigint, r: Rate) => {
const toScale = 10n ** BigInt(loc.exponent);
const fromScale = 10n ** BigInt(inv.exponent);
return r.multiply
? roundHalfAway(a * r.R * toScale, r.scale * fromScale)
: roundHalfAway(a * r.scale * toScale, r.R * fromScale);
};
const UK = jurisdiction === "UK";
const sourceLabel = (r: Rate) => {
const d = r.day === null ? "" : fmt(r.day);
const labels: Record<string, string> = {
"market-selling": UK ? "UK market selling rate of " + d : "selling rate of " + d,
"hmrc-period": "HMRC period rate for " + (r.day === null ? "" : fmtMonth(r.day)),
"bmf-monthly": "BMF monthly average rate for " + (r.day === null ? "" : fmtMonth(r.day)),
ecb: "ECB reference rate of " + d,
nbp: "NBP average rate of " + d,
agreed: UK ? "rate agreed with HMRC, dated " + d : "rate agreed with the tax authority, dated " + d,
"fixed-euro": "the irrevocably fixed euro conversion rate",
};
return labels[r.source];
};
const rateLine = (r: Rate) => "1 " + r.base + " = " + r.text + " " + r.quote + ", " + sourceLabel(r);
const rate = rateOf(conv.rate, "vatConversion.rate");
const bands = bandsOf(conv.bands, "vatConversion.bands");
// Advances: each band keeps the rate its own chargeable event was declared at.
if (conv.advances != null && !Array.isArray(conv.advances)) fail("vatConversion.advances must be an array");
const advances = ((conv.advances ?? []) as any[]).map((a, i) => {
const at = "vatConversion.advances[" + i + "]";
if (typeof a?.invoiceNumber !== "string" || !a.invoiceNumber.trim()) fail(at + ".invoiceNumber is required");
const chargeable = isoDay(a.chargeableDate, at + ".chargeableDate");
if (chargeable > taxPoint) fail(at + ".chargeableDate is after vatConversion.taxPointDate");
const abands = bandsOf(a.bands, at + ".bands");
for (const b of abands) {
if (!bands.some((x) => x.rate === b.rate)) fail(at + ".bands has a " + b.rate + "% band the invoice does not");
if (b.net < 0n || b.vat < 0n) fail(at + ".bands must not be negative");
}
return { number: a.invoiceNumber.trim() as string, chargeable, bands: abands, rate: rateOf(a.rate, at + ".rate") };
});
if (advances.length) {
bands.forEach((b, i) => {
if (b.net < 0n || b.vat < 0n) fail("vatConversion.bands[" + i + "] must not be negative when there are advances");
});
}
const left = bands.map((b) => {
let net = b.net;
let vat = b.vat;
for (const a of advances) {
for (const x of a.bands) {
if (x.rate === b.rate) {
net -= x.net;
vat -= x.vat;
}
}
}
if (advances.length && (net < 0n || vat < 0n)) fail("the advances exceed the " + b.rate + "% band");
return { rate: b.rate, net, vat };
});
// Warn on the legal choices the data shows; throwing is for facts that make the figures wrong.
const accepted: Record<string, string[]> = {
UK: ["market-selling", "hmrc-period", "agreed"],
EU: ["market-selling", "ecb"],
DE: ["bmf-monthly", "ecb", "agreed"],
PL: ["nbp", "ecb"],
BG: ["fixed-euro", "ecb", "market-selling"],
};
const names: Record<string, string> = {
"market-selling": "the market selling rate",
"hmrc-period": "an HMRC period rate",
ecb: "the ECB rate",
nbp: "the NBP rate",
"bmf-monthly": "the BMF monthly average",
"fixed-euro": "the fixed euro rate",
agreed: "a rate agreed with the tax authority",
};
const place: Record<string, string> = { UK: "the UK", EU: "the EU", DE: "Germany", PL: "Poland", BG: "Bulgaria" };
const easter = (y: number) => {
const a = y % 19, b = Math.floor(y / 100), c = y % 100;
const d = Math.floor(b / 4), e = b % 4, f = Math.floor((b + 8) / 25);
const g = Math.floor((b - f + 1) / 3), h = (19 * a + b - d - g + 15) % 30;
const i = Math.floor(c / 4), k = c % 4, l = (32 + 2 * e + 2 * i - h - k) % 7;
const m = Math.floor((a + 11 * h + 22 * l) / 451);
const month = Math.floor((h + l - 7 * m + 114) / 31), day = ((h + l - 7 * m + 114) % 31) + 1;
return Date.UTC(y, month - 1, day) / 86_400_000;
};
const holiday = (day: number) => {
const d = new Date(day * 86_400_000);
const y = d.getUTCFullYear();
const md = d.toISOString().slice(5, 10);
const fixed = ["01-01", "01-06", "05-01", "05-03", "08-15", "11-01", "11-11", "12-25", "12-26"];
if (y >= 2025) fixed.push("12-24");
const e = easter(y);
return fixed.includes(md) || day === e + 1 || day === e + 60;
};
const working = (day: number) => {
const wd = new Date(day * 86_400_000).getUTCDay();
return wd !== 0 && wd !== 6 && !holiday(day);
};
const upper = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
const warnings: Array<{ text: string }> = [];
const check = (r: Rate, reference: number, prefix: string, refWord: string) => {
if (r.day === null) return;
const out: string[] = [];
const ok = accepted[jurisdiction];
if (!ok.includes(r.source)) {
const list = ok.map((s) => names[s]);
out.push(
upper(sourceLabel(r)) + " is not a rate " + place[jurisdiction] + " accepts for VAT; use " +
(list.length > 1 ? list.slice(0, -1).join(", ") + " or " + list[list.length - 1] : list[0]) + ".",
);
}
if (jurisdiction !== "PL" && r.day > reference) {
out.push("The exchange rate is dated " + fmt(r.day) + ", after the tax point of " + fmt(reference) + ".");
}
if ((r.source === "hmrc-period" || r.source === "bmf-monthly") && monthKey(r.day) !== monthKey(reference)) {
out.push(
"A" + (r.source === "hmrc-period" ? "n HMRC period" : " BMF monthly") + " rate applies only to its own month: this one is for " +
fmtMonth(r.day) + ", the tax point is in " + fmtMonth(reference) + ".",
);
}
if (jurisdiction === "PL") {
let lwd = reference - 1;
while (!working(lwd)) lwd--;
if (r.day !== lwd) {
const head = "In Poland the rate is the one from the last working day before " + refWord + ", " + fmt(lwd) +
"; this one is dated " + fmt(r.day) + ", ";
out.push(
head + (r.day === reference
? "the day itself."
: r.day > reference
? "after " + refWord + "."
: !working(r.day)
? "which is not a working day."
: "before the last working day."),
);
}
}
for (const t of out) warnings.push({ text: prefix + t });
};
const issuedFirst = jurisdiction === "PL" && issue !== null && issue < taxPoint;
check(rate, issuedFirst ? issue! : taxPoint, "", issuedFirst ? "the date of issue" : "the tax point");
for (const a of advances) {
check(a.rate, a.chargeable, "Advance invoice " + a.number + ": ", "the tax point");
}
const sum = (xs: bigint[]) => xs.reduce((s, x) => s + x, 0n);
const lined = left.map((b) => ({ ...b, localNet: convert(b.net, rate), localVat: convert(b.vat, rate) }));
const line = (n: bigint, v: bigint, ln: bigint, lv: bigint) => ({
net: text(n, inv),
vat: text(v, inv),
localNet: text(ln, loc),
localVat: text(lv, loc),
});
const mainLine = rateLine(rate);
return {
converted: true,
sameCurrency: "",
vatCurrency: loc.code,
invoiceCurrency: inv.code,
statement: "VAT on this invoice is accounted for in " + loc.code + ". Each rate band is converted separately at " +
mainLine + ", and the " + loc.code + " totals are the sum of the bands." +
(advances.length
? " The bands are what this invoice charges after the advances below, each of which keeps the rate it was declared at."
: ""),
bands: lined.map((b) => ({ rate: b.rate + "%", ...line(b.net, b.vat, b.localNet, b.localVat) })),
total: line(sum(lined.map((b) => b.net)), sum(lined.map((b) => b.vat)), sum(lined.map((b) => b.localNet)), sum(lined.map((b) => b.localVat))),
hasAdvances: advances.length > 0,
advances: advances.map((a) => {
const c = a.bands.map((b) => ({ ...b, ln: convert(b.net, a.rate), lv: convert(b.vat, a.rate) }));
return {
label: "Advance invoice " + a.number + ", chargeable " + fmt(a.chargeable),
rateLine: rateLine(a.rate),
...line(sum(c.map((b) => b.net)), sum(c.map((b) => b.vat)), sum(c.map((b) => b.ln)), sum(c.map((b) => b.lv))),
};
}),
warnings,
};
},
}); arrangements/vat-in-local-currency/lines.ts /**
* What the VAT in local currency hands each of its arrangements: the bands,
* totals and advances, already converted and formatted. An arrangement places
* these and decides nothing, so both print the same lines under the same
* conditions.
*
* Installed by `dxcl add vat-in-local-currency`, with the arrangements.
*/
export interface VatInLocalCurrencyLines {
/** The currency the invoice is issued in, "EUR". */
invoiceCurrency: string;
/** The currency the VAT is owed in, "GBP". */
vatCurrency: string;
/** One entry per rate band, in the order the invoice gives them. */
bands: Array<{ rate: string; net: string; vat: string; localNet: string; localVat: string }>;
/** The sums of the bands, in both currencies. Never a converted gross. */
total: { net: string; vat: string; localNet: string; localVat: string };
/** Whether advances were deducted, which the loop below is empty without. */
hasAdvances: boolean;
/** One entry per advance, each at the rate it was declared at. */
advances: Array<{ label: string; rateLine: string; net: string; vat: string; localNet: string; localVat: string }>;
} arrangements/vat-in-local-currency/columns.arrangement.tsx import { Cell, Paragraph, Row, Table, type Yield } from "docxcelerate/template";
import type { VatInLocalCurrencyLines } from "./lines.ts";
/**
* One table with the local figures beside each band, then the total. The
* default: a reader checking the figures against the invoice's own VAT
* analysis looks along the row. Advances get a second table of the same shape.
*/
export const columns = (lines: VatInLocalCurrencyLines): Yield => (
<>
<Table
id="vat-local-bands"
columns={[{ width: "auto" }, { width: 30, align: "right" }, { width: 30, align: "right" }, {
width: 30,
align: "right",
}, { width: 30, align: "right" }]}
>
<Row id="vat-local-header" header>
<Cell>Rate</Cell>
<Cell>Net ({lines.invoiceCurrency})</Cell>
<Cell>VAT ({lines.invoiceCurrency})</Cell>
<Cell>Net ({lines.vatCurrency})</Cell>
<Cell>VAT ({lines.vatCurrency})</Cell>
</Row>
{lines.bands.map((band) => (
<Row id="vat-local-band">
<Cell>{band.rate}</Cell>
<Cell>{band.net}</Cell>
<Cell>{band.vat}</Cell>
<Cell>{band.localNet}</Cell>
<Cell>{band.localVat}</Cell>
</Row>
))}
<Row id="vat-local-total">
<Cell>Total</Cell>
<Cell>{lines.total.net}</Cell>
<Cell>{lines.total.vat}</Cell>
<Cell>{lines.total.localNet}</Cell>
<Cell>{lines.total.localVat}</Cell>
</Row>
</Table>
{lines.hasAdvances && (
<Paragraph id="vat-local-advances-intro">
Advances already invoiced, each at the rate of its own chargeable event:
</Paragraph>
)}
{lines.hasAdvances && (
<Table
id="vat-local-advances"
columns={[{ width: "auto" }, { width: 30, align: "right" }, { width: 30, align: "right" }, {
width: 30,
align: "right",
}, { width: 30, align: "right" }]}
>
<Row id="vat-local-advances-header" header>
<Cell>Advance</Cell>
<Cell>Net ({lines.invoiceCurrency})</Cell>
<Cell>VAT ({lines.invoiceCurrency})</Cell>
<Cell>Net ({lines.vatCurrency})</Cell>
<Cell>VAT ({lines.vatCurrency})</Cell>
</Row>
{lines.advances.map((advance) => (
<Row id="vat-local-advance">
<Cell>
<Paragraph>{advance.label}</Paragraph>
<Paragraph>{advance.rateLine}</Paragraph>
</Cell>
<Cell>{advance.net}</Cell>
<Cell>{advance.vat}</Cell>
<Cell>{advance.localNet}</Cell>
<Cell>{advance.localVat}</Cell>
</Row>
))}
</Table>
)}
</>
); arrangements/vat-in-local-currency/block.arrangement.tsx import { Paragraph, type Yield } from "docxcelerate/template";
import type { VatInLocalCurrencyLines } from "./lines.ts";
/**
* A separate statement under the invoice's totals, one paragraph per band. It
* suits an invoice whose own VAT table should not grow two columns.
*/
export const block = (lines: VatInLocalCurrencyLines): Yield => (
<>
{lines.bands.map((band) => (
<Paragraph id="vat-local-band">
{band.rate}: net {band.net} = {band.localNet}; VAT {band.vat} = {band.localVat}.
</Paragraph>
))}
<Paragraph id="vat-local-total">
Total in {lines.vatCurrency}: net {lines.total.localNet}, VAT {lines.total.localVat} (net {lines.total.net}, VAT{" "}
{lines.total.vat}).
</Paragraph>
{lines.hasAdvances && (
<Paragraph id="vat-local-advances-intro">
Advances already invoiced, each at the rate of its own chargeable event:
</Paragraph>
)}
{lines.advances.map((advance) => (
<Paragraph id="vat-local-advance">
{advance.label}, at {advance.rateLine}: net {advance.net} = {advance.localNet}; VAT {advance.vat} ={" "}
{advance.localVat}.
</Paragraph>
))}
</>
);