Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { roundDiv } from "./math_round_div.ts"; ← from math.round-div ^1.0.0 · built alongside by fune
import { type Money, money } from "./money_amount.ts"; ← from money.amount ^1.0.0 · built alongside by fune
import { STATE_RATES, STATE_RATES_HISTORY } from "./retail_sales_tax_us_data.ts"; ← this capability’s own data, compiled from data/state-rates.json into the same file by fune build
import { type UsSalesTax } from "./retail_sales_tax_us_types.ts";
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
function stateRate(state: string, onDate: string): number {
if (!STATE_RATES.some((r) => r.state === state)) throw new RangeError(`unknown US state "${state}"`);
let best: { validFrom: string; rate: number } | null = null;
for (const r of STATE_RATES) {
if (r.state !== state || onDate < r.validFrom || (r.validTo !== null && onDate > r.validTo)) continue;
if (best === null || r.validFrom > best.validFrom) best = { validFrom: r.validFrom, rate: r.ratePerMillion };
}
if (best !== null) return best.rate;
if (STATE_RATES_HISTORY !== "full") {
let earliest: string | null = null;
for (const r of STATE_RATES) {
if (r.state === state && (earliest === null || r.validFrom < earliest)) earliest = r.validFrom;
}
if (earliest !== null && onDate < earliest) {
throw new RangeError(
`no sales tax rate for ${state} on ${onDate}: this build was installed with history=${STATE_RATES_HISTORY}, ` +
`so it only carries rates from ${earliest}. Reinstall with history=full for older sales.`,
);
}
}
throw new RangeError(`no sales tax rate for ${state} on ${onDate}`);
}
/**
* US sales tax: the state's base rate on the date of sale plus the caller's
* local rate, applied once and rounded half up to the cent.
*/
export function salesTaxUs(amount: Money, state: string, localRatePerMillion: number, onDate: string): UsSalesTax {
if (!ISO_DATE.test(onDate)) throw new RangeError(`onDate must be an ISO date (YYYY-MM-DD), received "${onDate}"`);
if (amount.currency !== "USD") throw new RangeError(`US sales tax is charged in USD, received ${amount.currency}`);
if (!Number.isInteger(localRatePerMillion) || localRatePerMillion < 0 || localRatePerMillion >= 1000000) {
throw new RangeError(`localRatePerMillion must be from 0 to 999999, received ${localRatePerMillion}`);
}
const stateRatePerMillion = stateRate(state, onDate);
const combinedRatePerMillion = stateRatePerMillion + localRatePerMillion;
const tax = money(roundDiv(amount.minor * combinedRatePerMillion, 1000000, "half-up"), "USD");
return {
state,
stateRatePerMillion,
localRatePerMillion,
combinedRatePerMillion,
taxable: amount,
tax,
total: money(amount.minor + tax.minor, "USD"),
};
}