import { pool } from '../db'; import { getEffectiveBranchCode, type TenantContext } from './tenantScope'; export interface DeliveryPrintLineRow { order_code: string; order_item_id: string; sku_code: string; sku_name: string; item_name: string | null; customer_alias: string | null; category_name: string | null; spec: string | null; origin: string | null; quantity: number; unit: string; price: number; amount: number; processing_method: string | null; /** 明细备注 */ remark: string | null; supplier_code: string | null; supplier_name: string | null; picked_qty: number | null; loaded_qty: number | null; inspection_actual_qty: number | null; weigh_qty: number | null; weigh_unit: string | null; base_unit: string | null; weigh_qty_base: number | null; delivery_qty: number | null; actual_amount: number | null; box_no: string | null; box_count: number | null; sort_order: number; is_extra_dish?: boolean; is_returned?: boolean; } export interface DeliveryPrintOrderHeader { order_code: string; customer_code: string | null; company_name: string | null; customer_role: string | null; parent_customer_code: string | null; account_code: string | null; account_name: string | null; merchant_name: string | null; delivery_address: string | null; delivery_date: string | null; delivery_time_slot: string | null; total_amount: number | null; remark: string | null; cycle_code: string | null; order_status: number; branch_code: string | null; branch_name: string | null; task_code: string | null; delivery_person: string | null; delivery_person_phone: string | null; } export interface DeliveryPrintBundle { orders: DeliveryPrintOrderHeader[]; lines: DeliveryPrintLineRow[]; } function normalizeOrderCodes(codes: string[]): string[] { return [...new Set(codes.map((c) => String(c || '').trim()).filter(Boolean))]; } /** 配送单打印:订单头 + 明细(含分拣实拣、验收实收、装车数量) */ export async function fetchDeliveryPrintBundle( orderCodes: string[], ctx?: TenantContext | null, operatingBranchCode?: string | null ): Promise { const codes = normalizeOrderCodes(orderCodes); if (!codes.length) { return { orders: [], lines: [] }; } const branchCode = getEffectiveBranchCode(ctx ?? null, operatingBranchCode); const params: unknown[] = [codes]; let branchFilter = ''; if (branchCode && !ctx?.isSuperAdmin) { params.push(branchCode); branchFilter = ` AND o.branch_code = $${params.length}`; } const orderResult = await pool.query( `SELECT o.order_code, o.customer_code, c.company_name, c.customer_role, c.parent_customer_code, parent.company_name AS parent_company_name, COALESCE(parent.customer_code, CASE WHEN c.customer_role = 'account' THEN c.customer_code END, c.customer_code) AS account_code, COALESCE(parent.company_name, CASE WHEN c.customer_role = 'account' THEN c.company_name END, c.company_name) AS account_name, CASE WHEN c.customer_role = 'merchant' OR c.parent_customer_code IS NOT NULL THEN c.company_name ELSE c.company_name END AS merchant_name, COALESCE(NULLIF(TRIM(o.delivery_address), ''), NULLIF(TRIM(c.address), '')) AS delivery_address, to_char((COALESCE(o.delivery_date, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date, 'YYYY-MM-DD') AS delivery_date, o.delivery_time_slot, o.total_amount, o.remark, o.cycle_code, o.order_status, o.branch_code, b.branch_name, dt.task_code, dp.person_name AS delivery_person, dp.phone AS delivery_person_phone FROM orders o LEFT JOIN customers c ON c.customer_code = o.customer_code LEFT JOIN customers parent ON parent.customer_code = c.parent_customer_code LEFT JOIN branches b ON b.branch_code = o.branch_code LEFT JOIN delivery_tasks dt ON dt.order_code = o.order_code LEFT JOIN delivery_persons dp ON dp.person_code = dt.person_code WHERE o.order_code = ANY($1::text[]) ${branchFilter} ORDER BY o.customer_code NULLS LAST, o.order_code`, params ); const lineResult = await pool.query( `SELECT oi.order_code, oi.id AS order_item_id, oi.sku_code, COALESCE(NULLIF(TRIM(s.sku_name), ''), NULLIF(TRIM(oi.item_name), ''), oi.sku_code) AS sku_name, oi.item_name, COALESCE(NULLIF(TRIM(oi.customer_item_name), ''), NULLIF(TRIM(oi.item_name), ''), NULLIF(TRIM(s.sku_name), '')) AS customer_alias, oi.category_name, s.spec, s.origin, oi.quantity::float8 AS quantity, oi.unit, oi.price::float8 AS price, oi.amount::float8 AS amount, oi.processing_method, oi.remark, oi.supplier_code, sup.company_name AS supplier_name, pi.picked_qty::float8 AS picked_qty, pi.loaded_qty::float8 AS loaded_qty, insp.actual_qty::float8 AS inspection_actual_qty, -- 配送单称重:优先分拣重量,其次验收实收 / 实拣数量 COALESCE( NULLIF(pi.picked_weight, 0), NULLIF(insp.actual_qty, 0), NULLIF(pi.picked_qty, 0) )::float8 AS weigh_qty, CASE WHEN COALESCE( NULLIF(pi.picked_weight, 0), NULLIF(insp.actual_qty, 0), NULLIF(pi.picked_qty, 0) ) IS NOT NULL THEN COALESCE(NULLIF(TRIM(pi.unit), ''), NULLIF(TRIM(s.unit), ''), oi.unit) ELSE NULL END AS weigh_unit, COALESCE(NULLIF(TRIM(s.unit), ''), oi.unit) AS base_unit, CASE WHEN COALESCE( NULLIF(pi.picked_weight, 0), NULLIF(insp.actual_qty, 0), NULLIF(pi.picked_qty, 0) ) IS NULL THEN NULL WHEN COALESCE(NULLIF(TRIM(pi.unit), ''), NULLIF(TRIM(s.unit), ''), oi.unit) IS NOT DISTINCT FROM COALESCE(NULLIF(TRIM(s.unit), ''), oi.unit) THEN COALESCE( NULLIF(pi.picked_weight, 0), NULLIF(insp.actual_qty, 0), NULLIF(pi.picked_qty, 0) )::float8 WHEN s.unit_weight IS NOT NULL AND s.unit_weight > 0 THEN ROUND( COALESCE( NULLIF(pi.picked_weight, 0), NULLIF(insp.actual_qty, 0), NULLIF(pi.picked_qty, 0) )::numeric / s.unit_weight::numeric, 3 )::float8 ELSE COALESCE( NULLIF(pi.picked_weight, 0), NULLIF(insp.actual_qty, 0), NULLIF(pi.picked_qty, 0) )::float8 END AS weigh_qty_base, COALESCE(NULLIF(pi.loaded_qty, 0), NULLIF(pi.picked_qty, 0), insp.actual_qty, oi.quantity)::float8 AS delivery_qty, ROUND( COALESCE(NULLIF(pi.loaded_qty, 0), NULLIF(pi.picked_qty, 0), insp.actual_qty, oi.quantity)::numeric * COALESCE(oi.price, 0)::numeric, 2 )::float8 AS actual_amount, oi.box_no, oi.box_count::float8 AS box_count, COALESCE(oi.sort_order, 0) AS sort_order, COALESCE(oi.is_extra_dish, false) AS is_extra_dish, COALESCE(oi.is_returned, false) AS is_returned FROM order_items oi JOIN orders o_hdr ON o_hdr.order_code = oi.order_code LEFT JOIN skus s ON s.sku_code = oi.sku_code LEFT JOIN suppliers sup ON sup.supplier_code = oi.supplier_code LEFT JOIN picking_items pi ON pi.order_item_id = oi.id LEFT JOIN LATERAL ( SELECT cs.customer_sku_name FROM customer_skus cs WHERE cs.customer_code = o_hdr.customer_code AND cs.sku_code = oi.sku_code ORDER BY cs.usage_count DESC NULLS LAST, cs.id LIMIT 1 ) cs ON TRUE LEFT JOIN LATERAL ( SELECT i.actual_qty FROM inspections i WHERE i.order_code = oi.order_code AND i.sku_code IS NOT DISTINCT FROM oi.sku_code AND COALESCE(i.supplier_code, '') = COALESCE(oi.supplier_code, '') ORDER BY i.inspection_time DESC NULLS LAST, i.id DESC LIMIT 1 ) insp ON TRUE WHERE oi.order_code = ANY($1::text[]) ORDER BY oi.order_code, COALESCE(oi.sort_order, 0), oi.id`, [codes] ); return { orders: orderResult.rows.map((row) => ({ order_code: String(row.order_code), customer_code: row.customer_code ? String(row.customer_code) : null, company_name: row.company_name ? String(row.company_name) : null, customer_role: row.customer_role ? String(row.customer_role) : null, parent_customer_code: row.parent_customer_code ? String(row.parent_customer_code) : null, account_code: row.account_code ? String(row.account_code) : null, account_name: row.account_name ? String(row.account_name) : null, merchant_name: row.merchant_name ? String(row.merchant_name) : null, delivery_address: row.delivery_address ? String(row.delivery_address) : null, delivery_date: row.delivery_date ? String(row.delivery_date) : null, delivery_time_slot: row.delivery_time_slot ? String(row.delivery_time_slot) : null, total_amount: row.total_amount != null ? Number(row.total_amount) : null, remark: row.remark ? String(row.remark) : null, cycle_code: row.cycle_code ? String(row.cycle_code) : null, order_status: Number(row.order_status ?? 0), branch_code: row.branch_code ? String(row.branch_code) : null, branch_name: row.branch_name ? String(row.branch_name) : null, task_code: row.task_code ? String(row.task_code) : null, delivery_person: row.delivery_person ? String(row.delivery_person) : null, delivery_person_phone: row.delivery_person_phone ? String(row.delivery_person_phone) : null, })), lines: lineResult.rows.map((row) => ({ order_code: String(row.order_code), order_item_id: String(row.order_item_id), sku_code: String(row.sku_code), sku_name: String(row.sku_name || row.sku_code), item_name: row.item_name ? String(row.item_name) : null, customer_alias: row.customer_alias ? String(row.customer_alias) : null, category_name: row.category_name ? String(row.category_name) : null, spec: row.spec ? String(row.spec) : null, origin: row.origin ? String(row.origin) : null, quantity: Number(row.quantity ?? 0), unit: String(row.unit || ''), price: Number(row.price ?? 0), amount: Number(row.amount ?? 0), processing_method: row.processing_method ? String(row.processing_method) : null, remark: row.remark ? String(row.remark).trim() || null : null, supplier_code: row.supplier_code ? String(row.supplier_code) : null, supplier_name: row.supplier_name ? String(row.supplier_name) : null, picked_qty: row.picked_qty != null ? Number(row.picked_qty) : null, loaded_qty: row.loaded_qty != null ? Number(row.loaded_qty) : null, inspection_actual_qty: row.inspection_actual_qty != null ? Number(row.inspection_actual_qty) : null, weigh_qty: row.weigh_qty != null ? Number(row.weigh_qty) : null, weigh_unit: row.weigh_unit ? String(row.weigh_unit) : null, base_unit: row.base_unit ? String(row.base_unit) : null, weigh_qty_base: row.weigh_qty_base != null ? Number(row.weigh_qty_base) : null, delivery_qty: row.delivery_qty != null ? Number(row.delivery_qty) : null, actual_amount: row.actual_amount != null ? Number(row.actual_amount) : null, box_no: row.box_no ? String(row.box_no) : null, box_count: row.box_count != null ? Number(row.box_count) : null, sort_order: Number(row.sort_order ?? 0), is_extra_dish: Boolean(row.is_extra_dish), is_returned: Boolean(row.is_returned), })), }; }