/** * Shipping zones for the Checkout rates service picker. */ import type { DefaultServiceZone } from '../../../types/default-service'; export interface ZoneBrowseOption { /** Unique option value: `country:`, or `rest` for Rest of the world. */ value: string; label: string; /** Country quoted to find services; empty when the merchant must pick one (Rest of the world). */ country: string; /** True for Rest of the world, which has no countries of its own. */ needsCountry?: boolean; } /** Option value for "Rest of the world". */ export const REST_OF_WORLD = 'rest'; /** * What the merchant can find services for. The service list is global and a zone is quoted to its * first country, so zones quoted to the same country give the same services: they share one entry, * in WooCommerce's zone order, labelled with their names ("UK Mainland / UK Highlands"). Entries * that still share a label get their country added ("Europe (FR)"). * "Rest of the world" has no countries, so it is offered last with a country to pick, as long as it * has shipping methods. * * @param zones Shipping zones from the settings, in WooCommerce's order. * @return Dropdown options. */ export function zonesToBrowse(zones: DefaultServiceZone[]): ZoneBrowseOption[] { const byCountry = new Map(); let restOfWorld = false; for (const zone of zones) { const country = zone.countryCodes?.[0]?.trim() ?? ''; if (country === '') { restOfWorld = restOfWorld || (zone.id === 0 && (zone.methods?.length ?? 0) > 0); continue; } const names = byCountry.get(country) ?? []; const name = zone.name.trim(); if (!names.some((existing) => existing.toLowerCase() === name.toLowerCase())) { names.push(name); } byCountry.set(country, names); } const options: ZoneBrowseOption[] = [...byCountry.entries()].map(([country, names]) => ({ value: `country:${country}`, label: names.join(' / '), country, })); // Different countries under the same label: add the country, e.g. "Europe (FR)". const labelCounts = new Map(); for (const option of options) { const key = option.label.toLowerCase(); labelCounts.set(key, (labelCounts.get(key) ?? 0) + 1); } const labelled = options.map((option) => (labelCounts.get(option.label.toLowerCase()) ?? 0) > 1 ? { ...option, label: `${option.label} (${option.country})` } : option ); if (restOfWorld) { labelled.push({ value: REST_OF_WORLD, label: 'Rest of the world', country: '', needsCountry: true }); } return labelled; }