3519 lines
122 KiB
JavaScript
3519 lines
122 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
const { INTERCEPT_STATUS_NONE } = require('../../lib/intercept_guard');
|
||
|
||
const REVIEWED_INSPECTION_STATUS = 'fin';
|
||
const PICK_MODE_VIEW_META_MAP = {
|
||
1: {
|
||
mode_code: '1',
|
||
mode_name: '团购小波次',
|
||
require_box_allocations: true,
|
||
},
|
||
2: {
|
||
mode_code: '2',
|
||
mode_name: '散单单品单件',
|
||
require_box_allocations: false,
|
||
},
|
||
3: {
|
||
mode_code: '3',
|
||
mode_name: '散单先拣后分',
|
||
require_box_allocations: true,
|
||
},
|
||
4: {
|
||
mode_code: '4',
|
||
mode_name: '边拣边分',
|
||
require_box_allocations: true,
|
||
},
|
||
5: {
|
||
mode_code: '5',
|
||
mode_name: '团购大波次',
|
||
require_box_allocations: false,
|
||
},
|
||
};
|
||
|
||
class PickSystemService extends Service {
|
||
/**
|
||
* 按仓库获取订单分表模型。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Object|null>} 订单模型对象。
|
||
*/
|
||
async getOrderModel(warehouseId) {
|
||
const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||
if (!factory || typeof factory.getCurrentModel !== 'function') {
|
||
throw this.createBusinessError('订单分表模型工厂不可用', 500);
|
||
}
|
||
|
||
const model = await factory.getCurrentModel(warehouseId);
|
||
if (!model || typeof model.findOne !== 'function' || typeof model.findAll !== 'function') {
|
||
throw this.createBusinessError('订单分表模型不可用', 500);
|
||
}
|
||
|
||
return model;
|
||
}
|
||
|
||
/**
|
||
* 生成带业务状态码的错误对象。
|
||
*
|
||
* @param {string} message 错误文案。
|
||
* @param {number} [code=400] 错误码。
|
||
* @param {*} [data=null] 附加数据。
|
||
* @return {Error} 错误对象。
|
||
*/
|
||
createBusinessError(message, code = 400, data = null) {
|
||
const error = new Error(message);
|
||
error.code = code;
|
||
if (data && typeof data === 'object' && !Array.isArray(data)) {
|
||
error.data = data;
|
||
}
|
||
return error;
|
||
}
|
||
|
||
/**
|
||
* 获取数据表列名集合。
|
||
*
|
||
* 用于在不确定列是否存在时进行安全查询拼装,避免因列缺失导致 SQL 执行失败。
|
||
*
|
||
* @param {string} tableName 数据表名。
|
||
* @return {Promise<Set<string>>} 列名集合。
|
||
*/
|
||
async getTableColumnSet(tableName) {
|
||
const { ctx } = this;
|
||
const normalizedTableName = String(tableName || '').trim();
|
||
if (!normalizedTableName) {
|
||
return new Set();
|
||
}
|
||
|
||
const escapedTableName = normalizedTableName.replace(/`/g, '``');
|
||
|
||
try {
|
||
const rows = await ctx.model.query(`SHOW COLUMNS FROM \`${escapedTableName}\``, {
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
return new Set((Array.isArray(rows) ? rows : [])
|
||
.map(row => String(row && row.Field || '').trim())
|
||
.filter(Boolean));
|
||
} catch (error) {
|
||
ctx.logger.warn(`[pick.wavePickTaskDetail] 获取表字段失败,table=${normalizedTableName},将按兜底处理: ${error.message}`);
|
||
return new Set();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取订单商品分表数据并构建索引。
|
||
*
|
||
* 优先使用 OrderItemsFactory 当前分表模型;若模型不可用或查询失败,返回空映射而不抛异常。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {Array<number>} params.orderItemIds 订单明细ID列表。
|
||
* @return {Promise<Map<number, Object>>} 订单明细映射。
|
||
*/
|
||
async loadOrderItemMap(params = {}) {
|
||
const { ctx } = this;
|
||
const warehouseId = Number(params && params.warehouseId || 0);
|
||
const orderItemIds = Array.isArray(params && params.orderItemIds)
|
||
? params.orderItemIds.filter(id => Number.isInteger(id) && id > 0)
|
||
: [];
|
||
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderItemIds.length === 0) {
|
||
return new Map();
|
||
}
|
||
|
||
const factory = ctx.model && ctx.model.OrderItemsFactory;
|
||
if (!factory || typeof factory.getCurrentModel !== 'function') {
|
||
return new Map();
|
||
}
|
||
|
||
try {
|
||
const orderItemModel = await factory.getCurrentModel(warehouseId);
|
||
if (!orderItemModel || typeof orderItemModel.findAll !== 'function') {
|
||
return new Map();
|
||
}
|
||
|
||
const orderItemRows = await orderItemModel.findAll({
|
||
where: {
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: orderItemIds,
|
||
},
|
||
},
|
||
attributes: [ 'id', 'item_code', 'item_name', 'stock_id', 'plan_qty', 'item_snapshot', 'owner_code' ],
|
||
raw: true,
|
||
});
|
||
|
||
return new Map((Array.isArray(orderItemRows) ? orderItemRows : [])
|
||
.map(row => [ Number(row && row.id || 0), row ]));
|
||
} catch (error) {
|
||
ctx.logger.warn(`[pick.wavePickTaskDetail] 订单商品分表查询失败,将按空字段降级: ${error.message}`);
|
||
return new Map();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 解析订单商品快照 JSON。
|
||
*
|
||
* item_snapshot 是下单时从 wms_stock_warehouse 抓取的库存快照,
|
||
* 其 item_code / item_name 代表下单时的商品信息,比 order_items 列更准确。
|
||
*
|
||
* @param {*} rawSnapshot 原始快照数据。
|
||
* @return {Object} 解析后的快照对象。
|
||
*/
|
||
parseItemSnapshot(rawSnapshot) {
|
||
if (!rawSnapshot) {
|
||
return {};
|
||
}
|
||
|
||
if (typeof rawSnapshot === 'string') {
|
||
try {
|
||
const parsed = JSON.parse(rawSnapshot);
|
||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
||
} catch (_) {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
if (typeof rawSnapshot === 'object' && !Array.isArray(rawSnapshot)) {
|
||
return rawSnapshot;
|
||
}
|
||
|
||
return {};
|
||
}
|
||
|
||
/**
|
||
* 生成拣货明细汇总信息。
|
||
*
|
||
* @param {Array<Object>} pickingDetails 拣货明细列表。
|
||
* @return {{total_lines: number, total_qty: number, distinct_spaces: number, distinct_items: number}} 汇总结果。
|
||
*/
|
||
buildPickingSummary(pickingDetails = []) {
|
||
const normalizedDetails = Array.isArray(pickingDetails) ? pickingDetails : [];
|
||
const distinctSpaceIds = new Set();
|
||
const distinctItemKeys = new Set();
|
||
|
||
for (const detail of normalizedDetails) {
|
||
const spaceId = Number(detail && detail.space_id || 0);
|
||
if (spaceId > 0) {
|
||
distinctSpaceIds.add(spaceId);
|
||
}
|
||
|
||
const itemCode = String(detail && detail.item_code || '').trim();
|
||
const orderItemId = Number(detail && detail.order_item_id || 0);
|
||
if (itemCode) {
|
||
distinctItemKeys.add(`code:${itemCode}`);
|
||
} else if (orderItemId > 0) {
|
||
distinctItemKeys.add(`order_item_id:${orderItemId}`);
|
||
}
|
||
}
|
||
|
||
return {
|
||
total_lines: normalizedDetails.length,
|
||
total_qty: normalizedDetails.reduce((sum, detail) => sum + Number(detail && detail.quantity || 0), 0),
|
||
distinct_spaces: distinctSpaceIds.size,
|
||
distinct_items: distinctItemKeys.size,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取拣货模式视图元信息。
|
||
*
|
||
* @param {number} pickMode 拣货模式编码。
|
||
* @return {{mode_code: number, mode_name: string, require_box_allocations: boolean}} 视图元信息。
|
||
*/
|
||
getPickModeViewMeta(pickMode) {
|
||
const normalizedPickMode = Number(pickMode || 0);
|
||
const baseMeta = PICK_MODE_VIEW_META_MAP[normalizedPickMode] || {
|
||
mode_code: normalizedPickMode || 0,
|
||
mode_name: '未知模式',
|
||
require_box_allocations: false,
|
||
};
|
||
|
||
return {
|
||
mode_code: Number(baseMeta.mode_code || 0),
|
||
mode_name: String(baseMeta.mode_name || '').trim(),
|
||
require_box_allocations: Boolean(baseMeta.require_box_allocations),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 加载订单与波次映射关系。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {Array<number>} params.orderIds 订单ID列表。
|
||
* @return {Promise<Map<number, number>>} 订单ID到wave_id映射。
|
||
*/
|
||
async loadOrderWaveMap(params = {}) {
|
||
const { ctx } = this;
|
||
const warehouseId = Number(params && params.warehouseId || 0);
|
||
const orderIds = Array.isArray(params && params.orderIds)
|
||
? params.orderIds.filter(id => Number.isInteger(id) && id > 0)
|
||
: [];
|
||
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) {
|
||
return new Map();
|
||
}
|
||
|
||
try {
|
||
const orderModel = await this.getOrderModel(warehouseId);
|
||
const orderRows = await orderModel.findAll({
|
||
where: {
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: orderIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'wave_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
return new Map((Array.isArray(orderRows) ? orderRows : [])
|
||
.map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ])
|
||
.filter(([ orderId, waveId ]) => orderId > 0 && waveId > 0));
|
||
} catch (error) {
|
||
ctx.logger.warn(`[pick.wavePickTaskDetail] 订单wave_id查询失败,将按空映射降级: ${error.message}`);
|
||
return new Map();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 构建按拣货模式区分的拣货形态视图。
|
||
*
|
||
* @param {Object} params 构建参数。
|
||
* @param {number} params.pickMode 拣货模式。
|
||
* @param {number} params.taskId 任务ID。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {Array<Object>} params.pickingDetails 拣货明细。
|
||
* @param {Array<Object>} params.boxRows 框明细。
|
||
* @param {Array<Object>} params.taskOrderRows 任务订单关联明细。
|
||
* @param {Map<number, Object>} params.boxMapByNo 框号到框信息映射。
|
||
* @return {Promise<Object>} picking_view 结构。
|
||
*/
|
||
async buildPickingView(params = {}) {
|
||
const { ctx } = this;
|
||
const pickMode = Number(params && params.pickMode || 0);
|
||
const taskId = Number(params && params.taskId || 0);
|
||
const warehouseId = Number(params && params.warehouseId || 0);
|
||
const pickingDetails = Array.isArray(params && params.pickingDetails) ? params.pickingDetails : [];
|
||
const boxRows = Array.isArray(params && params.boxRows) ? params.boxRows : [];
|
||
const taskOrderRows = Array.isArray(params && params.taskOrderRows) ? params.taskOrderRows : [];
|
||
const boxMapByNo = params && params.boxMapByNo instanceof Map ? params.boxMapByNo : new Map();
|
||
const pickMeta = this.getPickModeViewMeta(pickMode);
|
||
|
||
const groupMap = new Map();
|
||
const buildGroupKey = detail => {
|
||
const spaceId = Number(detail && detail.space_id || 0);
|
||
const itemCode = String(detail && detail.item_code || '').trim();
|
||
const stockId = Number(detail && detail.stock_id || 0);
|
||
if (itemCode) {
|
||
return `${spaceId}::${itemCode}`;
|
||
}
|
||
return `${spaceId}::stock_${stockId}`;
|
||
};
|
||
|
||
for (const detail of pickingDetails) {
|
||
const groupKey = buildGroupKey(detail);
|
||
if (!groupMap.has(groupKey)) {
|
||
groupMap.set(groupKey, {
|
||
space_id: Number(detail && detail.space_id || 0),
|
||
space_name: String(detail && detail.space_name || '').trim(),
|
||
location_space: detail && detail.location_space ? detail.location_space : null,
|
||
item_code: String(detail && detail.item_code || '').trim(),
|
||
item_name: String(detail && detail.item_name || '').trim(),
|
||
stock_id: Number(detail && detail.stock_id || 0),
|
||
total_qty: 0,
|
||
box_allocations: [],
|
||
details: [],
|
||
store_id: detail.store_id != null ? Number(detail.store_id) : 0,
|
||
owner_code: String(detail.owner_code || '').trim(),
|
||
store_remark: String(detail.store_remark || '').trim(),
|
||
stock: detail.stock || null,
|
||
});
|
||
}
|
||
const groupItem = groupMap.get(groupKey);
|
||
groupItem.total_qty += Number(detail && detail.quantity || 0);
|
||
groupItem.details.push(detail);
|
||
}
|
||
|
||
const allocationMapByGroup = new Map();
|
||
const appendAllocation = (groupKey, boxId, allocatedQty) => {
|
||
const normalizedBoxId = Number(boxId || 0);
|
||
const normalizedQty = Number(allocatedQty || 0);
|
||
if (normalizedBoxId <= 0 || normalizedQty <= 0) {
|
||
return;
|
||
}
|
||
if (!allocationMapByGroup.has(groupKey)) {
|
||
allocationMapByGroup.set(groupKey, new Map());
|
||
}
|
||
const groupAllocationMap = allocationMapByGroup.get(groupKey);
|
||
groupAllocationMap.set(
|
||
normalizedBoxId,
|
||
Number(groupAllocationMap.get(normalizedBoxId) || 0) + normalizedQty
|
||
);
|
||
};
|
||
|
||
if (pickMeta.require_box_allocations) {
|
||
if (pickMode === 4) {
|
||
const boxNosByOrderId = new Map();
|
||
for (const row of taskOrderRows) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
const boxNo = Number(row && row.box_no || 0);
|
||
if (orderId <= 0 || boxNo <= 0) {
|
||
continue;
|
||
}
|
||
if (!boxNosByOrderId.has(orderId)) {
|
||
boxNosByOrderId.set(orderId, new Set());
|
||
}
|
||
boxNosByOrderId.get(orderId).add(boxNo);
|
||
}
|
||
|
||
for (const [ groupKey, groupItem ] of groupMap) {
|
||
for (const detail of groupItem.details) {
|
||
const orderId = Number(detail && detail.order_id || 0);
|
||
const quantity = Number(detail && detail.quantity || 0);
|
||
const boxNos = boxNosByOrderId.get(orderId);
|
||
if (!boxNos || quantity <= 0) {
|
||
continue;
|
||
}
|
||
for (const boxNo of boxNos) {
|
||
const boxInfo = boxMapByNo.get(Number(boxNo || 0));
|
||
const boxId = Number(boxInfo && boxInfo.box_id || 0);
|
||
appendAllocation(groupKey, boxId, quantity);
|
||
}
|
||
}
|
||
}
|
||
} else if (pickMode === 1) {
|
||
const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave');
|
||
const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND ptw.warehouse_id = :warehouseId' : '';
|
||
const taskWaveRows = await ctx.model.query(`
|
||
SELECT
|
||
ptw.wave_id,
|
||
ptw.box_no
|
||
FROM wms_wave_pick_task_wave ptw
|
||
WHERE ptw.task_id = :taskId
|
||
${taskWaveWarehouseFilterSql}
|
||
ORDER BY ptw.id ASC
|
||
`, {
|
||
replacements: { taskId, warehouseId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
const waveToBoxNosMap = new Map();
|
||
for (const row of Array.isArray(taskWaveRows) ? taskWaveRows : []) {
|
||
const waveId = Number(row && row.wave_id || 0);
|
||
const boxNo = Number(row && row.box_no || 0);
|
||
if (waveId <= 0 || boxNo <= 0) {
|
||
continue;
|
||
}
|
||
if (!waveToBoxNosMap.has(waveId)) {
|
||
waveToBoxNosMap.set(waveId, new Set());
|
||
}
|
||
waveToBoxNosMap.get(waveId).add(boxNo);
|
||
}
|
||
|
||
const orderIds = [ ...new Set(pickingDetails
|
||
.map(detail => Number(detail && detail.order_id || 0))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)) ];
|
||
const orderWaveMap = await this.loadOrderWaveMap({
|
||
warehouseId,
|
||
orderIds,
|
||
});
|
||
|
||
for (const [ groupKey, groupItem ] of groupMap) {
|
||
for (const detail of groupItem.details) {
|
||
const orderId = Number(detail && detail.order_id || 0);
|
||
const quantity = Number(detail && detail.quantity || 0);
|
||
const waveId = Number(orderWaveMap.get(orderId) || 0);
|
||
const boxNos = waveToBoxNosMap.get(waveId);
|
||
if (!boxNos || quantity <= 0) {
|
||
continue;
|
||
}
|
||
for (const boxNo of boxNos) {
|
||
const boxInfo = boxMapByNo.get(Number(boxNo || 0));
|
||
const boxId = Number(boxInfo && boxInfo.box_id || 0);
|
||
appendAllocation(groupKey, boxId, quantity);
|
||
}
|
||
}
|
||
}
|
||
} else if (pickMode === 3) {
|
||
const boxMapByRefId = new Map();
|
||
for (const row of boxRows) {
|
||
const refId = Number(row && row.ref_id || 0);
|
||
const boxId = Number(row && row.box_id || 0);
|
||
if (refId <= 0 || boxId <= 0) {
|
||
continue;
|
||
}
|
||
if (!boxMapByRefId.has(refId)) {
|
||
boxMapByRefId.set(refId, []);
|
||
}
|
||
boxMapByRefId.get(refId).push(row);
|
||
}
|
||
|
||
for (const [ groupKey, groupItem ] of groupMap) {
|
||
const stockId = Number(groupItem && groupItem.stock_id || 0);
|
||
const targetBoxes = boxMapByRefId.get(stockId);
|
||
if (!Array.isArray(targetBoxes) || targetBoxes.length === 0) {
|
||
continue;
|
||
}
|
||
const groupQty = Number(groupItem && groupItem.total_qty || 0);
|
||
if (groupQty <= 0) {
|
||
continue;
|
||
}
|
||
for (const boxInfo of targetBoxes) {
|
||
appendAllocation(groupKey, Number(boxInfo && boxInfo.box_id || 0), groupQty);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const itemList = Array.from(groupMap.entries()).map(([ groupKey, groupItem ]) => {
|
||
const groupAllocationMap = allocationMapByGroup.get(groupKey) || new Map();
|
||
const boxAllocations = pickMeta.require_box_allocations
|
||
? Array.from(groupAllocationMap.entries())
|
||
.map(([ boxId, allocatedQty ]) => {
|
||
const boxInfo = boxRows.find(row => Number(row && row.box_id || 0) === Number(boxId || 0)) || {};
|
||
return {
|
||
box_id: Number(boxInfo && boxInfo.box_id || 0),
|
||
box_no: Number(boxInfo && boxInfo.box_no || 0),
|
||
box_type: Number(boxInfo && boxInfo.box_type || 0),
|
||
required_qty: Number(boxInfo && boxInfo.required_qty || 0),
|
||
picked_qty: Number(boxInfo && boxInfo.picked_qty || 0),
|
||
allocated_qty: Number(allocatedQty || 0),
|
||
};
|
||
})
|
||
.sort((a, b) => {
|
||
const boxNoA = Number(a && a.box_no || 0);
|
||
const boxNoB = Number(b && b.box_no || 0);
|
||
if (boxNoA !== boxNoB) {
|
||
return boxNoA - boxNoB;
|
||
}
|
||
return Number(a && a.box_id || 0) - Number(b && b.box_id || 0);
|
||
})
|
||
: [];
|
||
|
||
return {
|
||
space_id: Number(groupItem && groupItem.space_id || 0),
|
||
space_name: String(groupItem && groupItem.space_name || '').trim(),
|
||
location_space: groupItem && groupItem.location_space ? groupItem.location_space : null,
|
||
item_code: String(groupItem && groupItem.item_code || '').trim(),
|
||
item_name: String(groupItem && groupItem.item_name || '').trim(),
|
||
stock_id: Number(groupItem && groupItem.stock_id || 0),
|
||
total_qty: Number(groupItem && groupItem.total_qty || 0),
|
||
// 拣货要求:取自商品资料链路(getStockDetails),merge_requirements=Y 时已回退为打包要求
|
||
pick_requirements: String(
|
||
(groupItem && groupItem.stock && groupItem.stock.pick_requirements) || ''
|
||
).trim(),
|
||
box_allocations: boxAllocations,
|
||
store_id: groupItem.store_id != null ? Number(groupItem.store_id) : 0,
|
||
owner_code: String(groupItem.owner_code || '').trim(),
|
||
store_remark: String(groupItem.store_remark || '').trim(),
|
||
};
|
||
});
|
||
|
||
itemList.sort((a, b) => {
|
||
const sequenceA = Number(a && a.location_space && a.location_space.pick_sequence || 0);
|
||
const sequenceB = Number(b && b.location_space && b.location_space.pick_sequence || 0);
|
||
if (sequenceA !== sequenceB) {
|
||
return sequenceA - sequenceB;
|
||
}
|
||
|
||
const priorityA = Number(a && a.location_space && a.location_space.pick_priority || 0);
|
||
const priorityB = Number(b && b.location_space && b.location_space.pick_priority || 0);
|
||
if (priorityA !== priorityB) {
|
||
return priorityA - priorityB;
|
||
}
|
||
|
||
const spaceIdA = Number(a && a.space_id || 0);
|
||
const spaceIdB = Number(b && b.space_id || 0);
|
||
if (spaceIdA !== spaceIdB) {
|
||
return spaceIdA - spaceIdB;
|
||
}
|
||
|
||
const itemCodeA = String(a && a.item_code || '').trim();
|
||
const itemCodeB = String(b && b.item_code || '').trim();
|
||
return itemCodeA.localeCompare(itemCodeB);
|
||
});
|
||
|
||
return {
|
||
mode_code: pickMeta.mode_code,
|
||
mode_name: pickMeta.mode_name,
|
||
require_box_allocations: pickMeta.require_box_allocations,
|
||
group_by: 'space+item',
|
||
sort_by: [ 'pick_sequence', 'pick_priority', 'space_id', 'item_code' ],
|
||
items: itemList,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 解析订单所属波次信息。
|
||
*
|
||
* @param {Object} order 订单记录。
|
||
* @return {{waveId: number, waveNo: string}} 波次信息。
|
||
*/
|
||
resolveWaveInfo(order = {}) {
|
||
const waveId = Number(order.wave_id || 0);
|
||
const waveNo = String(order.wave_no || '').trim();
|
||
return {
|
||
waveId: Number.isFinite(waveId) ? waveId : 0,
|
||
waveNo,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 判断订单是否已复核。
|
||
*
|
||
* 当前使用 `inspection_status === "fin"` 作为已复核判定。
|
||
*
|
||
* @param {Object} order 订单记录。
|
||
* @return {boolean} 是否已复核。
|
||
*/
|
||
isOrderReviewed(order = {}) {
|
||
return String(order.inspection_status || '').trim() === REVIEWED_INSPECTION_STATUS;
|
||
}
|
||
|
||
/**
|
||
* 根据波次信息构建订单查询条件。
|
||
*
|
||
* @param {Object} waveInfo 波次信息。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Object} Sequelize 查询条件。
|
||
*/
|
||
buildWaveOrderWhere(waveInfo = {}, warehouseId) {
|
||
const { Op } = this.app.Sequelize;
|
||
const where = {
|
||
warehouse_id: warehouseId,
|
||
};
|
||
|
||
if (waveInfo.waveId > 0 && waveInfo.waveNo) {
|
||
where[Op.or] = [
|
||
{ wave_id: waveInfo.waveId },
|
||
{ wave_no: waveInfo.waveNo },
|
||
];
|
||
return where;
|
||
}
|
||
|
||
if (waveInfo.waveId > 0) {
|
||
where.wave_id = waveInfo.waveId;
|
||
return where;
|
||
}
|
||
|
||
where.wave_no = waveInfo.waveNo;
|
||
return where;
|
||
}
|
||
|
||
/**
|
||
* 按波次信息查询拣货汇总。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.orderId 当前订单ID。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {string} [params.waveNo] 波次号。
|
||
* @param {number} [params.waveId] 波次ID。
|
||
* @param {number} [params.storeId] 货主ID。
|
||
* @param {boolean} params.fullDisplay 是否完整显示。
|
||
* @return {Promise<Object>} 波次拣货汇总结果。
|
||
*/
|
||
async queryPickingInfo(params = {}) {
|
||
const { Op } = this.app.Sequelize;
|
||
const { ctx } = this;
|
||
const {
|
||
orderId,
|
||
warehouseId,
|
||
waveNo,
|
||
waveId,
|
||
storeId,
|
||
fullDisplay,
|
||
} = params;
|
||
|
||
const normalizedOrderId = Number(orderId || 0);
|
||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||
throw this.createBusinessError('order_id 参数不合法', 400);
|
||
}
|
||
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const waveInfo = {
|
||
waveId: Number(waveId || 0),
|
||
waveNo: String(waveNo || '').trim(),
|
||
};
|
||
if (waveInfo.waveId <= 0 && !waveInfo.waveNo) {
|
||
throw this.createBusinessError('订单未分配波次号,暂无拣货信息', 400);
|
||
}
|
||
|
||
const orderModel = await this.getOrderModel(normalizedWarehouseId);
|
||
|
||
const waveOrderRows = await orderModel.findAll({
|
||
where: this.buildWaveOrderWhere(waveInfo, normalizedWarehouseId),
|
||
attributes: [ 'id', 'inspection_status', 'store_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
const orderIds = Array.isArray(waveOrderRows)
|
||
? waveOrderRows
|
||
.map(item => Number(item && item.id || 0))
|
||
.filter(id => id > 0)
|
||
: [];
|
||
|
||
if (orderIds.length === 0) {
|
||
throw this.createBusinessError('未找到波次对应订单', 404);
|
||
}
|
||
|
||
const orderStatusMap = new Map();
|
||
for (const row of waveOrderRows) {
|
||
const id = Number(row && row.id || 0);
|
||
if (id <= 0) {
|
||
continue;
|
||
}
|
||
orderStatusMap.set(id, {
|
||
inspection_status: String(row && row.inspection_status || '').trim(),
|
||
});
|
||
}
|
||
|
||
const pickingRows = await ctx.model.Picking.findAll({
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
warehouse_id: normalizedWarehouseId,
|
||
},
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
const spaceIds = Array.isArray(pickingRows)
|
||
? Array.from(new Set(pickingRows
|
||
.map(item => Number(item && item.space_id || 0))
|
||
.filter(id => id > 0)))
|
||
: [];
|
||
|
||
const locationRows = spaceIds.length > 0
|
||
? await ctx.model.LocationSpace.findAll({
|
||
where: {
|
||
id: {
|
||
[Op.in]: spaceIds,
|
||
},
|
||
warehouse_id: normalizedWarehouseId,
|
||
},
|
||
attributes: [
|
||
'id',
|
||
'space_code',
|
||
'custom_name',
|
||
'custom_barcode',
|
||
'zone_id',
|
||
'space_status',
|
||
'is_enabled',
|
||
'pick_sequence',
|
||
'pick_priority',
|
||
],
|
||
raw: true,
|
||
})
|
||
: [];
|
||
|
||
const locationMap = new Map();
|
||
for (const location of Array.isArray(locationRows) ? locationRows : []) {
|
||
const locationId = Number(location && location.id || 0);
|
||
if (locationId > 0) {
|
||
locationMap.set(locationId, location);
|
||
}
|
||
}
|
||
|
||
const currentStoreId = Number(storeId || (waveOrderRows[0] && waveOrderRows[0].store_id) || 0);
|
||
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
|
||
where: {
|
||
store_id: currentStoreId,
|
||
warehouse_id: normalizedWarehouseId,
|
||
},
|
||
attributes: [ 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', 'auth_status', 'warehouse_use_status', 'store_use_status' ],
|
||
raw: true,
|
||
});
|
||
|
||
const fullDisplayFlag = Boolean(fullDisplay);
|
||
const allDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => {
|
||
const currentOrderId = Number(row && row.order_id || 0);
|
||
const orderStatus = orderStatusMap.get(currentOrderId) || { inspection_status: 'none' };
|
||
const reviewed = this.isOrderReviewed(orderStatus);
|
||
const spaceId = Number(row && row.space_id || 0);
|
||
|
||
return {
|
||
id: Number(row && row.id || 0),
|
||
order_id: currentOrderId,
|
||
order_item_id: Number(row && row.order_item_id || 0),
|
||
storage_id: Number(row && row.storage_id || 0),
|
||
quantity: Number(row && row.quantity || 0),
|
||
space_id: spaceId,
|
||
space_name: String(row && row.space_name || ''),
|
||
picking_status: String(row && row.status || ''),
|
||
inspection_status: orderStatus.inspection_status,
|
||
reviewed,
|
||
location_space: locationMap.get(spaceId) || null,
|
||
store_warehouse: storeWarehouse || null,
|
||
};
|
||
});
|
||
|
||
const pendingReviewDetails = allDetails.filter(item => !item.reviewed);
|
||
const reviewedDetails = allDetails.filter(item => item.reviewed);
|
||
const displayDetails = fullDisplayFlag ? allDetails : pendingReviewDetails;
|
||
|
||
const sumQuantity = rows => rows.reduce((sum, item) => sum + Number(item && item.quantity || 0), 0);
|
||
|
||
return {
|
||
order_id: normalizedOrderId,
|
||
wave_id: waveInfo.waveId,
|
||
wave_no: waveInfo.waveNo,
|
||
full_display: fullDisplayFlag,
|
||
summary: {
|
||
total_count: allDetails.length,
|
||
pending_review_count: pendingReviewDetails.length,
|
||
reviewed_count: reviewedDetails.length,
|
||
quantity_total: sumQuantity(allDetails),
|
||
display_count: displayDetails.length,
|
||
display_quantity_total: sumQuantity(displayDetails),
|
||
},
|
||
list: displayDetails,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按订单ID查询其波次拣货信息。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.orderId 订单ID。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {boolean} params.fullDisplay 是否完整显示。
|
||
* @return {Promise<Object>} 波次拣货汇总结果。
|
||
*/
|
||
async queryByOrder(params = {}) {
|
||
const {
|
||
orderId,
|
||
warehouseId,
|
||
fullDisplay,
|
||
} = params;
|
||
|
||
const normalizedOrderId = Number(orderId || 0);
|
||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||
throw this.createBusinessError('order_id 参数不合法', 400);
|
||
}
|
||
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const orderModel = await this.getOrderModel(normalizedWarehouseId);
|
||
|
||
const order = await orderModel.findOne({
|
||
where: {
|
||
id: normalizedOrderId,
|
||
warehouse_id: normalizedWarehouseId,
|
||
},
|
||
attributes: [ 'id', 'store_id', 'wave_no', 'wave_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!order) {
|
||
throw this.createBusinessError('订单不存在', 404);
|
||
}
|
||
|
||
const waveInfo = this.resolveWaveInfo(order);
|
||
if (waveInfo.waveId <= 0 && !waveInfo.waveNo) {
|
||
throw this.createBusinessError('订单未分配波次号,暂无拣货信息', 400);
|
||
}
|
||
|
||
return await this.queryPickingInfo({
|
||
orderId: normalizedOrderId,
|
||
warehouseId: normalizedWarehouseId,
|
||
waveNo: waveInfo.waveNo,
|
||
waveId: waveInfo.waveId,
|
||
storeId: Number(order.store_id || 0),
|
||
fullDisplay,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询当前登录用户正在处理中的拣货任务。
|
||
*
|
||
* 仅供 PDA 使用:根据当前登录用户上下文(仓库 + 操作人)查询状态为 0/1/2 的最新任务。
|
||
*
|
||
* @param {Object} [params={}] 预留参数(当前无需传入)。
|
||
* @return {Promise<{task_id: number|null}>} 当前任务ID,无任务则为 null。
|
||
*/
|
||
async wavePickTaskCurrent(params = {}) {
|
||
const { ctx } = this;
|
||
void params;
|
||
|
||
const stateUser = ctx && ctx.state && ctx.state.user && typeof ctx.state.user === 'object'
|
||
? ctx.state.user
|
||
: null;
|
||
const ctxUser = ctx && ctx.user && typeof ctx.user === 'object'
|
||
? ctx.user
|
||
: null;
|
||
const currentUser = stateUser || ctxUser || {};
|
||
|
||
const warehouseId = Number(
|
||
currentUser.store_id
|
||
|| currentUser.warehouse_id
|
||
|| (ctxUser && (ctxUser.store_id || ctxUser.warehouse_id))
|
||
|| 0
|
||
);
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const pickUserId = Number(
|
||
currentUser.employees_id
|
||
|| currentUser.operator_id
|
||
|| currentUser.id
|
||
|| (ctxUser && (ctxUser.employees_id || ctxUser.operator_id || ctxUser.id))
|
||
|| 0
|
||
);
|
||
if (!Number.isInteger(pickUserId) || pickUserId <= 0) {
|
||
throw this.createBusinessError('未获取到操作人上下文', 401);
|
||
}
|
||
|
||
const taskRows = await ctx.model.query(`
|
||
SELECT
|
||
t.id AS task_id
|
||
FROM wms_wave_pick_task t
|
||
WHERE t.warehouse_id = :warehouseId
|
||
AND t.pick_user_id = :pickUserId
|
||
AND t.status IN (0, 1)
|
||
ORDER BY t.id DESC
|
||
LIMIT 1
|
||
`, {
|
||
replacements: {
|
||
warehouseId,
|
||
pickUserId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null;
|
||
const taskId = Number(taskRow && taskRow.task_id || 0);
|
||
|
||
return {
|
||
task_id: Number.isInteger(taskId) && taskId > 0 ? taskId : null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 查询拣货任务详情。
|
||
*
|
||
* 按 task_id 查询任务主信息,并返回与拣货直接相关的框明细与拣货明细;
|
||
* 仅允许任务创建人(pick_user_id)查看。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.taskId 任务ID。
|
||
* @param {number} params.operatorId 当前操作人ID。
|
||
* @return {Promise<{task: Object, boxes: Array<Object>, picking_details: Array<Object>, picking_summary: Object, picking_view: Object}>} 任务详情。
|
||
*/
|
||
async wavePickTaskDetail(params = {}) {
|
||
const { ctx } = this;
|
||
const taskId = Number(params && params.taskId || 0);
|
||
const operatorId = Number(params && params.operatorId || 0);
|
||
|
||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||
throw this.createBusinessError('task_id 必填且必须为正整数', 400);
|
||
}
|
||
if (!Number.isInteger(operatorId) || operatorId <= 0) {
|
||
throw this.createBusinessError('未获取到操作人上下文', 401);
|
||
}
|
||
|
||
const taskRows = await ctx.model.query(`
|
||
SELECT
|
||
t.id AS task_id,
|
||
t.task_no,
|
||
t.status,
|
||
t.pick_mode,
|
||
t.pick_user_id,
|
||
t.start_time AS start_at,
|
||
t.finish_time AS finish_at,
|
||
t.batch_no,
|
||
t.warehouse_id
|
||
FROM wms_wave_pick_task t
|
||
WHERE t.id = :taskId
|
||
LIMIT 1
|
||
`, {
|
||
replacements: { taskId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null;
|
||
if (!taskRow) {
|
||
throw this.createBusinessError('拣货任务不存在', 404);
|
||
}
|
||
|
||
const taskPickUserId = Number(taskRow.pick_user_id || 0);
|
||
if (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId) {
|
||
throw this.createBusinessError('当前操作人与任务创建人不一致,无权查看', 403);
|
||
}
|
||
|
||
// 首次进入详情时补写拣货开始时间,确保后续流程可感知“已开始”。
|
||
if (!taskRow.start_at) {
|
||
await ctx.model.query(`
|
||
UPDATE wms_wave_pick_task
|
||
SET
|
||
start_time = NOW(),
|
||
update_time = NOW()
|
||
WHERE id = :taskId
|
||
AND start_time IS NULL
|
||
`, {
|
||
replacements: { taskId },
|
||
});
|
||
|
||
const startTimeRows = await ctx.model.query(`
|
||
SELECT start_time AS start_at
|
||
FROM wms_wave_pick_task
|
||
WHERE id = :taskId
|
||
LIMIT 1
|
||
`, {
|
||
replacements: { taskId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
const startTimeRow = Array.isArray(startTimeRows) && startTimeRows.length > 0 ? startTimeRows[0] : null;
|
||
taskRow.start_at = startTimeRow && startTimeRow.start_at ? startTimeRow.start_at : taskRow.start_at;
|
||
}
|
||
|
||
const warehouseId = Number(taskRow.warehouse_id || 0);
|
||
const pickMode = Number(taskRow.pick_mode || 0);
|
||
|
||
// 查询任务关联的波次号
|
||
let taskWaveNo = '';
|
||
try {
|
||
const taskWaveNoRows = await ctx.model.query(`
|
||
SELECT
|
||
wb.wave_no
|
||
FROM wms_wave_pick_task_wave ptw
|
||
INNER JOIN wms_wave_batch wb ON wb.wave_id = ptw.wave_id
|
||
WHERE ptw.task_id = :taskId
|
||
ORDER BY ptw.id ASC
|
||
LIMIT 1
|
||
`, {
|
||
replacements: { taskId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
taskWaveNo = Array.isArray(taskWaveNoRows) && taskWaveNoRows.length > 0
|
||
? String(taskWaveNoRows[0].wave_no || '').trim()
|
||
: '';
|
||
} catch (error) {
|
||
ctx.logger.warn(`[pick.wavePickTaskDetail] 查询波次号失败,将降级为空: ${error.message}`);
|
||
}
|
||
|
||
const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order');
|
||
const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave');
|
||
const boxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box');
|
||
const taskOrderWarehouseFilterSql = taskOrderColumnSet.has('warehouse_id') ? ' AND pto.warehouse_id = :warehouseId' : '';
|
||
const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND ptw.warehouse_id = :warehouseId' : '';
|
||
const boxWarehouseFilterSql = boxColumnSet.has('warehouse_id') ? ' AND b.warehouse_id = :warehouseId' : '';
|
||
const boxExtraSelect = [];
|
||
if (boxColumnSet.has('ref_label')) {
|
||
boxExtraSelect.push('b.ref_label');
|
||
}
|
||
if (boxColumnSet.has('required_qty')) {
|
||
boxExtraSelect.push('b.required_qty');
|
||
}
|
||
if (boxColumnSet.has('picked_qty')) {
|
||
boxExtraSelect.push('b.picked_qty');
|
||
}
|
||
if (boxColumnSet.has('ref_id')) {
|
||
boxExtraSelect.push('b.ref_id');
|
||
}
|
||
|
||
const [ taskOrderRows, boxRows ] = await Promise.all([
|
||
ctx.model.query(`
|
||
SELECT
|
||
pto.order_id,
|
||
pto.box_no,
|
||
pto.pick_status
|
||
FROM wms_wave_pick_task_order pto
|
||
WHERE pto.task_id = :taskId
|
||
${taskOrderWarehouseFilterSql}
|
||
ORDER BY pto.id ASC
|
||
`, {
|
||
replacements: { taskId, warehouseId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}),
|
||
ctx.model.query(`
|
||
SELECT
|
||
b.id AS box_id,
|
||
b.box_no,
|
||
b.box_type,
|
||
b.box_status AS status${boxExtraSelect.length > 0 ? `,\n ${boxExtraSelect.join(',\n ')}` : ''}
|
||
FROM wms_wave_pick_task_box b
|
||
WHERE b.task_id = :taskId
|
||
${boxWarehouseFilterSql}
|
||
ORDER BY b.id ASC
|
||
`, {
|
||
replacements: { taskId, warehouseId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}),
|
||
]);
|
||
|
||
const normalizedTaskOrderRows = Array.isArray(taskOrderRows) ? taskOrderRows : [];
|
||
const taskOrderTotal = normalizedTaskOrderRows.length;
|
||
const taskOrderPicked = normalizedTaskOrderRows
|
||
.filter(row => Number(row && row.pick_status || 0) === 1)
|
||
.length;
|
||
const taskCompletedByOrder = taskOrderTotal > 0 && taskOrderPicked >= taskOrderTotal;
|
||
const taskCompletedByStatus = Number(taskRow && taskRow.status || 0) >= 2;
|
||
const isCompleted = taskCompletedByOrder || taskCompletedByStatus;
|
||
let orderIds = [ ...new Set(normalizedTaskOrderRows
|
||
.map(row => Number(row && row.order_id || 0))
|
||
.filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ];
|
||
let taskWaveCount = 0;
|
||
let orderSource = 'task_order';
|
||
const derivedWaveIds = [];
|
||
|
||
if (orderIds.length === 0 && [ 1, 5 ].includes(pickMode)) {
|
||
const taskWaveRows = await ctx.model.query(`
|
||
SELECT
|
||
ptw.wave_id
|
||
FROM wms_wave_pick_task_wave ptw
|
||
WHERE ptw.task_id = :taskId
|
||
${taskWaveWarehouseFilterSql}
|
||
ORDER BY ptw.id ASC
|
||
`, {
|
||
replacements: { taskId, warehouseId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
const normalizedTaskWaveRows = Array.isArray(taskWaveRows) ? taskWaveRows : [];
|
||
taskWaveCount = normalizedTaskWaveRows.length;
|
||
const fallbackWaveIds = [ ...new Set(normalizedTaskWaveRows
|
||
.map(row => Number(row && row.wave_id || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||
derivedWaveIds.push(...fallbackWaveIds.slice(0, 5));
|
||
|
||
if (fallbackWaveIds.length > 0) {
|
||
const orderModel = await this.getOrderModel(warehouseId);
|
||
const fallbackOrderRows = await orderModel.findAll({
|
||
where: {
|
||
wave_id: {
|
||
[this.app.Sequelize.Op.in]: fallbackWaveIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
|
||
orderIds = [ ...new Set((Array.isArray(fallbackOrderRows) ? fallbackOrderRows : [])
|
||
.map(row => Number(row && row.id || 0))
|
||
.filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ];
|
||
if (orderIds.length > 0) {
|
||
orderSource = 'task_wave_fallback';
|
||
}
|
||
}
|
||
}
|
||
|
||
if (orderIds.length > 0) {
|
||
const orderModel = await this.getOrderModel(warehouseId);
|
||
const orderExpressStatusRows = await orderModel.findAll({
|
||
where: {
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: orderIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'post_status' ],
|
||
raw: true,
|
||
});
|
||
|
||
const orderExpressStatusMap = new Map((Array.isArray(orderExpressStatusRows) ? orderExpressStatusRows : [])
|
||
.map(row => [ Number(row && row.id || 0), String(row && row.post_status || '').trim() ]));
|
||
const unassignedExpressOrderIds = orderIds
|
||
.filter(orderIdItem => {
|
||
const expressStatus = orderExpressStatusMap.get(orderIdItem) || '';
|
||
return expressStatus !== 'fin';
|
||
});
|
||
|
||
if (unassignedExpressOrderIds.length > 0) {
|
||
throw this.createBusinessError(
|
||
'存在未分配快递号订单,是否一键分配快递号?',
|
||
400,
|
||
{
|
||
action: 'assign_express',
|
||
order_ids: unassignedExpressOrderIds,
|
||
}
|
||
);
|
||
}
|
||
}
|
||
|
||
const pickingRows = orderIds.length > 0
|
||
? await ctx.model.Picking.findAll({
|
||
where: {
|
||
order_id: {
|
||
[this.app.Sequelize.Op.in]: orderIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'storage_id', 'space_id', 'space_name' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
})
|
||
: [];
|
||
|
||
const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : [];
|
||
const orderIdSet = new Set(orderIds);
|
||
const orderIdsWithPicking = new Set(normalizedPickingRows
|
||
.map(row => Number(row && row.order_id || 0))
|
||
.filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdSet.has(orderIdItem)));
|
||
const missingPickingOrderIds = orderIds
|
||
.filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0 && !orderIdsWithPicking.has(orderIdItem));
|
||
const invalidSpaceOrderIds = [ ...new Set(normalizedPickingRows
|
||
.filter(row => Number(row && row.space_id || 0) <= 0)
|
||
.map(row => Number(row && row.order_id || 0))
|
||
.filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdSet.has(orderIdItem))) ];
|
||
const unassignedSpaceOrderIds = [ ...new Set([ ...missingPickingOrderIds, ...invalidSpaceOrderIds ]) ];
|
||
if (unassignedSpaceOrderIds.length > 0) {
|
||
throw this.createBusinessError(
|
||
'存在未分配储位订单,是否一键分配储位?',
|
||
400,
|
||
{
|
||
action: 'assign_storage',
|
||
order_ids: unassignedSpaceOrderIds,
|
||
}
|
||
);
|
||
}
|
||
|
||
ctx.logger.info(
|
||
`[pick.wavePickTaskDetail] task_id=${taskId} pick_mode=${pickMode} warehouse_id=${warehouseId} task_order_count=${normalizedTaskOrderRows.length} task_wave_count=${taskWaveCount} derived_order_ids_count=${orderIds.length} picking_rows_count=${Array.isArray(pickingRows) ? pickingRows.length : 0} order_source=${orderSource} order_id_samples=${JSON.stringify(orderIds.slice(0, 5))} wave_id_samples=${JSON.stringify(derivedWaveIds)}`
|
||
);
|
||
|
||
const pickingSpaceIds = [ ...new Set((Array.isArray(pickingRows) ? pickingRows : [])
|
||
.map(row => Number(row && row.space_id || 0))
|
||
.filter(spaceId => Number.isInteger(spaceId) && spaceId > 0)) ];
|
||
|
||
const locationRows = pickingSpaceIds.length > 0
|
||
? await ctx.model.LocationSpace.findAll({
|
||
where: {
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: pickingSpaceIds,
|
||
},
|
||
},
|
||
attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode', 'pick_sequence', 'pick_priority' ],
|
||
raw: true,
|
||
})
|
||
: [];
|
||
|
||
const locationMap = new Map((Array.isArray(locationRows) ? locationRows : [])
|
||
.map(row => [ Number(row && row.id || 0), row ]));
|
||
|
||
const orderItemIds = [ ...new Set((Array.isArray(pickingRows) ? pickingRows : [])
|
||
.map(row => Number(row && row.order_item_id || 0))
|
||
.filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0)) ];
|
||
const orderItemMap = await this.loadOrderItemMap({
|
||
warehouseId,
|
||
orderItemIds,
|
||
});
|
||
|
||
// 通过 stock_warehouse 带缓存的公用链路(getStockDetails)批量查询商品资料,
|
||
// 以 stock_id 为准获取 item_code / item_name,与 order/base.js 等链路保持一致。
|
||
const stockIdsForDetail = [ ...new Set(
|
||
[ ...orderItemMap.values() ]
|
||
.map(row => Number(row && row.stock_id || 0))
|
||
.filter(sid => Number.isInteger(sid) && sid > 0)
|
||
) ];
|
||
const stockDetailMap = new Map();
|
||
if (stockIdsForDetail.length > 0) {
|
||
try {
|
||
const stockWarehouseSvc = ctx.service && ctx.service.systems && ctx.service.systems.stockWarehouse;
|
||
if (stockWarehouseSvc && typeof stockWarehouseSvc.getStockDetails === 'function') {
|
||
const stockDetails = await stockWarehouseSvc.getStockDetails(stockIdsForDetail, { warehouseId });
|
||
for (const detail of (Array.isArray(stockDetails) ? stockDetails : [])) {
|
||
stockDetailMap.set(Number(detail && detail.id || 0), detail);
|
||
}
|
||
}
|
||
} catch (error) {
|
||
ctx.logger.warn(`[pick.wavePickTaskDetail] getStockDetails 查询失败,将降级使用 order_items 列值: ${error.message}`);
|
||
}
|
||
}
|
||
|
||
// 批量查询货主备注名(wms_store_warehouse.store_remask),按 store_id 映射
|
||
const storeRemarkMap = new Map();
|
||
if (stockDetailMap.size > 0 && ctx.model && ctx.model.StoreWarehouse) {
|
||
const storeIdsForRemark = [ ...new Set(
|
||
[ ...stockDetailMap.values() ]
|
||
.map(detail => Number(detail.store_id || 0))
|
||
.filter(id => id > 0)
|
||
) ];
|
||
if (storeIdsForRemark.length > 0) {
|
||
try {
|
||
const swRows = await ctx.model.StoreWarehouse.findAll({
|
||
where: {
|
||
store_id: { [this.app.Sequelize.Op.in]: storeIdsForRemark },
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
raw: true,
|
||
});
|
||
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
|
||
const sid = Number(sw.store_id || 0);
|
||
if (sid > 0 && !storeRemarkMap.has(sid)) {
|
||
storeRemarkMap.set(sid, String(sw.store_remask || '').trim());
|
||
}
|
||
}
|
||
} catch (remarkError) {
|
||
ctx.logger.warn(`[pick.wavePickTaskDetail] 查询货主备注失败: ${remarkError.message}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
const normalizedBoxRows = Array.isArray(boxRows) ? boxRows : [];
|
||
const boxMapByNo = new Map(normalizedBoxRows
|
||
.map(row => [ Number(row && row.box_no || 0), row ])
|
||
.filter(([ boxNo ]) => boxNo > 0));
|
||
|
||
// 构建 stock_id → box_no 映射(从 wms_wave_pick_task_box.ref_id),用于给每个拣货明细行标注篮号
|
||
const boxNoByStockId = new Map();
|
||
for (const row of normalizedBoxRows) {
|
||
const sid = Number(row && row.ref_id || 0);
|
||
const bno = Number(row && row.box_no || 0);
|
||
if (sid > 0 && bno > 0 && !boxNoByStockId.has(sid)) {
|
||
boxNoByStockId.set(sid, bno);
|
||
}
|
||
}
|
||
|
||
const pickingDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => {
|
||
const orderItemId = Number(row && row.order_item_id || 0);
|
||
const currentSpaceId = Number(row && row.space_id || 0);
|
||
const locationRow = locationMap.get(currentSpaceId) || {};
|
||
const orderItemRow = orderItemMap.get(orderItemId) || {};
|
||
const stockId = Number(orderItemRow.stock_id || 0);
|
||
const stockDetail = stockDetailMap.get(stockId) || null;
|
||
const itemSnapshot = this.parseItemSnapshot(orderItemRow.item_snapshot);
|
||
|
||
// 构建 stock 字段:优先 getStockDetails 完整对象,兜底用 item_snapshot + order_items 拼装
|
||
const stock = stockDetail
|
||
? { ...stockDetail }
|
||
: {
|
||
id: stockId || null,
|
||
item_code: String(itemSnapshot.item_code || orderItemRow.item_code || '').trim(),
|
||
item_name: String(itemSnapshot.item_name || orderItemRow.item_name || '').trim(),
|
||
sku_property: String(itemSnapshot.sku_property || '').trim(),
|
||
stock_unit: String(itemSnapshot.stock_unit || '').trim(),
|
||
barcodes: [],
|
||
image_url: [],
|
||
store_id: 0,
|
||
};
|
||
// 确保 owner_code 在 stock 对象上(getStockDetails 不含此字段,需从 order_items 补)
|
||
if (!stock.owner_code) {
|
||
stock.owner_code = String(orderItemRow.owner_code || '').trim();
|
||
}
|
||
// 确保 store_remark 在 stock 对象上(getStockDetails 不含此字段,需从 wms_store_warehouse 补)
|
||
const stockStoreId = stock.store_id != null ? Number(stock.store_id) : 0;
|
||
if (!stock.store_remark) {
|
||
stock.store_remark = storeRemarkMap.get(stockStoreId) || '';
|
||
}
|
||
|
||
return {
|
||
order_id: Number(row && row.order_id || 0),
|
||
box_no: boxNoByStockId.get(stockId) || 0,
|
||
order_item_id: orderItemId,
|
||
quantity: Number(row && row.quantity || 0),
|
||
storage_id: Number(row && row.storage_id || 0),
|
||
space_id: currentSpaceId,
|
||
space_name: String(row && row.space_name || '').trim(),
|
||
location_space: {
|
||
space_code: String(locationRow.space_code || '').trim(),
|
||
custom_name: String(locationRow.custom_name || '').trim(),
|
||
custom_barcode: String(locationRow.custom_barcode || '').trim(),
|
||
pick_sequence: Number(locationRow.pick_sequence || 0),
|
||
pick_priority: Number(locationRow.pick_priority || 0),
|
||
},
|
||
// 优先 stock_warehouse(getStockDetails),兜底 item_snapshot,最终 order_items 列
|
||
item_code: stock.item_code,
|
||
item_name: stock.item_name,
|
||
stock_id: stockId,
|
||
plan_qty: Number(orderItemRow.plan_qty || 0),
|
||
item_snapshot: orderItemRow.item_snapshot || null,
|
||
store_id: stockStoreId,
|
||
owner_code: String(stock.owner_code || '').trim(),
|
||
store_remark: String(stock.store_remark || '').trim(),
|
||
stock,
|
||
};
|
||
});
|
||
|
||
// 排序 picking_details:box_no 已按库位顺序生成,直接按 box_no 升序即可
|
||
pickingDetails.sort((a, b) => {
|
||
const boxA = Number(a && a.box_no || 0);
|
||
const boxB = Number(b && b.box_no || 0);
|
||
if (boxA !== boxB) return boxA - boxB;
|
||
|
||
const codeA = String(a && a.item_code || '').trim();
|
||
const codeB = String(b && b.item_code || '').trim();
|
||
return codeA.localeCompare(codeB);
|
||
});
|
||
|
||
const pickingSummary = this.buildPickingSummary(pickingDetails);
|
||
const pickingView = await this.buildPickingView({
|
||
pickMode,
|
||
taskId,
|
||
warehouseId,
|
||
pickingDetails,
|
||
boxRows: normalizedBoxRows,
|
||
taskOrderRows: normalizedTaskOrderRows,
|
||
boxMapByNo,
|
||
});
|
||
|
||
const result = {
|
||
task: {
|
||
task_id: Number(taskRow.task_id || 0),
|
||
task_no: String(taskRow.task_no || '').trim(),
|
||
wave_no: taskWaveNo,
|
||
status: Number(taskRow.status || 0),
|
||
pick_mode: pickMode,
|
||
start_at: taskRow.start_at || null,
|
||
finish_at: taskRow.finish_at || null,
|
||
batch_no: String(taskRow.batch_no || '').trim(),
|
||
is_completed: isCompleted,
|
||
progress: {
|
||
total_orders: taskOrderTotal,
|
||
picked_orders: taskOrderPicked,
|
||
pending_orders: Math.max(0, taskOrderTotal - taskOrderPicked),
|
||
},
|
||
},
|
||
is_completed: isCompleted,
|
||
boxes: normalizedBoxRows.map(row => ({
|
||
box_id: Number(row && row.box_id || 0),
|
||
box_no: Number(row && row.box_no || 0),
|
||
box_type: Number(row && row.box_type || 0),
|
||
status: Number(row && row.status || 0),
|
||
ref_id: Number(row && row.ref_id || 0),
|
||
ref_label: String(row && row.ref_label || '').trim() || null,
|
||
required_qty: Number(row && row.required_qty || 0),
|
||
picked_qty: Number(row && row.picked_qty || 0),
|
||
})),
|
||
picking_summary: pickingSummary,
|
||
picking_view: pickingView,
|
||
};
|
||
|
||
// 团购模式(小波次 pick_mode=1 / 大波次 pick_mode=5)不需要返回拣货明细,减少带宽浪费
|
||
if (pickMode !== 1 && pickMode !== 5) {
|
||
result.picking_details = pickingDetails;
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 解析当前操作人上下文。
|
||
*
|
||
* @return {{operatorId: number, operatorName: string, warehouseId: number}} 上下文信息。
|
||
*/
|
||
resolveOperatorContext() {
|
||
const { ctx } = this;
|
||
const stateUser = ctx && ctx.state && ctx.state.user && typeof ctx.state.user === 'object'
|
||
? ctx.state.user
|
||
: null;
|
||
const ctxUser = ctx && ctx.user && typeof ctx.user === 'object'
|
||
? ctx.user
|
||
: null;
|
||
const operatorSource = stateUser || ctxUser || {};
|
||
|
||
const operatorId = Number((operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id) || 0);
|
||
const operatorName = String(
|
||
operatorSource.operator_name
|
||
|| operatorSource.employees_name
|
||
|| operatorSource.name
|
||
|| ''
|
||
).trim() || 'system';
|
||
const warehouseId = Number(operatorSource.store_id || operatorSource.warehouse_id || 0);
|
||
|
||
return {
|
||
operatorId,
|
||
operatorName,
|
||
warehouseId,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 规范化拣货车状态。
|
||
*
|
||
* @param {*} status 原始状态。
|
||
* @param {number} [defaultValue=1] 默认状态。
|
||
* @return {number} 规范化后的状态值,仅返回 0 或 1。
|
||
*/
|
||
normalizePickCartStatus(status, defaultValue = 1) {
|
||
if (status === undefined || status === null || status === '') {
|
||
return defaultValue;
|
||
}
|
||
|
||
const normalized = Number(status);
|
||
if (normalized === 0) {
|
||
return 0;
|
||
}
|
||
if (normalized === 1) {
|
||
return 1;
|
||
}
|
||
return Number(defaultValue) === 0 ? 0 : 1;
|
||
}
|
||
|
||
/**
|
||
* 构建拣货车详情输出。
|
||
*
|
||
* @param {Object} row 原始数据库记录。
|
||
* @return {Object} 标准化后的详情。
|
||
*/
|
||
buildPickCartDetail(row = {}) {
|
||
return {
|
||
cart_id: Number(row && (row.cart_id || row.id) || 0),
|
||
warehouse_id: Number(row && row.warehouse_id || 0),
|
||
cart_code: String(row && row.cart_code || '').trim(),
|
||
cart_name: String(row && row.cart_name || '').trim(),
|
||
status: Number(row && row.status || 0),
|
||
current_task_id: Number(row && row.current_task_id || 0) || null,
|
||
current_task_no: String(row && row.current_task_no || '').trim() || null,
|
||
current_task_status: row && row.current_task_status !== undefined && row.current_task_status !== null
|
||
? Number(row.current_task_status)
|
||
: null,
|
||
bind_user_id: Number(row && row.bind_user_id || 0) || null,
|
||
last_bind_time: row && row.last_bind_time ? row.last_bind_time : null,
|
||
last_seen_time: row && row.last_seen_time ? row.last_seen_time : null,
|
||
create_time: row && row.create_time ? row.create_time : null,
|
||
update_time: row && row.update_time ? row.update_time : null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按 ID 查询拣货车。
|
||
*
|
||
* @param {number} cartId 拣货车ID。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Object} [transaction=null] 事务对象。
|
||
* @return {Promise<Object|null>} 拣货车记录。
|
||
*/
|
||
async getPickCartById(cartId, warehouseId, transaction = null) {
|
||
const { ctx } = this;
|
||
const rows = await ctx.model.query(`
|
||
SELECT
|
||
c.id AS cart_id,
|
||
c.warehouse_id,
|
||
c.cart_code,
|
||
c.cart_name,
|
||
c.status,
|
||
c.current_task_id,
|
||
c.bind_user_id,
|
||
c.last_bind_time,
|
||
c.last_seen_time,
|
||
c.create_time,
|
||
c.update_time,
|
||
t.task_no AS current_task_no,
|
||
t.status AS current_task_status
|
||
FROM wms_pick_cart c
|
||
LEFT JOIN wms_wave_pick_task t
|
||
ON t.id = c.current_task_id
|
||
WHERE c.id = :cartId
|
||
AND c.warehouse_id = :warehouseId
|
||
LIMIT 1
|
||
`, {
|
||
replacements: {
|
||
cartId,
|
||
warehouseId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
...(transaction ? { transaction } : {}),
|
||
});
|
||
|
||
return Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
|
||
}
|
||
|
||
/**
|
||
* 按编码查询拣货车。
|
||
*
|
||
* @param {string} cartCode 拣货车编码。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Object} [transaction=null] 事务对象。
|
||
* @return {Promise<Object|null>} 拣货车记录。
|
||
*/
|
||
async getPickCartByCode(cartCode, warehouseId, transaction = null) {
|
||
const { ctx } = this;
|
||
const normalizedCartCode = String(cartCode || '').trim();
|
||
if (!normalizedCartCode) {
|
||
return null;
|
||
}
|
||
|
||
const rows = await ctx.model.query(`
|
||
SELECT
|
||
c.id AS cart_id,
|
||
c.warehouse_id,
|
||
c.cart_code,
|
||
c.cart_name,
|
||
c.status,
|
||
c.current_task_id,
|
||
c.bind_user_id,
|
||
c.last_bind_time,
|
||
c.last_seen_time,
|
||
c.create_time,
|
||
c.update_time,
|
||
t.task_no AS current_task_no,
|
||
t.status AS current_task_status
|
||
FROM wms_pick_cart c
|
||
LEFT JOIN wms_wave_pick_task t
|
||
ON t.id = c.current_task_id
|
||
WHERE c.warehouse_id = :warehouseId
|
||
AND c.cart_code = :cartCode
|
||
LIMIT 1
|
||
`, {
|
||
replacements: {
|
||
warehouseId,
|
||
cartCode: normalizedCartCode,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
...(transaction ? { transaction } : {}),
|
||
});
|
||
|
||
return Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
|
||
}
|
||
|
||
/**
|
||
* 查询拣货车编码是否重复。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {string} params.cartCode 拣货车编码。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {number} [params.excludeCartId=0] 排除的拣货车ID。
|
||
* @param {Object} [params.transaction=null] 事务对象。
|
||
* @return {Promise<Object>} 查重结果。
|
||
*/
|
||
async pickCartCodeDuplicateCheck(params = {}) {
|
||
const { ctx } = this;
|
||
const cartCode = String(params && params.cartCode || '').trim();
|
||
const warehouseId = Number(params && params.warehouseId || 0);
|
||
const excludeCartId = Number(params && params.excludeCartId || 0);
|
||
const transaction = params && params.transaction ? params.transaction : null;
|
||
|
||
if (!cartCode) {
|
||
throw this.createBusinessError('cart_code 必填', 400);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const rows = await ctx.model.query(`
|
||
SELECT
|
||
c.id AS cart_id,
|
||
c.cart_code,
|
||
c.cart_name,
|
||
c.status
|
||
FROM wms_pick_cart c
|
||
WHERE c.warehouse_id = :warehouseId
|
||
AND c.cart_code = :cartCode
|
||
AND (:excludeCartId <= 0 OR c.id <> :excludeCartId)
|
||
ORDER BY c.id DESC
|
||
LIMIT 1
|
||
`, {
|
||
replacements: {
|
||
warehouseId,
|
||
cartCode,
|
||
excludeCartId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
...(transaction ? { transaction } : {}),
|
||
});
|
||
|
||
const row = Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
|
||
return {
|
||
duplicated: Boolean(row),
|
||
cart_id: row ? Number(row.cart_id || 0) : null,
|
||
cart_code: row ? String(row.cart_code || '').trim() : null,
|
||
cart_name: row ? String(row.cart_name || '').trim() : null,
|
||
status: row ? Number(row.status || 0) : null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 确保拣货车编码未重复。
|
||
*
|
||
* @param {string} cartCode 拣货车编码。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {number} [excludeCartId=0] 排除的拣货车ID。
|
||
* @param {Object} [transaction=null] 事务对象。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async assertPickCartCodeUnique(cartCode, warehouseId, excludeCartId = 0, transaction = null) {
|
||
const duplicateResult = await this.pickCartCodeDuplicateCheck({
|
||
cartCode,
|
||
warehouseId,
|
||
excludeCartId,
|
||
transaction,
|
||
});
|
||
|
||
if (duplicateResult.duplicated) {
|
||
throw this.createBusinessError('拣货车编码已存在,请勿重复', 409, duplicateResult);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验任务存在性与归属。
|
||
*
|
||
* @param {number} taskId 任务ID。
|
||
* @param {number} operatorId 操作人ID。
|
||
* @return {Promise<Object>} 任务记录。
|
||
*/
|
||
async getOwnedTask(taskId, operatorId) {
|
||
const { ctx } = this;
|
||
const taskRows = await ctx.model.query(`
|
||
SELECT
|
||
t.id AS task_id,
|
||
t.task_no,
|
||
t.status,
|
||
t.pick_mode,
|
||
t.pick_user_id,
|
||
t.warehouse_id,
|
||
t.start_time,
|
||
t.finish_time,
|
||
t.ext_json,
|
||
t.source,
|
||
t.current_cart_id
|
||
FROM wms_wave_pick_task t
|
||
WHERE t.id = :taskId
|
||
LIMIT 1
|
||
`, {
|
||
replacements: { taskId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null;
|
||
if (!taskRow) {
|
||
throw this.createBusinessError('拣货任务不存在', 404);
|
||
}
|
||
|
||
const taskPickUserId = Number(taskRow.pick_user_id || 0);
|
||
// source=2 后台抓取创建的任务 pick_user_id 可能为 0,此时跳过归属校验
|
||
if (taskPickUserId !== 0 && (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId)) {
|
||
throw this.createBusinessError('当前操作人与任务创建人不一致,无权操作', 403);
|
||
}
|
||
|
||
return taskRow;
|
||
}
|
||
|
||
/**
|
||
* 统计任务订单拣货进度。
|
||
*
|
||
* @param {number} taskId 任务ID。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Object} [transaction] 事务对象。
|
||
* @return {Promise<{totalOrders:number,pickedOrders:number,pendingOrders:number,isCompleted:boolean}>} 进度信息。
|
||
*/
|
||
async getTaskPickProgress(taskId, warehouseId, transaction = null) {
|
||
const { ctx } = this;
|
||
const taskOrderRows = await ctx.model.query(`
|
||
SELECT
|
||
pto.order_id,
|
||
pto.pick_status
|
||
FROM wms_wave_pick_task_order pto
|
||
WHERE pto.task_id = :taskId
|
||
AND pto.warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
...(transaction ? { transaction } : {}),
|
||
});
|
||
|
||
const normalizedRows = Array.isArray(taskOrderRows) ? taskOrderRows : [];
|
||
const totalOrders = normalizedRows.length;
|
||
const pickedOrders = normalizedRows.filter(row => Number(row && row.pick_status || 0) === 1).length;
|
||
const pendingOrders = Math.max(0, totalOrders - pickedOrders);
|
||
const isCompleted = totalOrders > 0 && pickedOrders >= totalOrders;
|
||
|
||
return {
|
||
totalOrders,
|
||
pickedOrders,
|
||
pendingOrders,
|
||
isCompleted,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 拣货任务中间态提交。
|
||
*
|
||
* 用于保存阶段性进度,不进行最终确认。
|
||
*
|
||
* @param {Object} params 提交参数。
|
||
* @param {number} params.taskId 任务ID。
|
||
* @param {Object} [params.payload] 阶段性数据。
|
||
* @return {Promise<Object>} 保存结果。
|
||
*/
|
||
async wavePickTaskSubmit(params = {}) {
|
||
const { ctx } = this;
|
||
const taskId = Number(params && params.taskId || 0);
|
||
const payload = params && typeof params.payload === 'object' && !Array.isArray(params.payload)
|
||
? params.payload
|
||
: {};
|
||
|
||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||
throw this.createBusinessError('task_id 必填且必须为正整数', 400);
|
||
}
|
||
|
||
const { operatorId, operatorName, warehouseId } = this.resolveOperatorContext();
|
||
if (!Number.isInteger(operatorId) || operatorId <= 0) {
|
||
throw this.createBusinessError('未获取到操作人上下文', 401);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const taskRow = await this.getOwnedTask(taskId, operatorId);
|
||
const taskStatus = Number(taskRow && taskRow.status || 0);
|
||
if ([ 3, 9 ].includes(taskStatus)) {
|
||
throw this.createBusinessError('任务已完成或已取消,无法提交中间态', 400);
|
||
}
|
||
|
||
let extJson = {};
|
||
const extSource = taskRow && taskRow.ext_json;
|
||
if (extSource && typeof extSource === 'object' && !Array.isArray(extSource)) {
|
||
extJson = { ...extSource };
|
||
} else if (typeof extSource === 'string' && extSource.trim()) {
|
||
try {
|
||
const parsed = JSON.parse(extSource);
|
||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||
extJson = { ...parsed };
|
||
}
|
||
} catch (_) {
|
||
extJson = {};
|
||
}
|
||
}
|
||
|
||
extJson.pick_intermediate = {
|
||
payload,
|
||
updated_at: new Date().toISOString(),
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
};
|
||
|
||
await ctx.model.query(`
|
||
UPDATE wms_wave_pick_task
|
||
SET status = CASE WHEN status = 0 THEN 1 ELSE status END,
|
||
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
|
||
ext_json = :extJson,
|
||
update_time = NOW()
|
||
WHERE id = :taskId
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
extJson: JSON.stringify(extJson),
|
||
},
|
||
});
|
||
|
||
const progress = await this.getTaskPickProgress(taskId, warehouseId);
|
||
return {
|
||
task_id: taskId,
|
||
status: 'submitted',
|
||
is_completed: progress.isCompleted,
|
||
progress: {
|
||
total_orders: progress.totalOrders,
|
||
picked_orders: progress.pickedOrders,
|
||
pending_orders: progress.pendingOrders,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 拣货任务完全提交。
|
||
*
|
||
* 支持两种模式:
|
||
* - 1:全部确认(将任务下全部订单标记为已拣)
|
||
* - 2:部分确认(仅确认传入 order_ids)
|
||
*
|
||
* @param {Object} params 提交参数。
|
||
* @param {number} params.taskId 任务ID。
|
||
* @param {number} [params.mode=1] 提交模式:1全部确认,2部分确认。
|
||
* @param {Array<number>} [params.orderIds=[]] 部分确认时的订单ID列表。
|
||
* @return {Promise<Object>} 提交结果。
|
||
*/
|
||
async wavePickTaskComplete(params = {}) {
|
||
const { ctx } = this;
|
||
const taskId = Number(params && params.taskId || 0);
|
||
const mode = Number(params && params.mode || 1);
|
||
const orderIds = [ ...new Set((Array.isArray(params && params.orderIds) ? params.orderIds : [])
|
||
.map(id => Number(id || 0))
|
||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||
|
||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||
throw this.createBusinessError('task_id 必填且必须为正整数', 400);
|
||
}
|
||
if (![ 1, 2 ].includes(mode)) {
|
||
throw this.createBusinessError('mode 参数不合法,仅支持 1(全部确认) 或 2(部分确认)', 400);
|
||
}
|
||
|
||
const { operatorId, operatorName, warehouseId } = this.resolveOperatorContext();
|
||
if (!Number.isInteger(operatorId) || operatorId <= 0) {
|
||
throw this.createBusinessError('未获取到操作人上下文', 401);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const taskRow = await this.getOwnedTask(taskId, operatorId);
|
||
const taskStatus = Number(taskRow && taskRow.status || 0);
|
||
if ([ 3, 9 ].includes(taskStatus)) {
|
||
throw this.createBusinessError('任务已完成或已取消,无法再次提交', 400);
|
||
}
|
||
|
||
// source=1(PDA抓取创建)的任务必须先绑定拣货车才能提交
|
||
// source=2(扫描进任务/后台抓取)不强制要求绑定拣货车
|
||
const taskSource = Number(taskRow && taskRow.source || 0);
|
||
const taskCartId = Number(taskRow && taskRow.current_cart_id || 0);
|
||
if (taskSource === 1 && taskCartId <= 0) {
|
||
throw this.createBusinessError('PDA抓取任务必须先绑定拣货车才能提交', 400);
|
||
}
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
const taskOrderRows = await ctx.model.query(`
|
||
SELECT
|
||
pto.order_id,
|
||
pto.pick_status
|
||
FROM wms_wave_pick_task_order pto
|
||
WHERE pto.task_id = :taskId
|
||
AND pto.warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
transaction,
|
||
});
|
||
|
||
const normalizedRows = Array.isArray(taskOrderRows) ? taskOrderRows : [];
|
||
let taskOrderIds = [ ...new Set(normalizedRows
|
||
.map(row => Number(row && row.order_id || 0))
|
||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||
|
||
if (taskOrderIds.length <= 0) {
|
||
const pickMode = Number(taskRow.pick_mode || 0);
|
||
if ([ 1, 5 ].includes(pickMode)) {
|
||
const taskWaveWarehouseFilterSql = (await this.getTableColumnSet('wms_wave_pick_task_wave')).has('warehouse_id')
|
||
? ' AND ptw.warehouse_id = :warehouseId'
|
||
: '';
|
||
const taskWaveRows = await ctx.model.query(`
|
||
SELECT
|
||
ptw.wave_id
|
||
FROM wms_wave_pick_task_wave ptw
|
||
WHERE ptw.task_id = :taskId
|
||
${taskWaveWarehouseFilterSql}
|
||
ORDER BY ptw.id ASC
|
||
`, {
|
||
replacements: { taskId, warehouseId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
transaction,
|
||
});
|
||
|
||
const normalizedTaskWaveRows = Array.isArray(taskWaveRows) ? taskWaveRows : [];
|
||
const fallbackWaveIds = [ ...new Set(normalizedTaskWaveRows
|
||
.map(row => Number(row && row.wave_id || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||
|
||
if (fallbackWaveIds.length > 0) {
|
||
const orderModel = await this.getOrderModel(warehouseId);
|
||
const fallbackOrderRows = await orderModel.findAll({
|
||
where: {
|
||
wave_id: {
|
||
[this.app.Sequelize.Op.in]: fallbackWaveIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
taskOrderIds = [ ...new Set((Array.isArray(fallbackOrderRows) ? fallbackOrderRows : [])
|
||
.map(row => Number(row && row.id || 0))
|
||
.filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ];
|
||
}
|
||
}
|
||
}
|
||
|
||
if (taskOrderIds.length <= 0) {
|
||
throw this.createBusinessError('任务下无可确认订单', 400);
|
||
}
|
||
|
||
let targetOrderIds = [];
|
||
if (mode === 1) {
|
||
targetOrderIds = taskOrderIds;
|
||
} else {
|
||
if (orderIds.length <= 0) {
|
||
throw this.createBusinessError('部分确认模式下 order_ids 不能为空', 400);
|
||
}
|
||
targetOrderIds = orderIds.filter(id => taskOrderIds.includes(id));
|
||
if (targetOrderIds.length <= 0) {
|
||
throw this.createBusinessError('order_ids 未命中当前任务订单', 400);
|
||
}
|
||
}
|
||
|
||
// 检查目标订单是否进入拦截流程,拦截订单直接跳过:
|
||
// 不完成拣货、不扣减库存(不取出)、不报错,其余订单照常完成
|
||
// 同时记录打印状态:已打印面单的拦截订单保持不动,不做自动移出波次
|
||
const skippedInterceptedOrders = [];
|
||
if (targetOrderIds.length > 0) {
|
||
const interceptCheckModel = await this.getOrderModel(warehouseId);
|
||
const interceptedOrderRows = await interceptCheckModel.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: targetOrderIds,
|
||
},
|
||
intercept_status: {
|
||
[this.app.Sequelize.Op.ne]: INTERCEPT_STATUS_NONE,
|
||
},
|
||
},
|
||
attributes: [ 'id', 'intercept_status', 'print_status' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
if (interceptedOrderRows && interceptedOrderRows.length > 0) {
|
||
const interceptedOrderIdSet = new Set(
|
||
interceptedOrderRows.map(orderRow => Number(orderRow && orderRow.id || 0))
|
||
);
|
||
for (const orderRow of interceptedOrderRows) {
|
||
skippedInterceptedOrders.push({
|
||
order_id: Number(orderRow && orderRow.id || 0),
|
||
intercept_status: String(orderRow && orderRow.intercept_status || '').trim() || 'none',
|
||
print_status: String(orderRow && orderRow.print_status || '').trim().toLowerCase() || 'none',
|
||
});
|
||
}
|
||
targetOrderIds = targetOrderIds.filter(orderId => !interceptedOrderIdSet.has(orderId));
|
||
}
|
||
}
|
||
|
||
// 已打印面单的拦截订单保持不动:面单实物已在波次流程中,自动移出会导致
|
||
// 面单与波次记录分离,此类订单需人工通过 wave.batchRemoveOrders 处理
|
||
const printedSkippedOrderIdSet = new Set(skippedInterceptedOrders
|
||
.filter(item => {
|
||
const printStatus = String(item && item.print_status || '').trim().toLowerCase();
|
||
return printStatus && printStatus !== 'none';
|
||
})
|
||
.map(item => Number(item && item.order_id || 0)));
|
||
const keptInterceptedOrderIds = [ ...printedSkippedOrderIdSet ];
|
||
if (keptInterceptedOrderIds.length > 0) {
|
||
ctx.logger.warn(`[pick.wavePickTaskComplete] 已打印拦截订单保持不动,不自动移出波次,需人工处理, taskId=${taskId}, orderIds=${keptInterceptedOrderIds.join(',')}`);
|
||
}
|
||
|
||
// source !== 0(PDA/后台抓取创建的任务)时,被跳过的拦截订单中「未打印」的
|
||
// 直接从波次中移除:订单 wave_id 清零、删除波次索引、回写波次统计,
|
||
// 并移除任务订单关联;已打印的保持不动(见上方 keptInterceptedOrderIds)
|
||
const removedFromWaveOrderLogItems = [];
|
||
const removedFromWaveOrderIds = [];
|
||
const affectedWaveIdsForUnbind = [];
|
||
if (skippedInterceptedOrders.length > 0 && taskSource !== 0) {
|
||
const skippedOrderIds = skippedInterceptedOrders
|
||
.map(item => Number(item && item.order_id || 0))
|
||
.filter(orderId => !printedSkippedOrderIdSet.has(orderId));
|
||
const interceptOrderModel = await this.getOrderModel(warehouseId);
|
||
const removableRows = await interceptOrderModel.findAll({
|
||
attributes: [ 'id', 'wave_id', 'wave_no' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: skippedOrderIds,
|
||
},
|
||
wave_id: {
|
||
[this.app.Sequelize.Op.gt]: 0,
|
||
},
|
||
},
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
const normalizedRemovableRows = Array.isArray(removableRows) ? removableRows : [];
|
||
const affectedWaveIds = [ ...new Set(normalizedRemovableRows
|
||
.map(row => Number(row && row.wave_id || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||
affectedWaveIdsForUnbind.push(...affectedWaveIds);
|
||
|
||
if (normalizedRemovableRows.length > 0) {
|
||
await interceptOrderModel.update({
|
||
wave_id: 0,
|
||
wave_no: '',
|
||
wave_strategy_version: 0,
|
||
wave_scan_result: 0,
|
||
}, {
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: normalizedRemovableRows.map(row => Number(row.id)),
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
for (const row of normalizedRemovableRows) {
|
||
removedFromWaveOrderIds.push(Number(row && row.id || 0));
|
||
removedFromWaveOrderLogItems.push({
|
||
orderId: Number(row && row.id || 0),
|
||
operationCode: 'ORDER_WAVE_REMOVE',
|
||
message: `订单从波次 ${String(row && row.wave_no || '').trim() || '未知波次'} 中移除`,
|
||
});
|
||
}
|
||
|
||
if (affectedWaveIds.length > 0) {
|
||
const waveService = this.ctx.service
|
||
&& this.ctx.service.systemMethods
|
||
&& this.ctx.service.systemMethods.order
|
||
&& this.ctx.service.systemMethods.order.wave;
|
||
|
||
// 仅删除拦截单自身的索引行,不重建整波索引:
|
||
// 其余订单 wave_index 保持不变(仅跳号),避免与已放货的篮子编号
|
||
// (task_order.box_no / task_box.box_no 为创建时 wave_index 快照)错位,
|
||
// 保证复核/打印等按 wave_index 排序的环节仍与实物位置一致。
|
||
if (waveService && typeof waveService.deleteOrderWaveIndexByOrderIds === 'function') {
|
||
await waveService.deleteOrderWaveIndexByOrderIds({
|
||
warehouseId,
|
||
orderIds: normalizedRemovableRows.map(row => Number(row.id)),
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
// 按剩余索引行数回写波次统计(删除后未重建,剩余订单序号保持不变)
|
||
const remainingIndexRows = await this.ctx.model.query(`
|
||
SELECT wave_id, COUNT(*) AS remaining_count
|
||
FROM wms_order_wave_index
|
||
WHERE warehouse_id = :warehouseId
|
||
AND wave_id IN (:waveIds)
|
||
GROUP BY wave_id
|
||
`, {
|
||
replacements: {
|
||
warehouseId,
|
||
waveIds: affectedWaveIds,
|
||
},
|
||
type: this.ctx.model.QueryTypes.SELECT,
|
||
transaction,
|
||
});
|
||
|
||
const remainingCountMap = new Map();
|
||
for (const row of Array.isArray(remainingIndexRows) ? remainingIndexRows : []) {
|
||
const waveId = Number(row && row.wave_id || 0);
|
||
const remainingCount = Number(row && row.remaining_count || 0);
|
||
if (Number.isInteger(waveId) && waveId > 0) {
|
||
remainingCountMap.set(waveId, remainingCount);
|
||
}
|
||
}
|
||
|
||
const updatedWaveIds = [];
|
||
const emptiedWaveIds = [];
|
||
for (const waveId of affectedWaveIds) {
|
||
const remainingCount = Number(remainingCountMap.get(waveId) || 0);
|
||
if (remainingCount > 0) {
|
||
updatedWaveIds.push(waveId);
|
||
} else {
|
||
emptiedWaveIds.push(waveId);
|
||
}
|
||
}
|
||
|
||
for (const waveId of updatedWaveIds) {
|
||
const remainingCount = Number(remainingCountMap.get(waveId) || 0);
|
||
await this.ctx.model.query(`
|
||
UPDATE wms_wave_batch
|
||
SET total_orders = :remainingCount,
|
||
processed_orders = LEAST(processed_orders, :remainingCount),
|
||
update_time = NOW()
|
||
WHERE warehouse_id = :warehouseId
|
||
AND wave_id = :waveId
|
||
`, {
|
||
replacements: {
|
||
warehouseId,
|
||
waveId,
|
||
remainingCount,
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
if (emptiedWaveIds.length > 0) {
|
||
await this.ctx.model.query(`
|
||
UPDATE wms_wave_batch
|
||
SET total_orders = 0,
|
||
processed_orders = 0,
|
||
wave_status = -1,
|
||
update_time = NOW()
|
||
WHERE warehouse_id = :warehouseId
|
||
AND wave_id IN (:waveIds)
|
||
`, {
|
||
replacements: {
|
||
warehouseId,
|
||
waveIds: emptiedWaveIds,
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
}
|
||
|
||
// 移除任务订单关联记录,任务进度不再包含被移出波次的拦截单
|
||
await this.ctx.model.query(`
|
||
DELETE FROM wms_wave_pick_task_order
|
||
WHERE task_id = :taskId
|
||
AND warehouse_id = :warehouseId
|
||
AND order_id IN (:orderIds)
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
orderIds: normalizedRemovableRows.map(row => Number(row.id)),
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
// 同步移除拦截单对应的篮子明细(散单模式 box_type=2 绑定订单),避免遗留空盒
|
||
const taskBoxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box');
|
||
const taskBoxWarehouseFilterSql = taskBoxColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : '';
|
||
await this.ctx.model.query(`
|
||
DELETE FROM wms_wave_pick_task_box
|
||
WHERE task_id = :taskId
|
||
AND order_id IN (:orderIds)
|
||
${taskBoxWarehouseFilterSql}
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
orderIds: normalizedRemovableRows.map(row => Number(row.id)),
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
}
|
||
|
||
// 目标订单全部被拦截跳过:不做任何拣货/库存变更,直接成功返回
|
||
if (targetOrderIds.length <= 0) {
|
||
// mode=1(全部确认)时任务标记完成;mode=2 依据任务进度判断
|
||
const skipProgressBeforeComplete = await this.getTaskPickProgress(taskId, warehouseId, transaction);
|
||
const skipTaskCompleted = mode === 1 || skipProgressBeforeComplete.isCompleted;
|
||
if (skipTaskCompleted) {
|
||
await this.ctx.model.query(`
|
||
UPDATE wms_wave_pick_task
|
||
SET status = 2,
|
||
finish_time = CASE WHEN finish_time IS NULL THEN NOW() ELSE finish_time END,
|
||
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
|
||
update_time = NOW()
|
||
WHERE id = :taskId
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
// 同步更新波次关联状态为已拣
|
||
const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave');
|
||
const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : '';
|
||
await this.ctx.model.query(`
|
||
UPDATE wms_wave_pick_task_wave
|
||
SET status = 1,
|
||
pick_time = NOW(),
|
||
update_time = NOW()
|
||
WHERE task_id = :taskId
|
||
${taskWaveWarehouseFilterSql}
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
} else {
|
||
await this.ctx.model.query(`
|
||
UPDATE wms_wave_pick_task
|
||
SET status = CASE WHEN status = 0 THEN 1 ELSE status END,
|
||
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
|
||
update_time = NOW()
|
||
WHERE id = :taskId
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
await transaction.commit();
|
||
const skipProgress = await this.getTaskPickProgress(taskId, warehouseId);
|
||
await this._writePickCompleteActionLog({
|
||
taskId,
|
||
warehouseId,
|
||
operatorId,
|
||
operatorName,
|
||
targetOrderIds: [],
|
||
mode,
|
||
isCompleted: skipProgress.isCompleted,
|
||
progress: skipProgress,
|
||
skippedInterceptedOrders,
|
||
});
|
||
await this._afterSkipInterceptedPostActions({
|
||
warehouseId,
|
||
operatorId,
|
||
operatorName,
|
||
removedFromWaveOrderLogItems,
|
||
removedFromWaveOrderIds,
|
||
affectedWaveIds: affectedWaveIdsForUnbind,
|
||
});
|
||
return {
|
||
task_id: taskId,
|
||
mode,
|
||
confirmed_order_ids: [],
|
||
skipped_intercepted_order_ids: skippedInterceptedOrders.map(item => item.order_id),
|
||
skipped_intercepted_orders: skippedInterceptedOrders,
|
||
removed_from_wave_order_ids: removedFromWaveOrderIds,
|
||
kept_intercepted_order_ids: keptInterceptedOrderIds,
|
||
is_completed: skipProgress.isCompleted,
|
||
task_completed: skipTaskCompleted,
|
||
progress: {
|
||
total_orders: skipProgress.totalOrders,
|
||
picked_orders: skipProgress.pickedOrders,
|
||
pending_orders: skipProgress.pendingOrders,
|
||
},
|
||
};
|
||
}
|
||
|
||
// 检查目标订单是否已分配储位(storage_status='fin'),防止订单在波次中被取消储位分配后仍然完成拣货
|
||
if (targetOrderIds.length > 0) {
|
||
const orderModel = await this.getOrderModel(warehouseId);
|
||
const unallocatedOrders = await orderModel.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: targetOrderIds,
|
||
},
|
||
storage_status: {
|
||
[this.app.Sequelize.Op.ne]: 'fin',
|
||
},
|
||
},
|
||
attributes: [ 'id', 'storage_status' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
if (unallocatedOrders && unallocatedOrders.length > 0) {
|
||
const detailList = unallocatedOrders.map(
|
||
o => `订单${o.id}(storage_status=${o.storage_status})`
|
||
).join(';');
|
||
throw this.createBusinessError(
|
||
`以下订单未分配储位,无法完成拣货:${detailList}`,
|
||
400
|
||
);
|
||
}
|
||
}
|
||
|
||
await ctx.model.query(`
|
||
UPDATE wms_wave_pick_task_order
|
||
SET pick_status = 1,
|
||
picked_time = NOW(),
|
||
update_time = NOW()
|
||
WHERE task_id = :taskId
|
||
AND warehouse_id = :warehouseId
|
||
AND order_id IN (:orderIds)
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
orderIds: targetOrderIds,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
const orderModel = await this.getOrderModel(warehouseId);
|
||
await orderModel.update({
|
||
pick_status: 'fin',
|
||
}, {
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[this.app.Sequelize.Op.in]: targetOrderIds,
|
||
},
|
||
},
|
||
transaction,
|
||
validate: false,
|
||
hooks: false,
|
||
});
|
||
|
||
// 先查询并锁定 pending 的 picking 记录,汇总各 storage_id 的扣减量
|
||
const pickingSummaryRows = await ctx.model.query(`
|
||
SELECT
|
||
p.storage_id,
|
||
SUM(p.quantity) AS total_qty
|
||
FROM wms_picking p
|
||
WHERE p.order_id IN (:orderIds)
|
||
AND p.warehouse_id = :warehouseId
|
||
AND p.status = 'pending'
|
||
AND p.deleted_at IS NULL -- 排除软删除记录,防止已删除的 picking 纳入锁定量汇总
|
||
AND p.storage_id IS NOT NULL
|
||
AND p.storage_id > 0
|
||
GROUP BY p.storage_id
|
||
FOR UPDATE
|
||
`, {
|
||
replacements: {
|
||
orderIds: targetOrderIds,
|
||
warehouseId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
transaction,
|
||
});
|
||
|
||
const normalizedSummaryRows = Array.isArray(pickingSummaryRows) ? pickingSummaryRows : [];
|
||
if (normalizedSummaryRows.length > 0) {
|
||
const storageIds = normalizedSummaryRows.map(r => Number(r.storage_id));
|
||
const storageQtyMap = new Map();
|
||
for (const row of normalizedSummaryRows) {
|
||
storageQtyMap.set(Number(row.storage_id), Number(row.total_qty) || 0);
|
||
}
|
||
|
||
// 加行锁校验 locked_quantity >= 扣减数量
|
||
const storageRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
id: { [this.app.Sequelize.Op.in]: storageIds },
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'locked_quantity', 'quantity', 'store_id', 'stock_id', 'batch_no', 'inventory_type', 'space_id' ],
|
||
lock: transaction.LOCK.UPDATE,
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
for (const sRow of storageRows) {
|
||
const sid = Number(sRow.id);
|
||
const deduction = storageQtyMap.get(sid) || 0;
|
||
const locked = Number(sRow.locked_quantity) || 0;
|
||
if (locked < deduction) {
|
||
throw this.createBusinessError(
|
||
`库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需扣减 ${deduction}`,
|
||
400
|
||
);
|
||
}
|
||
}
|
||
|
||
// 构建 CASE WHEN 语句
|
||
const caseClauses = normalizedSummaryRows
|
||
.map(r => `WHEN ${Number(r.storage_id)} THEN ${Number(r.total_qty)}`)
|
||
.join(' ');
|
||
|
||
await ctx.model.query(`
|
||
UPDATE wms_storage
|
||
SET locked_quantity = locked_quantity - CASE id ${caseClauses} END,
|
||
quantity = quantity - CASE id ${caseClauses} END,
|
||
updated_at = NOW()
|
||
WHERE id IN (:storageIds)
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
storageIds,
|
||
warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
// 写入 wms_storage_transaction 出库流水
|
||
const transactionRows = [];
|
||
for (const sRow of storageRows) {
|
||
const sid = Number(sRow.id);
|
||
const deduction = storageQtyMap.get(sid) || 0;
|
||
if (deduction <= 0) continue;
|
||
const beforeQty = Number(sRow.quantity) || 0;
|
||
const beforeLocked = Number(sRow.locked_quantity) || 0;
|
||
transactionRows.push({
|
||
transaction_type: 'OUTBOUND',
|
||
warehouse_id: warehouseId,
|
||
store_id: Number(sRow.store_id) || 0,
|
||
stock_id: Number(sRow.stock_id) || 0,
|
||
storage_id: sid,
|
||
space_id: Number(sRow.space_id) || null,
|
||
quantity: deduction,
|
||
before_quantity: beforeQty,
|
||
after_quantity: Math.max(0, beforeQty - deduction),
|
||
before_locked_quantity: beforeLocked,
|
||
after_locked_quantity: Math.max(0, beforeLocked - deduction),
|
||
batch_no: sRow.batch_no || null,
|
||
inventory_type: sRow.inventory_type || 'ZP',
|
||
order_type: 'PICK_OUTBOUND',
|
||
order_no: targetOrderIds.join(',').slice(0, 255),
|
||
order_id: taskId,
|
||
source_order_codes: targetOrderIds.join(', '),
|
||
operator_id: String(operatorId),
|
||
operator_name: operatorName,
|
||
remark: '拣货完成出库',
|
||
created_at: new Date(),
|
||
});
|
||
}
|
||
|
||
if (transactionRows.length > 0) {
|
||
await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction });
|
||
}
|
||
|
||
}
|
||
|
||
// 扣减完成后,更新 wms_picking.status 为完成状态(加 status 条件防重复)
|
||
await ctx.model.query(`
|
||
UPDATE wms_picking
|
||
SET status = 'fin', updated_at = NOW()
|
||
WHERE order_id IN (:orderIds)
|
||
AND warehouse_id = :warehouseId
|
||
AND status = 'pending'
|
||
AND deleted_at IS NULL -- 排除软删除记录,防止重复标记已完成删除的 picking
|
||
`, {
|
||
replacements: {
|
||
orderIds: targetOrderIds,
|
||
warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction);
|
||
// mode=1(全部确认)时任务直接标记完成;mode=2 依据任务进度判断
|
||
const taskCompleted = mode === 1 || progress.isCompleted;
|
||
if (taskCompleted) {
|
||
await ctx.model.query(`
|
||
UPDATE wms_wave_pick_task
|
||
SET status = 2,
|
||
finish_time = CASE WHEN finish_time IS NULL THEN NOW() ELSE finish_time END,
|
||
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
|
||
update_time = NOW()
|
||
WHERE id = :taskId
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
// 同步更新波次关联状态为已拣
|
||
const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave');
|
||
const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : '';
|
||
await ctx.model.query(`
|
||
UPDATE wms_wave_pick_task_wave
|
||
SET status = 1,
|
||
pick_time = NOW(),
|
||
update_time = NOW()
|
||
WHERE task_id = :taskId
|
||
${taskWaveWarehouseFilterSql}
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
} else {
|
||
await ctx.model.query(`
|
||
UPDATE wms_wave_pick_task
|
||
SET status = CASE WHEN status = 0 THEN 1 ELSE status END,
|
||
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
|
||
update_time = NOW()
|
||
WHERE id = :taskId
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
await transaction.commit();
|
||
|
||
// 写入操作日志
|
||
await this._writePickCompleteActionLog({
|
||
taskId,
|
||
warehouseId,
|
||
operatorId,
|
||
operatorName,
|
||
targetOrderIds,
|
||
mode,
|
||
isCompleted: progress.isCompleted,
|
||
progress,
|
||
skippedInterceptedOrders,
|
||
});
|
||
|
||
// 被移出波次的拦截订单:写订单操作日志 + 触发策略快扫(不影响主流程)
|
||
await this._afterSkipInterceptedPostActions({
|
||
warehouseId,
|
||
operatorId,
|
||
operatorName,
|
||
removedFromWaveOrderLogItems,
|
||
removedFromWaveOrderIds,
|
||
affectedWaveIds: affectedWaveIdsForUnbind,
|
||
});
|
||
|
||
// 写入 order_operation_log 拣货完成日志
|
||
try {
|
||
const operationLogService = this.ctx
|
||
&& this.ctx.service
|
||
&& this.ctx.service.systems
|
||
&& this.ctx.service.systems.operationLog;
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
const logPayloads = targetOrderIds.map(orderId => ({
|
||
businessType: 'order',
|
||
businessId: `${orderId}`,
|
||
operationCode: 'ORDER_PICK_COMPLETE',
|
||
operator: {
|
||
id: operatorId ? String(operatorId) : null,
|
||
name: operatorName || 'system',
|
||
},
|
||
extras: {
|
||
message: `订单${orderId}拣货完成`,
|
||
warehouseId,
|
||
externalLogType: 'API',
|
||
},
|
||
}));
|
||
await operationLogService.createOperationLogs(logPayloads);
|
||
}
|
||
} catch (e) {
|
||
this.ctx.logger.warn('[pick.wavePickTaskComplete] 写入 order_operation_log 失败,不影响主流程', {
|
||
error: e && e.message,
|
||
targetOrderIds,
|
||
});
|
||
}
|
||
|
||
// 通知仓库面板刷新(大屏增量更新,失败不影响主流程)
|
||
await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId));
|
||
|
||
return {
|
||
task_id: taskId,
|
||
mode,
|
||
confirmed_order_ids: targetOrderIds,
|
||
skipped_intercepted_order_ids: skippedInterceptedOrders.map(item => item.order_id),
|
||
skipped_intercepted_orders: skippedInterceptedOrders,
|
||
removed_from_wave_order_ids: removedFromWaveOrderIds,
|
||
kept_intercepted_order_ids: keptInterceptedOrderIds,
|
||
is_completed: progress.isCompleted,
|
||
task_completed: taskCompleted,
|
||
progress: {
|
||
total_orders: progress.totalOrders,
|
||
picked_orders: progress.pickedOrders,
|
||
pending_orders: progress.pendingOrders,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 拦截单跳过后的收尾动作(均不影响主流程):
|
||
* 1. 写入被移出波次拦截订单的 ORDER_WAVE_REMOVE 操作日志;
|
||
* 2. 触发波次策略快速扫描,让移出波次的订单重新进入可抓取池。
|
||
*
|
||
* @param {Object} params 参数。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {number} params.operatorId 操作人ID。
|
||
* @param {string} params.operatorName 操作人名称。
|
||
* @param {Array<Object>} params.removedFromWaveOrderLogItems 波次移除日志项。
|
||
* @param {Array<number>} params.removedFromWaveOrderIds 被移出波次的订单ID。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async _afterSkipInterceptedPostActions(params = {}) {
|
||
const warehouseId = Number(params && params.warehouseId || 0);
|
||
const operatorId = Number(params && params.operatorId || 0);
|
||
const operatorName = String(params && params.operatorName || '').trim() || 'system';
|
||
const removedFromWaveOrderLogItems = Array.isArray(params && params.removedFromWaveOrderLogItems)
|
||
? params.removedFromWaveOrderLogItems
|
||
: [];
|
||
const removedFromWaveOrderIds = Array.isArray(params && params.removedFromWaveOrderIds)
|
||
? params.removedFromWaveOrderIds
|
||
: [];
|
||
const affectedWaveIds = Array.isArray(params && params.affectedWaveIds)
|
||
? params.affectedWaveIds
|
||
: [];
|
||
|
||
if (removedFromWaveOrderLogItems.length > 0) {
|
||
try {
|
||
const operationLogService = this.ctx
|
||
&& this.ctx.service
|
||
&& this.ctx.service.systems
|
||
&& this.ctx.service.systems.operationLog;
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
const logPayloads = removedFromWaveOrderLogItems.map(item => ({
|
||
businessType: 'order',
|
||
businessId: `${item.orderId}`,
|
||
operationCode: item.operationCode,
|
||
operator: {
|
||
id: operatorId ? String(operatorId) : null,
|
||
name: operatorName,
|
||
},
|
||
extras: {
|
||
message: item.message,
|
||
warehouseId,
|
||
externalLogType: 'API',
|
||
},
|
||
}));
|
||
await operationLogService.createOperationLogs(logPayloads);
|
||
}
|
||
} catch (e) {
|
||
this.ctx.logger.warn('[pick.wavePickTaskComplete] 写入波次移除操作日志失败,不影响主流程', {
|
||
error: e && e.message,
|
||
});
|
||
}
|
||
}
|
||
|
||
if (removedFromWaveOrderIds.length > 0) {
|
||
try {
|
||
const waveService = this.ctx.service
|
||
&& this.ctx.service.systemMethods
|
||
&& this.ctx.service.systemMethods.order
|
||
&& this.ctx.service.systemMethods.order.wave;
|
||
if (waveService && typeof waveService.enqueueWaveStrategyQuickScanPostOrderChange === 'function') {
|
||
waveService.enqueueWaveStrategyQuickScanPostOrderChange(
|
||
warehouseId,
|
||
removedFromWaveOrderIds,
|
||
{ triggerScan: true, source: 'pickSkipInterceptedRemoveWave' }
|
||
);
|
||
}
|
||
} catch (e) {
|
||
this.ctx.logger.warn('[pick.wavePickTaskComplete] 触发波次策略快扫失败,不影响主流程', {
|
||
error: e && e.message,
|
||
});
|
||
}
|
||
}
|
||
|
||
// 拦截订单被移出波次后,补触发打印完成解绑车核实:
|
||
// 打印链路对含拦截订单的波次无法解绑(拦截订单不可打印),提交拣货移除拦截订单后重查一次,
|
||
// 保证任务结束时车能被释放(不影响主流程)
|
||
if (affectedWaveIds.length > 0) {
|
||
try {
|
||
const printService = this.ctx
|
||
&& this.ctx.service
|
||
&& this.ctx.service.systemMethods
|
||
&& this.ctx.service.systemMethods.print;
|
||
if (printService && typeof printService.tryUnbindCartAfterPrintComplete === 'function') {
|
||
for (const waveId of [ ...new Set(affectedWaveIds) ]) {
|
||
await printService.tryUnbindCartAfterPrintComplete(waveId, warehouseId);
|
||
}
|
||
}
|
||
} catch (e) {
|
||
this.ctx.logger.warn('[pick.wavePickTaskComplete] 移除拦截订单后补触发解绑车失败,不影响主流程', {
|
||
error: e && e.message,
|
||
affectedWaveIds,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 写入拣货完成操作日志到 wms_wave_pick_action_log(内部方法)。
|
||
*
|
||
* @param {Object} params 日志参数。
|
||
* @param {number} params.taskId 波次拣货任务ID。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {number} params.operatorId 操作人ID。
|
||
* @param {string} params.operatorName 操作人名称。
|
||
* @param {Array<number>} params.targetOrderIds 确认完成的订单ID列表。
|
||
* @param {number} params.mode 提交模式(1全部确认 2部分确认)。
|
||
* @param {boolean} params.isCompleted 任务是否全部完成。
|
||
* @param {Object} params.progress 任务进度信息。
|
||
* @param {Array<Object>} params.skippedInterceptedOrders 被跳过的拦截订单(order_id + intercept_status)。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async _writePickCompleteActionLog(params = {}) {
|
||
const {
|
||
taskId,
|
||
warehouseId,
|
||
operatorId,
|
||
operatorName,
|
||
targetOrderIds,
|
||
mode,
|
||
isCompleted,
|
||
progress,
|
||
skippedInterceptedOrders,
|
||
} = params;
|
||
|
||
const requestId = `pick_complete_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||
|
||
await this.ctx.model.query(
|
||
`INSERT INTO wms_wave_pick_action_log (
|
||
task_id,
|
||
warehouse_id,
|
||
wave_id,
|
||
order_id,
|
||
sku_id,
|
||
location_id,
|
||
box_no,
|
||
cart_id,
|
||
qty_delta,
|
||
action_type,
|
||
request_id,
|
||
operator_id,
|
||
device_id,
|
||
seq_no,
|
||
snapshot
|
||
) VALUES (
|
||
:taskId,
|
||
:warehouseId,
|
||
:waveId,
|
||
:orderId,
|
||
:skuId,
|
||
:locationId,
|
||
:boxNo,
|
||
:cartId,
|
||
:qtyDelta,
|
||
:actionType,
|
||
:requestId,
|
||
:operatorId,
|
||
:deviceId,
|
||
:seqNo,
|
||
:snapshot
|
||
)`,
|
||
{
|
||
replacements: {
|
||
taskId: taskId || 0,
|
||
warehouseId: warehouseId || 0,
|
||
waveId: null,
|
||
orderId: Array.isArray(targetOrderIds) && targetOrderIds.length > 0 ? targetOrderIds[0] : null,
|
||
skuId: null,
|
||
locationId: null,
|
||
boxNo: null,
|
||
cartId: null,
|
||
qtyDelta: 0,
|
||
actionType: 'pick_complete',
|
||
requestId,
|
||
operatorId: operatorId || 0,
|
||
deviceId: null,
|
||
seqNo: 1,
|
||
snapshot: JSON.stringify({
|
||
task_id: taskId,
|
||
mode,
|
||
confirmed_order_ids: targetOrderIds,
|
||
confirmed_order_count: Array.isArray(targetOrderIds) ? targetOrderIds.length : 0,
|
||
skipped_intercepted_orders: Array.isArray(skippedInterceptedOrders) ? skippedInterceptedOrders : [],
|
||
is_completed: isCompleted,
|
||
progress: {
|
||
total_orders: progress && progress.totalOrders,
|
||
picked_orders: progress && progress.pickedOrders,
|
||
pending_orders: progress && progress.pendingOrders,
|
||
},
|
||
operator_name: operatorName || 'system',
|
||
}),
|
||
},
|
||
type: this.ctx.model.QueryTypes.INSERT,
|
||
}
|
||
);
|
||
}
|
||
|
||
/**
|
||
* PDA 扫码查询拣货车信息。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {string} params.cartCode 拣货车编码。
|
||
* @return {Promise<Object>} 拣货车详情。
|
||
*/
|
||
async pickCartScan(params = {}) {
|
||
const cartCode = String(params && params.cartCode || '').trim();
|
||
const { warehouseId } = this.resolveOperatorContext();
|
||
|
||
if (!cartCode) {
|
||
throw this.createBusinessError('cart_code 必填', 400);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const cartRow = await this.getPickCartByCode(cartCode, warehouseId);
|
||
if (!cartRow) {
|
||
throw this.createBusinessError('拣货车不存在', 404);
|
||
}
|
||
|
||
return this.buildPickCartDetail(cartRow);
|
||
}
|
||
|
||
/**
|
||
* 绑定拣货任务与拣货车。
|
||
*
|
||
* @param {Object} params 绑定参数。
|
||
* @param {number} params.taskId 拣货任务ID。
|
||
* @param {number} [params.cartId] 拣货车ID。
|
||
* @param {string} [params.cartCode] 拣货车编码。
|
||
* @return {Promise<Object>} 绑定结果。
|
||
*/
|
||
async wavePickTaskBindCart(params = {}) {
|
||
const { ctx } = this;
|
||
const taskId = Number(params && params.taskId || 0);
|
||
const cartId = Number(params && params.cartId || 0);
|
||
const cartCode = String(params && params.cartCode || '').trim();
|
||
const { operatorId, warehouseId } = this.resolveOperatorContext();
|
||
|
||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||
throw this.createBusinessError('task_id 必填且必须为正整数', 400);
|
||
}
|
||
if ((!Number.isInteger(cartId) || cartId <= 0) && !cartCode) {
|
||
throw this.createBusinessError('cart_id 或 cart_code 至少传一个', 400);
|
||
}
|
||
if (!Number.isInteger(operatorId) || operatorId <= 0) {
|
||
throw this.createBusinessError('未获取到操作人上下文', 401);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const taskRow = await this.getOwnedTask(taskId, operatorId);
|
||
const taskStatus = Number(taskRow && taskRow.status || 0);
|
||
if ([ 3, 9 ].includes(taskStatus)) {
|
||
throw this.createBusinessError('任务已完成或已取消,无法绑定拣货车', 400);
|
||
}
|
||
if (Number(taskRow && taskRow.warehouse_id || 0) !== warehouseId) {
|
||
throw this.createBusinessError('任务不属于当前仓库,无法绑定拣货车', 403);
|
||
}
|
||
|
||
const targetCartRow = cartId > 0
|
||
? await this.getPickCartById(cartId, warehouseId)
|
||
: await this.getPickCartByCode(cartCode, warehouseId);
|
||
if (!targetCartRow) {
|
||
throw this.createBusinessError('拣货车不存在', 404);
|
||
}
|
||
if (Number(targetCartRow.status || 0) !== 1) {
|
||
throw this.createBusinessError('拣货车已停用,无法绑定', 400);
|
||
}
|
||
|
||
const targetCartId = Number(targetCartRow.cart_id || 0);
|
||
const targetCartCode = String(targetCartRow.cart_code || '').trim();
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
// 检查任务是否已有活跃的车绑定(正常绑定流程,不支持换车,需先解绑)
|
||
const taskActiveBindingRows = await ctx.model.query(`
|
||
SELECT
|
||
b.id,
|
||
b.cart_id,
|
||
t.current_cart_code_snapshot AS cart_code
|
||
FROM wms_pick_task_cart_binding b
|
||
INNER JOIN wms_wave_pick_task t
|
||
ON t.id = b.task_id
|
||
WHERE b.task_id = :taskId
|
||
AND b.warehouse_id = :warehouseId
|
||
AND b.is_active = 1
|
||
ORDER BY b.id DESC
|
||
LIMIT 1
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
transaction,
|
||
});
|
||
|
||
const taskActiveBinding = Array.isArray(taskActiveBindingRows) && taskActiveBindingRows.length > 0
|
||
? taskActiveBindingRows[0]
|
||
: null;
|
||
if (taskActiveBinding) {
|
||
throw this.createBusinessError('任务已绑定拣货车,请先解绑后再重新绑定', 409, {
|
||
task_id: taskId,
|
||
cart_id: Number(taskActiveBinding.cart_id || 0),
|
||
cart_code: String(taskActiveBinding.cart_code || '').trim() || null,
|
||
});
|
||
}
|
||
|
||
// 检查车是否已有活跃的任务绑定
|
||
const cartActiveBindingRows = await ctx.model.query(`
|
||
SELECT
|
||
b.id,
|
||
b.task_id,
|
||
t.task_no
|
||
FROM wms_pick_task_cart_binding b
|
||
INNER JOIN wms_wave_pick_task t
|
||
ON t.id = b.task_id
|
||
WHERE b.cart_id = :cartId
|
||
AND b.warehouse_id = :warehouseId
|
||
AND b.is_active = 1
|
||
ORDER BY b.id DESC
|
||
LIMIT 1
|
||
`, {
|
||
replacements: {
|
||
cartId: targetCartId,
|
||
warehouseId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
transaction,
|
||
});
|
||
|
||
const cartActiveBinding = Array.isArray(cartActiveBindingRows) && cartActiveBindingRows.length > 0
|
||
? cartActiveBindingRows[0]
|
||
: null;
|
||
if (cartActiveBinding) {
|
||
const boundTaskId = Number(cartActiveBinding.task_id || 0);
|
||
if (boundTaskId === taskId) {
|
||
throw this.createBusinessError('该任务已绑定此拣货车,无需重复绑定', 409, {
|
||
task_id: taskId,
|
||
cart_id: targetCartId,
|
||
cart_code: targetCartCode,
|
||
});
|
||
}
|
||
// 车已有其他活跃绑定,无论旧任务状态如何均应阻止
|
||
throw this.createBusinessError('该拣货车已绑定其他任务,请先解绑后再重新绑定', 409, {
|
||
task_id: boundTaskId,
|
||
task_no: String(cartActiveBinding.task_no || '').trim() || null,
|
||
cart_id: targetCartId,
|
||
cart_code: targetCartCode,
|
||
});
|
||
}
|
||
|
||
await ctx.model.query(`
|
||
INSERT INTO wms_pick_task_cart_binding (
|
||
task_id,
|
||
cart_id,
|
||
cart_code_snapshot,
|
||
warehouse_id,
|
||
bind_user_id,
|
||
bind_type,
|
||
is_active,
|
||
bind_time,
|
||
create_time,
|
||
update_time
|
||
) VALUES (
|
||
:taskId,
|
||
:cartId,
|
||
:cartCode,
|
||
:warehouseId,
|
||
:operatorId,
|
||
1,
|
||
1,
|
||
NOW(),
|
||
NOW(),
|
||
NOW()
|
||
)
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
cartId: targetCartId,
|
||
cartCode: targetCartCode,
|
||
warehouseId,
|
||
operatorId,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
await ctx.model.query(`
|
||
UPDATE wms_wave_pick_task
|
||
SET current_cart_id = :cartId,
|
||
current_cart_code_snapshot = :cartCode,
|
||
update_time = NOW()
|
||
WHERE id = :taskId
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
taskId,
|
||
warehouseId,
|
||
cartId: targetCartId,
|
||
cartCode: targetCartCode,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
await transaction.commit();
|
||
|
||
const latestCartRow = await this.getPickCartById(targetCartId, warehouseId);
|
||
return {
|
||
task_id: taskId,
|
||
task_no: String(taskRow.task_no || '').trim(),
|
||
cart: this.buildPickCartDetail(latestCartRow || targetCartRow),
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 创建拣货车。
|
||
*
|
||
* @param {Object} params 创建参数。
|
||
* @param {string} params.cartCode 拣货车编码。
|
||
* @param {string} [params.cartName] 拣货车名称。
|
||
* @param {number} [params.status=1] 状态。
|
||
* @return {Promise<Object>} 创建结果。
|
||
*/
|
||
async pickCartCreate(params = {}) {
|
||
const { ctx } = this;
|
||
const cartCode = String(params && params.cartCode || '').trim();
|
||
const cartName = String(params && params.cartName || '').trim();
|
||
const status = this.normalizePickCartStatus(params && params.status, 1);
|
||
const { warehouseId } = this.resolveOperatorContext();
|
||
|
||
if (!cartCode) {
|
||
throw this.createBusinessError('cart_code 必填', 400);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
// 使用事务:唯一性检查 + INSERT + LAST_INSERT_ID() 在同一连接,避免竞态
|
||
const transaction = await ctx.model.transaction();
|
||
let cartId = 0;
|
||
try {
|
||
await this.assertPickCartCodeUnique(cartCode, warehouseId, 0, transaction);
|
||
|
||
await ctx.model.query(`
|
||
INSERT INTO wms_pick_cart (
|
||
warehouse_id,
|
||
cart_code,
|
||
cart_name,
|
||
status,
|
||
create_time,
|
||
update_time
|
||
) VALUES (
|
||
:warehouseId,
|
||
:cartCode,
|
||
:cartName,
|
||
:status,
|
||
NOW(),
|
||
NOW()
|
||
)
|
||
`, {
|
||
replacements: {
|
||
warehouseId,
|
||
cartCode,
|
||
cartName,
|
||
status,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
const idRows = await ctx.model.query('SELECT LAST_INSERT_ID() AS cart_id', {
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
transaction,
|
||
});
|
||
cartId = Number(Array.isArray(idRows) && idRows.length > 0 ? (idRows[0].cart_id || 0) : 0);
|
||
if (!Number.isInteger(cartId) || cartId <= 0) {
|
||
throw new Error('cartId 无效');
|
||
}
|
||
|
||
await transaction.commit();
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
if (error.message === 'cartId 无效') {
|
||
throw this.createBusinessError('拣货车创建失败', 500);
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
const cartRow = await this.getPickCartById(cartId, warehouseId);
|
||
return this.buildPickCartDetail(cartRow || {
|
||
cart_id: cartId,
|
||
warehouse_id: warehouseId,
|
||
cart_code: cartCode,
|
||
cart_name: cartName,
|
||
status,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 更新拣货车。
|
||
*
|
||
* @param {Object} params 更新参数。
|
||
* @param {number} params.cartId 拣货车ID。
|
||
* @param {string} [params.cartCode] 拣货车编码。
|
||
* @param {string} [params.cartName] 拣货车名称。
|
||
* @param {number} [params.status] 状态。
|
||
* @return {Promise<Object>} 更新结果。
|
||
*/
|
||
async pickCartUpdate(params = {}) {
|
||
const { ctx } = this;
|
||
const cartId = Number(params && params.cartId || 0);
|
||
const { warehouseId } = this.resolveOperatorContext();
|
||
|
||
if (!Number.isInteger(cartId) || cartId <= 0) {
|
||
throw this.createBusinessError('cart_id 必填且必须为正整数', 400);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const cartRow = await this.getPickCartById(cartId, warehouseId);
|
||
if (!cartRow) {
|
||
throw this.createBusinessError('拣货车不存在', 404);
|
||
}
|
||
|
||
const nextCartCode = params && params.cartCode !== undefined
|
||
? String(params.cartCode || '').trim()
|
||
: String(cartRow.cart_code || '').trim();
|
||
const nextCartName = params && params.cartName !== undefined
|
||
? String(params.cartName || '').trim()
|
||
: String(cartRow.cart_name || '').trim();
|
||
const nextStatus = params && params.status !== undefined
|
||
? this.normalizePickCartStatus(params.status, Number(cartRow.status || 1))
|
||
: Number(cartRow.status || 1);
|
||
|
||
if (!nextCartCode) {
|
||
throw this.createBusinessError('cart_code 必填', 400);
|
||
}
|
||
await this.assertPickCartCodeUnique(nextCartCode, warehouseId, cartId);
|
||
if (nextStatus === 0) {
|
||
// 通过绑定表检查车是否被活动任务占用
|
||
const activeBindingRows = await ctx.model.query(`
|
||
SELECT b.id
|
||
FROM wms_pick_task_cart_binding b
|
||
INNER JOIN wms_wave_pick_task t ON t.id = b.task_id
|
||
WHERE b.cart_id = :cartId
|
||
AND b.warehouse_id = :warehouseId
|
||
AND b.is_active = 1
|
||
AND t.status IN (0, 1)
|
||
LIMIT 1
|
||
`, {
|
||
replacements: { cartId, warehouseId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
if (Array.isArray(activeBindingRows) && activeBindingRows.length > 0) {
|
||
throw this.createBusinessError('拣货车已绑定活动任务,无法停用', 400);
|
||
}
|
||
}
|
||
|
||
await ctx.model.query(`
|
||
UPDATE wms_pick_cart
|
||
SET cart_code = :cartCode,
|
||
cart_name = :cartName,
|
||
status = :status,
|
||
update_time = NOW()
|
||
WHERE id = :cartId
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
cartId,
|
||
warehouseId,
|
||
cartCode: nextCartCode,
|
||
cartName: nextCartName,
|
||
status: nextStatus,
|
||
},
|
||
});
|
||
|
||
if (nextCartCode !== String(cartRow.cart_code || '').trim()) {
|
||
await ctx.model.query(`
|
||
UPDATE wms_pick_task_cart_binding
|
||
SET cart_code_snapshot = :cartCode,
|
||
update_time = NOW()
|
||
WHERE cart_id = :cartId
|
||
AND warehouse_id = :warehouseId
|
||
AND is_active = 1
|
||
`, {
|
||
replacements: {
|
||
cartId,
|
||
warehouseId,
|
||
cartCode: nextCartCode,
|
||
},
|
||
});
|
||
|
||
await ctx.model.query(`
|
||
UPDATE wms_wave_pick_task
|
||
SET current_cart_code_snapshot = :cartCode,
|
||
update_time = NOW()
|
||
WHERE current_cart_id = :cartId
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: {
|
||
cartId,
|
||
warehouseId,
|
||
cartCode: nextCartCode,
|
||
},
|
||
});
|
||
}
|
||
|
||
const latestCartRow = await this.getPickCartById(cartId, warehouseId);
|
||
return this.buildPickCartDetail(latestCartRow || {
|
||
...cartRow,
|
||
cart_id: cartId,
|
||
cart_code: nextCartCode,
|
||
cart_name: nextCartName,
|
||
status: nextStatus,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 删除拣货车。
|
||
*
|
||
* @param {Object} params 删除参数。
|
||
* @param {number} params.cartId 拣货车ID。
|
||
* @return {Promise<Object>} 删除结果。
|
||
*/
|
||
async pickCartDelete(params = {}) {
|
||
const { ctx } = this;
|
||
const cartId = Number(params && params.cartId || 0);
|
||
const { warehouseId } = this.resolveOperatorContext();
|
||
|
||
if (!Number.isInteger(cartId) || cartId <= 0) {
|
||
throw this.createBusinessError('cart_id 必填且必须为正整数', 400);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const cartRow = await this.getPickCartById(cartId, warehouseId);
|
||
if (!cartRow) {
|
||
throw this.createBusinessError('拣货车不存在', 404);
|
||
}
|
||
if (Number(cartRow.current_task_id || 0) > 0) {
|
||
throw this.createBusinessError('拣货车当前已绑定任务,无法删除', 400);
|
||
}
|
||
|
||
const bindingRows = await ctx.model.query(`
|
||
SELECT id
|
||
FROM wms_pick_task_cart_binding
|
||
WHERE cart_id = :cartId
|
||
AND warehouse_id = :warehouseId
|
||
AND is_active = 1
|
||
LIMIT 1
|
||
`, {
|
||
replacements: {
|
||
cartId,
|
||
warehouseId,
|
||
},
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
if (Array.isArray(bindingRows) && bindingRows.length > 0) {
|
||
throw this.createBusinessError('拣货车存在有效绑定记录,无法删除', 400);
|
||
}
|
||
|
||
await ctx.model.query(`
|
||
DELETE FROM wms_pick_cart
|
||
WHERE id = :cartId
|
||
AND warehouse_id = :warehouseId
|
||
LIMIT 1
|
||
`, {
|
||
replacements: {
|
||
cartId,
|
||
warehouseId,
|
||
},
|
||
});
|
||
|
||
return {
|
||
cart_id: cartId,
|
||
deleted: true,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 批量删除拣货车。已绑定任务或存在有效绑定记录的将被跳过。
|
||
*
|
||
* @param {Object} params 删除参数。
|
||
* @param {Array<number|string>} params.ids 拣货车ID列表。
|
||
* @return {Promise<Object>} { deleted_ids, skipped_ids, deleted_count, skipped_count }
|
||
*/
|
||
async pickCartBatchDelete(params = {}) {
|
||
const { ctx } = this;
|
||
const rawIds = Array.isArray(params && params.ids) ? params.ids : [];
|
||
const { warehouseId } = this.resolveOperatorContext();
|
||
|
||
if (!Array.isArray(rawIds) || rawIds.length === 0) {
|
||
throw this.createBusinessError('ids 必填且必须为非空数组', 400);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
// 去重并转为数字,过滤非法值
|
||
const idSet = new Set();
|
||
for (const id of rawIds) {
|
||
const num = Number(id);
|
||
if (Number.isInteger(num) && num > 0) {
|
||
idSet.add(num);
|
||
}
|
||
}
|
||
const ids = Array.from(idSet);
|
||
if (ids.length === 0) {
|
||
throw this.createBusinessError('ids 中没有合法的拣货车ID', 400);
|
||
}
|
||
|
||
// 1) 查出当前仓库下这些拣货车的 current_task_id
|
||
const cartRows = await ctx.model.query(`
|
||
SELECT id, cart_code, current_task_id
|
||
FROM wms_pick_cart
|
||
WHERE id IN (:ids)
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: { ids, warehouseId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
// 2) 查出有效绑定记录
|
||
const bindingRows = await ctx.model.query(`
|
||
SELECT cart_id
|
||
FROM wms_pick_task_cart_binding
|
||
WHERE cart_id IN (:ids)
|
||
AND warehouse_id = :warehouseId
|
||
AND is_active = 1
|
||
`, {
|
||
replacements: { ids, warehouseId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
const bindingCartIds = new Set(
|
||
(Array.isArray(bindingRows) ? bindingRows : []).map(r => Number(r.cart_id || 0)).filter(id => id > 0)
|
||
);
|
||
|
||
// 3) 分类:已绑定任务 / 有效绑定记录 → skip;其余 → delete
|
||
const skipIds = [];
|
||
const deleteIds = [];
|
||
for (const row of (Array.isArray(cartRows) ? cartRows : [])) {
|
||
const cartId = Number(row.id || 0);
|
||
if (Number(row.current_task_id || 0) > 0 || bindingCartIds.has(cartId)) {
|
||
skipIds.push(cartId);
|
||
} else {
|
||
deleteIds.push(cartId);
|
||
}
|
||
}
|
||
|
||
// ids 中存在但 cartRows 中不存在的(不属于该仓库或已不存在),也归入 skip
|
||
const foundIds = new Set((Array.isArray(cartRows) ? cartRows : []).map(r => Number(r.id || 0)));
|
||
for (const id of ids) {
|
||
if (!foundIds.has(id) && !skipIds.includes(id)) {
|
||
skipIds.push(id);
|
||
}
|
||
}
|
||
|
||
// 4) 执行删除
|
||
if (deleteIds.length > 0) {
|
||
await ctx.model.query(`
|
||
DELETE FROM wms_pick_cart
|
||
WHERE id IN (:deleteIds)
|
||
AND warehouse_id = :warehouseId
|
||
`, {
|
||
replacements: { deleteIds, warehouseId },
|
||
});
|
||
}
|
||
|
||
return {
|
||
deleted_ids: deleteIds,
|
||
skipped_ids: skipIds,
|
||
deleted_count: deleteIds.length,
|
||
skipped_count: skipIds.length,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 查询拣货车详情。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.cartId 拣货车ID。
|
||
* @return {Promise<Object>} 详情结果。
|
||
*/
|
||
async pickCartDetail(params = {}) {
|
||
const cartId = Number(params && params.cartId || 0);
|
||
const { warehouseId } = this.resolveOperatorContext();
|
||
|
||
if (!Number.isInteger(cartId) || cartId <= 0) {
|
||
throw this.createBusinessError('cart_id 必填且必须为正整数', 400);
|
||
}
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const cartRow = await this.getPickCartById(cartId, warehouseId);
|
||
if (!cartRow) {
|
||
throw this.createBusinessError('拣货车不存在', 404);
|
||
}
|
||
|
||
return this.buildPickCartDetail(cartRow);
|
||
}
|
||
|
||
/**
|
||
* 分页查询拣货车列表。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {Object} [params.pagination] 分页参数。
|
||
* @param {Object} [params.where] 查询条件。
|
||
* @return {Promise<Object>} 列表结果。
|
||
*/
|
||
async pickCartList(params = {}) {
|
||
const { ctx } = this;
|
||
const pagination = params && params.pagination && typeof params.pagination === 'object'
|
||
? params.pagination
|
||
: {};
|
||
const where = params && params.where && typeof params.where === 'object'
|
||
? params.where
|
||
: {};
|
||
const { warehouseId } = this.resolveOperatorContext();
|
||
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||
}
|
||
|
||
const page = Math.max(1, Number(pagination.page || 1));
|
||
const pageSize = Math.min(100, Math.max(1, Number(pagination.pageSize || pagination.page_size || 20)));
|
||
const offset = (page - 1) * pageSize;
|
||
const keyword = String(where.keyword || '').trim();
|
||
const status = where.status !== undefined && where.status !== null && where.status !== ''
|
||
? this.normalizePickCartStatus(where.status, null)
|
||
: null;
|
||
const currentTaskId = Number(where.current_task_id || where.currentTaskId || 0);
|
||
const replacements = {
|
||
warehouseId,
|
||
offset,
|
||
pageSize,
|
||
};
|
||
const filters = [ 'c.warehouse_id = :warehouseId' ];
|
||
|
||
if (keyword) {
|
||
replacements.keyword = `%${keyword}%`;
|
||
filters.push('(c.cart_code LIKE :keyword OR c.cart_name LIKE :keyword)');
|
||
}
|
||
if (status === 0 || status === 1) {
|
||
replacements.status = status;
|
||
filters.push('c.status = :status');
|
||
}
|
||
if (Number.isInteger(currentTaskId) && currentTaskId > 0) {
|
||
replacements.currentTaskId = currentTaskId;
|
||
filters.push('c.current_task_id = :currentTaskId');
|
||
}
|
||
|
||
const whereSql = filters.join(' AND ');
|
||
const countRows = await ctx.model.query(`
|
||
SELECT COUNT(1) AS total
|
||
FROM wms_pick_cart c
|
||
WHERE ${whereSql}
|
||
`, {
|
||
replacements,
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
const total = Number(countRows && countRows[0] && countRows[0].total || 0);
|
||
|
||
const rows = await ctx.model.query(`
|
||
SELECT
|
||
c.id AS cart_id,
|
||
c.warehouse_id,
|
||
c.cart_code,
|
||
c.cart_name,
|
||
c.status,
|
||
c.current_task_id,
|
||
c.bind_user_id,
|
||
c.last_bind_time,
|
||
c.last_seen_time,
|
||
c.create_time,
|
||
c.update_time,
|
||
t.task_no AS current_task_no,
|
||
t.status AS current_task_status
|
||
FROM wms_pick_cart c
|
||
LEFT JOIN wms_wave_pick_task t
|
||
ON t.id = c.current_task_id
|
||
WHERE ${whereSql}
|
||
ORDER BY c.id DESC
|
||
LIMIT :offset, :pageSize
|
||
`, {
|
||
replacements,
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
return {
|
||
list: (Array.isArray(rows) ? rows : []).map(row => this.buildPickCartDetail(row)),
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages: total > 0 ? Math.ceil(total / pageSize) : 0,
|
||
},
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = PickSystemService;
|