Files
SupplierSystem/server/src/services/deliveryLoadingService.ts
T
Ubuntu 5d33d7010f feat(抵扣批次): 订单侧可指定抵扣批次(方案甲)—— 出库只读、分拣对应得上
开发者:「这个调整出库后就只能是看了不能改;这边如果改了抵扣的批次后,那么分拣时
分拣的批次需要对应得上(当然分拣时分拣员也能改)」。方案甲(开发者选定)。

口径(写死并测):
- 唯一落点仍是 picking_items.outbound_batches(分拣界面默认值 / 分拣出库扣库 /
  发车核货扣库 / 批次报告推送 四个消费方零改动即对上)
- 还没拣货行(开了分拣的分公司抵扣时行不存在)⇒ 先落 order_items.cover_batches
  (迁移 20261041,只加列不建表),在 4 个建行入口带进新行:
  pickingService.insertPickingItems / skipInboundLoadingService / deliveryLoadingService(两处)
- 优先级:我方指定 > 抵扣 FIFO 计划 > 先进先出现算;分拣员完成分拣即覆盖行值
- 出库后只读(409 cover_batches_locked):出库流水 / 拣货行 outbound_at / 订单 ≥50
- 保存校验:批次须属该 SKU 且在本分公司、单批 ≤ 当前可用、合计 ≤ 该行已抵扣量
- 清理联动:释放/退货/删单/换货六个入口汇到 inventoryStockCoverService.clearAutoCoverBatchPlan
  一处(连同 FIFO 计划一起清);改绑 SKU 即时清;15 分钟兜底清扫(含"指定批次已不存在")
- 读侧防御:指定批次在当前 SKU 下不存在 ⇒ 该条目不当真,退回计划/FIFO
- 顺带修既有不一致:结案补扣出库此前不按批次计划扣(纯 FIFO),现与发车扣库共用
  loadPickItemBatchPlans

真库实测(BR003,夹具跑完清理残留 0):
- PUT 200 → order_items.cover_batches 落库、GET source=manual
- 已有空拣货行 ⇒ applied_to_picking_rows=1,该行 outbound_batches 即我方指定
- 直调 materialize:applied=1、再跑 0(幂等)、无指定的行 untouched=0
- 撤销:cleared=true、cover_batches=null、行内我方条目摘掉
- 状态 50 单:GET 三行 read_only=true/order_departed、PUT 409 cover_batches_locked
- 合计超抵扣量 ⇒ 400 batch_total_exceeds_cover

测试:server/tests/orderItemCoverBatches.test.ts(14 例)、stockCoverBatchQuery.test.ts(12 例)、
OrderStockCoverBatchesModal.contract.test.ts(8 例);前端 order 相关 29 文件 193 例全绿;
前端新增文案 2 条(已获批准):orders.coverBatch.manual / orders.coverBatch.fallbackHint
2026-10-13 10:53:52 +08:00

