Files
SupplierSystem/server/src/services/pickingService.ts
T
Ubuntu 75de81cd64
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(主系统计划): 对齐主系统 order_item_id 与 request_id 契约
主系统接口要求主系统订单行 UUID;从导入台账 payload.mainOrderItemId 读取并写入 outbox;request_id 归一化为主系统允许字符集。
2026-11-03 10:15:36 +08:00

3847 lines
144 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 { PoolClient } from 'pg';
import { pool } from '../db';
import { itemDisplayNameSql } from './itemDisplayNameSql';
import { isRetailOrder } from './retailOrder';
import { isOrderIndependentInbound } from './independentInbound';
import { completeOrderWithoutDriverDelivery } from './orderWorkflowFulfillmentService';
import { enqueueMainSystemWritebackForReadyOrder } from './mainSystemWriteback';
import { config } from '../config';
import type { TenantContext } from './tenantScope';
import { ensureSkuForPickingOutbound } from './skuProvisioningService';
import { chinaDeliveryDateBetweenSql, onOrAfterChinaDeliveryDateSql } from '../utils/chinaDate';
import { isOrderCodeSearch } from '../utils/orderCodeQuery';
import { buildSchedulerTenantContext } from './platformBranch';
import {
countPendingPickingTasks,
countUnfinishedPickingTasks,
countWarehouseItemsMissingPicking,
ensureDeliveryTaskForOrder,
tryAdvanceOrderToDelivery,
} from './orderWorkflowFulfillmentService';
import { fetchSortedOrderItemsForPicking } from './pickingRouteSortService';
import {
getPickingTaskMode,
getPickingZoneOrder,
isPickingWorkflowEnabled,
UNCATEGORIZED_SCOPE_KEY,
UNZONED_SCOPE_KEY,
} from './pickingConfigService';
import type { PickingOrderItemRow } from './pickingRouteSortService';
import { tryAutoAssignPickerOnTask } from './pickingAssignRuleService';
import { consumeReservationsForOrder, getClaimableStockQty, listPurchaseMergePeerOrderCodes } from './inventoryStockCoverService';
import { fifoDeductInventory, orderSkuSkippedPassThroughLedger } from './inventoryOutboundService';
import { batchSelectionOrderBy } from './inventoryBatchSelection';
import { catalogSkuBySpecJoin } from './catalogSkuBySpec';
import { notifyInventoryShortage } from './inventoryShortageNotificationService';
import { isPassThroughSku } from './stockModeService';
import { writeAuditLog } from './auditService';
import { supplierSkipInboundExistsSql } from './supplierSkipInbound';
import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery';
import {
isPickingWeightUnit,
normalizePickingSavedMeasures,
resolvePickingSettlementQty,
} from './orderItemSupplyUnitSync';
import { assertOrderActiveForFulfillment, orderNotDeletedSql } from './orderTrashScope';
import {
ORDER_ITEM_LABEL_BARCODE_SQL,
ORDER_ITEM_LABEL_LEDGER_JOIN_SQL,
ORDER_ITEM_OWN_BARCODE_SQL,
ORDER_ITEM_OWN_SKU_CODE_SQL,
} from './orderItemLabelBarcodeSql';
import { resolvePickingScanRow } from './labelScanResolver';
import { isPickingScaleRequired } from './pickingScaleService';
import { salesVisibleOrderSql } from './independentInbound';
import { buildSignedStoragePathForCtxChecked } from './storageObjectOwnership';
type PickingProgressRow = {
id: string;
required_qty: number;
picked_qty: number;
picked_weight?: number;
diff_reason?: string;
unit?: string | null;
/** 手选出库批次计划(分拣完成时选定);不传=不动,[]/空=默认 FIFO */
outbound_batches?: Array<{ batch_no: string; qty: number }> | null;
/**
* 分拣出库留证照片(可选;对象路径数组,挂到该商品行)。
* 见 docs/design/20261103-分拣出库拍照留证.md —— 不传/空=列不变(保留历史留证);绝不因缺照片而拒绝完成。
*/
outbound_photos?: string[];
};
/** 归一化手选批次计划 → [{batch_no, qty}];非法项丢弃;无有效项返回 null */
function normalizeOutboundBatches(raw: unknown): Array<{ batch_no: string; qty: number }> | null {
if (!Array.isArray(raw)) return null;
const out: Array<{ batch_no: string; qty: number }> = [];
for (const x of raw) {
const bn = String((x as any)?.batch_no ?? (x as any)?.batchNo ?? '').trim();
const q = Number((x as any)?.qty);
if (!bn || !Number.isFinite(q) || q <= 0) continue;
out.push({ batch_no: bn, qty: q });
}
return out.length ? out : null;
}
function isTruthyFlag(value: unknown): boolean {
return value === true || value === 't' || value === 'true' || value === 1;
}
/** 分拣作业行:非加菜,且订单尚未进入待配送 */
function pickingWarehouseWorkExistsSql(pickCodeExpr: string): string {
return `EXISTS (
SELECT 1
FROM picking_items pi_wh
JOIN orders o_wh ON o_wh.order_code = pi_wh.order_code
LEFT JOIN order_items oi_wh ON oi_wh.id = pi_wh.order_item_id
WHERE pi_wh.pick_code = ${pickCodeExpr}
AND ${orderNotDeletedSql('o_wh')}
AND o_wh.order_status < 50
AND COALESCE(oi_wh.is_extra_dish, false) = false
)`;
}
function pickingItemReviewStatus(
requiredQty: number,
pickedQty: number,
pickedWeight: number,
unit?: string | null
): number {
const settlement = resolvePickingSettlementQty(pickedQty, pickedWeight, unit);
if (Math.abs(requiredQty - settlement) < 0.0001) return 30;
return 20;
}
export { isPickingWeightUnit };
function trimSku(value: unknown): string {
return String(value || '').trim();
}
function businessError(message: string, status = 400): Error {
return Object.assign(new Error(message), { status });
}
function newPickCode() {
return `PK${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
}
/**
* 分拣出库后推进待配送:须订单在待分拣(45)、无未完成分拣单,且仓内商品均已进分拣(直送核货单不算)。
*
* 源状态谓词 `order_status = 45` 是必须的:上面两个前置都是「业务齐备性」条件,不是状态条件,
* 对 20/30/40 同样成立。本函数的调用方(出库确认)只保证 pick_status∈[30,40),
* 并不保证订单仍在 45 —— 订单可能已被「拒收退回(40→30)」或「仓内漏分拣打回(50→45)」改动。
* 缺这个谓词会靠调用时机兜底,一旦订单在 40/30 被扫到就会跳过验收环节直接进待配送。
*/
/**
* 分拣出库收尾推进。
*
* 返回值 `skipInboundAwaitingPickup=true` 表示:这是**主系统免入库**订单,已停在 50 待配送、
* **等主系统确认发车**(`preparations.picked_up` 事件)才收口 —— 调用方必须在**事务提交后**
* 触发回写(HTTP 永不在事务内),见设计文档 20261010 §3.4。
*/
async function maybeAdvanceOrderAfterPickingOutbound(
client: PoolClient,
orderCode: string
): Promise<{ skipInboundAwaitingPickup: boolean }> {
await consumeReservationsForOrder(client, orderCode);
const unfinishedPicks = await countUnfinishedPickingTasks(orderCode, client);
if (unfinishedPicks > 0) return { skipInboundAwaitingPickup: false };
const missingWarehouse = await countWarehouseItemsMissingPicking(orderCode, client);
if (missingWarehouse > 0) return { skipInboundAwaitingPickup: false };
// 主系统「免入库」订单:货由**主系统配送员直接来取**,我们只负责分拣。
// 判定读公开台账(无台账行 = 原生订单 ⇒ false,原生流程逐字节不变)。
// 见 docs/design/20261009-供应商侧库存抵扣与免入库推进方案.md §3.2
try {
const branchResult = await client.query<{ branch_code: string | null }>(
`SELECT branch_code FROM orders WHERE order_code = $1 LIMIT 1`,
[orderCode]
);
const branchCode = String(branchResult.rows[0]?.branch_code || '');
const { isOrderFullySkipInbound } = await import('./mainSystemPrepLedger');
// ⚠️ 传 `client` 复用当前事务的连接:本函数此刻已持有连接,
// 再去 pool 取第二条会在池满时自锁。
if (await isOrderFullySkipInbound({ branchCode, ourOrderCode: orderCode, db: client })) {
// 先走既有边 45→50(结案入口只接受来源状态 30 或 50,见 F9),全程不新增状态边。
await client.query(
`UPDATE orders SET order_status = 50 WHERE order_code = $1 AND order_status = 45`,
[orderCode]
);
if (config.mainSystemIntegration.skipInboundAwaitPickup) {
// 【2026-10-10 新口径】不再分拣完毕即结案:**停在 50 待配送,等主系统确认发车**
// (开发者原话:「分拣完成后等着主系统的分拣员来…点击了确认发车后,子系统的订单就标记为已完成」)。
// 不建配送任务(ensureDeliveryTaskForOrder 的免入库守卫已兜住),
// 对账也不会把它推到 60(tryAdvanceOrderToDelivering 无 options 时要求配送员已点开始,F8)。
// 回写 `status=30` 由调用方在**事务提交后**触发 —— 主系统必须先收到它才会推进到可发车。
return { skipInboundAwaitingPickup: true };
}
// 旧口径(默认关):分拣完毕即结案 90,跳过 50/60 配送环节
await completeOrderWithoutDriverDelivery(orderCode, client);
return { skipInboundAwaitingPickup: false };
}
} catch (error: unknown) {
// 判定失败不能把分拣流程带崩:退回原有 45→50 行为
console.error(
`[picking] 免入库判定失败,按普通订单推进 ${orderCode}:`,
(error as Error)?.message || error
);
}
await client.query(
`UPDATE orders SET order_status = 50 WHERE order_code = $1 AND order_status = 45`,
[orderCode]
);
return { skipInboundAwaitingPickup: false };
}
function newContainerCode() {
return `CT${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
}
function branchClause(ctx: TenantContext | null | undefined, alias: string, params: unknown[]) {
if (ctx?.branchCode && !ctx.isSuperAdmin) {
params.push(ctx.branchCode);
return `AND ${alias}.branch_code = $${params.length}`;
}
return '';
}
type Db = Pick<PoolClient, 'query'>;
/**
* 退货 / 删行后清掉「**还没动过**」的拣货行(2026-10-12 真库事故 `ORD_API_20261012_BR003_0002`)。
*
* 为什么需要:退货(红冲)路径此前只删「直送/免入库」的核货行,普通仓内行的拣货行**留着** ⇒
* ① 已退货/已删除的商品仍出现在分拣对话框(还带着 `fifo_cover` 出库批次);
* ② `confirmPickingComplete` 的「还有 N 项未确认分拣 / 实拣为 0」会拿这些行卡住整个分拣任务。
*
* 只删 `picked_qty` 与 `loaded_qty` **都为 0** 的行(没留下任何实物动作);
* 已经拣过/核过货的行保留 —— 它们仍需被复核,且与被保留的显示口径一致(不互锁)。
*/
export async function deleteUnworkedPickingRowsForItems(
db: Db,
itemIds: Array<string | null | undefined>
): Promise<number> {
const ids = [...new Set(itemIds.map((id) => String(id || '').trim()).filter(Boolean))];
if (!ids.length) return 0;
const result = await db.query(
`DELETE FROM picking_items pi
WHERE pi.order_item_id = ANY($1::uuid[])
AND COALESCE(pi.picked_qty, 0) = 0
AND COALESCE(pi.loaded_qty, 0) = 0`,
[ids]
);
return result.rowCount || 0;
}
/**
* **兜底清扫**(订单状态对账每轮调):把整单里「订单行已退货 / 已不存在、且没留下实物动作」的
* 拣货行删掉。用于清理**本次修复之前**留下的存量残留(真库 `ORD_API_20261012_BR003_0002` 的两行),
* 让历史单不需要跑数据修复脚本。已拣/已核货的行保留。
*/
export async function pruneStalePickingRowsForOrder(orderCode: string): Promise<number> {
const code = String(orderCode || '').trim();
if (!code) return 0;
const result = await pool.query(
`DELETE FROM picking_items pi
WHERE pi.order_code = $1
AND pi.order_item_id IS NOT NULL
AND COALESCE(pi.picked_qty, 0) = 0
AND COALESCE(pi.loaded_qty, 0) = 0
AND NOT EXISTS (
SELECT 1 FROM order_items oi
WHERE oi.id = pi.order_item_id
AND COALESCE(oi.is_returned, false) = false
)`,
[code]
);
return result.rowCount || 0;
}
async function filterUnpickedItems(items: PickingOrderItemRow[], db: Db): Promise<PickingOrderItemRow[]> {
if (!items.length) return [];
const ids = items.map((item) => item.id);
const covered = await db.query(
`SELECT pi.order_item_id::text AS id
FROM picking_items pi
INNER JOIN picking_tasks pt ON pt.pick_code = pi.pick_code
WHERE pi.order_item_id = ANY($1::uuid[])`,
[ids]
);
const taken = new Set(covered.rows.map((row) => String(row.id)));
return items.filter((item) => !taken.has(String(item.id)));
}
async function insertPickingItems(
db: Db,
pickCode: string,
items: PickingOrderItemRow[],
branchCode: string | null,
sortStart = 1
) {
let sortIdx = sortStart;
const insertedIds: string[] = [];
for (const item of items) {
const inserted = await db.query(
`INSERT INTO picking_items (pick_code, order_item_id, order_code, sku_code, item_name, required_qty, picked_qty, unit, review_status, branch_code, sort_order)
VALUES ($1, $2, $3, $4, $5, $6, 0, $7, 10, $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,
]
);
const insertedId = (inserted.rows as Array<{ id?: string }>)[0]?.id;
if (insertedId) insertedIds.push(String(insertedId));
sortIdx += 1;
}
/**
* 「我方指定的抵扣批次」随建行带进新行(2026-10-13 方案甲):
* 订单侧改过批次时,分拣界面默认值就是那几批(分拣员仍可现场改)。
* 幂等:只填 `outbound_batches` 为空的行。
*/
if (insertedIds.length) {
try {
const { materializeCoverBatchesForPickingRows } = await import(
'./orderItemCoverBatchesService'
);
await materializeCoverBatchesForPickingRows(db, { pickItemIds: insertedIds });
} catch (error: unknown) {
console.error(
'[picking] 带入我方指定抵扣批次失败(不影响建行):',
(error as Error)?.message || error
);
}
}
}
async function resolveCategoryLabels(
branchCode: string | null,
categoryCodes: string[],
db: Db
): Promise<Map<string, string>> {
const map = new Map<string, string>();
const codes = [...new Set(categoryCodes.filter((c) => c && c !== UNCATEGORIZED_SCOPE_KEY))];
if (!codes.length) return map;
const result = await db.query(
`SELECT category_code, category_name
FROM categories
WHERE category_code = ANY($1::text[])
AND ($2::text IS NULL OR branch_code = $2 OR branch_code IS NULL)
ORDER BY CASE WHEN branch_code = $2 THEN 0 ELSE 1 END`,
[codes, branchCode]
);
for (const row of result.rows) {
const code = String(row.category_code || '');
if (code && !map.has(code)) map.set(code, String(row.category_name || code));
}
return map;
}
export type CreatePickingTaskResult = {
pickCode: string;
created: boolean;
pickCodes: string[];
};
async function createOrderScopeTask(
input: {
orderCode: string;
warehouseCode?: string | null;
branchCode: string | null;
items: PickingOrderItemRow[];
},
db: Db
): Promise<CreatePickingTaskResult> {
// 仅 10/20 可继续承接;30 待出库已关闭,有未拣行时另建新单
const open = await db.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND COALESCE(scope_type, 'order') = 'order'
AND pick_status IN (10, 20)
LIMIT 1`,
[input.orderCode]
);
if (open.rows[0]?.pick_code) {
const pickCode = String(open.rows[0].pick_code);
const items = await filterUnpickedItems(input.items, db);
if (items.length) {
const maxSort = await db.query(
`SELECT COALESCE(MAX(sort_order), 0)::int AS m FROM picking_items WHERE pick_code = $1`,
[pickCode]
);
await insertPickingItems(
db,
pickCode,
items,
input.branchCode,
Number(maxSort.rows[0]?.m || 0) + 1
);
await tryAutoAssignPickerOnTask(db, {
pickCode,
branchCode: input.branchCode,
scopeType: 'order',
scopeKey: input.orderCode,
orderCode: input.orderCode,
});
return { pickCode, created: true, pickCodes: [pickCode] };
}
return { pickCode, created: false, pickCodes: [pickCode] };
}
const items = await filterUnpickedItems(input.items, db);
if (!items.length) {
const anyPick = await db.query(
`SELECT pick_code FROM picking_items WHERE order_code = $1 ORDER BY created_at DESC LIMIT 1`,
[input.orderCode]
);
if (anyPick.rows[0]?.pick_code) {
return {
pickCode: String(anyPick.rows[0].pick_code),
created: false,
pickCodes: [String(anyPick.rows[0].pick_code)],
};
}
throw businessError('订单没有可拣货明细');
}
const pickCode = newPickCode();
await db.query(
`INSERT INTO picking_tasks (
pick_code, order_code, warehouse_code, pick_status, branch_code,
scope_type, scope_key, scope_label
) VALUES ($1, $2, $3, 10, $4, 'order', $2, $2)`,
[pickCode, input.orderCode, input.warehouseCode || null, input.branchCode]
);
await insertPickingItems(db, pickCode, items, input.branchCode);
await tryAutoAssignPickerOnTask(db, {
pickCode,
branchCode: input.branchCode,
scopeType: 'order',
scopeKey: input.orderCode,
orderCode: input.orderCode,
});
return { pickCode, created: true, pickCodes: [pickCode] };
}
async function createCategoryScopeTasks(
input: {
orderCode: string;
warehouseCode?: string | null;
branchCode: string | null;
items: PickingOrderItemRow[];
},
db: Db
): Promise<CreatePickingTaskResult> {
const items = await filterUnpickedItems(input.items, db);
if (!items.length) {
const existing = await db.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND COALESCE(scope_type, 'order') = 'category'
ORDER BY created_at DESC LIMIT 1`,
[input.orderCode]
);
if (existing.rows[0]?.pick_code) {
const pickCode = String(existing.rows[0].pick_code);
return { pickCode, created: false, pickCodes: [pickCode] };
}
throw businessError('订单没有可拣货明细');
}
const groups = new Map<string, PickingOrderItemRow[]>();
for (const item of items) {
const key = String(item.category_code || '').trim() || UNCATEGORIZED_SCOPE_KEY;
const list = groups.get(key) || [];
list.push(item);
groups.set(key, list);
}
const labels = await resolveCategoryLabels(input.branchCode, [...groups.keys()], db);
const pickCodes: string[] = [];
let createdAny = false;
let primary = '';
for (const [scopeKey, groupItems] of groups) {
const open = await db.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND scope_type = 'category' AND scope_key = $2
AND pick_status IN (10, 20)
LIMIT 1`,
[input.orderCode, scopeKey]
);
if (open.rows[0]?.pick_code) {
const pickCode = String(open.rows[0].pick_code);
await insertPickingItems(db, pickCode, groupItems, input.branchCode);
await tryAutoAssignPickerOnTask(db, {
pickCode,
branchCode: input.branchCode,
scopeType: 'category',
scopeKey,
orderCode: input.orderCode,
});
pickCodes.push(pickCode);
if (!primary) primary = pickCode;
continue;
}
const pickCode = newPickCode();
const scopeLabel =
scopeKey === UNCATEGORIZED_SCOPE_KEY ? '未分类' : labels.get(scopeKey) || scopeKey;
await db.query(
`INSERT INTO picking_tasks (
pick_code, order_code, warehouse_code, pick_status, branch_code,
scope_type, scope_key, scope_label
) VALUES ($1, $2, $3, 10, $4, 'category', $5, $6)`,
[pickCode, input.orderCode, input.warehouseCode || null, input.branchCode, scopeKey, scopeLabel]
);
await insertPickingItems(db, pickCode, groupItems, input.branchCode);
await tryAutoAssignPickerOnTask(db, {
pickCode,
branchCode: input.branchCode,
scopeType: 'category',
scopeKey,
orderCode: input.orderCode,
});
pickCodes.push(pickCode);
createdAny = true;
if (!primary) primary = pickCode;
}
return { pickCode: primary || pickCodes[0], created: createdAny, pickCodes };
}
function zoneScopeKey(item: PickingOrderItemRow): string {
const zone = String(item.zone || '').trim();
return zone ? zone.slice(0, 100) : UNZONED_SCOPE_KEY;
}
/** 按区域拆单:同一订单内每个区域一张拣货单(与按分类/按商品同构;区域见 `PickingOrderItemRow.zone`) */
async function createZoneScopeTasks(
input: {
orderCode: string;
warehouseCode?: string | null;
branchCode: string | null;
items: PickingOrderItemRow[];
},
db: Db
): Promise<CreatePickingTaskResult> {
const items = await filterUnpickedItems(input.items, db);
if (!items.length) {
const existing = await db.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND COALESCE(scope_type, 'order') = 'zone'
ORDER BY created_at DESC LIMIT 1`,
[input.orderCode]
);
if (existing.rows[0]?.pick_code) {
const pickCode = String(existing.rows[0].pick_code);
return { pickCode, created: false, pickCodes: [pickCode] };
}
throw businessError('订单没有可拣货明细');
}
const groups = new Map<string, PickingOrderItemRow[]>();
for (const item of items) {
const key = zoneScopeKey(item);
const list = groups.get(key) || [];
list.push(item);
groups.set(key, list);
}
const pickCodes: string[] = [];
let createdAny = false;
let primary = '';
for (const [scopeKey, groupItems] of groups) {
const open = await db.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND scope_type = 'zone' AND scope_key = $2
AND pick_status IN (10, 20)
LIMIT 1`,
[input.orderCode, scopeKey]
);
const scopeLabel = scopeKey === UNZONED_SCOPE_KEY ? '未设区域' : scopeKey;
if (open.rows[0]?.pick_code) {
const pickCode = String(open.rows[0].pick_code);
await insertPickingItems(db, pickCode, groupItems, input.branchCode);
await tryAutoAssignPickerOnTask(db, {
pickCode,
branchCode: input.branchCode,
scopeType: 'zone',
scopeKey,
orderCode: input.orderCode,
});
pickCodes.push(pickCode);
if (!primary) primary = pickCode;
continue;
}
const pickCode = newPickCode();
await db.query(
`INSERT INTO picking_tasks (
pick_code, order_code, warehouse_code, pick_status, branch_code,
scope_type, scope_key, scope_label
) VALUES ($1, $2, $3, 10, $4, 'zone', $5, $6)`,
[pickCode, input.orderCode, input.warehouseCode || null, input.branchCode, scopeKey, scopeLabel]
);
await insertPickingItems(db, pickCode, groupItems, input.branchCode);
await tryAutoAssignPickerOnTask(db, {
pickCode,
branchCode: input.branchCode,
scopeType: 'zone',
scopeKey,
orderCode: input.orderCode,
});
pickCodes.push(pickCode);
createdAny = true;
if (!primary) primary = pickCode;
}
return { pickCode: primary || pickCodes[0], created: createdAny, pickCodes };
}
function skuScopeKey(item: PickingOrderItemRow): string {
const sku = String(item.sku_code || '').trim();
if (sku) return sku.slice(0, 100);
const name = String(item.item_name || '').trim();
if (name) return `N:${name}`.slice(0, 100);
return 'UNSKU';
}
async function createSkuScopeTasks(
input: {
orderCode: string;
warehouseCode?: string | null;
branchCode: string | null;
items: PickingOrderItemRow[];
},
db: Db
): Promise<CreatePickingTaskResult> {
const items = await filterUnpickedItems(input.items, db);
if (!items.length) {
const existing = await db.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND COALESCE(scope_type, 'order') = 'sku'
ORDER BY created_at DESC LIMIT 1`,
[input.orderCode]
);
if (existing.rows[0]?.pick_code) {
const pickCode = String(existing.rows[0].pick_code);
return { pickCode, created: false, pickCodes: [pickCode] };
}
throw businessError('订单没有可拣货明细');
}
const groups = new Map<string, PickingOrderItemRow[]>();
for (const item of items) {
const key = skuScopeKey(item);
const list = groups.get(key) || [];
list.push(item);
groups.set(key, list);
}
const pickCodes: string[] = [];
let createdAny = false;
let primary = '';
for (const [scopeKey, groupItems] of groups) {
const open = await db.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND scope_type = 'sku' AND scope_key = $2
AND pick_status IN (10, 20)
LIMIT 1`,
[input.orderCode, scopeKey]
);
const scopeLabel =
String(groupItems[0]?.item_name || '').trim() ||
String(groupItems[0]?.sku_code || '').trim() ||
scopeKey;
if (open.rows[0]?.pick_code) {
const pickCode = String(open.rows[0].pick_code);
await insertPickingItems(db, pickCode, groupItems, input.branchCode);
await tryAutoAssignPickerOnTask(db, {
pickCode,
branchCode: input.branchCode,
scopeType: 'sku',
scopeKey,
orderCode: input.orderCode,
});
pickCodes.push(pickCode);
if (!primary) primary = pickCode;
continue;
}
const pickCode = newPickCode();
await db.query(
`INSERT INTO picking_tasks (
pick_code, order_code, warehouse_code, pick_status, branch_code,
scope_type, scope_key, scope_label
) VALUES ($1, $2, $3, 10, $4, 'sku', $5, $6)`,
[pickCode, input.orderCode, input.warehouseCode || null, input.branchCode, scopeKey, scopeLabel]
);
await insertPickingItems(db, pickCode, groupItems, input.branchCode);
await tryAutoAssignPickerOnTask(db, {
pickCode,
branchCode: input.branchCode,
scopeType: 'sku',
scopeKey,
orderCode: input.orderCode,
});
pickCodes.push(pickCode);
createdAny = true;
if (!primary) primary = pickCode;
}
return { pickCode: primary || pickCodes[0], created: createdAny, pickCodes };
}
export async function createPickingTask(
input: { orderCode: string; warehouseCode?: string | null; branchCode?: string | null },
ctx?: TenantContext | null
): Promise<CreatePickingTaskResult> {
const orderCode = String(input.orderCode || '').trim();
if (!orderCode) throw businessError('缺少订单号');
/**
* 「散客录单」单**不建分拣任务**(2026-10-15 决策:散客单无分拣/无配送,确认即完成)。
* 收口放在这里(所有调用方共用的唯一建单入口),而不是逐个调用点打补丁。
* 返回 null 表示"本单不需要分拣任务",与既有各调用方对返回值的处理兼容。
*/
if (await isRetailOrder(orderCode, pool)) {
return null as unknown as CreatePickingTaskResult;
}
/**
* 独立进货只是补库存:全部入库后结案,不进分拣/配送。
* 放在唯一建单入口,覆盖下单即建、到 45 补建、手动/定时补建所有路径。
*/
if (await isOrderIndependentInbound(orderCode, pool)) {
return null as unknown as CreatePickingTaskResult;
}
const client = await pool.connect();
try {
await client.query('BEGIN');
// 同一订单的分拣任务创建串行化:并发下单/分配钩子/列表补建只能命中同一 open task。
await client.query(`SELECT pg_advisory_xact_lock(hashtext('picking_task:' || $1))`, [orderCode]);
const orderResult = await client.query(
`SELECT o.order_code, o.customer_code, o.branch_code, o.order_status, c.company_name
FROM orders o
LEFT JOIN customers c ON c.customer_code = o.customer_code
WHERE o.order_code = $1
LIMIT 1`,
[orderCode]
);
const order = orderResult.rows[0];
if (!order) throw businessError('订单不存在', 404);
const orderStatus = Number(order.order_status) || 0;
const branchCode =
input.branchCode || ctx?.branchCode || (order.branch_code ? String(order.branch_code) : null);
if (!(await isPickingWorkflowEnabled(branchCode))) {
throw businessError('该分公司未启用分拣出库环节');
}
const mode = await getPickingTaskMode(branchCode);
let result: CreatePickingTaskResult;
const items =
orderStatus >= 50 ? [] : await fetchSortedOrderItemsForPicking(orderCode, client);
if (!items.length && orderStatus >= 50 && (mode === 'category' || mode === 'sku' || mode === 'zone')) {
const existing = await client.query(
`SELECT pick_code FROM picking_items WHERE order_code = $1 ORDER BY created_at DESC LIMIT 1`,
[orderCode]
);
result = existing.rows[0]?.pick_code
? {
pickCode: String(existing.rows[0].pick_code),
created: false,
pickCodes: [String(existing.rows[0].pick_code)],
}
: { pickCode: '', created: false, pickCodes: [] };
} else if (mode === 'category') {
if (!items.length) throw businessError('订单没有可拣货明细');
result = await createCategoryScopeTasks(
{
orderCode,
warehouseCode: input.warehouseCode,
branchCode,
items,
},
client
);
} else if (mode === 'sku') {
if (!items.length) throw businessError('订单没有可拣货明细');
result = await createSkuScopeTasks(
{
orderCode,
warehouseCode: input.warehouseCode,
branchCode,
items,
},
client
);
} else if (mode === 'zone') {
if (!items.length) throw businessError('订单没有可拣货明细');
result = await createZoneScopeTasks(
{
orderCode,
warehouseCode: input.warehouseCode,
branchCode,
items,
},
client
);
} else {
if (!items.length) throw businessError('订单没有可拣货明细');
result = await createOrderScopeTask(
{
orderCode,
warehouseCode: input.warehouseCode,
branchCode,
items,
},
client
);
}
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
/**
* 提前配送 = 提前分拣完成:直接发车/结束配送前,把该单所有 open 分拣任务按计划量完成。
* 复用 confirmPickingComplete(扣库/幂等/审计都在原链路),不另写完成逻辑。
*/
export async function completeOrderPickingForDirectDelivery(
orderCode: string,
branchCode?: string | null,
operatorId?: string | null
): Promise<{ completed: boolean; pickCodes: string[] }> {
const code = String(orderCode || '').trim();
if (!code) return { completed: false, pickCodes: [] };
const branch = branchCode || null;
let open = await pool.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND COALESCE(pick_status, 10) < 30
ORDER BY created_at ASC`,
[code]
);
if (!open.rowCount) {
const anyTask = await pool.query(`SELECT 1 FROM picking_tasks WHERE order_code = $1 LIMIT 1`, [code]);
if (anyTask.rowCount) return { completed: false, pickCodes: [] };
await ensurePickingTaskOnOrderSubmit(code, branch).catch((error) => {
console.warn('[picking] 直接配送补建分拣任务失败', code, error);
});
open = await pool.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND COALESCE(pick_status, 10) < 30
ORDER BY created_at ASC`,
[code]
);
}
const pickCodes: string[] = [];
for (const row of open.rows) {
const pickCode = String(row.pick_code || '').trim();
if (!pickCode) continue;
const items = await pool.query(
`SELECT id, required_qty, picked_qty, picked_weight, unit, review_status
FROM picking_items WHERE pick_code = $1`,
[pickCode]
);
const rows = items.rows
.filter(
(item) =>
Number(item.review_status) < 20 ||
resolvePickingSettlementQty(item.picked_qty, item.picked_weight, item.unit) <= 0
)
.map((item) => {
const required = Number(item.required_qty) || 0;
return {
id: String(item.id),
required_qty: required,
picked_qty: isPickingWeightUnit(item.unit) ? 0 : required,
picked_weight: isPickingWeightUnit(item.unit) ? required : 0,
unit: item.unit ? String(item.unit) : null,
diff_reason: '提前配送:按计划量完成分拣',
};
});
if (rows.length) {
await updatePickingItemProgress({ pickCode, rows });
}
await confirmPickingComplete({
pickCode,
reviewerId: operatorId || null,
ctx: null,
deferAdvance: true,
});
pickCodes.push(pickCode);
}
return { completed: pickCodes.length > 0, pickCodes };
}
/**
* 下单提交后立即建分拣单(仅启用分拣流程的分公司);无库存/需采购也建。
* 失败不阻断下单,后续到 45 / 定时补建仍可兜底。
* 注意:不引入「订单未到 45 禁止完成分拣」的闸(供应商二选一允许早期分拣)。
*/
/**
* 改单/改供应商/自采/加菜后同步仍开放的分拣行(不重建任务、不建第二套)。
* - 新增或恢复为可拣的行:补到现有 open 任务(pick_status<40)
* - 订单行删除/退货/改成免入库或直送:删除**未动过**的拣货行
* - 已有 picked_qty/picked_weight/loaded_qty/照片的行绝不动
*/
export async function syncOpenPickingItemsForOrder(
orderCode: string,
branchCode?: string | null
): Promise<{ inserted: number; removed: number; pickCode: string | null }> {
const code = String(orderCode || '').trim();
if (!code) return { inserted: 0, removed: 0, pickCode: null };
const orderResult = await pool.query(
`SELECT order_status, branch_code, deleted_at FROM orders WHERE order_code = $1 LIMIT 1`,
[code]
);
const order = orderResult.rows[0];
if (!order || order.deleted_at) return { inserted: 0, removed: 0, pickCode: null };
if (Number(order.order_status) >= 50) return { inserted: 0, removed: 0, pickCode: null };
const branch = branchCode || (order.branch_code ? String(order.branch_code) : null);
const open = await pool.query(
`SELECT pick_code FROM picking_tasks
WHERE order_code = $1 AND pick_status < 40
ORDER BY CASE WHEN COALESCE(scope_type, 'order') = 'order' THEN 0 ELSE 1 END,
created_at ASC
LIMIT 1`,
[code]
);
const pickCode = open.rows[0]?.pick_code ? String(open.rows[0].pick_code) : null;
if (!pickCode) return { inserted: 0, removed: 0, pickCode: null };
// 删除真正失效且没有任何实物动作的行;有实拣/称重/核货/照片的行保守保留。
const removedResult = await pool.query(
`DELETE FROM picking_items pi
WHERE pi.order_code = $1
AND COALESCE(pi.picked_qty, 0) = 0
AND COALESCE(pi.picked_weight, 0) = 0
AND COALESCE(pi.loaded_qty, 0) = 0
AND COALESCE(array_length(pi.loading_photos, 1), 0) = 0
AND COALESCE(array_length(pi.outbound_photos, 1), 0) = 0
AND pi.order_item_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM order_items oi
WHERE oi.id = pi.order_item_id
AND oi.order_code = pi.order_code
AND COALESCE(oi.is_returned, false) = false
AND NOT ${supplierSkipInboundExistsSql('oi.supplier_code')}
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
)`,
[code]
);
const activeItems = await fetchSortedOrderItemsForPicking(code, pool, { includeExtraDish: true });
const missing = await filterUnpickedItems(activeItems, pool);
if (missing.length) {
await insertPickingItems(pool, pickCode, missing, branch);
}
return { inserted: missing.length, removed: removedResult.rowCount || 0, pickCode };
}
export async function ensurePickingTaskOnOrderSubmit(
orderCode: string,
branchCode?: string | null
): Promise<CreatePickingTaskResult | null> {
const code = String(orderCode || '').trim();
if (!code) return null;
const orderResult = await pool.query(
`SELECT order_status, branch_code, deleted_at FROM orders WHERE order_code = $1 LIMIT 1`,
[code]
);
const order = orderResult.rows[0];
if (!order || order.deleted_at) return null;
if (Number(order.order_status) >= 50) return null;
const branch = branchCode || (order.branch_code ? String(order.branch_code) : null);
if (!(await isPickingWorkflowEnabled(branch))) return null;
try {
return await createPickingTask({ orderCode: code, branchCode: branch }, null);
} catch (err) {
console.warn('[picking] 下单即建分拣单跳过', code, err instanceof Error ? err.message : err);
return null;
}
}
export type RepairMissingWarehousePickingResult = {
repaired: boolean;
demoted: boolean;
pickCode?: string;
reason?: string;
};
/**
* 混单误进 50:直送核货单已完成且有配送任务,但仓内行未挂拣货。
* 未发车则打回 45 并补建仓内拣货单。见 20260829-mixed-order-demote-missing-warehouse-pick。
*/
export async function repairMissingWarehousePickingForOrder(
orderCode: string,
ctx?: TenantContext | null
): Promise<RepairMissingWarehousePickingResult> {
const code = String(orderCode || '').trim();
if (!code) return { repaired: false, demoted: false, reason: '缺少订单号' };
const orderResult = await pool.query(
`SELECT order_status, branch_code, COALESCE(pending_backfill, false) AS pending_backfill
FROM orders WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`,
[code]
);
const order = orderResult.rows[0];
if (!order) return { repaired: false, demoted: false, reason: '订单不存在' };
const status = Number(order.order_status) || 0;
const branchCode = order.branch_code ? String(order.branch_code) : null;
if (!(await isPickingWorkflowEnabled(branchCode))) {
return { repaired: false, demoted: false, reason: '未启用分拣' };
}
if (status > 50) {
return { repaired: false, demoted: false, reason: '订单已发车或完成' };
}
if (order.pending_backfill === true && status === 50) {
return { repaired: false, demoted: false, reason: '待补录强推单不回退' };
}
const missing = await countWarehouseItemsMissingPicking(code);
if (missing <= 0) {
return { repaired: false, demoted: false, reason: '仓内行已进分拣' };
}
let demoted = false;
if (status === 50) {
const departed = await pool.query(
`SELECT 1 FROM delivery_tasks
WHERE order_code = $1 AND COALESCE(task_status, 10) >= 20
LIMIT 1`,
[code]
);
if (departed.rowCount) {
return { repaired: false, demoted: false, reason: '配送已开始,不回退' };
}
const back = await pool.query(
`UPDATE orders
SET order_status = 45, updated_at = NOW()
WHERE order_code = $1 AND order_status = 50 AND deleted_at IS NULL
RETURNING order_code`,
[code]
);
if (!back.rowCount) {
return { repaired: false, demoted: false, reason: '状态已变更' };
}
demoted = true;
} else if (status !== 45) {
return { repaired: false, demoted: false, reason: `当前状态 ${status}` };
}
try {
const created = await createPickingTask({ orderCode: code, branchCode }, ctx);
return {
repaired: true,
demoted,
pickCode: created.pickCode || created.pickCodes?.[0],
};
} catch (err) {
return {
repaired: demoted,
demoted,
reason: err instanceof Error ? err.message : String(err),
};
}
}
/** @deprecated 仅保存进度,不再直接置为待出库;请用 updatePickingItemProgress / confirmPickingComplete */
export async function savePickingReview(input: {
pickCode: string;
rows: PickingProgressRow[];
reviewerId?: string | null;
}) {
return updatePickingItemProgress({ pickCode: input.pickCode, rows: input.rows });
}
/**
* 保存分拣进度(数量/重量;不调单、不出库)。
* 已完成(30) 仍可改量并保持 30;已出库(≥40) 拒绝。
* 见 docs/design/20260829-completed-picking-editable.md
*/
export async function updatePickingItemProgress(input: {
pickCode: string;
rows: PickingProgressRow[];
operatorId?: string | null;
source?: string | null;
}) {
const client = await pool.connect();
/** 分拣保存可能写入"实际消耗的批次计划" ⇒ 报告候选在这一刻才成立,提交后入队(2026-10-24 核查项 1) */
let queueTarget: { branchCode: string; orderCode: string } | null = null;
const qtyChanges: Array<{
id: string;
orderCode: string | null;
oldPickedQty: number;
oldPickedWeight: number;
newPickedQty: number;
newPickedWeight: number;
branchCode: string | null;
}> = [];
try {
await client.query('BEGIN');
const taskResult = await client.query(
`SELECT pick_status, order_code, branch_code FROM picking_tasks WHERE pick_code = $1 FOR UPDATE`,
[input.pickCode]
);
const task = taskResult.rows[0];
if (!task) throw Object.assign(new Error('分拣任务不存在'), { status: 404 });
if (task.order_code && task.branch_code) {
queueTarget = { branchCode: String(task.branch_code), orderCode: String(task.order_code) };
}
if (Number(task.pick_status) >= 40) {
throw Object.assign(new Error('该单已出库,无法继续改量'), { status: 400 });
}
const wasCompleted = Number(task.pick_status) >= 30;
const scaleRequired = await isPickingScaleRequired();
let hasDiff = false;
for (const row of input.rows) {
const requiredQty = Number(row.required_qty) || 0;
const pickedQty = Number(row.picked_qty) || 0;
const pickedWeight = Number(row.picked_weight) || 0;
const existing = await client.query(
`SELECT unit, picked_qty, picked_weight, order_code
FROM picking_items WHERE id = $1 AND pick_code = $2`,
[row.id, input.pickCode]
);
const existingRow = existing.rows[0];
let unit = String(row.unit || existingRow?.unit || '').trim() || null;
const saved = normalizePickingSavedMeasures(pickedQty, pickedWeight, unit);
const settlement = resolvePickingSettlementQty(saved.picked_qty, saved.picked_weight, unit);
if (settlement <= 0) {
throw Object.assign(new Error('实拣数量/重量必须大于 0,不能按 0 确认分拣'), { status: 400 });
}
if (scaleRequired && isPickingWeightUnit(unit) && requiredQty > 0 && saved.picked_weight <= 0) {
throw Object.assign(new Error('已开启分拣称重,重量单位须录入实拣重量'), { status: 400 });
}
if (Math.abs(requiredQty - settlement) > 0.0001) hasDiff = true;
const itemStatus = pickingItemReviewStatus(requiredQty, saved.picked_qty, saved.picked_weight, unit);
const oldPickedQty = Number(existingRow?.picked_qty) || 0;
const oldPickedWeight = Number(existingRow?.picked_weight) || 0;
if (
Math.abs(oldPickedQty - saved.picked_qty) > 1e-9 ||
Math.abs(oldPickedWeight - saved.picked_weight) > 1e-9
) {
qtyChanges.push({
id: String(row.id),
orderCode: existingRow?.order_code ? String(existingRow.order_code) : null,
oldPickedQty,
oldPickedWeight,
newPickedQty: saved.picked_qty,
newPickedWeight: saved.picked_weight,
branchCode: task.branch_code ? String(task.branch_code) : null,
});
}
await client.query(
`UPDATE picking_items
SET picked_qty = $1, picked_weight = $2, review_status = $3, diff_reason = $4,
unit = COALESCE($7::varchar, unit),
outbound_batches = COALESCE($8::jsonb, outbound_batches)
WHERE id = $5 AND pick_code = $6`,
[
saved.picked_qty,
saved.picked_weight,
itemStatus,
row.diff_reason || null,
row.id,
input.pickCode,
unit,
row.outbound_batches !== undefined
? JSON.stringify(normalizeOutboundBatches(row.outbound_batches) || [])
: null,
]
);
}
if (wasCompleted) {
// 已完成单改量:保持 pick_status=30,仅刷新审核时间
await client.query(
`UPDATE picking_tasks SET reviewed_at = NOW() WHERE pick_code = $1 AND pick_status = 30`,
[input.pickCode]
);
} else {
const allItems = await client.query(
`SELECT required_qty, picked_qty, picked_weight, review_status FROM picking_items WHERE pick_code = $1`,
[input.pickCode]
);
const anyProgress = allItems.rows.some(
(row) => Number(row.review_status) >= 20 || Number(row.picked_qty) > 0 || Number(row.picked_weight) > 0
);
const nextStatus = anyProgress || hasDiff ? 20 : 10;
await client.query(
`UPDATE picking_tasks SET pick_status = $1 WHERE pick_code = $2 AND pick_status < 30`,
[nextStatus, input.pickCode]
);
}
await client.query('COMMIT');
// 分拣改量审计:失败只告警,不阻断正常分拣保存。
for (const change of qtyChanges) {
try {
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'picking_qty_edit',
targetTable: 'picking_items',
targetId: change.id,
oldValue: {
picked_qty: change.oldPickedQty,
picked_weight: change.oldPickedWeight,
},
newValue: {
picked_qty: change.newPickedQty,
picked_weight: change.newPickedWeight,
order_code: change.orderCode,
pick_code: input.pickCode,
source: input.source || 'picking_progress',
},
branchCode: change.branchCode,
actionCategory: 'picking',
});
} catch (auditError) {
console.warn('[picking] 分拣改量审计失败', change.id, auditError);
}
}
/** 提交后入队(尽力而为,失败不影响分拣保存):本单消耗的批次可能刚被确定 ⇒ 报告候选成立了 */
if (queueTarget) {
try {
const { enqueueReportPush } = await import('./reportPushQueueService');
await enqueueReportPush({
branchCode: queueTarget.branchCode,
kind: 'register',
ourOrderCode: queueTarget.orderCode,
reason: '分拣保存/批次计划更新',
});
} catch (queueError) {
console.warn('[picking] 报告推送入队失败(忽略):', (queueError as Error)?.message || queueError);
}
}
return { hasDiff };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
/**
* 分拣完成:固化实拣量/重量,置为待出库(30)。
* 不回写订单计划数量(quantity);不出库、不扣库存。
* 见 docs/design/20260829-picking-complete-keep-plan-qty.md
*/
/** 分拣完成时补未点的备货/采购并留责任审计;不阻断分拣。 */
async function backfillPendingFulfillmentForPicking(input: {
orderCode: string;
branchCode: string | null;
pickCode: string;
operatorId?: string | null;
}): Promise<void> {
const { orderCode, branchCode, pickCode } = input;
const preps = await pool.query(
`SELECT sku_code, item_name, supplier_code, prepare_qty
FROM supplier_preparations
WHERE order_code = $1 AND COALESCE(prepare_status, 10) < 30
AND COALESCE(is_stockout, false) = false
AND COALESCE(transferred_to_purchase, false) = false`,
[orderCode]
);
if (preps.rowCount) {
await pool.query(
`UPDATE supplier_preparations
SET prepare_status = 30, prepare_time = COALESCE(prepare_time, NOW())
WHERE order_code = $1 AND COALESCE(prepare_status, 10) < 30
AND COALESCE(is_stockout, false) = false
AND COALESCE(transferred_to_purchase, false) = false`,
[orderCode]
);
for (const row of preps.rows) {
await pool.query(
`INSERT INTO delivery_loading_backfill_logs
(branch_code, order_code, sku_code, item_name, supplier_code, missing_stage,
responsible_code, operator_id, confirmed_qty, inbound_qty, picking_qty,
inventory_action, pick_code, remark)
VALUES ($1,$2,$3,$4,$5,'prep',$5,$6,$7,0,0,'backfill_prep',$8,$9)`,
[
branchCode,
orderCode,
row.sku_code || null,
row.item_name || null,
row.supplier_code || null,
input.operatorId || null,
Number(row.prepare_qty) || 0,
pickCode,
'分拣完成时补完成备货(原责任人未点完成)',
]
).catch(() => undefined);
}
}
const purchases = await pool.query(
`SELECT purchase_code, sku_code, supplier_code, purchaser_code,
COALESCE(actual_qty, purchase_qty) AS qty,
COALESCE(actual_price, purchase_price) AS price
FROM purchase_orders
WHERE order_code = $1 AND COALESCE(purchase_status, 10) < 20`,
[orderCode]
);
if (purchases.rowCount) {
const { updatePurchaseOrderStatus } = await import('./purchaseOperationService');
for (const row of purchases.rows) {
try {
await updatePurchaseOrderStatus({
purchaseCode: String(row.purchase_code),
status: 20,
allowZeroCost: true,
actualQty: Number(row.qty) || undefined,
actualPrice: Number(row.price) || undefined,
branchCode: branchCode || '',
remark: '分拣完成时补完成采购',
});
await pool.query(
`INSERT INTO delivery_loading_backfill_logs
(branch_code, order_code, sku_code, supplier_code, purchaser_code, missing_stage,
responsible_code, operator_id, confirmed_qty, inbound_qty, picking_qty,
inventory_action, pick_code, remark)
VALUES ($1,$2,$3,$4,$5,'purchase',$5,$6,$7,0,0,'backfill_prep',$8,$9)`,
[
branchCode,
orderCode,
row.sku_code || null,
row.supplier_code || null,
row.purchaser_code || null,
input.operatorId || null,
Number(row.qty) || 0,
pickCode,
'分拣完成时补完成采购(原采购员未点完成)',
]
).catch(() => undefined);
} catch (error) {
console.warn('[picking] 补完成采购失败', row.purchase_code, error);
}
}
}
}
async function isNoAutoDeliveryOrder(
orderCode: string,
branchCode: string | null,
options?: { includeFullySkip?: boolean; includeSelfPickup?: boolean }
): Promise<boolean> {
try {
const [
{ isRetailOrder },
{ isOrderOnlyDirectDelivery },
{ isOrderIndependentInbound },
{ isSelfPickupOrder },
{ isOrderFullySkipInbound },
{ isDirectToDeliveryEnabled },
] = await Promise.all([
import('./retailOrder'),
import('./skuDirectDelivery'),
import('./independentInbound'),
import('./orderWorkflowFulfillmentService'),
import('./mainSystemPrepLedger'),
import('./directToDeliveryConfigService'),
]);
const includeFullySkip = options?.includeFullySkip !== false;
const includeSelfPickup = options?.includeSelfPickup !== false;
return (
(await isRetailOrder(orderCode, pool)) ||
(await isOrderOnlyDirectDelivery(orderCode, pool)) ||
(await isOrderIndependentInbound(orderCode, pool)) ||
(includeSelfPickup && (await isSelfPickupOrder(orderCode, pool))) ||
(await isDirectToDeliveryEnabled(branchCode).catch(() => false)) ||
(includeFullySkip &&
(await isOrderFullySkipInbound({ branchCode: branchCode || '', ourOrderCode: orderCode, db: pool })))
);
} catch (error) {
console.warn('[picking] 判定跳过自动入库/配送失败,按需谨慎处理', orderCode, error);
return false;
}
}
/**
* 分拣完成时补上游:普通单补备货/采购和(40/45)缺入库;照片缺失不阻断分拣。
* 待取货/全直送/自提/独立进货/散客跳过自动入库。
*/
async function autoInboundFromPickingBeforeComplete(input: {
pickCode: string;
branchCode: string | null;
ctx?: TenantContext | null;
}): Promise<void> {
const taskResult = await pool.query(
`SELECT pt.order_code, pt.branch_code, pt.pick_status
FROM picking_tasks pt WHERE pt.pick_code = $1 LIMIT 1`,
[input.pickCode]
);
const task = taskResult.rows[0];
if (!task || Number(task.pick_status) >= 40) return;
const orderCode = String(task.order_code || '').trim();
if (!orderCode) return;
const branchCode = input.branchCode || (task.branch_code ? String(task.branch_code) : null);
// 用户最终口径:分拣完成不再自动入库;只补未点的备货/采购成本并审计。
// 入库/分拣二选一由 T3 核货阶段按 30/40/45 处理。
await backfillPendingFulfillmentForPicking({
orderCode,
branchCode,
pickCode: input.pickCode,
operatorId: input.ctx?.userId || null,
}).catch((error) => console.warn('[picking] 分拣完成补备货/采购失败', orderCode, error));
const orderResult = await pool.query(
`SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`,
[orderCode]
);
const status = Number(orderResult.rows[0]?.order_status) || 0;
if (status >= 40) return;
// 30 待备货:完成备货成本,但清理本次新建的 pending inspection(不建验收/库存)。
const before = await pool.query(
`SELECT id FROM inspections
WHERE order_code = $1 AND actual_qty IS NULL AND quality_rating IS NULL`,
[orderCode]
);
const beforeIds = new Set(before.rows.map((row) => String(row.id)));
try {
const { finalizeAutoCompletedSupplierPreparations } = await import('./supplierPreparationStatusService');
await finalizeAutoCompletedSupplierPreparations(orderCode, { branchCode });
} catch (error) {
console.warn('[picking] 30 分拣完成补备货成本失败', orderCode, error);
}
const after = await pool.query(
`SELECT id FROM inspections
WHERE order_code = $1 AND actual_qty IS NULL AND quality_rating IS NULL`,
[orderCode]
);
const created = after.rows.map((row) => String(row.id)).filter((id) => !beforeIds.has(id));
if (created.length) {
await pool.query(
`DELETE FROM inspections WHERE id = ANY($1::uuid[]) AND actual_qty IS NULL
AND COALESCE(quality_rating, '') = ''`,
[created]
).catch(() => undefined);
}
}
/** 分拣全部完成后,不要求先验收,直接把 30/40/45 推到 50;配送任务仍走现有守卫。 */
async function forceOrderReadyForDeliveryAfterPicking(
orderCode: string,
branchCode?: string | null
): Promise<boolean> {
const code = String(orderCode || '').trim();
if (!code) return false;
const order = await pool.query(
`SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`,
[code]
);
const status = Number(order.rows[0]?.order_status);
if (![30, 40, 45].includes(status)) return false;
const inboundPresent = status === 40 || status === 45
? (await pool.query(
`SELECT 1 FROM inspections
WHERE order_code = $1 AND (actual_qty > 0 OR inbound_batch_no IS NOT NULL)
LIMIT 1`,
[code]
)).rowCount
: 0;
// 30→30;40/45 无入库→45(分拣完成无需入库);40/45 有入库保留原 flag。
const autoFlag = status === 30
? 30
: status === 40 && !inboundPresent
? 40
: status === 45 && !inboundPresent
? 45
: null;
// 散客/独立进货/全直送/自提/极简流转不强制 50;整单待取货可以 50,但配送由 ensure 守卫拦住。
if (await isNoAutoDeliveryOrder(code, branchCode || null, { includeFullySkip: false, includeSelfPickup: false })) return false;
if ((await countUnfinishedPickingTasks(code)) > 0) return false;
if ((await countWarehouseItemsMissingPicking(code)) > 0) return false;
const updated = await pool.query(
`UPDATE orders
SET order_status = 50,
updated_at = NOW(),
auto_advanced_from_status = CASE
WHEN $2::int IS NOT NULL THEN COALESCE(auto_advanced_from_status, $2::int)
ELSE auto_advanced_from_status
END,
auto_advanced_at = CASE
WHEN $2::int IS NOT NULL THEN NOW()
ELSE auto_advanced_at
END
WHERE order_code = $1 AND order_status IN (30, 40, 45)`,
[code, autoFlag]
);
if (!updated.rowCount) return false;
await ensureDeliveryTaskForOrder(code, branchCode || null).catch(() => undefined);
// 到 50(待配送/待取货)即通知主系统「备货完成」;不能只在发车路径回写,
// 否则待取货/免配送单永远停在主系统待备货。非阻塞、失败由对账兜底。
enqueueMainSystemWritebackForReadyOrder({ branchCode: branchCode || null, orderCode: code });
return true;
}
/** 分拣列表加载时修复“分拣已完成但订单仍停在 30/40/45”的历史卡单。 */
export async function recoverOrdersReadyForDeliveryAfterPicking(
ctx: TenantContext | null | undefined
): Promise<number> {
const params: unknown[] = [];
const branchFilter = branchClause(ctx, 'o', params);
const result = await pool.query(
`SELECT DISTINCT o.order_code, o.branch_code
FROM orders o
JOIN picking_tasks pt ON pt.order_code = o.order_code
WHERE o.order_status IN (30, 40, 45)
AND ${orderNotDeletedSql('o')}
${branchFilter}
AND pt.pick_status >= 30
AND NOT EXISTS (
SELECT 1 FROM picking_tasks pt2
WHERE pt2.order_code = o.order_code AND COALESCE(pt2.pick_status, 10) < 30
)
ORDER BY o.updated_at DESC NULLS LAST
LIMIT 50`,
params
);
let count = 0;
for (const row of result.rows) {
if (await forceOrderReadyForDeliveryAfterPicking(String(row.order_code), row.branch_code)) {
count += 1;
}
}
return count;
}
export async function confirmPickingComplete(input: {
pickCode: string;
rows?: PickingProgressRow[];
reviewerId?: string | null;
ctx?: TenantContext | null;
/** 直接配送补分拣用:由外层 tryAdvance 继续推进,避免递归发车。 */
deferAdvance?: boolean;
}) {
const pickCode = String(input.pickCode || '').trim();
if (!pickCode) throw Object.assign(new Error('缺少拣货单号'), { status: 400 });
const client = await pool.connect();
try {
await client.query('BEGIN');
const taskResult = await client.query(
`SELECT pick_code, pick_status, branch_code, order_code FROM picking_tasks WHERE pick_code = $1 FOR UPDATE`,
[pickCode]
);
const task = taskResult.rows[0];
if (!task) throw Object.assign(new Error('分拣任务不存在'), { status: 404 });
if (
input.ctx?.branchCode &&
task.branch_code &&
task.branch_code !== input.ctx.branchCode &&
!input.ctx.isSuperAdmin
) {
throw Object.assign(new Error('无权操作其他分公司分拣任务'), { status: 403 });
}
if (Number(task.pick_status) >= 40) {
throw Object.assign(new Error('该分拣任务已出库'), { status: 400 });
}
if (Number(task.pick_status) >= 30) {
await client.query('COMMIT');
return { pickCode, alreadyCompleted: true, syncedItems: 0, hasDiff: false };
}
/**
* 分拣完成前校验:**销售价为 0 的商品不允许完成分拣**(2026-10-20 开发者需求)。
* 放在后端而不是前端/小程序:网页端与小程序共用本接口 ⇒ 小程序零改动即生效。
*
* 覆盖范围:**该分拣单涉及的所有订单**(`picking_items.order_code` ∪ `picking_tasks.order_code`),
* 将来若出现"一单拣货包含多订单"的形态也不会漏拦。
* 例外:**独立进货单**(哨兵客户 `__INDEPENDENT_INBOUND__`,按设计销售价锁 0)。
* 散客单不豁免:散客也应有销售价,零价同样拦(补价后再分拣)。
*/
const pickOrderRows = await client.query<{ order_code: string | null }>(
`SELECT DISTINCT order_code FROM picking_items WHERE pick_code = $1 AND order_code IS NOT NULL
UNION
SELECT order_code FROM picking_tasks WHERE pick_code = $1 AND order_code IS NOT NULL`,
[pickCode]
);
const pickOrderCodes = pickOrderRows.rows
.map((r) => String(r.order_code || '').trim())
.filter(Boolean);
if (pickOrderCodes.length) {
const customerRows = await client.query<{ order_code: string; customer_code: string | null }>(
`SELECT order_code, customer_code FROM orders WHERE order_code = ANY($1::text[])`,
[pickOrderCodes]
);
const exemptCodes = new Set(
customerRows.rows
.filter((r) => String(r.customer_code || '') === '__INDEPENDENT_INBOUND__')
.map((r) => String(r.order_code))
);
const checkedOrders = pickOrderCodes.filter((code) => !exemptCodes.has(code));
if (checkedOrders.length) {
/**
* ⚠️ **排除已退回行**(2026-10-24 真机误拦):
* 退货流程会留下 `is_returned=true` 的历史行(其 `price` 被清零),这些行**不参与本次分拣**,
* 但旧查询把它们也算进来 ⇒ 明明在售行销售价 5/3 元,仍被拦「销售价为 0」,
* 而订单详情(只显示未退货行)看不到那两条,用户完全无法理解。
* 仍覆盖"该分拣单涉及的所有订单"的**在售行**(含散客;独立进货单上面已整体豁免)。
*/
const zeroPriced = await client.query<{ item_name: string | null; sku_code: string | null }>(
`SELECT item_name, sku_code FROM order_items
WHERE order_code = ANY($1::text[])
AND COALESCE(is_returned, false) = false
AND COALESCE(price, 0) <= 0
ORDER BY item_name NULLS LAST, sku_code NULLS LAST
LIMIT 20`,
[checkedOrders]
);
if (zeroPriced.rowCount) {
const names = zeroPriced.rows
.map((r) => String(r.item_name || r.sku_code || '').trim())
.filter(Boolean)
.join('、');
throw Object.assign(
new Error(
`以下商品销售价为 0,请前往订单管理设置销售价后再完成分拣:${names || '(未命名商品)'}`
),
{ status: 400, code: 'zero_sale_price' }
);
}
}
}
if (input.rows?.length) {
for (const row of input.rows) {
const requiredQty = Number(row.required_qty) || 0;
const pickedQty = Number(row.picked_qty) || 0;
const pickedWeight = Number(row.picked_weight) || 0;
const unit = String(row.unit || '').trim() || null;
const saved = normalizePickingSavedMeasures(pickedQty, pickedWeight, unit);
const settlement = resolvePickingSettlementQty(saved.picked_qty, saved.picked_weight, unit);
if (settlement <= 0) {
throw Object.assign(new Error('实拣数量/重量必须大于 0,不能按 0 完成分拣'), { status: 400 });
}
const itemStatus = pickingItemReviewStatus(requiredQty, saved.picked_qty, saved.picked_weight, unit);
// 出库留证照片(商品级,可选):行传了且非空 ⇒ 覆盖写;不传/空 ⇒ 列不变(保留历史留证)
const rowPhotos = Array.isArray(row.outbound_photos)
? row.outbound_photos.map((p) => String(p || '').trim()).filter(Boolean)
: [];
await client.query(
`UPDATE picking_items
SET picked_qty = $1, picked_weight = $2, review_status = $3, diff_reason = $4,
unit = COALESCE($7::varchar, unit),
outbound_batches = COALESCE($8::jsonb, outbound_batches),
outbound_photos = COALESCE($9::text[], outbound_photos)
WHERE id = $5 AND pick_code = $6`,
[
saved.picked_qty,
saved.picked_weight,
itemStatus,
row.diff_reason || null,
row.id,
pickCode,
unit,
row.outbound_batches !== undefined
? JSON.stringify(normalizeOutboundBatches(row.outbound_batches) || [])
: null,
rowPhotos.length ? rowPhotos : null,
]
);
}
}
const items = await client.query(
/**
* ⚠️ 与 `PICKING_ITEMS_ENRICHED_SQL` **同一套口径**(2026-10-12):退货/删行后没留下实物动作的
* 残留行不参与完成校验 —— 否则「界面看不到那两行、提交却报『还有 2 项未确认分拣』」互锁。
* 已拣/已核货的行照旧校验(历史事故:分拣完成会把实拣量写成结算量,不能漏行)。
*/
`SELECT pi.id, pi.order_item_id, pi.item_name, pi.required_qty, pi.picked_qty, pi.picked_weight,
pi.review_status, pi.unit, pi.order_code,
s.unit AS inventory_unit
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN skus s ON s.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
WHERE pi.pick_code = $1
AND (
pi.order_item_id IS NULL
OR (oi.id IS NOT NULL AND COALESCE(oi.is_returned, false) = false)
OR COALESCE(pi.picked_qty, 0) > 0
OR COALESCE(pi.loaded_qty, 0) > 0
)`,
[pickCode]
);
if (!items.rows.length) throw Object.assign(new Error('分拣任务没有明细'), { status: 400 });
const unconfirmed = items.rows.filter((row) => Number(row.review_status) < 20);
if (unconfirmed.length) {
throw Object.assign(new Error(`还有 ${unconfirmed.length} 项未确认分拣`), { status: 400 });
}
const zeroItems = items.rows.filter(
(row) => resolvePickingSettlementQty(row.picked_qty, row.picked_weight, row.unit) <= 0
);
if (zeroItems.length) {
throw Object.assign(new Error(`还有 ${zeroItems.length} 项实拣为 0,请改量后再分拣完成`), {
status: 400,
});
}
const scaleRequired = await isPickingScaleRequired();
const missingWeight = items.rows.filter((row) => {
const inventoryUnit = String(row.inventory_unit || '').trim();
if (!isPickingWeightUnit(inventoryUnit)) return false;
if ((Number(row.required_qty) || 0) <= 0) return false;
// 库存按重量管理,且订单单位不是重量单位时,必须称重;同单位沿用原有 scale 开关。
if (!scaleRequired && isPickingWeightUnit(row.unit)) return false;
return (Number(row.picked_weight) || 0) <= 0;
});
if (missingWeight.length) {
throw Object.assign(
new Error(`还有 ${missingWeight.length} 项重量单位未录入实拣重量`),
{ status: 400 }
);
}
let hasDiff = false;
for (const row of items.rows) {
const requiredQty = Number(row.required_qty) || 0;
const settlement = resolvePickingSettlementQty(row.picked_qty, row.picked_weight, row.unit);
if (Math.abs(requiredQty - settlement) > 0.0001) hasDiff = true;
}
await client.query(
`UPDATE picking_tasks
SET pick_status = 30,
reviewed_at = NOW(),
reviewer_id = $2,
pick_completed_at = NOW(),
pick_completed_by = $2
WHERE pick_code = $1`,
[pickCode, input.reviewerId || null]
);
const relatedOrderCodes = Array.from(
new Set(
[task.order_code, ...items.rows.map((row) => row.order_code)]
.map((code) => String(code || '').trim())
.filter(Boolean)
)
);
await client.query('COMMIT');
// 分拣完成即补上游/推进待配送(出库与装车核货合并,见 20260821-merge-outbound-with-loading)
for (const orderCode of relatedOrderCodes) {
await autoInboundFromPickingBeforeComplete({
pickCode,
branchCode: task.branch_code ? String(task.branch_code) : null,
ctx: input.ctx || null,
}).catch((error) => console.warn('[picking] 分拣完成自动补上游失败', orderCode, error));
// 分拣完成即无需入库:无实际入库时关闭 pending 验收并留 no_inventory 审计;有实际入库保留。
try {
const actualInbound = await pool.query(
`SELECT 1 FROM inspections
WHERE order_code = $1
AND (COALESCE(actual_qty, 0) > 0 OR inbound_batch_no IS NOT NULL)
LIMIT 1`,
[orderCode]
);
const deleted = await pool.query(
`DELETE FROM inspections
WHERE order_code = $1 AND actual_qty IS NULL AND COALESCE(quality_rating, '') = ''
RETURNING id`,
[orderCode]
);
if (!actualInbound.rowCount) {
await pool.query(
`INSERT INTO delivery_loading_backfill_logs
(branch_code, order_code, task_code, missing_stage, operator_id,
confirmed_qty, inbound_qty, picking_qty, inventory_action, pick_code, remark)
VALUES ($1,$2,$3,'picking',$4,0,0,0,'no_inventory',$5,$6)`,
[
task.branch_code ? String(task.branch_code) : null,
orderCode,
null,
input.reviewerId || null,
pickCode,
`分拣完成即无需入库:关闭 ${deleted.rowCount || 0} 条 pending 验收`,
]
).catch(() => undefined);
}
} catch (error) {
console.warn('[picking] 分拣完成关闭 pending 验收失败', orderCode, error);
}
if (!input.deferAdvance) {
await tryAdvanceOrderToDelivery(orderCode);
}
await forceOrderReadyForDeliveryAfterPicking(
orderCode,
task.branch_code ? String(task.branch_code) : null
);
}
// 订单单位与库存单位不一致(如订单 70 个 / 库存斤):分拣称重后,
// 先按实际重量调整本地计划数量/单位/实收,再写主系统同步 outbox。
// 库存扣减已由出库服务按 SKU 库存单位完成,这里不重复扣库。
for (const row of items.rows) {
const inventoryUnit = String(row.inventory_unit || '').trim();
if (
!inventoryUnit ||
!isPickingWeightUnit(inventoryUnit) ||
isPickingWeightUnit(row.unit) ||
!Number(row.picked_weight || 0) ||
!row.order_item_id
) {
continue;
}
try {
const { changeOrderItemPlan } = await import('./mainSystemPlanChangeService');
await changeOrderItemPlan({
orderCode: String(row.order_code || task.order_code || ''),
itemId: String(row.order_item_id),
afterQty: Number(row.picked_weight),
afterUnit: inventoryUnit,
actualReceivedQty: Number(row.picked_weight),
reason: '分拣称重后按实际重量',
requestId: `pick_${pickCode}_${row.id}`,
operatorId: input.reviewerId || null,
});
} catch (error) {
console.warn('[picking] 分拣后修改本地计划失败(不阻断分拣)', pickCode, (error as Error)?.message || error);
}
}
// 第九批「批次报告同步」触发点①:分拣完成 ⇒ 本次出库批次已确定,旁路异步推批次报告
// (未绑定/非主系统下发的行在推送侧被物理拦住;开关默认关 ⇒ 零出站。见 20261011-批次报告推送主系统.md)
const { triggerReportPush } = await import('./mainSystemReportPushService');
triggerReportPush(input.ctx?.branchCode);
return { pickCode, alreadyCompleted: false, syncedItems: 0, hasDiff, outbound: false };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
/** 兼容旧名:仅分拣完成,不再自动出库、不调单 */
/** pg 的 date/timestamptz → 中国时区 'YYYY-MM-DD' */
function toDateOnlyLocal(v: unknown): string | null {
if (v == null) return null;
const d = v instanceof Date ? v : new Date(String(v));
if (Number.isNaN(d.getTime())) return null;
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
/**
* 某分拣明细「本次可扣批次」:逐批可用 + SKU 级汇总(总可用 / 他单预留 / 本次可扣)。
* **只读**,不扣库。默认按 FIFO 顺序返回,供 UI 预分配。
* 见 docs/design/20261031-分拣出库可选批次与区域分组.md
*/
export async function listPickingOutboundBatches(input: {
pickItemId: string;
ctx?: TenantContext | null;
}): Promise<{
sku_code: string | null;
order_code: string | null;
/**
* **本订单行要求的规格**(`order_items.spec`,2026-10-16 方案丙 P3):空 = 客户没指定 ⇒ 与改前完全一致。
* 界面据此打「规格一致」标记;**不得**拿 SKU 档案规格反推。
*/
order_spec: string | null;
total_available: number;
other_reserved: number;
claimable: number;
batches: Array<{
batch_id: string;
batch_no: string;
available_qty: number;
storage_zone: string | null;
inbound_date: string | null;
production_date: string | null;
/** 本批货的规格(`inventory.spec`);空 = 未知(存量不回填) */
spec: string | null;
/**
* 是否命中本订单行要求的规格(归一化后精确相等)。由**服务端 SQL** `public.norm_spec` 算出
* —— 与实扣同一个函数;前端不得自己重算(口径漂移会让"标记"与"实扣"不一致)。
* 订单行没有规格 ⇒ 恒 false。
*/
spec_matched: boolean;
}>;
}> {
const pickItemId = String(input.pickItemId || '').trim();
if (!pickItemId) throw Object.assign(new Error('缺少分拣明细'), { status: 400 });
const itemRes = await pool.query(
`SELECT pi.sku_code, pi.order_code, pt.branch_code,
-- 本行要求的规格(方案丙 P3):抵扣/分拣同口径,界面标记也用它
(SELECT NULLIF(TRIM(oi.spec), '') FROM order_items oi WHERE oi.id = pi.order_item_id) AS order_spec
FROM picking_items pi
LEFT JOIN picking_tasks pt ON pt.pick_code = pi.pick_code
WHERE pi.id = $1::uuid LIMIT 1`,
[pickItemId]
);
const item = itemRes.rows[0];
if (!item) throw Object.assign(new Error('分拣明细不存在'), { status: 404 });
const skuCode = String(item.sku_code || '').trim();
const orderCode = String(item.order_code || '').trim() || null;
const branchCode = item.branch_code ? String(item.branch_code) : null;
const orderSpec = item.order_spec ? String(item.order_spec) : null;
if (
input.ctx?.branchCode &&
branchCode &&
branchCode !== input.ctx.branchCode &&
!input.ctx.isSuperAdmin
) {
throw Object.assign(new Error('无权查看其他分公司分拣明细'), { status: 403 });
}
const params: unknown[] = [skuCode, orderSpec];
let branchFilter = '';
if (branchCode) {
params.push(branchCode);
branchFilter = `AND branch_code = $${params.length}`;
}
const batchRes = await pool.query(
`SELECT id, batch_no, available_qty, storage_zone, created_at, production_date, expiry_date,
NULLIF(TRIM(spec), '') AS spec,
(NULLIF(TRIM($2), '') IS NOT NULL
AND public.norm_spec(spec) IS NOT DISTINCT FROM public.norm_spec($2)) AS spec_matched
FROM inventory
WHERE sku_code = $1 AND available_qty > 0 ${branchFilter}
-- ⚠️ 与抵扣/批次计划**同一份排序片段**:有规格 ⇒ 命中批优先、其余仍 FIFO;没规格 ⇒ 逐字等于改前
ORDER BY ${batchSelectionOrderBy({ orderSpecSql: '$2' })}`,
params
);
const batches = batchRes.rows.map((r) => ({
batch_id: String(r.id),
batch_no: String(r.batch_no),
available_qty: Number(r.available_qty) || 0,
storage_zone: r.storage_zone == null ? null : String(r.storage_zone),
inbound_date: toDateOnlyLocal(r.created_at),
production_date: toDateOnlyLocal(r.production_date),
// 排序就用它(先入库先出,同时刻空效期优先);展示出来才能解释“为什么先出这批”
expiry_date: toDateOnlyLocal(r.expiry_date),
// 方案丙 P3:本批货的规格 + 是否命中本行要求的规格(命中标记来自 SQL,前端不自算)
spec: r.spec == null ? null : String(r.spec),
spec_matched: r.spec_matched === true,
}));
const totalAvailable = batches.reduce((s, b) => s + b.available_qty, 0);
const claimable = await getClaimableStockQty(pool, skuCode, branchCode, orderCode || undefined);
const round3 = (n: number) => Math.round(n * 1000) / 1000;
return {
sku_code: skuCode || null,
order_code: orderCode,
order_spec: orderSpec,
total_available: round3(totalAvailable),
other_reserved: round3(Math.max(0, totalAvailable - claimable)),
claimable: round3(claimable),
batches,
};
}
export async function submitPickingAudit(input: {
pickCode: string;
reviewerId?: string | null;
ctx?: TenantContext | null;
rows?: PickingProgressRow[];
}) {
const data = await confirmPickingComplete({
pickCode: input.pickCode,
reviewerId: input.reviewerId,
ctx: input.ctx,
rows: input.rows,
});
return { ...data, outbound: false };
}
async function fifoDeduct(
client: PoolClient,
input: {
skuCode: string;
qty: number;
branchCode?: string | null;
orderCode?: string | null;
pickCode: string;
pickItemId?: string | null;
operatorId?: string | null;
itemName?: string | null;
/** 手选批次计划;不传 = 纯 FIFO */
batchPlan?: Array<{ batchNo: string; qty: number }> | null;
},
onBatchDeducted?: (
batch: { batchNo: string; costPrice: number; supplierCode?: string | null; inboundAt?: string | null },
deductedQty: number,
costPrice: number
) => void
) {
return fifoDeductInventory(client, input, onBatchDeducted);
}
async function resolvePickingItemSkus(
client: PoolClient,
input: { pickCode: string; orderCode?: string | null; branchCode?: string | null }
) {
const items = await client.query(
`SELECT pi.id, pi.item_name, pi.sku_code, pi.unit, pi.picked_qty, pi.picked_weight, pi.required_qty,
oi.sku_code AS order_sku,
catalog.code AS catalog_sku
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
${catalogSkuBySpecJoin({ nameExpr: 'pi.item_name', specExpr: 'oi.spec' })}
WHERE pi.pick_code = $1
AND (COALESCE(pi.picked_qty, 0) > 0 OR COALESCE(pi.picked_weight, 0) > 0)`,
[input.pickCode]
);
for (const item of items.rows) {
const resolved =
trimSku(item.sku_code) || trimSku(item.order_sku) || trimSku(item.catalog_sku);
if (resolved) {
if (!trimSku(item.sku_code)) {
await client.query(`UPDATE picking_items SET sku_code = $2 WHERE id = $1`, [
item.id,
resolved,
]);
}
continue;
}
await ensureSkuForPickingOutbound(client, {
pickItemId: item.id,
orderCode: input.orderCode,
itemName: item.item_name,
branchCode: input.branchCode,
unit: item.unit,
});
}
}
async function assertOutboundInventory(
client: PoolClient,
items: Array<{
id?: string;
item_name?: string | null;
sku_code?: string | null;
order_code?: string | null;
picked_qty?: unknown;
required_qty?: unknown;
}>,
branchCode?: string | null,
orderCode?: string | null
) {
const issues: string[] = [];
for (const item of items) {
const skuCode = trimSku(item.sku_code);
const itemOrderCode = trimSku(item.order_code) || trimSku(orderCode) || null;
const qty =
Number(item.picked_qty) > 0
? Number(item.picked_qty)
: Number(item.required_qty) || 0;
const label = trimSku(item.item_name) || skuCode || '未知商品';
if (qty <= 0) continue;
if (skuCode && (await isPassThroughSku({ skuCode, branchCode }, client))) {
continue;
}
if (
itemOrderCode &&
skuCode &&
(await orderSkuSkippedPassThroughLedger(client, itemOrderCode, skuCode))
) {
continue;
}
const loadBatchAvailable = async () => {
if (!itemOrderCode || !label) return 0;
const params: unknown[] = [itemOrderCode, label];
let branchFilter = '';
if (branchCode) {
params.push(branchCode);
branchFilter = `AND inv.branch_code = $${params.length}`;
}
let result = await client.query(
`SELECT COALESCE(SUM(inv.available_qty), 0) AS total
FROM inspections insp
JOIN inventory inv ON inv.batch_no = insp.inbound_batch_no
WHERE insp.order_code = $1
AND TRIM(COALESCE(insp.item_name, '')) = TRIM($2)
AND inv.available_qty > 0 ${branchFilter}`,
params
);
let total = Number(result.rows[0]?.total) || 0;
if (total < qty && branchCode) {
result = await client.query(
`SELECT COALESCE(SUM(inv.available_qty), 0) AS total
FROM inspections insp
JOIN inventory inv ON inv.batch_no = insp.inbound_batch_no
WHERE insp.order_code = $1
AND TRIM(COALESCE(insp.item_name, '')) = TRIM($2)
AND inv.available_qty > 0`,
[itemOrderCode, label]
);
total = Number(result.rows[0]?.total) || 0;
}
return total;
};
if (!skuCode) {
const batchAvailable = await loadBatchAvailable();
if (batchAvailable >= qty) continue;
issues.push(`${label} 缺少 SKU,请先完成验收入库`);
continue;
}
// 与 FIFO 一致:毛可用 − 他单预留(本单预留可消耗)
// 设计:docs/design/20260807-picking-outbound-claimable-assert.md
let available = await getClaimableStockQty(client, skuCode, branchCode, itemOrderCode);
if (available < qty && branchCode) {
available = await getClaimableStockQty(client, skuCode, null, itemOrderCode);
}
if (available < qty) {
available = Math.max(available, await loadBatchAvailable());
}
if (available < qty) {
let hint = '';
if (itemOrderCode && skuCode) {
const peers = await listPurchaseMergePeerOrderCodes(client, {
orderCode: itemOrderCode,
skuCode,
});
if (peers.length) {
hint = `(与订单 ${peers.slice(0, 5).join('、')}${peers.length > 5 ? ' 等' : ''} 合单共用库存)`;
}
}
const short = Math.round((qty - available) * 100) / 100;
issues.push(
`${label}(${skuCode}) 库存不足,需要 ${qty},扣除他单预留后可用 ${available}${hint}`
);
await notifyInventoryShortage({
orderCode: itemOrderCode,
branchCode,
skuCode,
itemName: label,
requiredQty: qty,
availableQty: available,
shortQty: short,
hint: hint || null,
stage: 'picking',
});
}
}
if (issues.length) {
const preview = issues.slice(0, 8).join(';');
const suffix = issues.length > 8 ? ` 等共 ${issues.length} 项` : '';
throw businessError(`无法出库:${preview}${suffix}`);
}
}
/** 订单详情「分拣出库」:按应拣量自动确认分拣完成并出库 */
export async function autoCompletePickingForOrderAdvance(input: {
pickCode: string;
operatorId?: string | null;
ctx?: TenantContext | null;
}) {
const taskResult = await pool.query(`SELECT pick_code, pick_status FROM picking_tasks WHERE pick_code = $1`, [
input.pickCode,
]);
const task = taskResult.rows[0];
if (!task) throw new Error('分拣任务不存在');
if (Number(task.pick_status) >= 40) {
return { pickCode: input.pickCode, alreadyOutbound: true };
}
const items = await pool.query(
`SELECT id, required_qty, picked_qty, picked_weight, review_status FROM picking_items WHERE pick_code = $1`,
[input.pickCode]
);
if (!items.rows.length) throw new Error('分拣任务没有明细');
const rows: PickingProgressRow[] = items.rows.map((item) => {
const requiredQty = Number(item.required_qty) || 0;
const pickedQty =
Number(item.picked_qty) > 0 || Number(item.picked_weight) > 0 || Number(item.review_status) >= 20
? Number(item.picked_qty) || 0
: requiredQty;
return {
id: String(item.id),
required_qty: requiredQty,
picked_qty: pickedQty,
picked_weight: Number(item.picked_weight) || 0,
};
});
if (Number(task.pick_status) < 30) {
await confirmPickingComplete({
pickCode: input.pickCode,
rows,
reviewerId: input.operatorId,
ctx: input.ctx,
});
}
await completePickingOutbound(input);
return { pickCode: input.pickCode, alreadyOutbound: false };
}
export async function completePickingOutbound(input: {
pickCode: string;
operatorId?: string | null;
ctx?: TenantContext | null;
/** 手选批次计划(按分拣明细 id);不传 = 全部按 FIFO */
itemPlans?: Array<{ pickItemId: string; batches: Array<{ batchNo: string; qty: number }> }> | null;
}) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const taskResult = await client.query(
`SELECT * FROM picking_tasks WHERE pick_code = $1 FOR UPDATE`,
[input.pickCode]
);
const task = taskResult.rows[0];
if (!task) throw businessError('分拣任务不存在', 404);
await assertOrderActiveForFulfillment(task.order_code, client);
if (input.ctx?.branchCode && task.branch_code && task.branch_code !== input.ctx.branchCode && !input.ctx.isSuperAdmin) {
throw businessError('无权操作其他分公司分拣任务', 403);
}
if (Number(task.pick_status) >= 40 || task.outbound_at) {
throw businessError('该分拣任务已出库,不能重复出库');
}
if (Number(task.pick_status) < 30) {
throw businessError('请先完成分拣后再出库');
}
await resolvePickingItemSkus(client, {
pickCode: input.pickCode,
orderCode: task.order_code,
branchCode: task.branch_code,
});
const allItems = await client.query(
`SELECT pi.*,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
o.order_status,
s.unit AS inventory_unit
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN orders o ON o.order_code = pi.order_code
LEFT JOIN skus s ON s.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
WHERE pi.pick_code = $1`,
[input.pickCode]
);
if (!allItems.rows.length) throw businessError('分拣任务没有明细');
// 手选批次计划:按分拣明细 id 归组(不传则全部走 FIFO)
const planByItem = new Map<string, Array<{ batchNo: string; qty: number }>>();
for (const plan of input.itemPlans || []) {
const id = String(plan?.pickItemId || '').trim();
if (!id || !Array.isArray(plan?.batches)) continue;
planByItem.set(id, plan.batches);
}
const outboundDetail: Array<{
sku_code: string | null;
sku_name: string | null;
batch_no: string;
inbound_at: string | null;
qty: number;
}> = [];
for (const code of new Set(
allItems.rows
.map((r: { order_code?: string | null }) => String(r.order_code || '').trim())
.filter(Boolean)
)) {
await assertOrderActiveForFulfillment(code, client);
}
const pendingRows = allItems.rows.filter(
(row: { outbound_at?: string | null }) => !row.outbound_at
);
/** 库存扣减口径:优先 SKU 库存单位;订单单位/个不能直接当斤。 */
const pickingSettlement = (row: { picked_qty?: unknown; picked_weight?: unknown; unit?: unknown; inventory_unit?: unknown }) =>
resolvePickingSettlementQty(row.picked_qty, row.picked_weight, String(row.inventory_unit || row.unit || ''));
const warehousePending = pendingRows.filter(
(row: { is_extra_dish?: unknown; order_status?: unknown }) =>
!isTruthyFlag(row.is_extra_dish) && Number(row.order_status) < 50
);
const items = warehousePending.filter((row) => pickingSettlement(row) > 0);
if (!items.length) {
if (!warehousePending.length) {
await client.query(
`UPDATE picking_items SET outbound_at = COALESCE(outbound_at, NOW()) WHERE pick_code = $1 AND outbound_at IS NULL`,
[input.pickCode]
);
await client.query(
`UPDATE picking_tasks SET pick_status = 40, outbound_at = COALESCE(outbound_at, NOW()) WHERE pick_code = $1`,
[input.pickCode]
);
await client.query('COMMIT');
return { success: true, skippedWarehouse: true };
}
if (!pendingRows.length) {
throw businessError('该分拣任务已全部出库');
}
throw businessError('实拣数量/重量均为 0,不能出库。请先按实际分拣量确认后再出库');
}
await assertOutboundInventory(
client,
items.map((row) => ({
...row,
picked_qty: pickingSettlement(row),
})),
task.branch_code,
task.order_code || items[0]?.order_code || null
);
for (const item of items) {
const outboundQty = pickingSettlement(item);
if (outboundQty <= 0 || !trimSku(item.sku_code)) continue;
if (await isPassThroughSku({ skuCode: trimSku(item.sku_code), branchCode: task.branch_code }, client)) {
continue;
}
if (
await orderSkuSkippedPassThroughLedger(
client,
String(item.order_code || task.order_code || ''),
trimSku(item.sku_code)
)
) {
continue;
}
await fifoDeduct(
client,
{
skuCode: trimSku(item.sku_code),
qty: outboundQty,
branchCode: task.branch_code,
orderCode: item.order_code || task.order_code,
pickCode: input.pickCode,
pickItemId: item.id,
operatorId: input.operatorId,
itemName: item.item_name,
batchPlan: planByItem.get(String(item.id)) || undefined,
},
(batch, deductedQty) => {
outboundDetail.push({
sku_code: trimSku(item.sku_code) || null,
sku_name: item.item_name ? String(item.item_name) : null,
batch_no: batch.batchNo,
inbound_at: batch.inboundAt ?? null,
qty: deductedQty,
});
}
);
}
await client.query(
`UPDATE picking_items SET outbound_at = NOW() WHERE pick_code = $1 AND outbound_at IS NULL`,
[input.pickCode]
);
await client.query(
`UPDATE picking_tasks SET pick_status = 40, outbound_at = NOW() WHERE pick_code = $1`,
[input.pickCode]
);
const orderCodesResult = await client.query(
`SELECT DISTINCT order_code FROM picking_items
WHERE pick_code = $1 AND order_code IS NOT NULL AND TRIM(order_code) <> ''`,
[input.pickCode]
);
const relatedOrderCodes = orderCodesResult.rows
.map((row) => String(row.order_code))
.filter(Boolean);
if (task.order_code && !relatedOrderCodes.includes(String(task.order_code))) {
relatedOrderCodes.push(String(task.order_code));
}
const awaitingPickup = new Set<string>();
for (const orderCode of relatedOrderCodes) {
const advance = await maybeAdvanceOrderAfterPickingOutbound(client, orderCode);
if (advance.skipInboundAwaitingPickup) awaitingPickup.add(orderCode);
}
await client.query('COMMIT');
// 主系统免入库:我方货备齐 ⇒ **事务提交后**非阻塞回写 status=30。
// 主系统必须先收到它才会推进到可发车;否则配送员不上门、picked_up 永不触发(死锁)。
// HTTP 永不在事务内 —— 这里已在 COMMIT 之后。见设计文档 20261010 §3.4。
for (const orderCode of awaitingPickup) {
enqueueMainSystemWritebackForReadyOrder({
branchCode: task.branch_code || null,
orderCode,
});
}
for (const orderCode of relatedOrderCodes) {
await tryAdvanceOrderToDelivery(orderCode);
const unfinishedAfter = await countUnfinishedPickingTasks(orderCode);
const missingWarehouse = await countWarehouseItemsMissingPicking(orderCode);
if (unfinishedAfter === 0 && missingWarehouse === 0) {
// 已结案(含"主系统免入库:分拣完毕即完成"与"商品直送齐套")不需要配送任务,
// 否则会给 90 的订单留下永远用不上的孤儿任务。
const st = await pool.query(`SELECT order_status FROM orders WHERE order_code = $1`, [orderCode]);
if (Number(st.rows[0]?.order_status) >= 90) continue;
await ensureDeliveryTaskForOrder(orderCode, task.branch_code || null);
}
}
// 出库留痕到系统操作日志(分拣员 + 逐批次:品名/批次/入库日/数量)
try {
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'picking_outbound',
targetTable: 'picking_tasks',
targetId: input.pickCode,
oldValue: null,
newValue: {
pick_code: input.pickCode,
order_codes: relatedOrderCodes,
batches: outboundDetail,
},
branchCode: task.branch_code || null,
actionCategory: 'picking',
});
} catch (auditError) {
console.error('[picking] writeAuditLog(outbound) failed:', auditError);
}
return { success: true };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
/** 扫码出库:扫拣货单号 → 整单出库;扫容器码 → 只出库该容器对应的一件 */
export async function outboundByScan(input: {
barcode: string;
operatorId?: string | null;
ctx?: TenantContext | null;
}) {
const code = String(input.barcode || '').trim();
if (!code) throw businessError('请扫描拣货单号或容器码');
const byPick = await pool.query(
`SELECT pick_code FROM picking_tasks WHERE pick_code = $1 LIMIT 1`,
[code]
);
if (!byPick.rows[0]) {
// 非拣货单号:按容器码逐件出库
return outboundPickingByContainer({
containerCode: code,
operatorId: input.operatorId,
ctx: input.ctx,
});
}
const pickCode = String(byPick.rows[0].pick_code);
const taskCheck = await pool.query(
`SELECT pick_code, pick_status, branch_code FROM picking_tasks WHERE pick_code = $1`,
[pickCode]
);
const task = taskCheck.rows[0];
if (!task) throw businessError('分拣任务不存在', 404);
if (
input.ctx?.branchCode &&
task.branch_code &&
task.branch_code !== input.ctx.branchCode &&
!input.ctx.isSuperAdmin
) {
throw businessError('无权操作其他分公司分拣任务', 403);
}
await completePickingOutbound({
pickCode,
operatorId: input.operatorId,
ctx: input.ctx,
});
await logPickingScan({
pickCode,
barcode: code,
scanType: 'outbound_pick',
operatorId: input.operatorId,
branchCode: task.branch_code,
}).catch(() => undefined);
return { pickCode, scanType: 'pick_code' as const, barcode: code, outbound: true, taskCompleted: true };
}
/** 扫容器码:只出库该容器对应的一件明细;整单明细全部出库后任务才置 40 并推进订单 */
export async function outboundPickingByContainer(input: {
containerCode: string;
operatorId?: string | null;
ctx?: TenantContext | null;
}) {
const code = String(input.containerCode || '').trim();
if (!code) throw businessError('请扫描容器码');
const containerResult = await pool.query(
`SELECT container_code, pick_code, pick_item_id FROM picking_containers WHERE container_code = $1 LIMIT 1`,
[code]
);
const container = containerResult.rows[0];
if (!container?.pick_code || !container?.pick_item_id) {
throw businessError(`未识别的拣货单或容器码:${code}`, 404);
}
const client = await pool.connect();
let taskCompleted = false;
let relatedOrderCodes: string[] = [];
/** 主系统免入库、已停在 50 等主系统取货的订单:事务提交后要回写 status=30(HTTP 不进事务) */
const awaitingPickupOrders = new Set<string>();
let taskBranchCode: string | null = null;
try {
await client.query('BEGIN');
const taskResult = await client.query(
`SELECT * FROM picking_tasks WHERE pick_code = $1 FOR UPDATE`,
[container.pick_code]
);
const task = taskResult.rows[0];
if (!task) throw businessError('分拣任务不存在', 404);
taskBranchCode = task.branch_code || null;
if (
input.ctx?.branchCode &&
task.branch_code &&
task.branch_code !== input.ctx.branchCode &&
!input.ctx.isSuperAdmin
) {
throw businessError('无权操作其他分公司分拣任务', 403);
}
if (Number(task.pick_status) >= 40 || task.outbound_at) {
throw businessError('该分拣任务已全部出库,不能重复出库');
}
if (Number(task.pick_status) < 30) {
throw businessError('请先完成分拣后再出库');
}
await assertOrderActiveForFulfillment(task.order_code, client);
await resolvePickingItemSkus(client, {
pickCode: task.pick_code,
orderCode: task.order_code,
branchCode: task.branch_code,
});
const itemResult = await client.query(
`SELECT pi.*,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
o.order_status,
s.unit AS inventory_unit
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN orders o ON o.order_code = pi.order_code
LEFT JOIN skus s ON s.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
WHERE pi.id = $1 AND pi.pick_code = $2 FOR UPDATE`,
[container.pick_item_id, task.pick_code]
);
const item = itemResult.rows[0];
if (!item) throw businessError('容器对应的拣货明细不存在', 404);
if (item.order_code) {
await assertOrderActiveForFulfillment(item.order_code, client);
}
if (item.outbound_at) {
// 重复扫同一件:不再扣库存,直接反馈已出库
const remainRes = await client.query(
`SELECT COUNT(*)::int AS n FROM picking_items WHERE pick_code = $1 AND outbound_at IS NULL`,
[task.pick_code]
);
await client.query('COMMIT');
return {
pickCode: String(task.pick_code),
scanType: 'container' as const,
barcode: code,
outbound: true,
alreadyOutbound: true,
itemName: item.item_name,
skuCode: item.sku_code,
remainingCount: Number(remainRes.rows[0]?.n) || 0,
taskCompleted: false,
};
}
const skipWarehouse =
isTruthyFlag(item.is_extra_dish) || Number(item.order_status) >= 50;
const outboundQty = resolvePickingSettlementQty(
item.picked_qty,
item.picked_weight,
String(item.inventory_unit || item.unit || '')
);
if (!skipWarehouse && outboundQty <= 0) {
throw businessError('该件实拣数量/重量为 0,不能出库');
}
if (!skipWarehouse) {
await assertOutboundInventory(
client,
[{ ...item, picked_qty: outboundQty }],
task.branch_code,
item.order_code || task.order_code || null
);
if (trimSku(item.sku_code)) {
const passThrough = await isPassThroughSku(
{ skuCode: trimSku(item.sku_code), branchCode: task.branch_code },
client
);
if (
!(
passThrough ||
(await orderSkuSkippedPassThroughLedger(
client,
String(item.order_code || task.order_code || ''),
trimSku(item.sku_code)
))
)
) {
await fifoDeduct(client, {
skuCode: trimSku(item.sku_code),
qty: outboundQty,
branchCode: task.branch_code,
orderCode: item.order_code || task.order_code,
pickCode: task.pick_code,
pickItemId: item.id,
operatorId: input.operatorId,
itemName: item.item_name,
});
}
}
}
await client.query(`UPDATE picking_items SET outbound_at = NOW() WHERE id = $1`, [item.id]);
await client.query(
`UPDATE picking_containers SET status = 40 WHERE container_code = $1`,
[code]
);
const remainAfter = await client.query(
`SELECT COUNT(*)::int AS n
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN orders o ON o.order_code = pi.order_code
WHERE pi.pick_code = $1
AND pi.outbound_at IS NULL
AND COALESCE(oi.is_extra_dish, false) = false
AND COALESCE(o.order_status, 0) < 50`,
[task.pick_code]
);
const remainingCount = Number(remainAfter.rows[0]?.n) || 0;
if (remainingCount === 0) {
await client.query(
`UPDATE picking_items SET outbound_at = COALESCE(outbound_at, NOW())
WHERE pick_code = $1 AND outbound_at IS NULL`,
[task.pick_code]
);
taskCompleted = true;
await client.query(
`UPDATE picking_tasks SET pick_status = 40, outbound_at = NOW() WHERE pick_code = $1`,
[task.pick_code]
);
const orderCodesResult = await client.query(
`SELECT DISTINCT order_code FROM picking_items
WHERE pick_code = $1 AND order_code IS NOT NULL AND TRIM(order_code) <> ''`,
[task.pick_code]
);
relatedOrderCodes = orderCodesResult.rows
.map((row) => String(row.order_code))
.filter(Boolean);
if (task.order_code && !relatedOrderCodes.includes(String(task.order_code))) {
relatedOrderCodes.push(String(task.order_code));
}
for (const orderCode of relatedOrderCodes) {
const advance = await maybeAdvanceOrderAfterPickingOutbound(client, orderCode);
if (advance.skipInboundAwaitingPickup) awaitingPickupOrders.add(orderCode);
}
}
await client.query('COMMIT');
// 主系统免入库:我方货备齐 ⇒ **事务提交后**非阻塞回写 status=30(HTTP 永不在事务内)。
// 见设计文档 20261010 §3.4。
for (const orderCode of awaitingPickupOrders) {
enqueueMainSystemWritebackForReadyOrder({
branchCode: taskBranchCode || task.branch_code || null,
orderCode,
});
}
await logPickingScan({
pickCode: String(task.pick_code),
pickItemId: String(item.id),
skuCode: item.sku_code ? trimSku(item.sku_code) : undefined,
barcode: code,
scanType: 'outbound_container',
operatorId: input.operatorId,
branchCode: task.branch_code,
}).catch(() => undefined);
return {
pickCode: String(task.pick_code),
scanType: 'container' as const,
barcode: code,
outbound: true,
alreadyOutbound: false,
itemName: item.item_name,
skuCode: item.sku_code,
remainingCount,
taskCompleted,
};
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
if (taskCompleted) {
for (const orderCode of relatedOrderCodes) {
await tryAdvanceOrderToDelivery(orderCode);
const unfinishedAfter = await countUnfinishedPickingTasks(orderCode);
const missingWarehouse = await countWarehouseItemsMissingPicking(orderCode);
if (unfinishedAfter === 0 && missingWarehouse === 0) {
await ensureDeliveryTaskForOrder(orderCode, taskBranchCode);
}
}
}
}
}
export async function logPickingScan(input: {
pickCode: string;
pickItemId?: string;
skuCode?: string;
barcode: string;
scanQty?: number;
scanType?: string;
operatorId?: string | null;
branchCode?: string | null;
}) {
await pool.query(
`INSERT INTO picking_scan_logs (pick_code, pick_item_id, sku_code, barcode, scan_qty, scan_type, operator_id, branch_code)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[
input.pickCode,
input.pickItemId || null,
input.skuCode || null,
input.barcode,
Number(input.scanQty) || 1,
input.scanType || 'review',
input.operatorId || null,
input.branchCode || null,
]
);
}
export async function listUnpickedItems(pickCode: string) {
// 与结算口径一致:斤类用称重,非斤用件数
const result = await pool.query(
`SELECT id, sku_code, item_name, required_qty, picked_qty, picked_weight, unit
FROM picking_items
WHERE pick_code = $1
AND (
CASE
WHEN (
COALESCE(unit, '') ILIKE '%斤%'
OR COALESCE(unit, '') ILIKE '%公斤%'
OR COALESCE(unit, '') ILIKE '%千克%'
OR COALESCE(unit, '') ILIKE '%两%'
OR LOWER(TRIM(COALESCE(unit, ''))) IN ('kg', 'g')
OR TRIM(COALESCE(unit, '')) = '克'
) AND COALESCE(picked_weight, 0) > 0 THEN picked_weight
ELSE COALESCE(picked_qty, 0)
END
) < COALESCE(required_qty, 0)
ORDER BY sort_order NULLS LAST, created_at ASC`,
[pickCode]
);
return result.rows;
}
/** 扫码分拣:匹配 SKU 条码/编码,累加已拣数量并返回未分拣提示 */
export async function scanPickingBarcode(input: {
pickCode: string;
barcode: string;
operatorId?: string | null;
branchCode?: string | null;
incrementQty?: number;
ctx?: TenantContext | null;
}) {
const barcode = input.barcode.trim();
if (!barcode) throw new Error('条码不能为空');
/**
* **按「纸上的码」定位到行**(2026-10-13):
* 分拣面同一份查询(`listPickingItemsEnriched`)里,先看哪一行的**标签值**(`label_barcode`,即标签上真印的
* 那个码)等于扫码串,再看哪一行的**我方码**(`barcode`/`sku_code`)等于它 —— 后者兜旧标签与手输 SKU。
*
* 为什么不再"先把码翻译成我方 SKU 再按 SKU 找行":那样会先丢掉行级唯一性,一旦主系统的 SKU 与我方另一个
* 商品的编码相同(两套命名空间同码),就会**静默把数量记到本单里另一个商品上**(真库已复现)。
* 命中集合内 SKU 不唯一 ⇒ 直接报错,绝不猜。见 docs/design/20261013-扫码按标签值定位行(消除跨系统SKU同码错行).md
*/
const enrichedRows = await listPickingItemsEnriched([input.pickCode]);
const scanTarget = resolvePickingScanRow(enrichedRows, barcode);
const item = scanTarget?.row as
| {
id: string;
sku_code: string;
item_name: string | null;
required_qty: number | string;
picked_qty: number | string;
picked_weight?: number | string | null;
unit: string | null;
review_status?: number | string | null;
}
| undefined;
const skuCode = item?.sku_code;
const taskResult = await pool.query(
`SELECT pick_code, pick_status, branch_code, order_code FROM picking_tasks WHERE pick_code = $1`,
[input.pickCode]
);
const task = taskResult.rows[0];
if (!task) throw new Error('分拣单不存在');
if (Number(task.pick_status) >= 40) throw new Error('分拣单已出库,无法继续扫码');
if (Number(task.pick_status) >= 30) throw new Error('分拣单已完成,请扫码出库');
if (
input.ctx?.branchCode &&
task.branch_code &&
task.branch_code !== input.ctx.branchCode &&
!input.ctx.isSuperAdmin
) {
throw new Error('无权操作该分拣单');
}
if (!item || !skuCode) {
/**
* 本分拣单里没有任何一行能解释这个码。文案要能区分两件事,且**报用户扫到的原串**
* (旧实现会报一个用户没扫过的代码,误导排障):
* · 全局商品库里认识这个码 ⇒ 是本单不包含它("该配送单不包含商品");
* · 完全不认识 ⇒ "未找到条码对应商品"。
*/
const known = await pool.query(
`SELECT sku_code FROM skus WHERE barcode = $1 OR sku_code = $1 LIMIT 1`,
[barcode]
);
if (known.rows[0]?.sku_code) throw new Error(`该配送单不包含商品「${barcode}」`);
throw new Error(`未找到条码对应商品:${barcode}`);
}
const requiredQty = Number(item.required_qty) || 0;
const currentPicked = Number(item.picked_qty) || 0;
const increment = Number(input.incrementQty) || 1;
const newPicked = Math.min(requiredQty, Math.round((currentPicked + increment) * 100) / 100);
const completed = newPicked >= requiredQty;
const reviewStatus = completed ? 30 : newPicked > 0 ? 20 : 10;
await pool.query(`UPDATE picking_items SET picked_qty = $1, review_status = $2 WHERE id = $3`, [
newPicked,
reviewStatus,
item.id,
]);
await logPickingScan({
pickCode: input.pickCode,
pickItemId: item.id,
skuCode,
barcode,
scanQty: increment,
scanType: 'pick',
operatorId: input.operatorId,
branchCode: input.branchCode || task.branch_code,
});
const unpickedItems = await listUnpickedItems(input.pickCode);
const unpickedCount = unpickedItems.length;
// 扫齐只推进到分拣中(20);真正待出库(30)必须走 confirmPickingComplete
if (Number(task.pick_status) < 30) {
await pool.query(`UPDATE picking_tasks SET pick_status = 20 WHERE pick_code = $1 AND pick_status < 30`, [
input.pickCode,
]);
}
return {
skuCode,
itemName: item.item_name,
requiredQty,
pickedQty: newPicked,
unit: item.unit,
completed,
unpickedCount,
unpickedItems,
allPicked: unpickedCount === 0,
};
}
export async function stagePickingContainer(input: {
pickCode: string;
pickItemId: string;
orderCode?: string | null;
branchCode?: string | null;
}) {
const pickCode = String(input.pickCode || '').trim();
const pickItemId = String(input.pickItemId || '').trim();
if (!pickCode || !pickItemId) {
throw Object.assign(new Error('缺少拣货单号或商品明细'), { status: 400 });
}
const itemResult = await pool.query(
`SELECT id, pick_code, item_name, sku_code, picked_qty, picked_weight, required_qty, unit
FROM picking_items
WHERE id = $1 AND pick_code = $2
LIMIT 1`,
[pickItemId, pickCode]
);
const item = itemResult.rows[0] as
| {
id: string;
pick_code: string;
item_name: string | null;
sku_code: string | null;
picked_qty: number;
picked_weight: number;
required_qty: number;
unit?: string | null;
}
| undefined;
if (!item) {
throw Object.assign(new Error('拣货明细不存在或不属于该拣货单'), { status: 404 });
}
const existing = await pool.query(
`SELECT container_code FROM picking_containers WHERE pick_item_id = $1 LIMIT 1`,
[pickItemId]
);
if (existing.rows[0]?.container_code) {
return {
containerCode: String(existing.rows[0].container_code),
pickItemId,
itemName: item.item_name,
skuCode: item.sku_code,
alreadyStaged: true,
};
}
if (resolvePickingSettlementQty(item.picked_qty, item.picked_weight, item.unit) <= 0) {
throw Object.assign(new Error('请先分拣该商品后再装框'), { status: 400 });
}
const containerCode = newContainerCode();
await pool.query(
`INSERT INTO picking_containers (
container_code, pick_code, order_code, pick_item_id, item_count, status, staged_at, branch_code
) VALUES ($1, $2, $3, $4, 1, 20, NOW(), $5)`,
[containerCode, pickCode, input.orderCode || null, pickItemId, input.branchCode || null]
);
return {
containerCode,
pickItemId,
itemName: item.item_name,
skuCode: item.sku_code,
alreadyStaged: false,
};
}
/**
* 自愈:待出库(30) 单上若仍有实拣结算量≤0 的行(完成后又追加的新货),
* 回退到分拣中(20),清完成标记,保留已拣>0 行数据。
* 设计:docs/design/20260807-picking-reopen-on-late-items.md
*/
async function reopenCompletedTasksWithUnpickedLines(ctx: TenantContext | null | undefined) {
const params: unknown[] = [];
let branchFilter = '';
if (ctx?.branchCode && !ctx.isSuperAdmin) {
params.push(ctx.branchCode);
branchFilter = `AND pt.branch_code = $${params.length}`;
}
const result = await pool.query(
`UPDATE picking_tasks pt
SET pick_status = 20,
pick_completed_at = NULL,
pick_completed_by = NULL,
reviewed_at = NULL,
reviewer_id = NULL
WHERE pt.pick_status = 30
${branchFilter}
AND EXISTS (
SELECT 1
FROM picking_items pi
JOIN orders o_re ON o_re.order_code = pi.order_code
LEFT JOIN order_items oi_re ON oi_re.id = pi.order_item_id
WHERE pi.pick_code = pt.pick_code
AND ${orderNotDeletedSql('o_re')}
AND o_re.order_status < 50
AND COALESCE(oi_re.is_extra_dish, false) = false
AND (
CASE
WHEN COALESCE(pi.picked_weight, 0) > 0 THEN pi.picked_weight
ELSE COALESCE(pi.picked_qty, 0)
END
) <= 0
)
RETURNING pt.pick_code`,
params
);
return result.rowCount || 0;
}
async function closePickingTasksWithoutWarehouseWork(ctx: TenantContext | null | undefined) {
const params: unknown[] = [];
const branchFilter = branchClause(ctx, 'pt', params);
const result = await pool.query(
`UPDATE picking_tasks pt
SET pick_status = 40,
outbound_at = COALESCE(pt.outbound_at, NOW())
WHERE COALESCE(pt.pick_status, 10) < 40
${branchFilter}
AND EXISTS (SELECT 1 FROM picking_items pi0 WHERE pi0.pick_code = pt.pick_code)
AND NOT ${pickingWarehouseWorkExistsSql('pt.pick_code')}
RETURNING pt.pick_code`,
params
);
return result.rowCount || 0;
}
export async function syncMissingPickingTasks(ctx: TenantContext | null | undefined) {
await reopenCompletedTasksWithUnpickedLines(ctx);
await closePickingTasksWithoutWarehouseWork(ctx);
const params: unknown[] = [];
let branchFilter = '';
if (ctx?.branchCode && !ctx.isSuperAdmin) {
params.push(ctx.branchCode);
branchFilter = `AND o.branch_code = $${params.length}`;
}
const deliveryWindow = onOrAfterChinaDeliveryDateSql('o', params);
const candidates = await pool.query(
`SELECT o.order_code, o.branch_code, o.customer_code, o.order_status
FROM orders o
WHERE ${deliveryWindow}
${branchFilter}
AND o.deleted_at IS NULL
-- 独立进货单不进分拣(哨兵客户;见 docs/design/20261012-独立进货(自用哨兵客户).md §4)
AND ${salesVisibleOrderSql('o')}
AND (
o.order_status = 45
OR (
o.order_status = 50
AND COALESCE(o.pending_backfill, false) = false
AND NOT EXISTS (
SELECT 1 FROM delivery_tasks dt
WHERE dt.order_code = o.order_code
AND COALESCE(dt.task_status, 10) >= 20
)
AND EXISTS (
SELECT 1 FROM order_items oi
WHERE oi.order_code = o.order_code
AND COALESCE(oi.is_returned, false) = false
AND COALESCE(oi.is_extra_dish, false) = false
AND COALESCE(oi.quantity, 0) > 1e-9
AND NOT ${supplierSkipInboundExistsSql('oi.supplier_code')}
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
AND NOT EXISTS (
SELECT 1 FROM picking_items pi WHERE pi.order_item_id = oi.id
)
)
)
)
ORDER BY o.updated_at DESC NULLS LAST, o.created_at DESC
LIMIT 80`,
params
);
const pickCodes: string[] = [];
let advanced = 0;
for (const row of candidates.rows) {
const branchCode = row.branch_code ? String(row.branch_code) : null;
const pickingEnabled = await isPickingWorkflowEnabled(branchCode);
if (Number(row.order_status) === 50) {
if (!pickingEnabled) continue;
const repaired = await repairMissingWarehousePickingForOrder(String(row.order_code), ctx);
if (repaired.pickCode) pickCodes.push(repaired.pickCode);
continue;
}
if (!pickingEnabled) {
const result = await tryAdvanceOrderToDelivery(String(row.order_code));
if (result.advanced) advanced += 1;
continue;
}
const advance = await tryAdvanceOrderToDelivery(String(row.order_code));
if (advance.advanced) {
advanced += 1;
continue;
}
const mode = await getPickingTaskMode(branchCode);
if (mode === 'category') {
const uncovered = await pool.query(
`SELECT 1
FROM order_items oi
WHERE oi.order_code = $1
AND COALESCE(oi.is_returned, false) = false
AND COALESCE(oi.is_extra_dish, false) = false
AND NOT EXISTS (
SELECT 1 FROM picking_items pi WHERE pi.order_item_id = oi.id
)
LIMIT 1`,
[row.order_code]
);
if (!uncovered.rowCount) continue;
} else {
const uncovered = await pool.query(
`SELECT 1
FROM order_items oi
WHERE oi.order_code = $1
AND COALESCE(oi.is_returned, false) = false
AND COALESCE(oi.is_extra_dish, false) = false
AND NOT EXISTS (
SELECT 1 FROM picking_items pi WHERE pi.order_item_id = oi.id
)
LIMIT 1`,
[row.order_code]
);
if (!uncovered.rowCount) continue;
}
try {
const result = await createPickingTask(
{ orderCode: String(row.order_code), branchCode },
ctx
);
for (const code of result.pickCodes || [result.pickCode]) {
if (code) pickCodes.push(code);
}
} catch {
// 订单尚无可用明细时跳过
}
}
if (advanced > 0 && !pickCodes.length) {
return { synced: advanced, pickCodes, skippedPicking: true };
}
return { synced: pickCodes.length || advanced, pickCodes };
}
export type RebuildOpenPickingResult = {
deleted: number;
created: number;
skipped: number;
orderCodes: string[];
pickCodes: string[];
};
/**
* 切换拣货模式后:删除「未开工」进行中拣货单,按新模式重建。
* 已有拣货数量 / 复核中 / 已装框 / 有扫码记录的单跳过。
*/
export async function rebuildUntouchedOpenPickingTasks(
branchCode: string,
ctx?: TenantContext | null
): Promise<RebuildOpenPickingResult> {
const branch = String(branchCode || '').trim();
if (!branch) throw businessError('缺少分公司编码');
const params: unknown[] = [branch];
const deliveryWindow = onOrAfterChinaDeliveryDateSql('o2', params);
const open = await pool.query(
`SELECT pt.pick_code, pt.pick_status, pt.order_code
FROM picking_tasks pt
WHERE pt.branch_code = $1
AND COALESCE(pt.pick_status, 10) < 40
AND EXISTS (
SELECT 1
FROM picking_items pi2
JOIN orders o2 ON o2.order_code = pi2.order_code
LEFT JOIN order_items oi2 ON oi2.id = pi2.order_item_id
WHERE pi2.pick_code = pt.pick_code
AND ${orderNotDeletedSql('o2')}
AND o2.order_status < 50
AND COALESCE(oi2.is_extra_dish, false) = false
AND ${deliveryWindow}
)
ORDER BY pt.created_at ASC`,
params
);
const toDelete: string[] = [];
let skipped = 0;
for (const row of open.rows) {
const pickCode = String(row.pick_code);
const status = Number(row.pick_status) || 10;
if (status > 10) {
skipped += 1;
continue;
}
const busy = await pool.query(
`SELECT
EXISTS (
SELECT 1 FROM picking_items
WHERE pick_code = $1 AND COALESCE(picked_qty, 0) > 0
) AS has_picked,
EXISTS (
SELECT 1 FROM picking_containers WHERE pick_code = $1 LIMIT 1
) AS has_container,
EXISTS (
SELECT 1 FROM picking_scan_logs WHERE pick_code = $1 LIMIT 1
) AS has_scan`,
[pickCode]
);
const flags = busy.rows[0] || {};
if (flags.has_picked || flags.has_container || flags.has_scan) {
skipped += 1;
continue;
}
toDelete.push(pickCode);
}
if (!toDelete.length) {
return { deleted: 0, created: 0, skipped, orderCodes: [], pickCodes: [] };
}
const orderRows = await pool.query(
`SELECT DISTINCT order_code
FROM (
SELECT NULLIF(TRIM(pi.order_code), '') AS order_code
FROM picking_items pi
WHERE pi.pick_code = ANY($1::text[])
UNION
SELECT NULLIF(TRIM(pt.order_code), '')
FROM picking_tasks pt
WHERE pt.pick_code = ANY($1::text[])
) x
WHERE order_code IS NOT NULL
ORDER BY order_code`,
[toDelete]
);
const orderCodes = orderRows.rows.map((r) => String(r.order_code));
await pool.query(`DELETE FROM picking_scan_logs WHERE pick_code = ANY($1::text[])`, [toDelete]);
await pool.query(`DELETE FROM picking_containers WHERE pick_code = ANY($1::text[])`, [toDelete]);
// 部分 tenant schema 克隆后 picking_items 无 ON DELETE CASCADE,须显式删明细
await pool.query(`DELETE FROM picking_items WHERE pick_code = ANY($1::text[])`, [toDelete]);
await pool.query(`DELETE FROM picking_tasks WHERE pick_code = ANY($1::text[])`, [toDelete]);
// 清掉历史孤儿明细(任务已不存在但仍占 order_item_id)
if (orderCodes.length) {
await pool.query(
`DELETE FROM picking_items pi
WHERE pi.order_code = ANY($1::text[])
AND NOT EXISTS (
SELECT 1 FROM picking_tasks pt WHERE pt.pick_code = pi.pick_code
)`,
[orderCodes]
);
}
const mode = await getPickingTaskMode(branch);
const createdPickCodes: string[] = [];
for (const orderCode of orderCodes) {
try {
const result = await createPickingTask({ orderCode, branchCode: branch }, ctx);
for (const code of result.pickCodes || [result.pickCode]) {
if (code) createdPickCodes.push(code);
}
} catch {
// 订单已不可建拣货单时跳过
}
}
return {
deleted: toDelete.length,
created: createdPickCodes.length,
skipped,
orderCodes,
pickCodes: [...new Set(createdPickCodes)],
};
}
/** 每日定时推送:为当天配送日的待分拣订单生成分拣任务 */
export async function pushDailyPickingTasks(branchCode?: string | null) {
const ctx = branchCode ? buildSchedulerTenantContext(branchCode) : null;
return syncMissingPickingTasks(ctx);
}
export type PickingAssignee = {
id: string;
full_name: string | null;
username: string | null;
branch_code: string | null;
display_name: string;
/**
* 该用户的角色码(`picker` / `warehouse` / `delivery` …)。
*
* 为什么给前端(开发者 2026-10-11):分拣池**按设计**包含"勾了分拣出库的配送员"
* (见迁移 `20260725_picking_manage_permission.sql`:`picking_manage` 本就授给 delivery),
* 只列"分拣员"会让本地(无任何 picker 账号)下拉变空。故**范围不变、界面标出角色**:
* 「张三(配送人员)」,避免被误认成专责分拣员。
*/
roles: string[];
};
/** 可供 Web 分配/改派的分拣作业人员(**仓内作业角色**:picker 分拣员 / warehouse 仓管;配送员不在其列) */
export async function listPickingAssignees(ctx: TenantContext | null): Promise<PickingAssignee[]> {
const params: unknown[] = [];
let branchFilter = '';
if (ctx?.branchCode && !ctx.isSuperAdmin) {
params.push(ctx.branchCode);
branchFilter = `AND p.branch_code = $${params.length}`;
}
const result = await pool.query(
`SELECT p.id, p.full_name, p.username, p.branch_code,
COALESCE(NULLIF(TRIM(p.full_name), ''), NULLIF(TRIM(p.username), ''), p.id::text) AS sort_name,
string_agg(DISTINCT ur.role::text, ',' ORDER BY ur.role::text) AS roles
FROM profiles p
JOIN user_roles ur ON ur.user_id = p.id
JOIN role_permissions rp ON rp.role::text = ur.role::text
JOIN permissions perm ON perm.id = rp.permission_id AND perm.permission_code = 'picking_manage'
WHERE COALESCE(p.status, 1) = 1
-- 2026-10-11 开发者定稿:**按权限/角色区分** —— 配送员不得作为分拣员被分配
-- (历史迁移 20260725 曾把 picking_manage 授给 delivery,导致配送员混进分拣池;
-- 现按"仓内作业角色"收口:分拣员 picker + 仓管 warehouse)
AND ur.role::text = ANY(ARRAY['picker', 'warehouse']::text[])
${branchFilter}
GROUP BY p.id, p.full_name, p.username, p.branch_code
ORDER BY sort_name ASC`,
params
);
return result.rows.map((row) => {
const display =
String(row.full_name || '').trim() || String(row.username || '').trim() || String(row.id).slice(0, 8);
return {
id: String(row.id),
full_name: row.full_name ? String(row.full_name) : null,
username: row.username ? String(row.username) : null,
branch_code: row.branch_code ? String(row.branch_code) : null,
display_name: display,
roles: String(row.roles || '')
.split(',')
.map((role) => role.trim())
.filter(Boolean),
};
});
}
export async function assignPickingTaskPicker(input: {
pickCode: string;
pickerId: string | null;
ctx?: TenantContext | null;
}) {
const pickCode = String(input.pickCode || '').trim();
if (!pickCode) throw businessError('缺少拣货单号');
const taskResult = await pool.query(
`SELECT pick_code, branch_code, pick_status, picker_id
FROM picking_tasks WHERE pick_code = $1 LIMIT 1`,
[pickCode]
);
const task = taskResult.rows[0];
if (!task) throw businessError('分拣任务不存在', 404);
if (
input.ctx?.branchCode &&
task.branch_code &&
task.branch_code !== input.ctx.branchCode &&
!input.ctx.isSuperAdmin
) {
throw businessError('无权操作其他分公司分拣任务', 403);
}
if (Number(task.pick_status) >= 40) {
throw businessError('已出库任务不能改派');
}
const pickerId = input.pickerId ? String(input.pickerId).trim() : null;
let pickerName: string | null = null;
if (pickerId) {
const assignees = await listPickingAssignees(input.ctx || null);
const matched = assignees.find((row) => row.id === pickerId);
if (!matched) {
// 超管跨分公司时扩大校验:用户存在且有分拣权限即可
const fallback = await pool.query(
`SELECT p.id, p.full_name, p.username, p.branch_code
FROM profiles p
JOIN user_roles ur ON ur.user_id = p.id
JOIN role_permissions rp ON rp.role::text = ur.role::text
JOIN permissions perm ON perm.id = rp.permission_id AND perm.permission_code = 'picking_manage'
WHERE p.id = $1 AND COALESCE(p.status, 1) = 1
LIMIT 1`,
[pickerId]
);
if (!fallback.rowCount) {
throw businessError('分拣员不存在或未开通分拣出库权限');
}
if (
input.ctx?.branchCode &&
!input.ctx.isSuperAdmin &&
fallback.rows[0].branch_code &&
fallback.rows[0].branch_code !== input.ctx.branchCode
) {
throw businessError('只能分配给本公司分拣员');
}
pickerName =
String(fallback.rows[0].full_name || '').trim() ||
String(fallback.rows[0].username || '').trim() ||
null;
} else {
pickerName = matched.display_name;
}
}
await pool.query(`UPDATE picking_tasks SET picker_id = $1::uuid WHERE pick_code = $2`, [
pickerId,
pickCode,
]);
return {
pickCode,
pickerId,
pickerName,
previousPickerId: task.picker_id ? String(task.picker_id) : null,
};
}
/** 按订单分拣时 scope_label 是单号,不能当客户名 */
const PICKING_TASK_COMPANY_NAME_SQL = `
CASE
WHEN pt.scope_type = 'customer' THEN COALESCE(NULLIF(TRIM(pt.scope_label), ''), c.company_name)
ELSE COALESCE(
c.company_name,
CASE
WHEN pt.scope_type = 'category' AND pt.scope_key = '${UNCATEGORIZED_SCOPE_KEY}' THEN '未分类'
ELSE NULL
END
)
END
`;
export async function listPickingTasks(
ctx: TenantContext | null,
limit = 50,
offset = 0,
options?: {
dateField?: 'delivery_date' | 'created_at';
dateFrom?: string | null;
dateTo?: string | null;
/** 搜索关键词;以 ORD_ 开头时按订单号直查并忽略日期窗口 */
search?: string | null;
}
) {
await syncMissingPickingTasks(ctx);
await recoverOrdersReadyForDeliveryAfterPicking(ctx).catch(() => 0);
const params: unknown[] = [];
const branchFilter = branchClause(ctx, 'pt', params);
const from = String(options?.dateFrom || '').trim().slice(0, 10);
const to = String(options?.dateTo || '').trim().slice(0, 10);
const search = String(options?.search || '').trim();
const orderCodeSearch = isOrderCodeSearch(search);
const hasRange =
!orderCodeSearch && /^\d{4}-\d{2}-\d{2}$/.test(from) && /^\d{4}-\d{2}-\d{2}$/.test(to);
let deliveryWindow = 'TRUE';
if (hasRange) {
const start = from <= to ? from : to;
const end = from <= to ? to : from;
if (options?.dateField === 'created_at') {
params.push(start, end);
deliveryWindow = `(o2.created_at AT TIME ZONE 'Asia/Shanghai')::date BETWEEN $${params.length - 1}::date AND $${params.length}::date`;
} else {
deliveryWindow = chinaDeliveryDateBetweenSql('o2', params, start, end);
}
}
let orderCodeFilter = '';
if (orderCodeSearch) {
params.push(`%${search.replace(/[%_]/g, '\\$&')}%`);
orderCodeFilter = ` AND COALESCE(pt.order_code, '') ILIKE $${params.length}`;
}
const zoneOrder = await getPickingZoneOrder(ctx?.branchCode || null);
params.push(zoneOrder);
const zoneOrderParam = `$${params.length}`;
params.push(limit, offset);
const tasks = await pool.query(
`SELECT pt.id, pt.pick_code, pt.order_code, pt.warehouse_code, pt.pick_status, pt.created_at, pt.branch_code,
pt.picker_id,
pt.scope_type, pt.scope_key, pt.scope_label,
COALESCE(NULLIF(TRIM(pr.full_name), ''), NULLIF(TRIM(pr.username), '')) AS picker_name,
COALESCE(
(SELECT MIN(o.delivery_date)
FROM picking_items pix
JOIN orders o ON o.order_code = pix.order_code
WHERE pix.pick_code = pt.pick_code),
o_anchor.delivery_date
) AS delivery_date,
COALESCE(
(SELECT MIN(o.created_at)
FROM picking_items pix
JOIN orders o ON o.order_code = pix.order_code
WHERE pix.pick_code = pt.pick_code),
o_anchor.created_at
) AS order_created_at,
COALESCE(
(SELECT MIN(o.delivery_address)
FROM picking_items pix
JOIN orders o ON o.order_code = pix.order_code
WHERE pix.pick_code = pt.pick_code),
o_anchor.delivery_address
) AS delivery_address,
CASE
WHEN pt.scope_type = 'customer' THEN pt.scope_key
ELSE o_anchor.customer_code
END AS customer_code,
${PICKING_TASK_COMPANY_NAME_SQL} AS company_name,
(
SELECT string_agg(DISTINCT pix.order_code, ',' ORDER BY pix.order_code)
FROM picking_items pix
WHERE pix.pick_code = pt.pick_code AND pix.order_code IS NOT NULL
) AS order_codes,
COUNT(pi.id)::int AS item_count
FROM picking_tasks pt
LEFT JOIN orders o_anchor ON o_anchor.order_code = pt.order_code
LEFT JOIN customers c ON c.customer_code = CASE
WHEN pt.scope_type = 'customer' THEN pt.scope_key
ELSE o_anchor.customer_code
END
LEFT JOIN profiles pr ON pr.id = pt.picker_id
LEFT JOIN picking_items pi ON pi.pick_code = pt.pick_code
WHERE 1=1 ${branchFilter}${orderCodeFilter}
AND EXISTS (
SELECT 1
FROM picking_items pi2
JOIN orders o2 ON o2.order_code = pi2.order_code
LEFT JOIN order_items oi2 ON oi2.id = pi2.order_item_id
WHERE pi2.pick_code = pt.pick_code
AND ${orderNotDeletedSql('o2')}
-- 未完成单仍只要待配送前;已完成单(≥30)订单推进到 50+ 后仍须在「已完成」可见
AND (
COALESCE(pt.pick_status, 10) >= 30
OR o2.order_status < 50
)
AND COALESCE(oi2.is_extra_dish, false) = false
-- 直送免入库的核货单(纯直送行的 pick_status=40 假单)不在分拣管理列表露出
AND NOT ${supplierSkipInboundExistsSql('oi2.supplier_code')}
AND NOT ${skuDirectDeliveryAppliesSql('oi2.sku_code', 'oi2.order_code')}
AND ${deliveryWindow}
)
GROUP BY pt.id, pr.full_name, pr.username, o_anchor.delivery_date, o_anchor.created_at, o_anchor.delivery_address,
o_anchor.order_code, o_anchor.customer_code, c.company_name
ORDER BY
array_position(${zoneOrderParam}::text[], pt.scope_key) ASC NULLS LAST,
CASE WHEN pt.picker_id IS NULL THEN 0 ELSE 1 END ASC,
delivery_address ASC NULLS LAST,
pt.order_code ASC NULLS LAST,
pt.created_at DESC
LIMIT $${params.length - 1} OFFSET $${params.length}`,
params
);
return tasks.rows;
}
function myPickingDateWindowSql(
orderAlias: string,
params: unknown[],
options?: {
dateField?: 'delivery_date' | 'created_at' | string | null;
dateFrom?: string | null;
dateTo?: string | null;
}
): string {
const dateField = String(options?.dateField || '').trim() === 'created_at' ? 'created_at' : 'delivery_date';
const from = String(options?.dateFrom || '').trim().slice(0, 10);
const to = String(options?.dateTo || '').trim().slice(0, 10);
const fromOk = /^\d{4}-\d{2}-\d{2}$/.test(from);
const toOk = /^\d{4}-\d{2}-\d{2}$/.test(to);
if (!fromOk && !toOk) {
return onOrAfterChinaDeliveryDateSql(orderAlias, params);
}
const dayExpr =
dateField === 'created_at'
? `(${orderAlias}.created_at AT TIME ZONE 'Asia/Shanghai')::date`
: `COALESCE(${orderAlias}.delivery_date::date, ${orderAlias}.created_at::date)`;
if (fromOk && toOk) {
const start = from <= to ? from : to;
const end = from <= to ? to : from;
if (dateField === 'delivery_date') {
return chinaDeliveryDateBetweenSql(orderAlias, params, start, end);
}
params.push(start, end);
return `${dayExpr} BETWEEN $${params.length - 1}::date AND $${params.length}::date`;
}
if (fromOk) {
params.push(from);
return `${dayExpr} >= $${params.length}::date`;
}
params.push(to);
return `${dayExpr} <= $${params.length}::date`;
}
/** 小程序:仅返回分配给当前分拣员的任务 */
export async function listMyPickingTasks(
pickerId: string,
ctx: TenantContext | null,
limit = 50,
options?: {
dateField?: 'delivery_date' | 'created_at' | string | null;
dateFrom?: string | null;
dateTo?: string | null;
}
) {
await syncMissingPickingTasks(ctx);
await recoverOrdersReadyForDeliveryAfterPicking(ctx).catch(() => 0);
const params: unknown[] = [pickerId];
const branchFilter = branchClause(ctx, 'pt', params);
const deliveryWindow = myPickingDateWindowSql('o2', params, options);
const zoneOrder = await getPickingZoneOrder(ctx?.branchCode || null);
params.push(zoneOrder);
const zoneOrderParam = `$${params.length}`;
params.push(limit);
const tasks = await pool.query(
`SELECT pt.id, pt.pick_code, pt.order_code, pt.warehouse_code, pt.pick_status, pt.created_at, pt.branch_code,
pt.picker_id,
pt.scope_type, pt.scope_key, pt.scope_label,
COALESCE(NULLIF(TRIM(pr.full_name), ''), NULLIF(TRIM(pr.username), '')) AS picker_name,
COALESCE(
(SELECT MIN(o.delivery_date)
FROM picking_items pix
JOIN orders o ON o.order_code = pix.order_code
WHERE pix.pick_code = pt.pick_code),
o_anchor.delivery_date
) AS delivery_date,
COALESCE(
(SELECT MIN(o.delivery_address)
FROM picking_items pix
JOIN orders o ON o.order_code = pix.order_code
WHERE pix.pick_code = pt.pick_code),
o_anchor.delivery_address
) AS delivery_address,
CASE
WHEN pt.scope_type = 'customer' THEN pt.scope_key
ELSE o_anchor.customer_code
END AS customer_code,
${PICKING_TASK_COMPANY_NAME_SQL} AS company_name,
(
SELECT string_agg(DISTINCT pix.order_code, ',' ORDER BY pix.order_code)
FROM picking_items pix
WHERE pix.pick_code = pt.pick_code AND pix.order_code IS NOT NULL
) AS order_codes,
COUNT(pi.id)::int AS item_count
FROM picking_tasks pt
LEFT JOIN orders o_anchor ON o_anchor.order_code = pt.order_code
LEFT JOIN customers c ON c.customer_code = CASE
WHEN pt.scope_type = 'customer' THEN pt.scope_key
ELSE o_anchor.customer_code
END
LEFT JOIN profiles pr ON pr.id = pt.picker_id
LEFT JOIN picking_items pi ON pi.pick_code = pt.pick_code
WHERE pt.picker_id = $1
AND pt.pick_status < 40
${branchFilter}
AND EXISTS (
SELECT 1
FROM picking_items pi2
JOIN orders o2 ON o2.order_code = pi2.order_code
LEFT JOIN order_items oi2 ON oi2.id = pi2.order_item_id
WHERE pi2.pick_code = pt.pick_code
AND ${orderNotDeletedSql('o2')}
AND o2.order_status < 50
AND COALESCE(oi2.is_extra_dish, false) = false
AND ${deliveryWindow}
)
GROUP BY pt.id, pr.full_name, pr.username, o_anchor.delivery_date, o_anchor.delivery_address,
o_anchor.order_code, o_anchor.customer_code, c.company_name
ORDER BY array_position(${zoneOrderParam}::text[], pt.scope_key) ASC NULLS LAST,
delivery_address ASC NULLS LAST, pt.order_code ASC NULLS LAST, pt.created_at DESC
LIMIT $${params.length}`,
params
);
return tasks.rows;
}
/**
* 分拣出库首页角标:分配给当前分拣员/配送员的未完成任务数(pick_status < 40)。
* WHERE 对齐 listMyPickingTasks,但只 COUNT、不同步任务、不带 GROUP BY/LIMIT。
*/
export async function countMyPendingPickingTasks(
pickerId: string,
ctx: TenantContext | null
): Promise<number> {
const id = String(pickerId || '').trim();
if (!id) return 0;
const params: unknown[] = [id];
const branchFilter = branchClause(ctx, 'pt', params);
const deliveryWindow = onOrAfterChinaDeliveryDateSql('o2', params);
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM picking_tasks pt
WHERE pt.picker_id = $1
AND pt.pick_status < 40
${branchFilter}
AND EXISTS (
SELECT 1
FROM picking_items pi2
JOIN orders o2 ON o2.order_code = pi2.order_code
LEFT JOIN order_items oi2 ON oi2.id = pi2.order_item_id
WHERE pi2.pick_code = pt.pick_code
AND ${orderNotDeletedSql('o2')}
AND o2.order_status < 50
AND COALESCE(oi2.is_extra_dish, false) = false
AND ${deliveryWindow}
)`,
params
);
return Number(result.rows[0]?.c) || 0;
}
/** 导出仅为测试/校验:分拣列表 SQL(商品名档案优先、快照另存) */
export const PICKING_ITEMS_ENRICHED_SQL = `
SELECT pi.id, pi.pick_code, pi.order_code, pi.order_item_id,
${itemDisplayNameSql({
skuName: 's.sku_name',
orderItemName: 'oi.item_name',
pickingItemName: 'pi.item_name',
})} AS item_name,
pi.item_name AS item_name_snapshot,
pi.required_qty, pi.picked_qty,
pi.picked_weight, pi.unit,
s.unit AS inventory_unit,
pi.review_status, pi.diff_reason, pi.sort_order, pi.created_at,
-- 商品分类(分拣列表批量打印按「分类」排队用;纯读,oi 已在 JOIN 中)
oi.category_name AS category_name,
${ORDER_ITEM_OWN_SKU_CODE_SQL} AS sku_code,
${ORDER_ITEM_OWN_BARCODE_SQL} AS barcode,
-- 分拣标签二维码内容(2026-10-13 方案 A,开发者确认;取值链唯一来源见 orderItemLabelBarcodeSql.ts):
-- 有主系统来源的行 ⇒ 印主系统的 SKU 编码(台账 main_system_order_import_items.main_sku_code);
-- 主系统扫码入口是 SELECT sku_code FROM skus WHERE barcode=$1 OR sku_code=$1(查他们自己的表),
-- 印他们的码 ⇒ 他们零改造即可核货/入库。
-- 无主系统来源(我方自建单 / 自采行)⇒ 回退上面的 barcode 链(我方条码/SKU),保持原样。
-- 我方自己扫码:扫码解析按**这张纸上印的码**优先定位到行(services/labelScanResolver.ts),
-- 所以同一个标签值无论是我方码还是主系统码,都能落到正确的那一行。
${ORDER_ITEM_LABEL_BARCODE_SQL} AS label_barcode,
pcn.container_code, pcn.staged_at,
COALESCE(NULLIF(TRIM(bz.storage_zone), ''), NULLIF(TRIM(s.storage_zone), '')) AS storage_zone,
pi.outbound_batches,
pi.outbound_photos,
o_del.delivery_date::text AS delivery_date
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN orders o_del ON o_del.order_code = pi.order_code
-- 有 SKU 编码 ⇒ 按码直配;没有 ⇒ 按品名兜底(**规格消歧 + 多义拒绝猜测**,唯一实现)
LEFT JOIN product_catalog catalog ON catalog.item_type = 'product'
AND catalog.code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
${catalogSkuBySpecJoin({ nameExpr: 'pi.item_name', specExpr: 'oi.spec', alias: 'catalog_fb' })}
LEFT JOIN skus s ON s.sku_code = COALESCE(
NULLIF(TRIM(pi.sku_code), ''),
NULLIF(TRIM(oi.sku_code), ''),
catalog.code,
catalog_fb.code
)
-- 区域(2026-11-05):**批次实际区优先**(该商品可扣库存里 FIFO 首个有区域的批次)→ 回退商品默认区
LEFT JOIN LATERAL (
SELECT inv.storage_zone
FROM inventory inv
WHERE inv.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
AND inv.available_qty > 0
AND NULLIF(TRIM(inv.storage_zone), '') IS NOT NULL
AND (oi.branch_code IS NULL OR inv.branch_code = oi.branch_code)
ORDER BY inv.created_at ASC, inv.expiry_date ASC NULLS FIRST
LIMIT 1
) bz ON true
LEFT JOIN picking_containers pcn ON pcn.pick_item_id = pi.id
-- 主系统行级台账:该行对应的**主系统 SKU**(分拣标签二维码用;取值链唯一来源见 orderItemLabelBarcodeSql.ts)
${ORDER_ITEM_LABEL_LEDGER_JOIN_SQL}
WHERE pi.pick_code = ANY($1)
AND COALESCE(oi.is_extra_dish, false) = false
/**
* ⚠️ 退货/删行后的**残留行**不得再出现在分拣面(2026-10-12 真库事故
* ORD_API_20261012_BR003_0002:抄手皮、龙口粉丝已从订单里退货,分拣对话框却仍有这两行、
* 还带 FIFO 出库批次 ⇒ 分拣员会照着拣一批订单里不存在的货)。
*
* 只挡「**没有留下任何实物动作**(picked_qty / loaded_qty 都为 0)+ 订单行已退货或已不存在」
* 的行:已经拣过/核过货的行必须继续可见 —— 完成分拣的校验(confirmPickingComplete)仍会
* 把这些行算进「未确认分拣」,两边口径必须一致,否则会互锁(界面看不到、提交又报没确认)。
*/
AND (
pi.order_item_id IS NULL
OR (oi.id IS NOT NULL AND COALESCE(oi.is_returned, false) = false)
OR COALESCE(pi.picked_qty, 0) > 0
OR COALESCE(pi.loaded_qty, 0) > 0
)
AND (
pi.order_code IS NULL
OR EXISTS (
SELECT 1 FROM orders _o_pick
WHERE _o_pick.order_code = pi.order_code
AND _o_pick.deleted_at IS NULL
AND (
_o_pick.order_status < 50
OR EXISTS (
SELECT 1 FROM picking_tasks _pt
WHERE _pt.pick_code = pi.pick_code
AND COALESCE(_pt.pick_status, 0) >= 30
)
)
)
)
ORDER BY pi.sort_order NULLS LAST, pi.created_at ASC`;
export async function listPickingItemsEnriched(pickCodes: string[]) {
if (!pickCodes.length) return [];
const result = await pool.query(PICKING_ITEMS_ENRICHED_SQL, [pickCodes]);
return Promise.all(result.rows.map(async (row: any) => {
const photos = Array.isArray(row.outbound_photos)
? row.outbound_photos.map((p: unknown) => String(p || '').trim()).filter(Boolean)
: [];
const urls: string[] = [];
for (const photo of photos) {
// T9F-5:`delivery-photos` 旧 key 先异步反查归属再签;跨租户/毒化 key 不返回 URL。
try {
urls.push(await buildSignedStoragePathForCtxChecked(undefined, 'delivery-photos', photo));
} catch {
urls.push('');
}
}
return {
...row,
outbound_photos: photos,
// 分拣出库留证照(商品级)的可读链接:签名 15 分钟有效。见 docs/design/20261103-分拣出库拍照留证.md
outbound_photo_urls: urls,
};
}));
}