import { overseasRequest } from './overseas.js' const BASE = '/pda/v1/last-leg/return-inventory' const encoded = (value) => encodeURIComponent(String(value || '').trim()) const count = (value) => Number.isFinite(Number(value)) ? Math.max(0, Number(value)) : 0 function isNotFound(error) { const code = String(error?.code || '').toUpperCase() return code === 'A0404' || code === '404' } function normalizeItems(items) { return Array.isArray(items) ? items.map((item) => ({ skuCode: String(item.skuCode || ''), productNameZh: String(item.productNameZh || ''), quantity: count(item.quantity ?? item.availableQuantity) })) : [] } export function normalizePackingPreview(value = {}) { return { customerKey: value.customerId == null ? '' : String(value.customerId), orders: Array.isArray(value.orders) ? value.orders.map((item) => ({ returnNo: String(item.returnNo || ''), customerReferenceNo: String(item.customerReferenceNo || ''), status: String(item.status || '') })) : [], skus: Array.isArray(value.skus) ? value.skus.map((item) => ({ skuCode: String(item.skuCode || ''), productNameZh: String(item.productNameZh || ''), availableQuantity: count(item.availableQuantity) })) : [] } } export function normalizeReturnLabel(value = {}) { return { cartonMark: String(value.cartonMark || ''), sourceBatchNo: String(value.sourceBatchNo || ''), sourceReturnNo: String(value.sourceReturnNo || ''), totalQuantity: count(value.totalQuantity), length: count(value.length), width: count(value.width), height: count(value.height), weight: count(value.weight), items: normalizeItems(value.items), generatedAt: value.generatedAt || null, printableHtml: String(value.printableHtml || '') } } export async function findPackingOrders(returnNo = '') { const query = String(returnNo || '').trim() try { return normalizePackingPreview(await overseasRequest('GET', `${BASE}/packing/orders${query ? `?returnNo=${encoded(query)}` : ''}`)) } catch (error) { if (isNotFound(error)) return normalizePackingPreview() throw error } } export async function mergeReturnCartons(request) { const value = await overseasRequest('POST', `${BASE}/cartons/merge`, request) return { cartonMark: String(value?.cartonMark || ''), skuCode: String(value?.skuCode || ''), totalQuantity: count(value?.totalQuantity), label: normalizeReturnLabel(value?.label) } } export async function getReturnCartonLabel(cartonMark) { return normalizeReturnLabel(await overseasRequest('GET', `${BASE}/cartons/${encoded(cartonMark)}/label`)) }