TaxID.utils.ts50 lines · main
1import { TAX_IDS, TaxId } from './TaxID.constants'
2
3/**
4 * Returns the country code to send to Orb for tax validation.
5 *
6 * Most tax IDs use their display country (countryIso2), but some territories
7 * share another country's tax system — e.g., Isle of Man uses GB VAT.
8 * In these cases, taxCountryIso2 overrides the country sent to Orb.
9 */
10export const getEffectiveTaxCountry = (taxId: TaxId): string =>
11 taxId.taxCountryIso2 ?? taxId.countryIso2
12
13/**
14 * Resolves a stored tax ID (from Orb) back to its TAX_IDS UI entry.
15 *
16 * Uses billingCountry (from the customer's address) to disambiguate when
17 * multiple entries share the same Orb type+country — e.g., both "UK VAT"
18 * and "IM VAT" map to {type: 'gb_vat', country: 'GB'} in Orb, but differ
19 * by billing address country (GB vs IM).
20 *
21 * When billingCountry is unavailable, falls back to the stored country.
22 */
23export const resolveStoredTaxId = (
24 type: string,
25 taxCountry: string,
26 billingCountry?: string
27): TaxId | undefined => {
28 const candidates = TAX_IDS.filter((option) => option.type === type)
29 const preferredCountry = billingCountry ?? taxCountry
30
31 return candidates.find((o) => o.countryIso2 === preferredCountry)
32}
33
34export const sanitizeTaxIdValue = (taxId: { name: string; value: string }) => {
35 const selectedTaxId = TAX_IDS.find((option) => option.name === taxId.name)
36
37 const vatIdPrefix = selectedTaxId?.vatPrefix
38
39 // if the value doesn't start with the prefix, prepend them
40 if (vatIdPrefix && !taxId.value.startsWith(vatIdPrefix)) {
41 return `${vatIdPrefix}${taxId.value}`
42 }
43
44 return taxId.value
45}
46
47/** Ignore id property amongst tax ids */
48export const checkTaxIdEqual = (a: any, b: any) => {
49 return a?.type === b?.type && a?.value === b?.value
50}