/** * Checkout rates: let customers pick a courier service at checkout with live prices. * Saves on its own (PUT /settings/checkout), like the default services section. */ import { __, sprintf } from '@wordpress/i18n'; import { useCallback, useEffect, useMemo, useState, createInterpolateElement, } from '@wordpress/element'; import { Button, Flex, Notice, SelectControl, TextControl, ToggleControl, // Stable in WordPress for years, still exported under its experimental name. __experimentalToggleGroupControl as ToggleGroupControl, __experimentalToggleGroupControlOption as ToggleGroupControlOption, } from '@wordpress/components'; import { Spinner } from '@woocommerce/components'; import apiFetch from '@wordpress/api-fetch'; import { CourierSelectWithList } from '../../shared/components'; import { useQuotesFetcher } from '../../shared/hooks'; import { cmToStoreUnit, FALLBACK_PARCEL_CM, formatCurrency, getShippingZonesUrl, kgToStoreUnit, } from '../../shared/utils'; import type { DefaultShippingSettings } from '../../types'; import type { DefaultServiceZone } from '../../types/default-service'; import { REST_OF_WORLD, zonesToBrowse } from './utils/checkoutRatesZones'; import { serviceChipLabel } from './utils/serviceChipLabel'; import { customerServiceName, pickupKind, pickupTags } from './utils/customerServiceName'; import { pickupPhoneNotice } from './utils/pickupPhoneNotice'; /** Which field error each form field clears when changed. */ const FIELD_ERROR_KEYS: Partial> = { services: 'services', percent: 'markup.percent', fixed: 'markup.fixed', rounding: 'rounding', maxRates: 'maxRates', enabled: 'services', }; /** Fallback when WooCommerce's country list is not on the page. */ const FALLBACK_COUNTRIES = [ { value: 'US', label: 'United States (US)' }, { value: 'CA', label: 'Canada' }, { value: 'AU', label: 'Australia' }, { value: 'NZ', label: 'New Zealand' }, { value: 'JP', label: 'Japan' }, { value: 'CN', label: 'China' }, { value: 'AE', label: 'United Arab Emirates' }, { value: 'ZA', label: 'South Africa' }, ]; /** * Countries for the Rest of the world lookup, from WooCommerce's admin settings (code → name), * sorted by name; a short list of common destinations if they are not available. */ function countriesFromWooCommerce(): { value: string; label: string }[] { const countries = (window as unknown as { wcSettings?: { countries?: Record } }).wcSettings?.countries; if (!countries || typeof countries !== 'object' || Object.keys(countries).length === 0) { return FALLBACK_COUNTRIES; } const decode = (text: string) => { const el = document.createElement('textarea'); el.innerHTML = text; return el.value; }; return Object.entries(countries) .map(([value, label]) => ({ value, label: decode(String(label)) })) .sort((a, b) => a.label.localeCompare(b.label)); } import type { Quote, Service } from '../../types/quote'; import type { CheckoutRatesError, CheckoutPriceDirection, CheckoutRatesResponse, CheckoutRounding, } from '../../types/checkout-rates'; import { markedUpPrice } from './utils/checkoutRatesPrice'; import { hasPickupLookup, isPickupQuote } from '../order-ship/utils/pickupPoint'; const PATH = '/parcel2go-shipping/v1/settings/checkout'; const FALLBACK_WEIGHT_KG = 1; /** Worked example on the screen: a £4.20 quote before VAT, £5.04 with VAT. */ const EXAMPLE_NET = 4.2; const EXAMPLE_GROSS = 5.04; /** Sample markup the example uses until the merchant enters their own. */ const SAMPLE_PERCENT = 10; const SAMPLE_FIXED = 0.5; /** Longest name a merchant can give a service (CheckoutSettings::MAX_CUSTOMER_NAME). */ const MAX_CUSTOMER_NAME = 60; /** Largest markup percentage (CheckoutSettings::MAX_MARKUP_PERCENT). */ const MAX_MARKUP_PERCENT = 200; /** Largest percentage a merchant can take off (CheckoutSettings::MAX_REDUCTION_PERCENT). */ const MAX_REDUCTION_PERCENT = 100; const ROUNDING_OPTIONS: { value: CheckoutRounding; label: string }[] = [ { value: 'none', label: __('No rounding', 'parcel2go-shipping') }, { value: 'up_10p', label: __('Up to the next 10p', 'parcel2go-shipping') }, { value: 'up_pound', label: __('Up to the next £1', 'parcel2go-shipping') }, { value: 'end_99', label: __('Up to a price ending in 99p', 'parcel2go-shipping') }, ]; /** * A picked service, with the merchant's own name for customers (empty: the suggested name) and, * for pickup point services, whether the customer collects from a locker or a shop. */ type CheckoutService = Service & { customerName?: string; pickup?: '' | 'locker' | 'shop' }; interface FormState { enabled: boolean; services: CheckoutService[]; direction: CheckoutPriceDirection; percent: string; fixed: string; rounding: CheckoutRounding; maxRates: string; } export interface CheckoutRatesFormProps { storeAddress: DefaultShippingSettings | null; defaultPackage: { length: number; width: number; height: number } | null; defaultWeightKg?: number; weightUnit: string; dimensionUnit: string; /** The store's WooCommerce shipping zones (with their country codes). */ zones: DefaultServiceZone[]; /** Told whenever the form gains or loses unsaved changes, so the page can warn before they are lost. */ onDirtyChange?: (dirty: boolean) => void; } function toFormState(data: CheckoutRatesResponse): FormState { return { enabled: data.enabled, services: data.services.map((slug) => { const details = data.serviceDetails?.[slug]; return { slug, name: details?.name || slug, courier: details?.courier ?? '', courierSlug: details?.courierSlug ?? '', dropOffProviderGroup: '', customerName: details?.customerName ?? '', pickup: details?.pickup ?? '', }; }), direction: data.markup.direction ?? 'increase', percent: String(data.markup.percent), fixed: String(data.markup.fixed), rounding: data.rounding, maxRates: String(data.maxRates), }; } export function CheckoutRatesForm({ storeAddress, defaultPackage, defaultWeightKg, weightUnit, dimensionUnit, zones, onDirtyChange, }: CheckoutRatesFormProps) { const [data, setData] = useState(null); const [form, setForm] = useState(null); const [loadError, setLoadError] = useState(null); const [saving, setSaving] = useState(false); // The list of names grows with the services picked, so it stays folded until the merchant opens it. const [namesOpen, setNamesOpen] = useState(false); // The merchant closed the price reduction warning; it comes back when they pick Decrease again. const [reductionNoticeClosed, setReductionNoticeClosed] = useState(false); const [feedback, setFeedback] = useState<{ status: 'success' | 'error'; message: string; } | null>(null); const [fieldErrors, setFieldErrors] = useState>({}); const browseZones = useMemo( () => zonesToBrowse(zones).map((option) => option.value === REST_OF_WORLD ? { ...option, label: __('Rest of the world', 'parcel2go-shipping') } : option ), [zones] ); const [browseZoneId, setBrowseZoneId] = useState(''); // The picked zone, else the first one (and again if the picked zone is deleted). const browseZone = browseZones.find((zone) => zone.value === browseZoneId) ?? browseZones[0] ?? null; // Rest of the world has no countries of its own: the merchant picks one to look up services for. const worldCountries = useMemo(() => countriesFromWooCommerce(), []); const [worldCountry, setWorldCountry] = useState('US'); const browseCountry = browseZone?.needsCountry ? worldCountry : browseZone?.country ?? ''; const load = useCallback(async () => { setLoadError(null); try { const response = (await apiFetch({ path: PATH })) as CheckoutRatesResponse; setData(response); setForm(toFormState(response)); } catch (e) { setLoadError( (e as CheckoutRatesError)?.message || __('Could not load checkout rates settings.', 'parcel2go-shipping') ); } }, []); useEffect(() => { load(); }, [load]); // The merchant fixes a missing fallback in WooCommerce's shipping zones, often in another tab: // re-check the zones when they come back, so Save unlocks without a reload. Only the zones are // refreshed, so unsaved edits stay. const refreshZones = useCallback(async () => { try { const response = (await apiFetch({ path: PATH })) as CheckoutRatesResponse; setData((prev) => (prev ? { ...prev, zones: response.zones } : prev)); } catch { // Keep what we have; saving re-checks on the server anyway. } }, []); useEffect(() => { const onVisible = () => { if (document.visibilityState === 'visible') refreshZones(); }; window.addEventListener('focus', refreshZones); document.addEventListener('visibilitychange', onVisible); return () => { window.removeEventListener('focus', refreshZones); document.removeEventListener('visibilitychange', onVisible); }; }, [refreshZones]); // Quote the default parcel, as the default services section does. const parcels = useMemo(() => { const hasPackage = defaultPackage && defaultPackage.length > 0 && defaultPackage.width > 0 && defaultPackage.height > 0; const size = hasPackage ? defaultPackage : { length: cmToStoreUnit(FALLBACK_PARCEL_CM.length, dimensionUnit), width: cmToStoreUnit(FALLBACK_PARCEL_CM.width, dimensionUnit), height: cmToStoreUnit(FALLBACK_PARCEL_CM.height, dimensionUnit), }; const weight = typeof defaultWeightKg === 'number' && defaultWeightKg > 0 ? defaultWeightKg : kgToStoreUnit(FALLBACK_WEIGHT_KG, weightUnit); return [ { ref: 'checkout-rates', weight, length: size.length, width: size.width, height: size.height, value: 100, }, ]; }, [defaultPackage, defaultWeightKg, weightUnit, dimensionUnit]); const origin = useMemo( () => ({ country: storeAddress?.country ?? '', countryName: storeAddress?.country ?? '', postcode: storeAddress?.postcode || undefined, }), [storeAddress] ); const quotesFetcher = useQuotesFetcher({ origin, parcels }); // Locker and shop services of any carrier; ones with no provider are left out. const pickableQuotes = useMemo( () => quotesFetcher.quotesList.filter( (quote: Quote) => !isPickupQuote(quote) || hasPickupLookup(quote) ), [quotesFetcher.quotesList] ); // Chip text: pickup point services say so, so the merchant knows the customer collects. const checkoutChipLabel = useCallback( // Chips are drawn from form.services, so each one is a CheckoutService. (service: Service) => (service as CheckoutService).pickup ? sprintf( /* translators: %s: courier service name */ __('%s (pickup point)', 'parcel2go-shipping'), serviceChipLabel(service) ) : serviceChipLabel(service), [] ); const update = useCallback((patch: Partial) => { setForm((prev) => (prev ? { ...prev, ...patch } : prev)); setFeedback(null); // A field the merchant has just changed no longer shows its old error. const fixed = Object.keys(patch).map((key) => FIELD_ERROR_KEYS[key as keyof FormState] ?? key); setFieldErrors((prev) => { if (!fixed.some((key) => key in prev)) return prev; const next = { ...prev }; fixed.forEach((key) => delete next[key]); return next; }); }, []); const isDirty = useMemo(() => { if (!data || !form) return false; // Switched off and saved off: the settings are hidden, so edits made before switching off // are nothing to save or warn about. if (!form.enabled && !data.enabled) return false; return ( JSON.stringify(toFormState(data)) !== JSON.stringify(form) ); }, [data, form]); // Save and Discard clear it; leaving the section (unmount) has nothing left to keep. useEffect(() => { onDirtyChange?.(isDirty); }, [isDirty, onDirtyChange]); useEffect(() => () => onDirtyChange?.(false), [onDirtyChange]); const save = useCallback(async () => { if (!form) return; setSaving(true); setFeedback(null); setFieldErrors({}); try { const response = (await apiFetch({ path: PATH, method: 'PUT', data: { enabled: form.enabled, services: form.services.map((service) => ({ slug: service.slug, name: service.name, courier: service.courier, courierSlug: service.courierSlug, customerName: service.customerName ?? '', pickup: service.pickup ?? '', })), markup: { direction: form.direction, percent: form.percent, fixed: form.fixed }, rounding: form.rounding, maxRates: form.maxRates, }, })) as CheckoutRatesResponse; setData(response); setForm(toFormState(response)); setFeedback({ status: 'success', message: __('Checkout rates saved.', 'parcel2go-shipping'), }); } catch (e) { const error = e as CheckoutRatesError; setFieldErrors(error?.data?.errors ?? {}); if (error?.code === 'p2g_zone_without_fallback') { // A zone lost its fallback since the page loaded: show the standing warning (which locks // Save) rather than a one-off message. const missing = error.data?.zones ?? []; setData((prev) => prev ? { ...prev, zones: { ...prev.zones, withoutFallback: missing } } : prev ); return; } setFeedback({ status: 'error', message: error?.message || __('Could not save checkout rates.', 'parcel2go-shipping'), }); } finally { setSaving(false); } }, [form]); if (loadError) { return ( {loadError} ); } if (!data || !form) { return ( ); } const percent = Number(form.percent) || 0; const fixed = Number(form.fixed) || 0; const decrease = form.direction === 'decrease'; const sign = decrease ? -1 : 1; const operator = decrease ? ' - ' : ' + '; // What the checkout marks up: before VAT when WooCommerce taxes shipping, else the price with VAT. const marksUpNet = data.tax.enabled; // Until the merchant enters a markup, illustrate with a sample one so the example shows each step. const usesSampleMarkup = percent <= 0 && fixed <= 0; const examplePercent = usesSampleMarkup ? SAMPLE_PERCENT : percent; const exampleFixed = usesSampleMarkup ? SAMPLE_FIXED : fixed; // "£5.04 + 10% + £0.50 = £6.04, rounded up to £6.99": percentage, then fixed amount, then rounding. const exampleSum = (base: number, label: string) => { const parts = [`${formatCurrency(base)} ${label}`]; if (examplePercent > 0) parts.push(`${examplePercent}%`); if (exampleFixed > 0) parts.push(formatCurrency(exampleFixed)); const beforeRounding = markedUpPrice(base, sign * examplePercent, sign * exampleFixed, 'none'); const rounded = markedUpPrice(base, sign * examplePercent, sign * exampleFixed, form.rounding); const sum = `${parts.join(operator)} = ${formatCurrency(beforeRounding)}`; return rounded === beforeRounding ? sum : sprintf( /* translators: 1: the markup sum, 2: rounded price */ __('%1$s, rounded up to %2$s', 'parcel2go-shipping'), sum, formatCurrency(rounded) ); }; // With a reduction, what the merchant pays on top of what the customer pays, per label. const exampleBase = marksUpNet ? EXAMPLE_NET : EXAMPLE_GROSS; const exampleLoss = decrease ? exampleBase - markedUpPrice(exampleBase, -examplePercent, -exampleFixed, form.rounding) : 0; const exampleText = [ sprintf( /* translators: %s: worked example, e.g. "£5.04 label (inc. VAT) + 10% + £0.50 = £6.04" */ __('Example: %s.', 'parcel2go-shipping'), marksUpNet ? exampleSum(EXAMPLE_NET, __('label (before VAT)', 'parcel2go-shipping')) : exampleSum(EXAMPLE_GROSS, __('label (inc. VAT)', 'parcel2go-shipping')) ), marksUpNet ? __('WooCommerce then adds VAT for the customer.', 'parcel2go-shipping') : '', exampleLoss > 0.004 ? sprintf( /* translators: %s: amount, e.g. £1.00 */ __('You pay %s more per label than the customer pays you.', 'parcel2go-shipping'), formatCurrency(exampleLoss) ) : '', usesSampleMarkup ? __('Enter your markup to see your own price.', 'parcel2go-shipping') : '', ] .filter(Boolean) .join(' '); // A delivery area whose Live courier rates method has Tax status "None" marks up the price with VAT. const untaxedExampleText = marksUpNet ? sprintf( /* translators: %s: worked example, e.g. "£5.04 label (inc. VAT) + 10% + £0.50 = £6.04" */ __( 'Where Live courier rates is set to Tax status "None" in a delivery area, the markup is added to the price with VAT: %s.', 'parcel2go-shipping' ), exampleSum(EXAMPLE_GROSS, __('label (inc. VAT)', 'parcel2go-shipping')) ) : null; // A saved reduction, shown by the toggle so anyone opening settings sees it straight away. const savedReduction = data.enabled && data.markup.direction === 'decrease' && (data.markup.percent > 0 || data.markup.fixed > 0) ? [ data.markup.percent > 0 ? `${data.markup.percent}%` : '', data.markup.fixed > 0 ? formatCurrency(data.markup.fixed) : '', ] .filter(Boolean) .join(' + ') : ''; const showReductionNotice = decrease && !reductionNoticeClosed; const phoneNotice = pickupPhoneNotice(form.services, data.checkoutPhone?.field); const notGbp = data.currency !== '' && data.currency !== 'GBP'; // Only a concern once the merchant switches live rates on: while off, customers never see them. // The server refuses to save live rates on without a fallback, so Save waits until it's fixed. const showFallbackNotice = form.enabled && data.zones.withoutFallback.length > 0; // Locked while switching saved rates off, and while a missing fallback stops any save: nothing // entered could be kept. const settingsLocked = !form.enabled || showFallbackNotice; const zonesLink = ( {__('shipping zones', 'parcel2go-shipping')} ); return ( {feedback && ( {feedback.message} )} {notGbp && ( {__( 'Live courier rates are only available for stores that charge in pounds (GBP).', 'parcel2go-shipping' )} )} {showFallbackNotice && ( {sprintf( /* translators: %s: shipping zone names */ __( 'Add a shipping method every customer can use (for example Flat rate) to %s, so customers can still check out if live rates are unavailable. Free shipping that needs a coupon or minimum spend does not count. You can change and save these settings once it is added.', 'parcel2go-shipping' ), data.zones.withoutFallback.join(', ') )} )} {data.enabled && data.zones.withLiveRates.length === 0 && ( {createInterpolateElement( __( 'Live courier rates are on, but not added to any of your . Add "Live courier rates" to each zone where customers should see them.', 'parcel2go-shipping' ), { zones: zonesLink } )} )} {data.tax.enabled && !data.tax.hasShippingRate && ( {__( 'WooCommerce taxes are on, but no UK tax rate applies to shipping. Customers will not be charged VAT on shipping, while you still pay VAT on the label.', 'parcel2go-shipping' )} )} and keep another method every customer can use in each zone.', 'parcel2go-shipping' ), { zones: zonesLink } )} checked={form.enabled} disabled={notGbp && !form.enabled} onChange={(enabled) => update({ enabled })} /> {savedReduction && ( {sprintf( /* translators: %s: the reduction, e.g. "10% + £0.50" */ __('Prices reduced by %s', 'parcel2go-shipping'), savedReduction )} )} {/* Settings show once live rates are switched on. Switching saved rates off keeps them in view, greyed out, until the merchant saves or discards. */} {(form.enabled || data.enabled) && (

{__('Services customers can choose', 'parcel2go-shipping')}

{__( 'Pick services for each of your shipping zones. Customers only see the ones that deliver to their address.', 'parcel2go-shipping' )}

({ value, label, }))} disabled={browseZones.length === 0} onChange={(value) => { setBrowseZoneId(value); quotesFetcher.setActiveCacheKey(null); }} />
{browseZone?.needsCountry && (
{ setWorldCountry(value); quotesFetcher.setActiveCacheKey(null); }} />
)} {browseZones.length === 0 && (

{createInterpolateElement( __( 'You have no shipping zones with countries yet. Create one in your , for example "United Kingdom", then come back to pick its services.', 'parcel2go-shipping' ), { zones: zonesLink } )}

)} { if (!browseZone || !browseCountry) return; const key = `checkout-rates:${browseZone.value}:${browseCountry}`; quotesFetcher.setActiveCacheKey(key); quotesFetcher.fetchQuotes(key, { country: browseCountry, }); }} chipLabel={checkoutChipLabel} quotesList={pickableQuotes} quotesLoading={quotesFetcher.quotesLoading} quotesError={quotesFetcher.quotesError} selectedCouriers={form.services} onAddCourier={(service) => { if (form.services.some((s) => s.slug === service.slug)) return; const quote = quotesFetcher.quotesList.find( (q: Quote) => q.service.slug === service.slug ); update({ services: [ ...form.services, { ...service, pickup: pickupKind(quote?.tags) }, ], }); }} onRemoveCourier={(service) => update({ services: form.services.filter((s) => s.slug !== service.slug), }) } canFetch={!!storeAddress?.country?.trim() && !!browseCountry} missingMessage={ !storeAddress?.country?.trim() ? __( 'Set your store address in Default shipping details to find services.', 'parcel2go-shipping' ) : null } /> {fieldErrors.services && (

{fieldErrors.services}

)} {phoneNotice && (
{createInterpolateElement( phoneNotice === 'hidden' ? __( 'Locker and shop services need the customer\'s phone number, so the courier can send them the collection code. Your checkout does not ask for a phone number, so these orders cannot be booked until you add one. Change the phone field to Required.', 'parcel2go-shipping' ) : __( 'Locker and shop services need the customer\'s phone number, so the courier can send them the collection code. Your checkout\'s phone field is optional, so customers can leave it empty and you will need to add a number before booking. Change the phone field to Required.', 'parcel2go-shipping' ), { link: data.checkoutPhone?.editUrl ? ( ) : ( ), } )}
)}
{form.services.length > 0 && (

{__('Names customers see', 'parcel2go-shipping')}

{__( 'Courier service names like "Collection" or "Drop Off" describe how you send the parcel, which can confuse customers. We\'ve given them simpler names, but you can change them below.', 'parcel2go-shipping' )}

{namesOpen && ( {form.services.map((service) => { const suggested = customerServiceName( service, pickupTags(service.pickup) ); return ( {serviceChipLabel(service)}
update({ services: form.services.map((s) => s.slug === service.slug ? { ...s, customerName } : s ), }) } />
); })}
)}
)}