1405 lines
52 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { PoolClient } from 'pg';
import { pool } from '../db';
import { fetchSortedOrderItemsForPicking } from './pickingRouteSortService';
import { upsertActiveReservation } from './inventoryStockCoverService';
import { isDeliveryLoadingScaleEnabled } from './pickingScaleService';
import { calcItemAmount } from './orderPricingService';
import { loadWeightUnitFactors, sumWeightInJin } from './unitConversionService';
import { upsertCustomerStatementForOrder } from './financeReconciliationService';
import { saveBase64Upload } from './storageUploadService';
import { isDeliveryLoadingPhotoRequired, isDeliveryLoadingQtyEditEnabled } from './deliveryPhotoService';
import { writeAuditLog } from './auditService';
import { attachCategoryPhotoInspectionRequirements } from './inspectionPhotoService';
import { ensureSkipInboundLoadingLines } from './skipInboundLoadingService';
import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery';
import { displayPickedMeasureForUnit, isPickingWeightUnit } from './orderItemSupplyUnitSync';
function isExtraDishFlag(value: unknown): boolean {
return value === true || value === 't' || value === 'true';
}
function sanitizeLoadingUnit(raw: unknown, fallback: string | null): string | null {
const next = String(raw ?? '').trim().slice(0, 32);
return next || fallback;
}
/** 与管理员保存订单一致:抬头总价=未退货行金额合计,总重按斤折算 */
async function refreshOrderHeaderTotals(db: PoolClient, orderCode: string) {
const code = String(orderCode || '').trim();
if (!code) return;
const weightFactors = await loadWeightUnitFactors(db);
const allItems = await db.query(
`SELECT quantity, unit FROM order_items
WHERE order_code = $1 AND COALESCE(is_returned, false) = false`,
[code]
);
const totalWeight = sumWeightInJin(allItems.rows, weightFactors);
await db.query(
`UPDATE orders o
SET total_amount = COALESCE((
SELECT ROUND(SUM(COALESCE(oi.amount, 0))::numeric, 2)
FROM order_items oi
WHERE oi.order_code = o.order_code
AND COALESCE(oi.is_returned, false) = false
), 0),
total_weight = $2,
updated_at = NOW()
WHERE o.order_code = $1`,
[code, totalWeight]
);
}
async function listExtraDishOrderItemIds(orderCode: string): Promise<Set<string>> {
const result = await pool.query(
`SELECT id::text AS id
FROM order_items
WHERE order_code = $1 AND COALESCE(is_extra_dish, false) = true`,
[orderCode]
);
return new Set(result.rows.map((row) => String(row.id)));
}
export interface DeliveryLoadingItem {
id: string;
pick_code: string;
sku_code: string | null;
item_name: string | null;
required_qty: number;
loaded_qty: number;
picked_weight: number;
unit: string | null;
/** 订单计划单位,应配展示用;实配单位为 unit */
required_unit: string | null;
barcode: string | null;
loaded_done: boolean;
/** 分拣已称重时配送员不可改 */
weigh_locked: boolean;
/** 配送员可补录称重(权限开且未锁定) */
weigh_editable: boolean;
/** 商品信息分类名(SKU→categories,可含「父 / 子」) */
category_name: string | null;
/** 一级分类(与配送单 resolveTopCategory 一致) */
category_top: string;
/** 按配送单序重排后的序号(1-based) */
seq_no: number;
/** 入库验收已有有效照片 */
has_inbound_photo: boolean;
/** 直送必拍;已入库则分类要拍且无验收照才补拍 */
needs_loading_photo: boolean;
/** 已补拍张数 */
loading_photo_count: number;
/** 配送中加菜:司机自买,仍须核货 */
is_extra_dish: boolean;
skip_inbound: boolean;
/** 勾选「核货改实配」且未发车:可改实配(单位只读) */
qty_editable: boolean;
}
export function loadingPhotosSatisfied(
items: Array<{
needs_loading_photo: boolean;
loading_photo_count: number;
skip_inbound?: boolean;
is_extra_dish?: boolean;
}>,
rolePhotoRequired: boolean
): boolean {
return items.every((item) => {
if (!item.needs_loading_photo || item.loading_photo_count >= 1) return true;
if (item.skip_inbound || item.is_extra_dish) return false;
return !rolePhotoRequired;
});
}
/** 加菜须核货照 + 已记上货后才能拍照送达 / 结束配送 */
export function extraDishPhotosSatisfied(
items: Array<{
is_extra_dish?: boolean;
loaded_done?: boolean;
loading_photo_count?: number;
}>
): boolean {
return items.every((item) => {
if (!item.is_extra_dish) return true;
return Boolean(item.loaded_done) && Number(item.loading_photo_count || 0) >= 1;
});
}
/** 同一订单 + 订单明细(SKU,否则品名)是否已有入库验收照 */
export function inboundInspectionPhotoExistsSql(aliases: {
orderCode: string;
orderItemId: string;
sku: string;
itemName: string;
}): string {
return `EXISTS (
SELECT 1 FROM inspections i
WHERE i.order_code = ${aliases.orderCode}
AND i.inspection_time IS NOT NULL
AND COALESCE(array_length(i.inspection_photos, 1), 0) > 0
AND (
(
${aliases.orderItemId} IS NOT NULL
AND EXISTS (
SELECT 1 FROM order_items oim
WHERE oim.id = ${aliases.orderItemId}
AND oim.order_code = i.order_code
AND (
(
NULLIF(TRIM(oim.sku_code), '') IS NOT NULL
AND i.sku_code IS NOT DISTINCT FROM oim.sku_code
)
OR (
NULLIF(TRIM(oim.sku_code), '') IS NULL
AND TRIM(COALESCE(i.item_name, '')) = TRIM(COALESCE(oim.item_name, ''))
)
)
)
)
OR (
${aliases.orderItemId} IS NULL
AND (
(
NULLIF(TRIM(${aliases.sku}), '') IS NOT NULL
AND i.sku_code IS NOT DISTINCT FROM ${aliases.sku}
)
OR TRIM(COALESCE(i.item_name, '')) = TRIM(COALESCE(${aliases.itemName}, ''))
)
)
)
)`;
}
/** 与 Web 配送单 sortLinesByCategory 一致:一级分类名 → 品名(zh-CN) */
function resolveTopCategory(category?: string | null): string {
const raw = String(category || '').trim();
if (!raw) return '未分类';
const top = raw.split(/\s*[//]\s*/)[0]?.trim();
return top || raw;
}
function sortLoadingItemsLikeDeliveryNote<T extends { category_name?: string | null; item_name?: string | null }>(
items: T[]
): T[] {
return [...items].sort((a, b) => {
const cat = resolveTopCategory(a.category_name).localeCompare(
resolveTopCategory(b.category_name),
'zh-CN'
);
if (cat !== 0) return cat;
return String(a.item_name || '').localeCompare(String(b.item_name || ''), 'zh-CN');
});
}
async function assertDeliveryPersonTask(taskCode: string, personCode: string) {
const taskResult = await pool.query(
`SELECT task_code, order_code, person_code, task_status, loading_completed_at, branch_code
FROM delivery_tasks WHERE task_code = $1 LIMIT 1`,
[taskCode]
);
const task = taskResult.rows[0];
if (!task) {
throw Object.assign(new Error('配送任务不存在'), { status: 404, code: 'not_found' });
}
if (task.person_code && task.person_code !== personCode) {
throw Object.assign(new Error('无权操作该配送任务'), { status: 403, code: 'forbidden' });
}
return task as {
task_code: string;
order_code: string;
person_code: string | null;
task_status: number;
loading_completed_at: string | null;
branch_code: string | null;
};
}
function newPickCode() {
return `PK${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
}
/** 配送核货明细:无仓管分拣任务时,从订单明细补建(跳过分拣的分公司也适用) */
async function ensureDeliveryLoadingPickTask(orderCode: string): Promise<string> {
const statusRes = await pool.query(`SELECT order_status FROM orders WHERE order_code = $1`, [orderCode]);
const orderStatus = Number(statusRes.rows[0]?.order_status) || 0;
if (orderStatus < 50) {
await ensureSkipInboundLoadingLines(orderCode);
const skipPick = await pool.query(
`SELECT pi.pick_code
FROM picking_items pi
JOIN order_items oi ON oi.id = pi.order_item_id
JOIN suppliers s ON s.supplier_code = oi.supplier_code AND COALESCE(s.skip_inbound, false) = true
LEFT JOIN skus sku ON sku.sku_code = oi.sku_code
WHERE pi.order_code = $1
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
ORDER BY pi.created_at DESC
LIMIT 1`,
[orderCode]
);
if (skipPick.rows[0]?.pick_code) return String(skipPick.rows[0].pick_code);
}
const fromItems = await pool.query(
`SELECT pi.pick_code
FROM picking_items pi
LEFT JOIN picking_tasks pt ON pt.pick_code = pi.pick_code
WHERE pi.order_code = $1
ORDER BY pt.created_at DESC NULLS LAST, pi.created_at DESC
LIMIT 1`,
[orderCode]
);
if (fromItems.rows[0]?.pick_code) {
return String(fromItems.rows[0].pick_code);
}
const existing = await pool.query(
`SELECT pt.pick_code,
(SELECT COUNT(*)::int FROM picking_items pi WHERE pi.pick_code = pt.pick_code) AS item_count
FROM picking_tasks pt
WHERE pt.order_code = $1
ORDER BY CASE
WHEN (SELECT COUNT(*) FROM picking_items pi WHERE pi.pick_code = pt.pick_code) > 0 THEN 0
ELSE 1
END,
pt.created_at DESC
LIMIT 1`,
[orderCode]
);
const row = existing.rows[0];
if (row?.pick_code && Number(row.item_count) > 0) {
return String(row.pick_code);
}
const orderResult = await pool.query(`SELECT branch_code FROM orders WHERE order_code = $1`, [orderCode]);
const branchCode = orderResult.rows[0]?.branch_code || null;
const extraIds = await listExtraDishOrderItemIds(orderCode);
const items = (await fetchSortedOrderItemsForPicking(orderCode)).filter(
(item) => !extraIds.has(String(item.id))
);
if (row?.pick_code && !items.length) {
return String(row.pick_code);
}
if (!items.length) {
// 全是加菜、且没有可复用的分拣单:不新建空任务(避免变成「最新单」把原分拣行藏掉)
if (row?.pick_code) return String(row.pick_code);
const pickCode = newPickCode();
await pool.query(
`INSERT INTO picking_tasks (pick_code, order_code, warehouse_code, pick_status, branch_code)
VALUES ($1, $2, NULL, 40, $3)`,
[pickCode, orderCode, branchCode]
);
return pickCode;
}
const client = await pool.connect();
try {
await client.query('BEGIN');
const pickCode = row?.pick_code ? String(row.pick_code) : newPickCode();
if (!row?.pick_code) {
await client.query(
`INSERT INTO picking_tasks (pick_code, order_code, warehouse_code, pick_status, branch_code)
VALUES ($1, $2, NULL, 40, $3)`,
[pickCode, orderCode, branchCode]
);
} else {
await client.query(`DELETE FROM picking_items WHERE pick_code = $1`, [pickCode]);
}
const insertedIds: string[] = [];
for (let sortIdx = 0; sortIdx < items.length; sortIdx += 1) {
const item = items[sortIdx];
const inserted = await client.query(
`INSERT INTO picking_items (
pick_code, order_item_id, order_code, sku_code, item_name, required_qty, picked_qty,
loaded_qty, unit, review_status, branch_code, sort_order
) VALUES ($1, $2, $3, $4, $5, $6, $6, 0, $7, 30, $8, $9)
RETURNING id::text AS id`,
[
pickCode,
item.id,
item.order_code,
item.sku_code,
item.item_name || item.sku_code,
Number(item.quantity) || 0,
item.unit,
item.branch_code || branchCode,
sortIdx + 1,
]
);
const insertedId = (inserted.rows as Array<{ id?: string }>)[0]?.id;
if (insertedId) insertedIds.push(String(insertedId));
}
// 「我方指定的抵扣批次」随建行带进新行(2026-10-13 方案甲);幂等:只填空行
if (insertedIds.length) {
try {
const { materializeCoverBatchesForPickingRows } = await import(
'./orderItemCoverBatchesService'
);
await materializeCoverBatchesForPickingRows(client, { pickItemIds: insertedIds });
} catch (error: unknown) {
console.error(
'[delivery-loading] 带入我方指定抵扣批次失败(不影响建行):',
(error as Error)?.message || error
);
}
}
await client.query('COMMIT');
return pickCode;
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
const LOADING_ITEMS_SQL = `
SELECT pi.id, pi.pick_code, pi.item_name, pi.required_qty, pi.loaded_qty, pi.picked_qty, pi.picked_weight, pi.unit,
COALESCE(NULLIF(TRIM(oi.unit), ''), pi.unit) AS required_unit,
COALESCE(
NULLIF(TRIM(pi.sku_code), ''),
NULLIF(TRIM(oi.sku_code), ''),
NULLIF(TRIM(catalog.code), '')
) AS sku_code,
COALESCE(
NULLIF(TRIM(s.barcode), ''),
NULLIF(TRIM(catalog.barcode), ''),
NULLIF(TRIM(s.sku_code), ''),
NULLIF(TRIM(pi.sku_code), ''),
NULLIF(TRIM(oi.sku_code), ''),
NULLIF(TRIM(catalog.code), '')
) AS barcode,
COALESCE(
NULLIF(TRIM(oi.category_name), ''),
NULLIF(TRIM(oi_fb.category_name), ''),
NULLIF(TRIM(cat.category_name), '')
) AS category_name,
COALESCE(
NULLIF(TRIM(oi.category_code), ''),
NULLIF(TRIM(oi_fb.category_code), ''),
NULLIF(TRIM(s.category_code), ''),
NULLIF(TRIM(catalog.parent_code), '')
) AS category_code,
COALESCE(oi.branch_code, oi_fb.branch_code, pi.branch_code) AS branch_code,
${inboundInspectionPhotoExistsSql({
orderCode: 'pi.order_code',
orderItemId: 'pi.order_item_id',
sku: 'pi.sku_code',
itemName: 'pi.item_name',
})} AS has_inbound_photo,
COALESCE(array_length(pi.loading_photos, 1), 0) AS loading_photo_count,
COALESCE(skip_sup.skip_inbound, false) AS skip_inbound,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN LATERAL (
-- 无 order_item_id 时按订单+SKU 回找明细快照
SELECT oi2.category_name, oi2.category_code, oi2.branch_code
FROM order_items oi2
WHERE pi.order_item_id IS NULL
AND oi2.order_code = pi.order_code
AND (
oi2.sku_code IS NOT DISTINCT FROM pi.sku_code
OR (pi.sku_code IS NULL AND TRIM(oi2.item_name) = TRIM(pi.item_name))
)
ORDER BY oi2.id DESC
LIMIT 1
) oi_fb ON TRUE
LEFT JOIN product_catalog catalog ON catalog.item_type = 'product' AND (
catalog.code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
OR (
COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), '')) IS NULL
AND TRIM(catalog.name) = TRIM(pi.item_name)
)
)
LEFT JOIN skus s ON s.sku_code = COALESCE(
NULLIF(TRIM(pi.sku_code), ''),
NULLIF(TRIM(oi.sku_code), ''),
catalog.code
)
LEFT JOIN LATERAL (
SELECT CASE
WHEN NULLIF(TRIM(parent.category_name), '') IS NOT NULL
THEN parent.category_name || ' / ' || c.category_name
ELSE c.category_name
END AS category_name
FROM categories c
LEFT JOIN categories parent
ON parent.category_code = c.parent_code
AND parent.branch_code = c.branch_code
WHERE c.category_code = COALESCE(
NULLIF(TRIM(oi.category_code), ''),
NULLIF(TRIM(oi_fb.category_code), ''),
NULLIF(TRIM(s.category_code), ''),
NULLIF(TRIM(catalog.parent_code), '')
)
ORDER BY CASE
WHEN c.branch_code IS NOT DISTINCT FROM COALESCE(oi.branch_code, oi_fb.branch_code, pi.branch_code) THEN 0
ELSE 1
END
LIMIT 1
) cat ON TRUE
LEFT JOIN suppliers skip_sup ON skip_sup.supplier_code = oi.supplier_code
WHERE pi.order_code = $1
AND COALESCE(oi.is_returned, false) = false
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
`;
function mapLoadingItem(
row: Record<string, unknown>,
seqNo: number,
deliveryScaleEnabled: boolean,
qtyEditEnabled: boolean
): DeliveryLoadingItem {
const required = Number(row.required_qty) || 0;
const loaded = Number(row.loaded_qty) || 0;
const pickedQty = Number(row.picked_qty) || 0;
const pickedWeight = Number(row.picked_weight) || 0;
const unit = row.unit ? String(row.unit) : null;
const displayPicked = displayPickedMeasureForUnit(unit, pickedQty, pickedWeight);
const weighLocked = isPickingWeightUnit(unit) ? pickedWeight > 0 : displayPicked > 0;
const categoryName = row.category_name ? String(row.category_name) : null;
const hasInboundPhoto =
row.has_inbound_photo === true || row.has_inbound_photo === 't' || row.has_inbound_photo === 'true';
const loadingPhotoCount = Number(row.loading_photo_count) || 0;
const skipInbound =
row.skip_inbound === true || row.skip_inbound === 't' || row.skip_inbound === 'true';
const extraDish = isExtraDishFlag(row.is_extra_dish);
const categoryRequiresPhoto =
row.requires_photo_inspection !== false && row.requires_photo_inspection !== 'f';
return {
id: String(row.id),
pick_code: String(row.pick_code),
sku_code: row.sku_code ? String(row.sku_code) : null,
item_name: row.item_name ? String(row.item_name) : null,
required_qty: required,
loaded_qty: loaded,
picked_weight: displayPicked,
unit: row.unit ? String(row.unit) : null,
required_unit: row.required_unit ? String(row.required_unit) : row.unit ? String(row.unit) : null,
barcode: row.barcode ? String(row.barcode) : null,
loaded_done: required <= 0 || loaded > 0,
weigh_locked: qtyEditEnabled ? false : weighLocked,
weigh_editable:
skipInbound && deliveryScaleEnabled && !weighLocked && !qtyEditEnabled,
category_name: categoryName,
category_top: resolveTopCategory(categoryName),
seq_no: seqNo,
has_inbound_photo: hasInboundPhoto,
needs_loading_photo: skipInbound || extraDish || (categoryRequiresPhoto && !hasInboundPhoto),
loading_photo_count: loadingPhotoCount,
skip_inbound: skipInbound,
qty_editable: skipInbound || qtyEditEnabled,
is_extra_dish: extraDish,
};
}
const MISSING_NON_EXTRA_LOADING_SQL = `
SELECT oi.id::text AS id,
$2::text AS pick_code,
oi.item_name,
COALESCE(oi.quantity, 0)::float AS required_qty,
0::float AS loaded_qty,
0::float AS picked_qty,
0::float AS picked_weight,
oi.unit,
oi.unit AS required_unit,
COALESCE(NULLIF(TRIM(oi.sku_code), ''), NULLIF(TRIM(catalog.code), '')) AS sku_code,
COALESCE(
NULLIF(TRIM(s.barcode), ''),
NULLIF(TRIM(catalog.barcode), ''),
NULLIF(TRIM(s.sku_code), ''),
NULLIF(TRIM(oi.sku_code), ''),
NULLIF(TRIM(catalog.code), '')
) AS barcode,
COALESCE(NULLIF(TRIM(oi.category_name), ''), NULLIF(TRIM(cat.category_name), '')) AS category_name,
COALESCE(NULLIF(TRIM(oi.category_code), ''), NULLIF(TRIM(s.category_code), ''), catalog.parent_code) AS category_code,
oi.branch_code,
${inboundInspectionPhotoExistsSql({
orderCode: 'oi.order_code',
orderItemId: 'oi.id',
sku: 'oi.sku_code',
itemName: 'oi.item_name',
})} AS has_inbound_photo,
0::int AS loading_photo_count,
COALESCE(skip_sup.skip_inbound, false) AS skip_inbound,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish
FROM order_items oi
LEFT JOIN product_catalog catalog ON catalog.item_type = 'product' AND (
catalog.code = NULLIF(TRIM(oi.sku_code), '')
OR (NULLIF(TRIM(oi.sku_code), '') IS NULL AND TRIM(catalog.name) = TRIM(oi.item_name))
)
LEFT JOIN skus s ON s.sku_code = COALESCE(NULLIF(TRIM(oi.sku_code), ''), catalog.code)
LEFT JOIN suppliers skip_sup ON skip_sup.supplier_code = oi.supplier_code
LEFT JOIN LATERAL (
SELECT CASE
WHEN NULLIF(TRIM(parent.category_name), '') IS NOT NULL
THEN parent.category_name || ' / ' || c.category_name
ELSE c.category_name
END AS category_name
FROM categories c
LEFT JOIN categories parent
ON parent.category_code = c.parent_code
AND parent.branch_code = c.branch_code
WHERE c.category_code = COALESCE(NULLIF(TRIM(oi.category_code), ''), NULLIF(TRIM(s.category_code), ''), catalog.parent_code)
ORDER BY CASE
WHEN c.branch_code IS NOT DISTINCT FROM oi.branch_code THEN 0
ELSE 1
END
LIMIT 1
) cat ON TRUE
WHERE oi.order_code = $1
AND COALESCE(oi.is_returned, false) = false
AND NOT EXISTS (
SELECT 1 FROM picking_items pi WHERE pi.order_item_id = oi.id
)
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
`;
async function listLoadingItems(orderCode: string, anchorPickCode: string, orderStatus = 50) {
const deliveryScaleEnabled = await isDeliveryLoadingScaleEnabled();
const qtyEditEnabled = await isDeliveryLoadingQtyEditEnabled();
const earlySkipOnly = orderStatus < 50;
const [picked, missing] = await Promise.all([
pool.query(
earlySkipOnly ? `${LOADING_ITEMS_SQL} AND COALESCE(skip_sup.skip_inbound, false) = true` : LOADING_ITEMS_SQL,
[orderCode]
),
earlySkipOnly
? Promise.resolve({ rows: [] as Record<string, unknown>[] })
: pool.query(MISSING_NON_EXTRA_LOADING_SQL, [orderCode, anchorPickCode]),
]);
const sorted = sortLoadingItemsLikeDeliveryNote(
[...picked.rows, ...missing.rows].map((row) => ({
...row,
category_name: row.category_name ? String(row.category_name) : null,
item_name: row.item_name ? String(row.item_name) : null,
}))
);
const withCategoryPhoto = await attachCategoryPhotoInspectionRequirements(
sorted.map((row) => ({
...row,
branch_code: row.branch_code ? String(row.branch_code) : null,
category_code: row.category_code ? String(row.category_code) : null,
sku_code: row.sku_code ? String(row.sku_code) : null,
}))
);
return {
items: withCategoryPhoto.map((row, idx) =>
mapLoadingItem(row, idx + 1, deliveryScaleEnabled, qtyEditEnabled)
),
picking_scale_enabled: deliveryScaleEnabled,
};
}
async function markLoadingCompleteIfReady(
taskCode: string,
orderCode: string,
anchorPickCode: string,
orderStatus = 50
) {
const { items } = await listLoadingItems(orderCode, anchorPickCode, orderStatus);
const allLoaded = items.length > 0 && items.every((item) => item.loaded_done);
if (allLoaded) {
await pool.query(
`UPDATE delivery_tasks SET loading_completed_at = COALESCE(loading_completed_at, NOW()) WHERE task_code = $1`,
[taskCode]
);
} else {
await pool.query(
`UPDATE delivery_tasks
SET loading_completed_at = NULL
WHERE task_code = $1 AND COALESCE(task_status, 0) < 20`,
[taskCode]
);
}
return allLoaded;
}
export async function getDeliveryLoadingState(taskCode: string, personCode: string) {
const task = await assertDeliveryPersonTask(taskCode, personCode);
return buildDeliveryLoadingState(task);
}
/** Web 配送管理只读查看核货明细;权限与分公司范围由路由层校验。 */
export async function getDeliveryLoadingStateForManagement(taskCode: string) {
const taskResult = await pool.query(
`SELECT task_code, order_code, person_code, task_status, loading_completed_at
FROM delivery_tasks WHERE task_code = $1 LIMIT 1`,
[taskCode]
);
const task = taskResult.rows[0];
if (!task) {
throw Object.assign(new Error('配送任务不存在'), { status: 404, code: 'not_found' });
}
return buildDeliveryLoadingState(task);
}
async function buildDeliveryLoadingState(task: {
task_code: string;
order_code: string;
task_status: number;
loading_completed_at: string | null;
}) {
const orderCode = String(task.order_code);
const orderRow = await pool.query(`SELECT order_status FROM orders WHERE order_code = $1`, [orderCode]);
const orderStatus = Number(orderRow.rows[0]?.order_status) || 0;
const pickCode = await ensureDeliveryLoadingPickTask(orderCode);
const { items, picking_scale_enabled } = await listLoadingItems(orderCode, pickCode, orderStatus);
const loadedCount = items.filter((item) => item.loaded_done).length;
const allLoaded = loadedCount === items.length && items.length > 0;
const loadingPhotoRequired = await isDeliveryLoadingPhotoRequired();
const loadingQtyEditEnabled = await isDeliveryLoadingQtyEditEnabled();
const skipInboundPhotoDuty = items.some(
(item) => (item.skip_inbound || item.is_extra_dish) && item.needs_loading_photo
);
const effectivePhotoRequired = loadingPhotoRequired || skipInboundPhotoDuty;
const photosOk = loadingPhotosSatisfied(items, loadingPhotoRequired);
const extraDishPhotosOk = extraDishPhotosSatisfied(items);
return {
task_code: task.task_code,
order_code: task.order_code,
pick_code: pickCode,
task_status: Number(task.task_status),
loading_completed_at: task.loading_completed_at,
items,
loaded_count: loadedCount,
total_count: items.length,
all_loaded: allLoaded,
loading_photo_required: effectivePhotoRequired,
loading_qty_edit_enabled: loadingQtyEditEnabled,
can_start_delivery:
allLoaded && photosOk && Number(task.task_status) < 20 && orderStatus >= 50,
can_sign_delivery: extraDishPhotosOk,
picking_scale_enabled,
order_status: orderStatus,
};
}
type ConfirmPickRow = {
id: string;
order_item_id: string | null;
required_qty: number | string;
loaded_qty?: number | string;
picked_qty: number | string;
picked_weight: number | string | null;
unit: string | null;
sku_code: string | null;
item_name?: string | null;
order_item_name?: string | null;
order_code: string | null;
branch_code: string | null;
ordered_quantity: unknown;
order_sku: string | null;
order_unit?: string | null;
order_quantity?: number | string | null;
order_amount?: number | string | null;
order_price?: number | string | null;
order_locked_price?: number | string | null;
unit_cost?: number | string | null;
is_extra_dish?: unknown;
skip_inbound?: unknown;
};
const CONFIRM_PICK_SELECT = `
SELECT pi.id, pi.order_item_id, pi.required_qty, pi.loaded_qty, pi.picked_qty, pi.picked_weight, pi.unit, pi.sku_code,
pi.item_name, pi.order_code, pi.branch_code,
oi.ordered_quantity, oi.sku_code AS order_sku, oi.unit AS order_unit, oi.item_name AS order_item_name,
oi.quantity AS order_quantity, oi.amount AS order_amount, oi.price AS order_price, oi.locked_price AS order_locked_price,
oi.is_extra_dish, oi.unit_cost,
COALESCE(skip_sup.skip_inbound, false) AS skip_inbound
`;
const CONFIRM_PICK_FROM = `
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN suppliers skip_sup ON skip_sup.supplier_code = oi.supplier_code
`;
async function resolveOrCreatePickingItemForLoading(
client: PoolClient,
pickCode: string,
orderCode: string,
itemId: string
): Promise<ConfirmPickRow> {
const byPiId = await client.query(
`${CONFIRM_PICK_SELECT}
${CONFIRM_PICK_FROM}
WHERE pi.id = $1::uuid AND pi.order_code = $2
LIMIT 1`,
[itemId, orderCode]
);
if (byPiId.rows[0]) {
return byPiId.rows[0] as ConfirmPickRow;
}
const byOiOnPick = await client.query(
`${CONFIRM_PICK_SELECT}
${CONFIRM_PICK_FROM}
WHERE pi.order_code = $1 AND pi.order_item_id = $2::uuid
LIMIT 1`,
[orderCode, itemId]
);
if (byOiOnPick.rows[0]) {
return byOiOnPick.rows[0] as ConfirmPickRow;
}
const orderItem = await client.query(
`SELECT oi.id, oi.order_code, oi.sku_code, oi.item_name, oi.quantity, oi.unit, oi.branch_code,
oi.ordered_quantity, COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
COALESCE(oi.is_returned, false) AS is_returned
FROM order_items oi
WHERE oi.id = $1::uuid AND oi.order_code = $2
LIMIT 1`,
[itemId, orderCode]
);
const oi = orderItem.rows[0];
if (!oi) {
throw Object.assign(new Error('商品不在本配送单中'), { status: 404, code: 'not_found' });
}
if (oi.is_returned === true || oi.is_returned === 't' || oi.is_returned === 'true') {
throw Object.assign(new Error('退货商品无需配送员核货'), { status: 400, code: 'returned' });
}
const existingAny = await client.query(
`${CONFIRM_PICK_SELECT}
${CONFIRM_PICK_FROM}
WHERE pi.order_item_id = $1::uuid
ORDER BY pi.created_at DESC
LIMIT 1`,
[oi.id]
);
if (existingAny.rows[0]) {
return existingAny.rows[0] as ConfirmPickRow;
}
const sort = await client.query(
`SELECT COALESCE(MAX(sort_order), 0)::int AS m FROM picking_items WHERE pick_code = $1`,
[pickCode]
);
const requiredQty = Number(oi.quantity) || 0;
const inserted = await client.query(
`INSERT INTO picking_items (
pick_code, order_item_id, order_code, sku_code, item_name, required_qty, picked_qty,
loaded_qty, unit, review_status, branch_code, sort_order
) VALUES ($1, $2, $3, $4, $5, $6, 0, 0, $7, 30, $8, $9)
RETURNING id, order_item_id, required_qty, picked_qty, picked_weight, unit, sku_code, order_code, branch_code`,
[
pickCode,
oi.id,
oi.order_code,
oi.sku_code,
oi.item_name || oi.sku_code,
requiredQty,
oi.unit,
oi.branch_code,
Number(sort.rows[0]?.m || 0) + 1,
]
);
const insertedId = (inserted.rows[0] as { id?: string } | undefined)?.id;
// 「我方指定的抵扣批次」随建行带进新行(2026-10-13 方案甲);幂等:只填空行
if (insertedId) {
try {
const { materializeCoverBatchesForPickingRows } = await import(
'./orderItemCoverBatchesService'
);
await materializeCoverBatchesForPickingRows(client, { pickItemIds: [String(insertedId)] });
} catch (error: unknown) {
console.error(
'[delivery-loading] 带入我方指定抵扣批次失败(不影响建行):',
(error as Error)?.message || error
);
}
}
return {
...(inserted.rows[0] as ConfirmPickRow),
ordered_quantity: oi.ordered_quantity,
order_sku: oi.sku_code,
order_unit: oi.unit,
};
}
export async function confirmDeliveryLoadingItem(input: {
taskCode: string;
personCode: string;
itemId: string;
/** 勾选核货改实配后生效;未勾选忽略 */
loadedQty?: number | null;
/** 勾选核货改实配后写入 picking_items.unit;未勾选忽略 */
unit?: string | null;
/** 配送员补录称重(仅分拣未称且角色勾选称重时;有核货改实配时用 loadedQty 覆盖) */
pickedWeight?: number | null;
operatorId?: string | null;
}) {
const task = await assertDeliveryPersonTask(input.taskCode, input.personCode);
const pickCode = await ensureDeliveryLoadingPickTask(String(task.order_code));
const qtyEditEnabled = await isDeliveryLoadingQtyEditEnabled();
let canEditQty = qtyEditEnabled;
let requiredQty = 0;
let nextLoaded = 0;
let nextWeight: number | null = null;
let existingWeight = 0;
let existingLoaded = 0;
let skipInbound = false;
let resolvedId = input.itemId;
let auditOrderItemId: string | null = null;
let auditUnit: string | null = null;
let existingAuditUnit: string | null = null;
let auditSku = '';
let auditItemName = '';
let qtyEdited = false;
let existingOrderQty = 0;
let existingOrderAmount = 0;
let nextOrderAmount = 0;
const client = await pool.connect();
try {
await client.query('BEGIN');
let item: ConfirmPickRow;
try {
item = await resolveOrCreatePickingItemForLoading(
client,
pickCode,
String(task.order_code),
input.itemId
);
} catch (error) {
const code = (error as { code?: string }).code;
if (code === '22P02') {
throw Object.assign(new Error('商品不在本配送单中'), { status: 404, code: 'not_found' });
}
throw error;
}
if (Number(task.task_status) >= 20 && !isExtraDishFlag(item.is_extra_dish)) {
throw Object.assign(new Error('配送已开始,无法继续核货'), { status: 400, code: 'invalid_state' });
}
resolvedId = String(item.id);
skipInbound = isExtraDishFlag(item.skip_inbound);
canEditQty = qtyEditEnabled || skipInbound;
requiredQty = Number(item.required_qty) || 0;
existingLoaded = Number(item.loaded_qty) || 0;
existingWeight = Number(item.picked_weight) || 0;
const existingUnit = item.unit ? String(item.unit) : null;
let nextUnit = existingUnit;
auditOrderItemId = item.order_item_id ? String(item.order_item_id) : null;
auditSku = String(item.sku_code || item.order_sku || '').trim();
auditItemName = String(item.item_name || item.order_item_name || '').trim();
if (canEditQty) {
const requestedQty =
input.loadedQty != null && Number.isFinite(Number(input.loadedQty))
? Number(input.loadedQty)
: existingLoaded > 0
? existingLoaded
: requiredQty;
if (!(requestedQty > 0)) {
throw Object.assign(new Error('实配数量须大于 0'), { status: 400, code: 'invalid_qty' });
}
nextLoaded = Math.round(requestedQty * 1000) / 1000;
nextUnit = sanitizeLoadingUnit(input.unit, existingUnit);
qtyEdited =
Math.abs(nextLoaded - existingLoaded) > 1e-6 ||
String(nextUnit || '') !== String(existingUnit || '');
existingAuditUnit = existingUnit;
auditUnit = nextUnit;
} else {
nextLoaded = requiredQty > 0 ? Math.round(requiredQty * 100) / 100 : 0;
if (input.pickedWeight != null && Number(input.pickedWeight) > 0) {
if (!skipInbound && !(await isDeliveryLoadingScaleEnabled())) {
throw Object.assign(new Error('未开通配送称重权限'), { status: 403, code: 'forbidden' });
}
if (existingWeight > 0) {
throw Object.assign(new Error('分拣已称重,配送不可修改'), { status: 400, code: 'weigh_locked' });
}
nextWeight = Math.round(Number(input.pickedWeight) * 1000) / 1000;
}
}
const nextPicked = Math.max(Number(item.picked_qty) || 0, nextLoaded);
await client.query(
`UPDATE picking_items
SET loaded_qty = $2::numeric,
picked_qty = CASE WHEN $3::numeric > picked_qty THEN $3::numeric ELSE picked_qty END,
picked_weight = CASE
WHEN $5::boolean THEN picked_weight
WHEN $4::numeric IS NOT NULL AND COALESCE(picked_weight, 0) <= 0 THEN $4::numeric
ELSE picked_weight
END,
unit = CASE WHEN $5::boolean THEN COALESCE($6, unit) ELSE unit END
WHERE id = $1`,
[item.id, nextLoaded, nextPicked, nextWeight, canEditQty, nextUnit]
);
const skuCode = String(item.sku_code || item.order_sku || '').trim();
const orderCode = String(item.order_code || task.order_code || '').trim();
if (item.order_item_id && skuCode && orderCode && nextLoaded > 0) {
await upsertActiveReservation(client, {
orderItemId: String(item.order_item_id),
orderCode,
skuCode,
branchCode: item.branch_code ? String(item.branch_code) : null,
qty: nextLoaded,
});
}
const effectiveWeight = nextWeight != null && nextWeight > 0 ? nextWeight : existingWeight;
// 核货改实配:新口径只写 picking_items.loaded_qty,订单 quantity 始终保留计划量。
// delivery_qty 在订单结案事务内统一冻结,避免配送员核货过程中反复改写订单计划。
if (canEditQty && item.order_item_id) {
existingOrderQty = Number(item.order_quantity) || 0;
existingOrderAmount = Number(item.order_amount) || 0;
const salePrice =
Number(item.order_locked_price) > 0
? Number(item.order_locked_price)
: Number(item.order_price) || 0;
nextOrderAmount = calcItemAmount(nextLoaded, salePrice);
const orderUnit = item.order_unit ? String(item.order_unit).trim() : '';
const unitChanged = Boolean(nextUnit && String(nextUnit).trim() !== orderUnit);
const qtyChangedOnOrder = Math.abs(nextLoaded - existingOrderQty) > 1e-6;
void qtyChangedOnOrder;
void unitChanged;
}
// 分拣称重也只保存在 picking_items;订单计划量不在核货阶段被覆盖。
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
if (qtyEdited) {
try {
await writeAuditLog({
operatorId: input.operatorId || null,
operatorRole: 'delivery',
operationType: 'delivery_loading_qty_edit',
targetTable: 'picking_items',
targetId: resolvedId,
actionCategory: 'delivery',
branchCode: task.branch_code ? String(task.branch_code) : null,
oldValue: {
loaded_qty: existingLoaded,
quantity: existingOrderQty,
amount: existingOrderAmount,
picked_weight: existingWeight,
unit: existingAuditUnit,
skip_inbound: skipInbound,
required_qty: requiredQty,
item_name: auditItemName || null,
},
newValue: {
loaded_qty: nextLoaded,
quantity: nextLoaded,
amount: nextOrderAmount,
picked_weight: nextWeight != null ? nextWeight : existingWeight,
unit: auditUnit,
skip_inbound: skipInbound,
order_code: task.order_code,
order_item_id: auditOrderItemId,
sku_code: auditSku,
item_name: auditItemName || null,
required_qty: requiredQty,
task_code: input.taskCode,
},
});
} catch (err) {
console.error('[delivery-loading] 实配审计写入失败', err);
}
}
const orderStatusRow = await pool.query(
`SELECT order_status FROM orders WHERE order_code = $1`,
[task.order_code]
);
const orderStatus = Number(orderStatusRow.rows[0]?.order_status) || 0;
const allLoaded = await markLoadingCompleteIfReady(
input.taskCode,
String(task.order_code),
pickCode,
orderStatus
);
const { items } = await listLoadingItems(String(task.order_code), pickCode, orderStatus);
const loadedCount = items.filter((row) => row.loaded_done).length;
return {
item_id: resolvedId,
loaded_qty: nextLoaded,
required_qty: requiredQty,
picked_weight: nextWeight != null ? nextWeight : existingWeight,
loaded_count: loadedCount,
total_count: items.length,
all_loaded: allLoaded,
can_start_delivery:
allLoaded &&
loadingPhotosSatisfied(items, await isDeliveryLoadingPhotoRequired()) &&
orderStatus >= 50 &&
Number(task.task_status) < 20,
};
}
export const MAX_LOADING_PHOTOS = 1;
export async function uploadDeliveryLoadingPhoto(input: {
taskCode: string;
personCode: string;
itemId: string;
content: string;
ext?: string;
}) {
const content = String(input.content || '').trim();
if (!content) {
throw Object.assign(new Error('缺少照片内容'), { status: 400, code: 'invalid_request' });
}
const task = await assertDeliveryPersonTask(input.taskCode, input.personCode);
const pickCode = await ensureDeliveryLoadingPickTask(String(task.order_code));
const client = await pool.connect();
let item: ConfirmPickRow;
try {
item = await resolveOrCreatePickingItemForLoading(
client,
pickCode,
String(task.order_code),
input.itemId
);
if (Number(task.task_status) >= 20 && !isExtraDishFlag(item.is_extra_dish)) {
throw Object.assign(new Error('配送已开始,无法补拍'), { status: 400, code: 'invalid_state' });
}
const inbound = await client.query(
`SELECT ${inboundInspectionPhotoExistsSql({
orderCode: 'pi.order_code',
orderItemId: 'pi.order_item_id',
sku: 'pi.sku_code',
itemName: 'pi.item_name',
})} AS has_inbound_photo,
COALESCE(array_length(pi.loading_photos, 1), 0)::int AS loading_photo_count
FROM picking_items pi
WHERE pi.id = $1
LIMIT 1`,
[item.id]
);
const row = inbound.rows[0];
if (!row) {
throw Object.assign(new Error('商品不在本配送单中'), { status: 404, code: 'not_found' });
}
const hasInbound =
row.has_inbound_photo === true || row.has_inbound_photo === 't' || row.has_inbound_photo === 'true';
if (hasInbound && !isExtraDishFlag(item.is_extra_dish)) {
throw Object.assign(new Error('该商品已有入库验收照片,无需补拍'), {
status: 400,
code: 'inbound_photo_exists',
});
}
} finally {
client.release();
}
const filename = await saveBase64Upload('inspection-photos', content, input.ext || 'jpg', {
objectPrefix: 'delivery-loading',
});
const updated = await pool.query(
`UPDATE picking_items
SET loading_photos = ARRAY[$2]::text[]
WHERE id = $1
RETURNING COALESCE(array_length(loading_photos, 1), 0)::int AS loading_photo_count`,
[item.id, filename]
);
return {
picking_item_id: String(item.id),
path: filename,
loading_photo_count: Number(updated.rows[0]?.loading_photo_count) || 0,
};
}
/** 发车前撤销单行核货(装车量归零) */
export async function unconfirmDeliveryLoadingItem(input: {
taskCode: string;
personCode: string;
itemId: string;
}) {
const task = await assertDeliveryPersonTask(input.taskCode, input.personCode);
const pickCode = await ensureDeliveryLoadingPickTask(String(task.order_code));
const itemResult = await pool.query(
`SELECT pi.id, pi.order_item_id, pi.sku_code, pi.order_code, pi.branch_code, pi.required_qty,
pi.picked_weight, pi.unit,
oi.ordered_quantity, oi.sku_code AS order_sku, oi.quantity AS order_qty, oi.unit AS order_unit,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
COALESCE(skip_sup.skip_inbound, false) AS skip_inbound
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN suppliers skip_sup ON skip_sup.supplier_code = oi.supplier_code
WHERE pi.id = $1 AND pi.order_code = $2 LIMIT 1`,
[input.itemId, task.order_code]
);
const item = itemResult.rows[0];
if (!item) {
throw Object.assign(new Error('商品不在本配送单中'), { status: 404, code: 'not_found' });
}
if (Number(task.task_status) >= 20 && !isExtraDishFlag(item.is_extra_dish)) {
throw Object.assign(new Error('配送已开始,无法撤销核货'), { status: 400, code: 'invalid_state' });
}
const orderedBaseline = Math.max(
0,
Number(item.ordered_quantity) || Number(item.order_qty) || Number(item.required_qty) || 0
);
const existingWeight = Number(item.picked_weight) || 0;
// 已称重:撤销核货不得把结算打回订货量(重量仍保留);无称重:按订货基线
const settlementQty = existingWeight > 0 ? existingWeight : orderedBaseline;
const requiredDisplay = orderedBaseline > 0 ? orderedBaseline : Number(item.required_qty) || 0;
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(
`UPDATE picking_items
SET loaded_qty = 0,
required_qty = CASE WHEN $2::numeric > 0 THEN $2::numeric ELSE required_qty END,
unit = CASE WHEN $3::varchar IS NOT NULL AND $3::varchar != '' THEN $3::varchar ELSE unit END
WHERE id = $1`,
[input.itemId, requiredDisplay, item.order_unit ? String(item.order_unit) : null]
);
// 撤销核货只归零 loaded_qty;不再把订单 quantity 在计划/实配之间互换。
const skuCode = String(item.sku_code || item.order_sku || '').trim();
const orderCode = String(item.order_code || task.order_code || '').trim();
if (item.order_item_id && skuCode && orderCode) {
await upsertActiveReservation(client, {
orderItemId: String(item.order_item_id),
orderCode,
skuCode,
branchCode: item.branch_code ? String(item.branch_code) : null,
// 预留仍按订货/应配基线;结算量另按称重处理
qty: orderedBaseline > 0 ? orderedBaseline : settlementQty,
});
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
const orderStatusRow = await pool.query(
`SELECT order_status FROM orders WHERE order_code = $1`,
[task.order_code]
);
const orderStatus = Number(orderStatusRow.rows[0]?.order_status) || 0;
const allLoaded = await markLoadingCompleteIfReady(
input.taskCode,
String(task.order_code),
pickCode,
orderStatus
);
const { items } = await listLoadingItems(String(task.order_code), pickCode, orderStatus);
const loadedCount = items.filter((row) => row.loaded_done).length;
return {
item_id: input.itemId,
loaded_qty: 0,
required_qty: requiredDisplay,
picked_weight: existingWeight,
loaded_count: loadedCount,
total_count: items.length,
all_loaded: allLoaded,
can_start_delivery:
allLoaded &&
loadingPhotosSatisfied(items, await isDeliveryLoadingPhotoRequired()) &&
orderStatus >= 50 &&
Number(task.task_status) < 20,
};
}
function scanCodeTail(barcode: string) {
const raw = String(barcode || '').trim();
if (raw.length <= 8) return raw;
return raw.slice(-8);
}
/** 本单容器:订单号或本单拣货单号命中;order_code 为空仍可用 pick_code 认本车 */
const OWN_ORDER_CONTAINER_SQL = `
SELECT pc.pick_item_id, pc.pick_code, pi.order_code
FROM picking_containers pc
LEFT JOIN picking_items pi ON pi.id = pc.pick_item_id
WHERE pc.container_code = $1
AND (
pi.order_code = $2
OR pc.pick_code IN (SELECT DISTINCT pi2.pick_code FROM picking_items pi2 WHERE pi2.order_code = $2)
OR pc.pick_code IN (SELECT pt.pick_code FROM picking_tasks pt WHERE pt.order_code = $2)
)
LIMIT 1
`;
const FOREIGN_ORDER_CONTAINER_SQL = `
SELECT pc.container_code, pi.order_code
FROM picking_containers pc
LEFT JOIN picking_items pi ON pi.id = pc.pick_item_id
WHERE pc.container_code = $1
AND NOT (
pi.order_code = $2
OR pc.pick_code IN (SELECT DISTINCT pi2.pick_code FROM picking_items pi2 WHERE pi2.order_code = $2)
OR pc.pick_code IN (SELECT pt.pick_code FROM picking_tasks pt WHERE pt.order_code = $2)
)
LIMIT 1
`;
export async function scanDeliveryLoadingBarcode(input: {
taskCode: string;
personCode: string;
barcode: string;
}) {
const barcode = String(input.barcode || '').trim();
if (!barcode) throw Object.assign(new Error('条码不能为空'), { status: 400 });
const task = await assertDeliveryPersonTask(input.taskCode, input.personCode);
if (Number(task.task_status) >= 20) {
throw Object.assign(new Error('配送已开始,无法继续扫码核货'), { status: 400, code: 'invalid_state' });
}
const orderCode = String(task.order_code);
const pickCode = await ensureDeliveryLoadingPickTask(orderCode);
const orderStatusRow = await pool.query(
`SELECT order_status FROM orders WHERE order_code = $1`,
[orderCode]
);
const orderStatus = Number(orderStatusRow.rows[0]?.order_status) || 0;
const { items: loadingItems } = await listLoadingItems(orderCode, pickCode, orderStatus);
let matched: (typeof loadingItems)[number] | undefined;
const ownContainer = await pool.query(OWN_ORDER_CONTAINER_SQL, [barcode, orderCode]);
if (ownContainer.rows[0]?.pick_item_id) {
const pickItemId = String(ownContainer.rows[0].pick_item_id);
matched = loadingItems.find((row) => String(row.id) === pickItemId);
if (!matched) {
throw Object.assign(new Error('本车货物不包含该容器商品'), {
status: 404,
code: 'not_found',
});
}
}
if (!matched) {
matched = loadingItems.find(
(row) => row.barcode && row.barcode.toLowerCase() === barcode.toLowerCase()
);
}
if (!matched) {
const skuResult = await pool.query(
`SELECT sku_code FROM skus WHERE barcode = $1 OR sku_code = $1 LIMIT 1`,
[barcode]
);
const skuCode = skuResult.rows[0]?.sku_code ? String(skuResult.rows[0].sku_code) : null;
if (skuCode) {
matched =
loadingItems.find((row) => row.sku_code === skuCode && !row.loaded_done) ||
loadingItems.find((row) => row.sku_code === skuCode);
}
}
if (!matched) {
const foreign = await pool.query(FOREIGN_ORDER_CONTAINER_SQL, [barcode, orderCode]);
if (foreign.rows[0]) {
throw Object.assign(new Error(`该容器不属于本车货物(${scanCodeTail(barcode)})`), {
status: 404,
code: 'not_found',
});
}
const skuMiss = await pool.query(
`SELECT sku_code FROM skus WHERE barcode = $1 OR sku_code = $1 LIMIT 1`,
[barcode]
);
if (!skuMiss.rows[0]?.sku_code) {
throw Object.assign(new Error(`未找到条码对应商品或容器:${barcode}`), {
status: 404,
code: 'not_found',
});
}
throw Object.assign(new Error(`本车货物不包含商品「${barcode}」`), {
status: 404,
code: 'not_found',
});
}
const confirmed = await confirmDeliveryLoadingItem({
taskCode: input.taskCode,
personCode: input.personCode,
itemId: matched.id,
});
return {
item_id: confirmed.item_id,
sku_code: matched.sku_code,
item_name: matched.item_name,
loaded_qty: confirmed.loaded_qty,
required_qty: confirmed.required_qty,
loaded_done: confirmed.loaded_qty > 0 || confirmed.required_qty <= 0,
loaded_count: confirmed.loaded_count,
total_count: confirmed.total_count,
all_loaded: confirmed.all_loaded,
can_start_delivery: confirmed.can_start_delivery,
};
}
export async function applySkipInboundSettlementForOrder(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_orderCode: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_client: PoolClient
) {
// 配送实配只落 picking_items.loaded_qty,订单详情作「实收数量」展示;不改计划数量 quantity
}
export async function assertDeliveryLoadingComplete(taskCode: string, personCode: string) {
const state = await getDeliveryLoadingState(taskCode, personCode);
if (!state.all_loaded) {
const pending = state.total_count - state.loaded_count;
throw Object.assign(
new Error(`尚有 ${pending} 项品类未确认有货,请完成核对后再发车`),
{ status: 400, code: 'loading_incomplete' }
);
}
return state;
}
/** 仅发车路径调用;不要并入 assertDeliveryLoadingComplete(定位上报会复用后者) */
export async function assertDeliveryLoadingPhotosIfRequired(taskCode: string, personCode: string) {
const rolePhotoRequired = await isDeliveryLoadingPhotoRequired();
const state = await getDeliveryLoadingState(taskCode, personCode);
const missing = (state.items || []).filter(
(item) => item.needs_loading_photo && item.loading_photo_count < 1
);
const mustBlock = missing.filter(
(item) => item.skip_inbound || item.is_extra_dish || rolePhotoRequired
);
if (mustBlock.length) {
throw Object.assign(
new Error(`还有 ${mustBlock.length} 项直送或加菜未拍照,请各拍 1 张后再发车`),
{ status: 400, code: 'loading_photo_required' }
);
}
}
export async function assertExtraDishLoadingPhotos(taskCode: string, personCode: string) {
const state = await getDeliveryLoadingState(taskCode, personCode);
if (extraDishPhotosSatisfied(state.items || [])) return state;
const pending = (state.items || []).filter(
(item) => item.is_extra_dish && (!item.loaded_done || item.loading_photo_count < 1)
).length;
throw Object.assign(
new Error(`还有 ${pending} 项加菜未拍核货照,请拍完后再拍照送达`),
{ status: 400, code: 'extra_dish_photo_required' }
);
}