import type { Order, OrderItem, QuotePayload } from '../../../types'; import { parseNum } from '../../../shared/utils'; import { StoreSettingsResponse } from 'types/settings'; /** Per-item dimensions (numbers) for building a multi-parcel quote payload. */ export interface ItemDimensions { length: number; width: number; height: number; weight: number; } /** * Build POST /quotes body with one parcel per order item. * @param getItemDimensions - Returns dimensions for each item (from overrides, item, or defaults). */ export function buildQuotePayloadFromItems( order: Order, store: StoreSettingsResponse | null, getItemDimensions: (itemIndex: number, item: OrderItem) => ItemDimensions ): QuotePayload | null { if (!store?.country || !order?.shipping?.country || !order.items?.length) return null; const parcels = order.items.map((item, index) => { const dimensions = getItemDimensions(index, item); const lineTotal = parseNum(item.total) ?? 0; const valuePence = Math.max(1, Math.round(lineTotal * 100)); return { ref: item.product_id ?? `item-${index}`, weight: dimensions.weight > 0 ? dimensions.weight : 1, length: Math.max(1, Math.round(dimensions.length)), width: Math.max(1, Math.round(dimensions.width)), height: Math.max(1, Math.round(dimensions.height)), value: valuePence, }; }); return { origin: { country: store.country, countryName: store.countryName, postcode: store.postcode || undefined, }, destination: { country: order.shipping.country, countryName: order.shipping.country_name ?? order.shipping.country, postcode: order.shipping.postcode || undefined, }, parcels, }; }