{__('Your price', 'parcel2go-shipping')}

{decrease ? marksUpNet ? __( 'Customers pay the label price (before VAT) minus your reduction, and WooCommerce adds VAT. The reduction applies in this order: the percentage, then the fixed amount, then rounding.', 'parcel2go-shipping' ) : __( 'Customers pay the label price (inc. VAT) minus your reduction. The reduction applies in this order: the percentage, then the fixed amount, then rounding.', 'parcel2go-shipping' ) : marksUpNet ? __( 'Customers pay the label price (before VAT) plus your markup, and WooCommerce adds VAT. The markup applies in this order: the percentage, then the fixed amount, then rounding.', 'parcel2go-shipping' ) : __( 'Customers pay the label price (inc. VAT) plus your markup. The markup applies in this order: the percentage, then the fixed amount, then rounding.', 'parcel2go-shipping' )}

{ const direction = (value as CheckoutPriceDirection) ?? 'increase'; if (direction === 'decrease') setReductionNoticeClosed(false); update({ direction }); }} >
update({ percent: percentValue })} help={fieldErrors['markup.percent']} />
update({ fixed: fixedValue })} help={fieldErrors['markup.fixed']} />
update({ rounding: rounding as CheckoutRounding }) } />

{exampleText}

{showReductionNotice && (
setReductionNoticeClosed(true)}> {__( 'Customers will pay less than your label costs. You pay the difference on every order. If this is a mistake, switch back to "Add to the label price".', 'parcel2go-shipping' )}
)} {untaxedExampleText && (

{untaxedExampleText}

)}
({ value: String(n), label: String(n), }))} onChange={(maxRates) => update({ maxRates })} />
)} {!form.enabled && data.enabled && (

{__( 'Save to stop showing live courier rates at checkout. Your services and price are kept for next time.', 'parcel2go-shipping' )}

)} {(form.enabled || data.enabled) && ( {isDirty && ( )} )}
); }