TaxID.utils.ts 1.7 KB

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