1501 lines
58 KiB
TypeScript
1501 lines
58 KiB
TypeScript
import { itemDisplayNameSql } from './itemDisplayNameSql';
|
||
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 { freezeOrderSettlementQtyOnComplete } from './orderItemSupplyUnitSync';
|
||
import { attachCategoryPhotoInspectionRequirements } from './inspectionPhotoService';
|
||
import { ensureSkipInboundLoadingLines } from './skipInboundLoadingService';
|
||
import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery';
|
||
import { displayPickedMeasureForUnit, isPickingWeightUnit } from './orderItemSupplyUnitSync';
|
||
import {
|
||
ORDER_ITEM_LABEL_BARCODE_NO_PICK_ROW_SQL,
|
||
ORDER_ITEM_LABEL_BARCODE_SQL,
|
||
ORDER_ITEM_LABEL_LEDGER_JOIN_SQL,
|
||
ORDER_ITEM_OWN_BARCODE_NO_PICK_ROW_SQL,
|
||
ORDER_ITEM_OWN_BARCODE_SQL,
|
||
} from './orderItemLabelBarcodeSql';
|
||
import { defaultScanLevels, scanMatchSet } from './labelScanResolver';
|
||
|
||
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;
|
||
/** 标签二维码里印的值(主系统来源行 = 他们的 SKU);核货扫码按它优先定位到行 */
|
||
label_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();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 配送核货「商品名」取值链(2026-10-21 开发者指定):**商品档案优先**。
|
||
* ① `skus.sku_name` → ② `order_items.item_name` → ③ `picking_items.item_name`
|
||
*
|
||
* 为什么必须优先档案名:订单行/分拣行里存的是**下单当刻的快照名**,商品档案改名后
|
||
* 若不优先取档案,核货界面会一直显示旧名称(本系统与主系统都踩过同一个坑)。
|
||
*
|
||
* 三处 SQL(核货列表 / 无分拣行补行 / 确认拣货回写)共用本函数,避免口径漂移;
|
||
* 全空时返回 `NULL`(与原来"取不到就是 null"的语义一致,不造空串)。
|
||
*/
|
||
export function deliveryLoadingItemNameSql(columns: {
|
||
/** 档案名来源,通常是 `s.sku_name` / `sk.sku_name` */
|
||
skuName?: string | null;
|
||
/** 订单行快照名,通常是 `oi.item_name` */
|
||
orderItemName?: string | null;
|
||
/** 分拣行快照名,通常是 `pi.item_name` */
|
||
pickingItemName?: string | null;
|
||
}): string {
|
||
// 2026-10-21:取值链已抽到 `itemDisplayNameSql`(核货/分拣/标签打印共用一份),这里只做委托
|
||
return itemDisplayNameSql(columns);
|
||
}
|
||
|
||
/** 导出仅为测试:验证「商品名取值链」已落到核货列表 SQL(生产消费方不变) */
|
||
export const LOADING_ITEMS_SQL = `
|
||
SELECT pi.id, pi.pick_code,
|
||
${deliveryLoadingItemNameSql({
|
||
skuName: 's.sku_name',
|
||
orderItemName: 'oi.item_name',
|
||
pickingItemName: 'pi.item_name',
|
||
})} AS 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,
|
||
${ORDER_ITEM_OWN_BARCODE_SQL} AS barcode,
|
||
-- 标签二维码里印的值(与分拣界面/小程序打印**同一份取值链**,见 orderItemLabelBarcodeSql.ts):
|
||
-- 核货扫码按它优先定位到行 —— 主系统来源行印的是他们的 SKU,直接比对 SKU 会张冠李戴
|
||
${ORDER_ITEM_LABEL_BARCODE_SQL} AS label_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
|
||
-- 主系统行级台账:该行对应的**主系统 SKU**(= 标签上印的值;取值链唯一来源见 orderItemLabelBarcodeSql.ts)
|
||
${ORDER_ITEM_LABEL_LEDGER_JOIN_SQL}
|
||
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,
|
||
label_barcode: row.label_barcode ? String(row.label_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,
|
||
};
|
||
}
|
||
|
||
/** 导出仅为测试:无分拣行补行 SQL 的商品名取值链 */
|
||
export const MISSING_NON_EXTRA_LOADING_SQL = `
|
||
SELECT oi.id::text AS id,
|
||
$2::text AS pick_code,
|
||
${deliveryLoadingItemNameSql({
|
||
skuName: 's.sku_name',
|
||
orderItemName: 'oi.item_name',
|
||
})} AS 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,
|
||
${ORDER_ITEM_OWN_BARCODE_NO_PICK_ROW_SQL} AS barcode,
|
||
-- 这批行没有分拣行(标签仍由分拣行打印)⇒ 标签值与分拣面同一条链,只是少 pi.sku_code 一层
|
||
${ORDER_ITEM_LABEL_BARCODE_NO_PICK_ROW_SQL} AS label_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)
|
||
-- 主系统行级台账(该行的主系统 SKU = 标签值);取值链唯一来源见 orderItemLabelBarcodeSql.ts
|
||
-- ⚠️ 台账 our_order_item_id **不是唯一键**(同名重复认领时多条台账行指向同一订单行)
|
||
-- ⇒ 必须用 LATERAL LIMIT 1 只取一条,否则核货列表按「每条台账行」成倍放大。
|
||
LEFT JOIN LATERAL (
|
||
SELECT msi_main.main_sku_code
|
||
FROM public.main_system_order_import_items msi_main
|
||
WHERE msi_main.our_order_item_id = oi.id
|
||
ORDER BY (NULLIF(TRIM(msi_main.main_sku_code), '') IS NULL) ASC,
|
||
msi_main.created_at ASC NULLS LAST,
|
||
msi_main.prep_id ASC
|
||
LIMIT 1
|
||
) msi ON TRUE
|
||
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;
|
||
};
|
||
|
||
/** 导出仅为测试:确认拣货 SQL 的商品名取值链与 skus 关联 */
|
||
export 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,
|
||
${deliveryLoadingItemNameSql({
|
||
skuName: 'sk.sku_name',
|
||
orderItemName: 'oi.item_name',
|
||
pickingItemName: 'pi.item_name',
|
||
})} AS 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
|
||
`;
|
||
|
||
/** 导出仅为测试:确认拣货 SQL 的 FROM/JOIN(含 skus 关联) */
|
||
export const CONFIRM_PICK_FROM = `
|
||
FROM picking_items pi
|
||
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
|
||
LEFT JOIN skus sk ON sk.sku_code = COALESCE(
|
||
NULLIF(TRIM(pi.sku_code), ''),
|
||
NULLIF(TRIM(oi.sku_code), '')
|
||
)
|
||
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;订单计划量不在**核货事务内**被覆盖 ——
|
||
// 事务提交后由 `freezeOrderSettlementQtyOnComplete` 统一对齐(出库/核货/结案同一函数、同一口径)。
|
||
|
||
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);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 核货改实配后**再对齐一次**「计划数量 = 实收」(开发者 2026-10-15 决策)。
|
||
*
|
||
* 出库那一刻对齐用的是**实拣量/称重值**(那时还没核货);配送员**真的改了实配**时要跟着走
|
||
* (例:拣 11、核货改成 10.5 ⇒ 计划量 10.5);口径与出库/结案同一函数(幂等、写需求快照)。
|
||
*
|
||
* ⚠️ 只有**真人改过**(`canEditQty`,即本单开着核货改实配或该行免入库)才触发:
|
||
* 不可改的行走的是"把 `required_qty` 镜像进 `loaded_qty` 当作已核货标记"的分支
|
||
* (`loaded_done: loaded > 0` 承重,去不掉),那不是实收 —— 若也触发,会把出库刚对齐好的
|
||
* 计划量**拉回计划值**。已 90 的单也不在这里改(事后修正走「管理员改实收」的 force 入口)。
|
||
* 非阻塞:失败只告警,不回滚核货。
|
||
*/
|
||
if (qtyEdited && canEditQty && task.order_code) {
|
||
try {
|
||
await freezeOrderSettlementQtyOnComplete(pool, String(task.order_code));
|
||
} catch (err) {
|
||
console.warn('[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) {
|
||
/**
|
||
* **按「纸上的码」定位到行**(2026-10-13):先比标签值(`label_barcode`,主系统来源行印的是**他们的 SKU**),
|
||
* 再比我方码(`barcode` / `sku_code`,旧标签与手输)。命中集合内 SKU 不唯一 ⇒ 直接报错,绝不猜
|
||
* —— 否则主系统 SKU 与我方另一个商品同码时,会把核货量记到别的商品上(真库已复现)。
|
||
* 见 docs/design/20261013-扫码按标签值定位行(消除跨系统SKU同码错行).md
|
||
*/
|
||
const scanSet = scanMatchSet(loadingItems, barcode, defaultScanLevels<DeliveryLoadingItem>());
|
||
if (scanSet) {
|
||
matched = scanSet.rows.find((row) => !row.loaded_done) || scanSet.rows[0];
|
||
}
|
||
}
|
||
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',
|
||
});
|
||
}
|
||
/**
|
||
* 全局商品库里认识这个码 ⇒ 是「本车不包含它」;完全不认识 ⇒ 「未找到条码对应商品或容器」。
|
||
* (标签值/台账反查已在上面的 L1 解析里做过,这里不再重复;报错文案带**用户扫到的原串**。)
|
||
*/
|
||
const skuMiss = await pool.query(
|
||
`SELECT sku_code FROM skus WHERE barcode = $1 OR sku_code = $1 LIMIT 1`,
|
||
[barcode]
|
||
);
|
||
const knownSku = skuMiss.rows[0]?.sku_code ? String(skuMiss.rows[0].sku_code) : null;
|
||
if (!knownSku) {
|
||
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' }
|
||
);
|
||
}
|