Compare commits

..

No commits in common. "93c0a620c7f801663bec6ad4c3b32e974728ea34" and "145fc04022e83c009cfd845be321c197a6b0d878" have entirely different histories.

75 changed files with 704 additions and 8810 deletions

File diff suppressed because one or more lines are too long

View File

@ -464,13 +464,9 @@ function resolveItemQuantity(item) {
* @param {number} [options.wave_index] 当前波次内序号。
* @param {number} [options.platforms_index] 平台内序号。
* @param {string} [options.expressInterfaceName] 快递渠道显示名。
* @param {number} [options.fallbackTotalQty] 订单级商品总数(items_total),优先于商品明细数量累加。
* @param {number} [options.fallbackItemsCount] 订单级商品种类数(items_count),仅当商品总数与明细累加均为 0 时兜底。
* @param {number} [options.waveSource] 波次来源(wms_wave_batch.source),与 waveType 共同决定商品明细行尾是否追加「波次总单数×数量」。
* @param {number} [options.waveType] 波次类型(wms_wave_batch.wave_type)。
* @param {number} [options.fallbackTotalQty] 兜底商品总数。
* @param {string} [options.packageMaterialName] 推荐包材名称,非空时追加到波次号前。
* @return {Array<string>} 自定义区文本行数组。首行头部分在快递渠道名后追加 商品总数【n】(优先取订单级商品总数 items_total,其次商品明细数量累加,最后 items_count 兜底);
* 当 waveSource=0 且 waveType=1 时,商品明细行尾追加「波次总单数×该行商品数量」。
* @return {Array<string>} 自定义区文本行数组。
*/
function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) {
const safeItems = Array.isArray(items) ? items : [];
@ -483,13 +479,6 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options =
const isHideMode = displayType === WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE;
// 波次总单数、来源与类型:wave.source=0(普通波次)且 wave_type=1 时,
// 商品明细行尾追加「波次总单数 × 该行商品数量」(如 500 单 × 3 件 = 1500)
const waveTotalOrders = toNumber(safeOptions.wave_total_orders, 0);
const waveSource = toNumber(safeOptions.waveSource, 0);
const waveType = toNumber(safeOptions.waveType, 0);
const shouldAppendWaveMultiply = waveSource === 0 && waveType === 1 && waveTotalOrders > 0;
const detailLines = [];
// HIDE 模式下跳过商品明细行构建,但仍保留 headerLine(波次号、快递渠道等)的输出
@ -509,7 +498,7 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options =
'storage_code',
]);
const barcode = resolveItemBarcodeText(item);
const { qtyText, qtyNumber } = resolveItemQuantity(item);
const { qtyText } = resolveItemQuantity(item);
let line = '';
switch (displayType) {
@ -537,17 +526,13 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options =
}
if (line) {
line = line.replace(/\s{2,}/g, ' ');
// wave.source=0 且 wave_type=1:行尾追加 波次总单数 × 该行商品数量(数量与乘数之间以两个空格分隔)
if (shouldAppendWaveMultiply && qtyNumber > 0) {
line += ` ${waveTotalOrders * qtyNumber}`;
}
detailLines.push(line);
detailLines.push(line.replace(/\s{2,}/g, ' '));
}
}
}
const waveNo = String(safeOptions.waveNo || '').trim();
const waveTotalOrders = toNumber(safeOptions.wave_total_orders, 0);
const waveIndex = toNumber(safeOptions.wave_index, 0);
const platformsIndex = toNumber(safeOptions.platforms_index, 0);
const expressInterfaceName = String(safeOptions.expressInterfaceName || '').trim();
@ -561,25 +546,7 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options =
? `${waveNo} [${waveTotalOrders}-${waveIndex}]`
: waveNo;
const waveHeaderText = packageMaterialLabel + waveBodyText;
// 商品总数:优先取订单级商品总数(items_total,权威字段),
// 其次累加所有商品明细的数量,最后用商品种类数(items_count)兜底。
// 订单 items 快照可能是宽松文本(stock_id+数量)甚至陈旧不完整,不能无条件信任明细累加结果
const computedTotalQty = safeItems.reduce((total, item) => {
if (!isPlainObject(item)) {
return total;
}
const { qtyNumber } = resolveItemQuantity(item);
return total + (Number.isFinite(qtyNumber) && qtyNumber > 0 ? qtyNumber : 0);
}, 0);
const fallbackTotalQty = toNumber(safeOptions.fallbackTotalQty, 0);
const fallbackItemsCount = toNumber(safeOptions.fallbackItemsCount, 0);
const totalQty = fallbackTotalQty > 0
? fallbackTotalQty
: (computedTotalQty > 0 ? computedTotalQty : fallbackItemsCount);
const totalQtyLabel = totalQty > 0 ? `商品总数【${totalQty}】` : '';
const headerParts = [ waveHeaderText, expressInterfaceName, totalQtyLabel ].filter(Boolean);
const headerParts = [ waveHeaderText, expressInterfaceName ].filter(Boolean);
const headerLine = headerParts.join(' ');
if (detailLines.length === 0) {
@ -1286,7 +1253,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') {
* @param {string[]} warnings 风险提示列表。
* @param {Object} policyConfig 策略配置对象。
* @param {string} customDataTemplateURL 自定义区模板地址默认值。
* @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。
* @param extraCustomLines
*/
function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL, extraCustomLines = []) {
if (platform !== 'kuaishou') {
@ -1326,10 +1293,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
|| safeOrderDelivery.logistics_interface_name
|| safeOrderDelivery.logistics_name
),
fallbackTotalQty: Number(safeOrderDelivery.items_total || 0),
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -1439,7 +1403,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。
* @param extraCustomLines
*/
function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) {
if (platform !== 'pdd') {
@ -1479,10 +1443,7 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli
|| safeOrderDelivery.logistics_interface_name
|| safeOrderDelivery.logistics_name
),
fallbackTotalQty: Number(safeOrderDelivery.items_total || 0),
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -1675,10 +1636,7 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD
|| safeOrderDelivery.logistics_interface_name
|| safeOrderDelivery.logistics_name
),
fallbackTotalQty: Number(safeOrderDelivery.items_total || 0),
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -1768,7 +1726,7 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD
* @param {Object} policyConfig 策略配置对象。
* @param {string} customControlTemplateURL 菜鸟自定义区模板地址。
* @param {string[]} warnings 风险提示列表。
* @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。
* @param extraCustomLines
*/
function applyCainiaoExpressFieldMapping(
platform,
@ -1818,10 +1776,7 @@ function applyCainiaoExpressFieldMapping(
|| safeOrderDelivery.logistics_interface_name
|| safeOrderDelivery.logistics_name
),
fallbackTotalQty: Number(safeOrderDelivery.items_total || 0),
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customControlText = appendExtraCustomLines(
@ -1982,7 +1937,7 @@ function resolveXhsMainContentFromPrintinfo(printinfo, warnings = []) {
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param {string[]} warnings 风险提示列表。
* @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。
* @param extraCustomLines
*/
function applyXhsExpressFieldMapping(
platform,
@ -2028,10 +1983,7 @@ function applyXhsExpressFieldMapping(
|| safeOrderDelivery.logistics_interface_name
|| safeOrderDelivery.logistics_name
),
fallbackTotalQty: Number(safeOrderDelivery.items_total || 0),
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -2088,7 +2040,7 @@ function applyXhsExpressFieldMapping(
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。
* @param extraCustomLines
*/
function applySphExpressFieldMapping(
platform,
@ -2147,10 +2099,7 @@ function applySphExpressFieldMapping(
|| safeOrderDelivery.logistics_interface_name
|| safeOrderDelivery.logistics_name
),
fallbackTotalQty: Number(safeOrderDelivery.items_total || 0),
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -2232,7 +2181,7 @@ function resolveJdTemplateUrlFromOrderExpress(orderExpress) {
* @param {Object} policyConfig 策略配置对象。
* @param {Object} templateSample 模板样例对象。
* @param {string[]} warnings 风险提示列表。
* @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。
* @param extraCustomLines
*/
function applyJdExpressFieldMapping(
platform,
@ -2322,10 +2271,7 @@ function applyJdExpressFieldMapping(
|| safeOrderDelivery.logistics_interface_name
|| safeOrderDelivery.logistics_name
),
fallbackTotalQty: Number(safeOrderDelivery.items_total || 0),
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = appendExtraCustomLines(

View File

@ -81,11 +81,6 @@ module.exports = app => {
allowNull: true,
comment: '来源平台名称',
},
oaid_order_source_code: {
type: STRING(50),
allowNull: true,
comment: 'OAID订单来源编码',
},
create_channel: {
type: STRING(20),
allowNull: false,

View File

@ -56,10 +56,10 @@ module.exports = app => {
comment: '来源类型',
},
order_status: {
type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED', 'TRANSFERRED'),
type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'),
allowNull: false,
defaultValue: 'CREATED',
comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废, TRANSFERRED=已转订单',
comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废',
},
sync_status: {
type: ENUM('PENDING', 'SUCCESS', 'FAILED'),
@ -107,81 +107,6 @@ module.exports = app => {
allowNull: true,
comment: '备注',
},
receiver_company: {
type: STRING(200),
allowNull: true,
comment: '收件人公司名称(receiverInfo.company)',
},
receiver_name: {
type: STRING(50),
allowNull: true,
comment: '收件人姓名(receiverInfo.name)',
},
receiver_zip_code: {
type: STRING(50),
allowNull: true,
comment: '收件人邮编(receiverInfo.zipCode)',
},
receiver_tel: {
type: STRING(50),
allowNull: true,
comment: '收件人固定电话(receiverInfo.tel)',
},
receiver_mobile: {
type: STRING(50),
allowNull: true,
comment: '收件人移动电话(receiverInfo.mobile)',
},
receiver_email: {
type: STRING(50),
allowNull: true,
comment: '收件人电子邮箱(receiverInfo.email)',
},
receiver_country_code: {
type: STRING(50),
allowNull: true,
comment: '收件人国家二字码(receiverInfo.countryCode)',
},
receiver_province: {
type: STRING(50),
allowNull: true,
comment: '收件人省份(receiverInfo.province)',
},
receiver_city: {
type: STRING(50),
allowNull: true,
comment: '收件人城市(receiverInfo.city)',
},
receiver_area: {
type: STRING(50),
allowNull: true,
comment: '收件人区域(receiverInfo.area)',
},
receiver_town: {
type: STRING(50),
allowNull: true,
comment: '收件人村镇(receiverInfo.town)',
},
receiver_detail_address: {
type: STRING(200),
allowNull: true,
comment: '收件人详细地址(receiverInfo.detailAddress)',
},
receiver_id: {
type: STRING(50),
allowNull: true,
comment: '收件人证件号(receiverInfo.id)',
},
source_platform_code: {
type: STRING(50),
allowNull: true,
comment: '来源平台编码(转订单时优先使用,为空时兜底平台)',
},
source_platform_name: {
type: STRING(200),
allowNull: true,
comment: '来源平台名称快照',
},
express_code: {
type: STRING(50),
allowNull: true,
@ -327,11 +252,6 @@ module.exports = app => {
return this.order_status === 'CANCELLED';
};
/** 判断订单是否已转销售订单 */
OrderStockout.prototype.isTransferred = function() {
return this.order_status === 'TRANSFERRED';
};
/** 当前订单是否允许审核 */
OrderStockout.prototype.canConfirm = function() {
return [ 'CREATED', 'PENDING' ].includes(this.order_status);

View File

@ -111,12 +111,6 @@ module.exports = app => {
defaultValue: 'N',
comment: '是否批次管理',
},
need_recheck: {
type: CHAR(1),
allowNull: false,
defaultValue: 'Y',
comment: '是否需要复核:Y=需要复核,N=不需要复核',
},
create_at: {
type: DATE,
allowNull: false,

View File

@ -59,7 +59,6 @@ module.exports = app => {
receiver_address: '',
group_wave_prefix: 'B',
delete_order_wave_prefix: 'A',
default_location_id: null,
single_order_pack_max_minutes: 3,
group_order_pack_max_minutes: 40,
inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES,
@ -330,17 +329,6 @@ module.exports = app => {
normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules);
normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules);
const rawDefaultLocationId = parsed.default_location_id;
if (rawDefaultLocationId === undefined || rawDefaultLocationId === null || rawDefaultLocationId === '') {
normalized.default_location_id = null;
} else {
const defaultLocationId = Number(rawDefaultLocationId);
if (!Number.isInteger(defaultLocationId) || defaultLocationId <= 0) {
throw new Error('subject_config.default_location_id 必须是正整数库位ID');
}
normalized.default_location_id = defaultLocationId;
}
if (Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_enabled')) {
normalized.cutoff_order_enabled = normalizeBooleanFlag(parsed.cutoff_order_enabled, 'subject_config.cutoff_order_enabled');
}

View File

@ -37,14 +37,6 @@ module.exports = app => {
required: false,
description: '控制该货主在当前仓库下是否允许使用收货单快捷入库',
}),
Object.freeze({
key: 'allow_receiving_direct_putaway',
name: '收货单直入库存',
type: 'flag',
default: 0,
required: false,
description: '控制该货主在当前仓库下是否允许使用收货单直入库存(一步写库存并生成入库单)',
}),
Object.freeze({
key: 'allow_mix_batch',
name: '允许混批',
@ -119,14 +111,6 @@ module.exports = app => {
required: false,
description: '货主在当前仓下默认使用的快递编码',
}),
Object.freeze({
key: 'stockout_default_express_code',
name: '出库单默认快递',
type: 'list',
default: 'ZT',
required: false,
description: '货主在当前仓下出库单默认使用的快递编码,默认 ZT 自提',
}),
Object.freeze({
key: 'default_platform_code',
name: '默认平台',
@ -737,10 +721,6 @@ module.exports = app => {
value: normalizePolicyConfigOptionValue(item),
label: String(item.name || item.code || ''),
})),
stockout_default_express_code: expressRows.map(item => ({
value: normalizePolicyConfigOptionValue(item),
label: String(item.name || item.code || ''),
})),
default_platform_code: platformRows.map(item => ({
value: normalizePolicyConfigOptionValue(item),
label: String(item.name || item.code || ''),

View File

@ -155,9 +155,8 @@ module.exports = app => {
fields: [ 'wave_status', 'create_time' ],
},
{
name: 'uniq_wave_no',
name: 'idx_wave_no',
fields: [ 'wave_no' ],
unique: true,
},
{
name: 'idx_warehouse',

View File

@ -2163,6 +2163,14 @@ class InboxFunctionsService extends Service {
const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id));
const alreadyExist = existingASList.map(r => r.after_sale_no);
const existedPairs = expressList
.filter(e => existingWaybillIds.has(e.id))
.map(e => {
const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id));
return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' };
})
.filter(p => p.as_no);
// 第三步:创建工单(含原文)并映射 waybill_id → 工单号
const createdNos = [];
const waybillToAsNo = {}; // waybill_id → after_sale_no 映射(新建 + 已存在)
@ -2277,18 +2285,12 @@ class InboxFunctionsService extends Service {
}
}
// 第六步:客户回信模板(单号+诉求,区分是否已通知快递)
const REPLY_TEXT = {
addr: { done: '修改地址已经登记', notify: '并已通知快递修改' },
return: { done: '催退回已经登记', notify: '并已通知快递处理' },
};
const replyText = REPLY_TEXT[issue.sub_type] || REPLY_TEXT.addr;
const lines = expressList.map(e => {
const head = `运单${e.waybill_code}${replyText.done}`;
return notifiedWaybillIds.has(e.id)
? `${head}·${replyText.notify}`
: `${head},稍后客服将人工跟进`;
});
// 第六步:客户回信模板(单号+诉求+工单)
const createdPairs = toCreate.map(e => ({
waybill: e.waybill_code,
as_no: waybillToAsNo[e.id] || '',
}));
const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`);
if (notFound.length > 0) {
lines.push(`未找到运单:${notFound.join('、')},请核实单号`);
}
@ -2306,7 +2308,7 @@ class InboxFunctionsService extends Service {
after_sale_nos: [ ...createdNos, ...alreadyExist ],
notified_groups: notifiedTotal,
not_found: notFound,
message: lines.join('\n'),
message: `${lines.join('\n')},稍后客服将人工核实跟进`,
direct_reply: true,
},
};
@ -3170,11 +3172,9 @@ class InboxFunctionsService extends Service {
},
raw: true,
});
// 视频地址拼接 CDN 域名(与 order.packing.list、queryReturn 对齐)
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
const urls = videos
.filter(v => String(v.status || '') !== 'failed')
.map(v => this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url))
.map(v => String(v.video_url || '').trim())
.filter(Boolean);
if (urls.length === 0) {
@ -3924,45 +3924,6 @@ class InboxFunctionsService extends Service {
};
}
}
/**
* 获取仓库的录制电脑 ID(带缓存)。
* @param {number} warehouseId 仓库ID
* @return {Promise<number|null>} 录制电脑ID,找不到返回 null
*/
async _getRecordingComputerId(warehouseId) {
const cacheKey = `_recordingComputer_${warehouseId}`;
if (this[cacheKey] !== undefined) {
return this[cacheKey];
}
const row = await this.ctx.model.PrintComputer.findOne({
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
attributes: [ 'id' ],
raw: true,
});
this[cacheKey] = row ? row.id : null;
return this[cacheKey];
}
/**
* 构建视频完整 URL。
* 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath}
* @param {number} warehouseId 仓库ID
* @param {number|null} recordingComputerId 录制电脑ID
* @param {string} videoPath 视频路径
* @return {string} 完整 URL
*/
_buildVideoUrl(warehouseId, recordingComputerId, videoPath) {
const path = String(videoPath || '').trim();
if (!path || !recordingComputerId) {
return path;
}
// 已是完整 URL 时原样返回,避免重复拼接
if (/^https?:\/\//i.test(path)) {
return path;
}
return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${path}`;
}
}
module.exports = InboxFunctionsService;

View File

@ -179,35 +179,10 @@ class orderServer extends MainService {
});
if (!existingOrder) {
// current 表未命中时回退查询配送域表(dispatch):
// 订单已流转到配送表中且已取消,视为取消成功(幂等),直接返回
const DispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(info.warehouseId);
const dispatchOrder = await DispatchModel.findOne({
where: {
delivery_order_code: orderCode,
warehouse_id: info.warehouseId,
store_id: info.storeId,
},
transaction,
lock: transaction.LOCK.UPDATE,
});
if (dispatchOrder && String(dispatchOrder.status || '').trim() === 'cancel') {
await transaction.rollback();
return this.success('取消订单成功');
}
await transaction.rollback();
return this.fail('未找到对应的订单');
}
// 幂等处理:订单在配送表中且已取消,直接返回取消成功
const currentStatus = String(existingOrder.status || '').trim();
if (currentStatus === 'cancel') {
await transaction.rollback();
return this.success('取消订单成功');
}
const pickStatus = String(existingOrder.pick_status || 'none').trim();
const printStatus = String(existingOrder.print_status || 'none').trim();

View File

@ -40,113 +40,18 @@ class stockoutServer extends MainService {
const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length;
// 快递编码解析(简化口径,独立于订单兜底链):
// 1. 货主开启 enable_external_express_code 且传了 logisticsCode 时,按
// wms_express_setting 映射 → 系统快递列表 匹配;
// 2. 未传 / 未开启 / 匹配不到 → 使用出库单兜底快递编码(stockout_default_express_code,
// 默认 ZT 自提),不再回退订单默认快递;不走订单的快递策略漏斗(matchPolicy)。
let expressCode = null;
let expressName = null;
try {
const deliveryOrderService = ctx.service.systems.deliveryOrder;
const policyConfig = await deliveryOrderService.getStoreWarehousePolicyConfig(storeId, warehouseId);
const expressList = await ctx.service.systems.express.getExpressList();
const findExpress = code => {
const upperCode = String(code || '').trim().toUpperCase();
if (!upperCode || !Array.isArray(expressList)) {
return null;
}
return expressList.find(item => item
&& String(item.code || item.value || '').trim().toUpperCase() === upperCode) || null;
};
const externalCode = String(deliveryOrder.logisticsCode || '').trim();
const enableExternal = deliveryOrderService.normalizePolicyFlag(
policyConfig && policyConfig.enable_external_express_code
);
if (enableExternal && externalCode) {
// 1) wms_express_setting 外部编码映射 → 系统快递编码
const settingSnapshot = await deliveryOrderService.resolveExpressSettingSnapshot(externalCode, warehouseId);
if (settingSnapshot && settingSnapshot.expressCode) {
const sysCode = String(settingSnapshot.expressCode).trim();
const sysItem = findExpress(sysCode);
expressCode = sysCode;
expressName = sysItem
? String(sysItem.name || sysItem.label || sysCode).trim()
: String(settingSnapshot.name || sysCode).trim();
} else {
// 2) 系统快递列表直接匹配
const matched = findExpress(externalCode);
if (matched) {
expressCode = String(matched.code || matched.value || externalCode).trim();
expressName = String(matched.name || matched.label || expressCode).trim();
}
}
}
if (!expressCode) {
// 兜底:出库单兜底快递编码(货主配置,默认 ZT 自提),不回退订单默认快递
const fallbackCode = String(policyConfig && policyConfig.stockout_default_express_code || '').trim() || 'ZT';
const fallbackItem = findExpress(fallbackCode);
expressCode = fallbackItem
? String(fallbackItem.code || fallbackItem.value || fallbackCode).trim()
: fallbackCode;
expressName = fallbackItem
? String(fallbackItem.name || fallbackItem.label || fallbackCode).trim()
: fallbackCode;
}
} catch (err) {
ctx.logger.warn(`[stockout.create] 快递编码解析失败,保持为空: ${err.message}`);
}
// 收件人信息解析(receiverInfo 13 个标准字段落库,供转订单与确认回传使用)
const receiver = deliveryOrder.receiverInfo && typeof deliveryOrder.receiverInfo === 'object'
? deliveryOrder.receiverInfo
: {};
const receiverFields = {
receiver_company: receiver.company,
receiver_name: receiver.name,
receiver_zip_code: receiver.zipCode,
receiver_tel: receiver.tel,
receiver_mobile: receiver.mobile,
receiver_email: receiver.email,
receiver_country_code: receiver.countryCode,
receiver_province: receiver.province,
receiver_city: receiver.city,
receiver_area: receiver.area,
receiver_town: receiver.town,
receiver_detail_address: receiver.detailAddress,
receiver_id: receiver.id,
};
for (const key of Object.keys(receiverFields)) {
const rawValue = receiverFields[key];
receiverFields[key] = rawValue === undefined || rawValue === null
? null
: String(rawValue).trim() || null;
}
// 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细
const errors = [];
const items = [];
for (let i = 0; i < orderLine.length; i++) {
const line = orderLine[i];
let wmsStock = await app.model.StockStore.findByPk(line.itemId);
const wmsStock = await app.model.StockStore.findByPk(line.itemId);
// 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权
if (wmsStock && Number(wmsStock.store_id) !== Number(this.storeId)) {
wmsStock = null;
}
// 外部渠道(奇门)itemId 可能是平台商品标识或条码而非 WMS 主键,
// 主键查不到或跨货主时降级按 item_code + 仓库货主维度查找
if (!wmsStock && line.itemCode) {
const stockWhere = {
item_code: line.itemCode,
warehouse_id: warehouseId,
store_id: storeId,
};
if (this.appKey) {
stockWhere.app_key = this.appKey;
}
wmsStock = await app.model.StockStore.findOne({ where: stockWhere });
errors.push(
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`
);
continue;
}
if (!wmsStock) {
errors.push(
@ -199,9 +104,6 @@ class stockoutServer extends MainService {
? new Date(deliveryOrder.createTime)
: null,
remark: deliveryOrder.remark || null,
express_code: expressCode,
express_name: expressName,
...receiverFields,
warehouse_id: warehouseId,
store_id: storeId,
qimen_owner_code: items[0].ownerCode,

View File

@ -61,7 +61,6 @@ const CREATE_CHANNEL_LABELS = Object.freeze({
MANUAL: '手工单',
API: '接口',
QM: '奇门',
STOCKOUT: '出库转单',
});
const ORDER_TABLE_TYPE_ALIASES = Object.freeze({
current: 'current',

View File

@ -1891,12 +1891,7 @@ class PendingOrderService extends OrderBaseService {
};
// 快照 ctx 数据(setImmediate 回调中 ctx 可能已失效)
// 显式传入的仓库ID优先:Qimen 创建订单等无登录用户上下文的异步链路 ctx.user 为空,
// 调用方必须显式传 warehouseId,否则回传任务会因"缺少仓库上下文"静默失败
const explicitWarehouseId = Number(requestData.warehouse_id ?? requestData.warehouseId ?? 0);
const warehouseId = Number.isFinite(explicitWarehouseId) && explicitWarehouseId > 0
? explicitWarehouseId
: this.getWarehouseId();
const warehouseId = this.getWarehouseId();
const operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
@ -2821,22 +2816,9 @@ class PendingOrderService extends OrderBaseService {
post_status: 'none',
};
const platformName = String(platform.name || '').trim();
// 更新前查询候选订单,筛出平台实际发生变化的订单,用于逐单写入订单日志
const candidateOrders = await model.findAll({
where,
attributes: [ 'id', 'sys_platform_code', 'sys_platform_name' ],
raw: true,
});
const changedOrders = Array.isArray(candidateOrders)
? candidateOrders.filter(order => String(order.sys_platform_code || '').trim() !== String(platform.code || '').trim())
: [];
const [ affectedRows ] = await model.update({
sys_platform_code: platform.code,
sys_platform_name: platformName,
sys_platform_name: String(platform.name || '').trim(),
updated_at: new Date(),
}, { where });
@ -2853,9 +2835,9 @@ class PendingOrderService extends OrderBaseService {
warehouseId: logWarehouseId,
orderIds,
sys_platform_code: platform.code,
sys_platform_name: platformName,
sys_platform_name: String(platform.name || '').trim(),
updated_count: count,
message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${platformName}),共更新 ${count} 条`,
message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${String(platform.name || '').trim()}),共更新 ${count} 条`,
},
beforeChanges: null,
});
@ -2863,39 +2845,6 @@ class PendingOrderService extends OrderBaseService {
this.ctx.logger.warn('[PendingOrderService.updateOrderPlatform] 写入操作日志失败,不影响业务', logErr);
}
// 为实际发生平台变化的订单逐单写入订单日志(订单详情页可见)
try {
const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (opLogService && typeof opLogService.createOperationLogs === 'function' && changedOrders.length > 0) {
const logPayloads = changedOrders
.map(order => {
const orderId = Number(order.id);
if (!Number.isInteger(orderId) || orderId <= 0) {
return null;
}
const originalName = String(order.sys_platform_name || order.sys_platform_code || '未知').trim();
return {
businessType: 'order',
businessId: String(orderId),
operationCode: 'ORDER_UPDATE_PLATFORM',
operator,
extras: {
warehouseId: logWarehouseId,
message: `修改订单平台:${originalName} → ${platform.code}(${platformName})`,
externalLogType: 'NONE',
},
};
})
.filter(Boolean);
if (logPayloads.length > 0) {
await opLogService.createOperationLogs(logPayloads);
}
}
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.updateOrderPlatform] 写入订单日志失败,不影响业务', logErr);
}
return this.success('ok', {
updated_count: count,
sys_platform_code: platform.code,
@ -3201,8 +3150,6 @@ class PendingOrderService extends OrderBaseService {
* 2. 若原订单已分配储位(storage_status='fin'),先清除已分配库存;
* 3. 取消原订单(step->9, status->'cancel')并记录"克隆"日志;
* 4. 以原订单业务数据创建新订单,所有流程状态字段重置为初始落库状态;
* 同步状态继承原订单:原订单已同步(sync_status=fin)则新订单直接置 fin 避免重复回传,
* 否则重置为 padding 重新走同步;
* 5. 对新订单记录"克隆创建"日志。
*
* @param {Object} data 请求体。
@ -3234,20 +3181,14 @@ class PendingOrderService extends OrderBaseService {
throw new Error('订单当前状态不允许克隆');
}
// 2. 若已分配储位,先清除库存。
// 已同步订单同样允许克隆;库存释放失败不阻断克隆(与 cancelOrder 降级策略一致),
// 原订单残留占用保留在原订单名下,克隆新订单不重新占用库存
// (新订单 storage_status 重置为 none,创建过程不触发储位分配与库存锁定)。
// 2. 若已分配储位,先清除库存
if (String(original.storage_status || '').trim() === 'fin') {
try {
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: [ orderId ],
});
} catch (storageErr) {
this.ctx.logger.warn(
`[PendingOrderService.cloneOrder] 清除已分配库存失败,不影响克隆,orderId=${orderId}`,
storageErr
);
throw new Error(`清除已分配库存失败:${storageErr.message}`);
}
}
@ -3330,11 +3271,8 @@ class PendingOrderService extends OrderBaseService {
};
// 业务字段白名单(从原订单复制)
// 注意:不含 delivery_order_code —— 该字段受 (delivery_order_code, store_id, warehouse_id)
// 唯一索引约束,且原订单取消后仍留在 current 表占用索引,复制原单号会触发唯一键冲突
// (Sequelize UniqueConstraintError,对外表现为 "Validation error")。新单号见下方生成逻辑。
const COPY_FIELDS = [
'pre_delivery_order_code', 'pre_delivery_order_id',
'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id',
'order_type', 'warehouse_code', 'warehouse_id', 'store_id', 'from_key',
'source_platform_code', 'source_platform_name', 'source_order_codes',
'sys_platform_code', 'sys_platform_name',
@ -3351,21 +3289,11 @@ class PendingOrderService extends OrderBaseService {
];
const newOrderData = { ...RESET_FIELDS };
// 克隆单生成全新发货单号(与手工单 createOrder 相同的生成规则)
newOrderData.delivery_order_code = `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`;
// 同步状态继承:原订单已同步(sync_status=fin)则新订单直接置 fin,避免重复回传平台;
// 未同步/同步失败(padding/error)重置为 padding 重新走同步流程
newOrderData.sync_status = String(original.sync_status || '').trim() === 'fin' ? 'fin' : 'padding';
for (const field of COPY_FIELDS) {
if (original[field] !== undefined) {
newOrderData[field] = original[field];
}
}
// 克隆追溯链:原订单无前置单号时,把原单号写入新订单 pre_delivery_order_code
const originalDeliveryCode = String(original.delivery_order_code || '').trim();
if (originalDeliveryCode && !String(newOrderData.pre_delivery_order_code || '').trim()) {
newOrderData.pre_delivery_order_code = originalDeliveryCode;
}
// 克隆单同样由仓库序列表统一发号;发号失败直接抛错,不回退分表自增,
// 避免分表自增与序列表发号区间重叠产生冲突 id

View File

@ -806,7 +806,6 @@ class RecheckOrderService extends OrderBaseService {
barcodes: Array.isArray(item.barcodes) ? [ ...item.barcodes ] : [],
images: Array.isArray(item.images) ? [ ...item.images ] : [],
has_shared_barcode: Boolean(item.has_shared_barcode),
need_recheck: String(item.need_recheck || 'Y').trim(),
plan_qty: Number(item.plan_qty || 0),
store_id: item.store_id != null ? Number(item.store_id) : 0,
owner_code: String(item.owner_code || '').trim(),
@ -1383,11 +1382,8 @@ class RecheckOrderService extends OrderBaseService {
}
}
// 5. 检测共享条码:以订单货主(store_id)为判定范围,
// 仅当条码在订单货主下(wms_stock_warehouse.store_id = 订单 store_id)绑定到多个不同 stock_id 时视为共享;
// 跨货主同码不提示。无货主(store_id<=0)的订单不做共享判定。
// 已删除(delete_at/deleted_at 非空)或弃用(is_valid≠'Y')的商品资料不参与共享判定。
const sharedBarcodeMap = new Map();
// 5. 检测共享条码:查询当前所有条码是否也出现在其他 stock_id 中
const sharedBarcodeSet = new Set();
if (barcodeMap.size > 0) {
const allBarcodes = [];
for (const [ , barcodes ] of barcodeMap) {
@ -1395,44 +1391,21 @@ class RecheckOrderService extends OrderBaseService {
allBarcodes.push(bc);
}
}
const orderStoreIds = [ ...new Set(
orderList
.map(order => Number(order.store_id || 0))
.filter(storeId => storeId > 0)
) ];
if (allBarcodes.length > 0
&& orderStoreIds.length > 0
&& this.ctx.model
&& this.ctx.model.StockBarcode) {
if (allBarcodes.length > 0 && this.ctx.model && this.ctx.model.StockBarcode) {
const sharedRows = await this.ctx.model.query(
`SELECT sb.barcode, sw.store_id, COUNT(DISTINCT sb.stock_id) AS cnt
FROM wms_stock_barcodes sb
INNER JOIN wms_stock_warehouse sw
ON sw.id = sb.stock_id
AND sw.is_valid = 'Y'
AND sw.delete_at IS NULL
AND sw.deleted_at IS NULL
WHERE sb.barcode IN (:barcodes)
AND sb.warehouse_id = :warehouseId
AND sw.warehouse_id = :warehouseId
AND sw.store_id IN (:orderStoreIds)
GROUP BY sb.barcode, sw.store_id
`SELECT barcode, COUNT(DISTINCT stock_id) AS cnt
FROM wms_stock_barcodes
WHERE barcode IN (:barcodes)
AND warehouse_id = :warehouseId
GROUP BY barcode
HAVING cnt > 1`,
{
replacements: { barcodes: allBarcodes, warehouseId, orderStoreIds },
replacements: { barcodes: allBarcodes, warehouseId },
type: this.ctx.model.QueryTypes.SELECT,
}
);
for (const row of (Array.isArray(sharedRows) ? sharedRows : [])) {
const rowStoreId = Number(row.store_id || 0);
const rowBarcode = String(row.barcode || '').trim();
if (rowStoreId <= 0 || !rowBarcode) {
continue;
}
if (!sharedBarcodeMap.has(rowStoreId)) {
sharedBarcodeMap.set(rowStoreId, new Set());
}
sharedBarcodeMap.get(rowStoreId).add(rowBarcode);
sharedBarcodeSet.add(String(row.barcode || '').trim());
}
}
}
@ -1465,9 +1438,7 @@ class RecheckOrderService extends OrderBaseService {
const hasSharedBarcode = (() => {
const arr = barcodeMap.get(sid);
const orderStoreId = Number(order.store_id || 0);
const sharedBarcodeSet = orderStoreId > 0 ? sharedBarcodeMap.get(orderStoreId) : null;
if (Array.isArray(arr) && arr.length > 0 && sharedBarcodeSet) {
if (Array.isArray(arr) && arr.length > 0) {
return arr.some(bc => sharedBarcodeSet.has(bc));
}
return false;
@ -1482,7 +1453,6 @@ class RecheckOrderService extends OrderBaseService {
barcodes,
images,
has_shared_barcode: hasSharedBarcode,
need_recheck: String(stockInfo.need_recheck || 'Y').trim(),
plan_qty: Number(item.plan_qty || 0),
store_id: stockInfo.store_id != null ? Number(stockInfo.store_id) : 0,
owner_code: String(item.owner_code || '').trim(),

View File

@ -563,13 +563,7 @@ class WaveService extends OrderBaseService {
}
/**
* 获取当天前缀下的下一个波次序号(原子取号)。
*
* 基于序列表 wms_number_sequence 的单条 upsert 原子递增:
* INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE
* current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1)
* 其中 :seed 为当日该前缀主表已有最大序号,保证与历史编号对齐;
* 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下不再撞号。
* 查询当天前缀下的下一个波次序号。
*
* @param {string} prefix 波次编号前缀。
* @param {string} datePart 日期片段(YYYYMMDD)。
@ -580,54 +574,32 @@ class WaveService extends OrderBaseService {
const normalizedPrefix = String(prefix || '').trim() || 'B';
const normalizedDatePart = String(datePart || '').trim();
const pattern = `${normalizedPrefix}${normalizedDatePart}%`;
const prefixDatePartLength = normalizedPrefix.length + normalizedDatePart.length;
const bizType = `wave_no_${normalizedPrefix.slice(0, 20)}`;
const sql = `
SELECT wave_no
FROM wms_wave_batch
WHERE wave_no LIKE :pattern
ORDER BY wave_no DESC
LIMIT 1
`;
// 历史对齐种子:当日该前缀主表已有最大序号(无则为 0)
const seedRows = await this.ctx.model.query(
`SELECT IFNULL(MAX(CAST(SUBSTRING(wave_no, :startPos) AS UNSIGNED)), 0) AS max_seq
FROM wms_wave_batch
WHERE wave_no LIKE :pattern`,
{
replacements: {
pattern,
startPos: prefixDatePartLength + 1,
},
type: this.ctx.model.QueryTypes.SELECT,
transaction,
}
);
const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq || 0);
const rows = await this.ctx.model.query(sql, {
replacements: { pattern },
type: this.ctx.model.QueryTypes.SELECT,
transaction,
});
// 原子取号:全局维度(warehouse_id=0)按「前缀+日期」递增,唯一键串行化并发事务
await this.ctx.model.query(
`INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at)
VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW())
ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`,
{
replacements: {
warehouseId: 0,
bizType,
datePart: normalizedDatePart,
seed,
},
transaction,
}
);
const seqRows = await this.ctx.model.query(
'SELECT LAST_INSERT_ID() AS seq',
{
type: this.ctx.model.QueryTypes.SELECT,
transaction,
}
);
const sequence = Number(seqRows && seqRows[0] && seqRows[0].seq || 0);
if (!Number.isInteger(sequence) || sequence <= 0) {
const latestWaveNo = String(rows && rows[0] && rows[0].wave_no || '').trim();
if (!latestWaveNo) {
return 1;
}
return sequence;
const match = latestWaveNo.match(/(\d{5})$/);
const lastSequence = match ? Number(match[1]) : 0;
if (!Number.isInteger(lastSequence) || lastSequence <= 0) {
return 1;
}
return lastSequence + 1;
}
/**
@ -727,22 +699,6 @@ class WaveService extends OrderBaseService {
return 0;
}
/**
* 判断数据库错误是否为唯一键冲突(重复键 ER_DUP_ENTRY)。
*
* @param {*} error 数据库异常对象。
* @return {boolean} 是否唯一键冲突。
*/
isDuplicateEntryError(error) {
const errno = Number(
error && (error.original && error.original.errno || error.parent && error.parent.errno || error.errno) || 0
);
const code = String(
error && (error.original && error.original.code || error.parent && error.parent.code || error.code) || ''
);
return errno === 1062 || code === 'ER_DUP_ENTRY';
}
/**
* 新增一条“已就绪”波次批次记录,并返回自增 wave_id。
*
@ -790,9 +746,12 @@ class WaveService extends OrderBaseService {
const normalizedWaveType = Number(waveType) === 2 ? 2 : 1;
const normalizedSourceInput = Number(source);
const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0;
const retryOnDuplicate = !normalizedWaveNoInput;
const maxWaveNoAttempts = retryOnDuplicate ? 3 : 1;
let normalizedWaveNo = normalizedWaveNoInput;
if (!normalizedWaveNo) {
const datePart = this.getCurrentDatePart();
const sequence = await this.getNextWaveNoSequence(normalizedWavePrefix, datePart, transaction);
normalizedWaveNo = this.buildWaveNo(normalizedWavePrefix, datePart, sequence);
}
const creator = this.getWaveCreator();
const sql = `
@ -836,49 +795,23 @@ class WaveService extends OrderBaseService {
)
`;
// 撞号重试:唯一索引兜底下,并发撞号时自动重新取号(最多 3 次)
let createResult = null;
for (let attempt = 1; attempt <= maxWaveNoAttempts; attempt += 1) {
if (!normalizedWaveNo) {
const datePart = this.getCurrentDatePart();
const sequence = await this.getNextWaveNoSequence(normalizedWavePrefix, datePart, transaction);
normalizedWaveNo = this.buildWaveNo(normalizedWavePrefix, datePart, sequence);
}
try {
createResult = await this.ctx.model.query(sql, {
replacements: {
waveNo: normalizedWaveNo,
waveType: normalizedWaveType,
totalOrders: normalizedTotalOrders,
itemDetailMachine: normalizedItemDetailMachine,
itemPartType: normalizedItemPartType,
itemPart: normalizedItemPart,
distinguishExpress: normalizedDistinguishExpress,
logisticsName: normalizedLogisticsName,
itemSnapshotKey: normalizedItemSnapshotKey,
warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0,
creator,
source: normalizedSource,
},
transaction,
});
break;
} catch (error) {
const isDuplicateWaveNo = this.isDuplicateEntryError(error);
if (!retryOnDuplicate || !isDuplicateWaveNo || attempt >= maxWaveNoAttempts) {
throw error;
}
this.ctx.logger.warn(
'[wave.createWaveBatchReady] 波次编号 %s 已存在(撞号),自动重新取号重试 %d/%d',
normalizedWaveNo,
attempt,
maxWaveNoAttempts
);
normalizedWaveNo = '';
}
}
const createResult = await this.ctx.model.query(sql, {
replacements: {
waveNo: normalizedWaveNo,
waveType: normalizedWaveType,
totalOrders: normalizedTotalOrders,
itemDetailMachine: normalizedItemDetailMachine,
itemPartType: normalizedItemPartType,
itemPart: normalizedItemPart,
distinguishExpress: normalizedDistinguishExpress,
logisticsName: normalizedLogisticsName,
itemSnapshotKey: normalizedItemSnapshotKey,
warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0,
creator,
source: normalizedSource,
},
transaction,
});
let insertedWaveId = this.extractInsertId(createResult);
if (!Number.isInteger(insertedWaveId) || insertedWaveId <= 0) {

View File

@ -97,8 +97,6 @@ class PickService extends MainService {
* @param {Array<number>} params.orderIds 波次订单ID集合。
* @param {string} [params.remark=''] 备注。
* @param {number} [params.source=2] 任务来源:1-PDA抓取创建,2-扫描进任务/后台抓取,默认为2。
* @param {boolean} [params.excludeUnclaimed=false] 普通波次(source=0)计算拣货数量时是否剔除未领料
* (claim_status != fin)订单:true 时未领料订单不写入任务订单/筐,也不计入 order_count。
* @return {Promise<{task_id: number, task_no: string}>} 创建结果。
*/
async createWavePickTask(params = {}) {
@ -111,7 +109,6 @@ class PickService extends MainService {
const operatorName = String(params && params.operatorName || '').trim() || 'system';
const source = Number(params && params.source !== undefined ? params.source : 2);
const remark = String(params && params.remark || '').trim();
const excludeUnclaimed = Boolean(params && params.excludeUnclaimed);
const normalizedOrderIds = [ ...new Set((Array.isArray(params && params.orderIds) ? params.orderIds : [])
.map(id => Number(id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
@ -137,13 +134,11 @@ class PickService extends MainService {
[this.app.Sequelize.Op.in]: normalizedOrderIds,
},
},
attributes: [ 'id', 'intercept_status', 'claim_status' ],
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
// 拦截流程中的订单不允许抓取波次,直接剔除
const orderRowMap = new Map((Array.isArray(orderRows) ? orderRows : [])
.map(row => [ Number(row && row.id || 0), row ]));
const interceptedOrderIds = new Set((Array.isArray(orderRows) ? orderRows : [])
.filter(row => isInterceptedOrderStatus(row && row.intercept_status))
.map(row => Number(row && row.id || 0))
@ -154,28 +149,9 @@ class PickService extends MainService {
ctx.logger.info('[pick.createWavePickTask] 剔除拦截订单: %s', excludedIds.join(','));
}
}
// 领料语义(普通波次 source=0):未领料订单(claim_status != fin)不参与拣货数量计算,直接剔除
const unclaimedOrderIds = excludeUnclaimed
? new Set(normalizedOrderIds.filter(id => {
const row = orderRowMap.get(id);
return !row || String(row && row.claim_status || '') !== 'fin';
}))
: new Set();
if (unclaimedOrderIds.size > 0) {
const excludedIds = normalizedOrderIds.filter(id => unclaimedOrderIds.has(id));
if (excludedIds.length > 0) {
ctx.logger.info('[pick.createWavePickTask] 剔除未领料订单: %s', excludedIds.join(','));
}
}
const activeOrderIds = normalizedOrderIds
.filter(id => !interceptedOrderIds.has(id) && !unclaimedOrderIds.has(id));
const activeOrderIds = normalizedOrderIds.filter(id => !interceptedOrderIds.has(id));
if (activeOrderIds.length <= 0) {
const emptyReason = unclaimedOrderIds.size > 0
? '波次下订单均未领料或均被拦截,无法创建任务'
: '波次下订单均已被拦截,无法创建任务';
throw Object.assign(new Error(emptyReason), { code: 400 });
throw Object.assign(new Error('波次下订单均已被拦截,无法创建任务'), { code: 400 });
}
const orderNoMap = new Map((Array.isArray(orderRows) ? orderRows : [])
@ -698,7 +674,6 @@ class PickService extends MainService {
let targetWaveId = 0;
let targetWaveNo = '';
let targetWaveType = 2;
let targetWaveSource = 0;
let selectedOrderIds = [];
const orderId = Number(orderExpress && orderExpress.order_id || 0);
@ -731,7 +706,7 @@ class PickService extends MainService {
if (orderWaveId > 0) {
const waveByIdRows = await ctx.model.query(
`
SELECT wave_id, wave_no, wave_type, source
SELECT wave_id, wave_no, wave_type
FROM wms_wave_batch
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
@ -753,11 +728,10 @@ class PickService extends MainService {
targetWaveId = Number(waveRow.wave_id || 0);
targetWaveNo = String(waveRow.wave_no || '').trim();
targetWaveType = Number(waveRow.wave_type || 2);
targetWaveSource = Number(waveRow.source || 0);
} else {
const waveByNoRows = await ctx.model.query(
`
SELECT wave_id, wave_no, wave_type, source
SELECT wave_id, wave_no, wave_type
FROM wms_wave_batch
WHERE warehouse_id = :warehouseId
AND wave_no = :waveNo
@ -779,12 +753,11 @@ class PickService extends MainService {
targetWaveId = Number(waveRow.wave_id || 0);
targetWaveNo = String(waveRow.wave_no || '').trim();
targetWaveType = Number(waveRow.wave_type || 2);
targetWaveSource = Number(waveRow.source || 0);
}
} else {
const waveRows = await ctx.model.query(
`
SELECT wave_id, wave_no, wave_type, source
SELECT wave_id, wave_no, wave_type
FROM wms_wave_batch
WHERE warehouse_id = :warehouseId
AND wave_no = :waveNo
@ -807,45 +780,12 @@ class PickService extends MainService {
targetWaveId = Number(waveRow.wave_id || 0);
targetWaveNo = String(waveRow.wave_no || '').trim();
targetWaveType = Number(waveRow.wave_type || 2);
targetWaveSource = Number(waveRow.source || 0);
}
if (!Number.isInteger(targetWaveId) || targetWaveId <= 0 || !targetWaveNo) {
return this.fail('目标波次信息不完整', {}, 400);
}
// 领料前置校验:source=0 普通波次需整波领料,未领料阻隔创建拣货任务
// (拦截订单未领料不阻隔拣货,拦截订单将在任务创建时被剔除)
if (targetWaveSource === 0) {
const claimGatePickMode = await this.getWavePickModeByWaveId(targetWaveId);
let claimGateOrderModel = null;
try {
claimGateOrderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId);
} catch (error) {
return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500);
}
const claimGateStats = await this.getWaveClaimGateStats({
orderModel: claimGateOrderModel,
warehouseId: normalizedWarehouseId,
waveId: targetWaveId,
waveNo: targetWaveNo,
});
if (claimGateStats.total_order_count > 0 && claimGateStats.unclaimed_order_count > 0) {
return this.fail('订单未领料,请先领料后再拣货', {
action: 'wave_claim',
wave_id: targetWaveId,
wave_no: targetWaveNo,
wave_type: targetWaveType,
wave_source: targetWaveSource,
pick_mode: claimGatePickMode,
unclaimed_order_count: claimGateStats.unclaimed_order_count,
intercepted_order_count: claimGateStats.intercepted_order_count,
total_order_count: claimGateStats.total_order_count,
}, 400);
}
}
const activeTaskRows = await ctx.model.query(
`
SELECT t.id AS task_id, t.pick_user_id, t.pick_user_name
@ -1102,8 +1042,6 @@ class PickService extends MainService {
orderIds: selectedOrderIds,
remark: `pick.query keyword=${normalizedKeyword}`,
source: 2,
// 普通波次(source=0):计算拣货数量时剔除未领料(claim_status != fin)订单
excludeUnclaimed: targetWaveSource === 0,
});
return this.success('ok', {
@ -1288,7 +1226,7 @@ class PickService extends MainService {
// --- 按 wave_id 直接查波次 ---
const waveRows = await ctx.model.query(
`SELECT wave_id, wave_no, wave_type, source
`SELECT wave_id, wave_no, wave_type
FROM wms_wave_batch
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
@ -1306,7 +1244,6 @@ class PickService extends MainService {
const targetWaveId = Number(waveRow.wave_id || 0);
const targetWaveNo = String(waveRow.wave_no || '').trim();
const targetWaveType = Number(waveRow.wave_type || 2);
const targetWaveSource = Number(waveRow.source || 0);
if (!Number.isInteger(targetWaveId) || targetWaveId <= 0 || !targetWaveNo) {
return this.fail('目标波次信息不完整', {}, 400);
@ -1455,8 +1392,6 @@ class PickService extends MainService {
orderIds: selectedOrderIds,
remark: `pick.wavePickComplete wave_id=${waveId}`,
source: 2,
// 普通波次(source=0):计算拣货数量时剔除未领料(claim_status != fin)订单
excludeUnclaimed: targetWaveSource === 0,
});
taskId = createdTask.task_id;
} catch (error) {
@ -1602,78 +1537,6 @@ class PickService extends MainService {
return linkRow ? Number(linkRow.pick_mode || 0) : 0;
}
/**
* 统计波次下领料门禁相关数量(普通波次 source=0 领料前置校验)。
*
* 统计口径:
* - total_order_count:波次下全部订单数(含拦截订单);
* - intercepted_order_count:拦截订单数(intercept_status != none);
* - unclaimed_order_count:非拦截且未领料(claim_status != fin)订单数,
* 拦截订单未领料不阻隔拣货,不计入该数量。
*
* @param {Object} params 统计参数。
* @param {Object} params.orderModel 订单分表模型。
* @param {number} params.warehouseId 仓库ID。
* @param {number} params.waveId 波次ID。
* @param {string} [params.waveNo=''] 波次编码(wave_id 未命中时回退按 wave_no 统计)。
* @return {Promise<{total_order_count: number, intercepted_order_count: number, unclaimed_order_count: number}>}
* 统计结果。
*/
async getWaveClaimGateStats(params = {}) {
const { ctx } = this;
const orderModel = params && params.orderModel;
const warehouseId = Number(params && params.warehouseId || 0);
const waveId = Number(params && params.waveId || 0);
const waveNo = String(params && params.waveNo || '').trim();
if (!orderModel || typeof orderModel.findAll !== 'function') {
ctx.logger.warn('[pick.getWaveClaimGateStats] 订单模型不可用,返回空统计');
return { total_order_count: 0, intercepted_order_count: 0, unclaimed_order_count: 0 };
}
let rows = [];
if (Number.isInteger(waveId) && waveId > 0) {
rows = await orderModel.findAll({
where: {
warehouse_id: warehouseId,
wave_id: waveId,
},
attributes: [ 'id', 'claim_status', 'intercept_status' ],
raw: true,
});
rows = Array.isArray(rows) ? rows : [];
}
if (rows.length === 0 && waveNo) {
const fallbackRows = await orderModel.findAll({
where: {
warehouse_id: warehouseId,
wave_no: waveNo,
},
attributes: [ 'id', 'claim_status', 'intercept_status' ],
raw: true,
});
rows = Array.isArray(fallbackRows) ? fallbackRows : [];
}
const orderIds = [ ...new Set(rows
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
const interceptedOrderIds = new Set(rows
.filter(item => isInterceptedOrderStatus(item && item.intercept_status))
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0));
const unclaimedOrderCount = rows
.filter(item => String(item && item.claim_status || '') !== 'fin'
&& orderIds.includes(Number(item && item.id || 0))
&& !interceptedOrderIds.has(Number(item && item.id || 0)))
.length;
return {
total_order_count: orderIds.length,
intercepted_order_count: interceptedOrderIds.size,
unclaimed_order_count: unclaimedOrderCount,
};
}
/**
* 扫描面单号领取整波(领料)。
*
@ -1683,10 +1546,8 @@ class PickService extends MainService {
* 并写入 ORDER_WAVE_CLAIM 订单操作日志,返回波次ID(wave_id)与波次编码(wave_no);
* 策略抓取波次(source=1/2)无需领料,返回 400 并提示「该波次为抓取波次,无需领料」
* (失败 data 含 no_claim_needed=true、wave_id、wave_no);
* 波次下存在未打印订单(print_status != fin,拦截订单除外)时禁止领料,
* 返回 400 并提示「波次未打印,禁止领料」(失败 data 含 wave_id、wave_no、unprinted_order_count、
* intercepted_order_count,拦截订单未打印不阻隔领料);
* 拦截订单整体跳过领料:既不置为领料完成,其未打印状态也不阻隔整波领料。
* 波次下存在未打印订单(print_status != fin)时禁止领料,
* 返回 400 并提示「波次未打印,禁止领料」(失败 data 含 wave_id、wave_no、unprinted_order_count);
* 其余未知类型返回通用不支持提示。
* 波次内订单已全部领单时返回 already_claimed 幂等结果并提示已领料。
*
@ -1841,7 +1702,7 @@ class PickService extends MainService {
warehouse_id: normalizedWarehouseId,
wave_id: targetWaveId,
},
attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status' ],
attributes: [ 'id', 'claim_status', 'print_status' ],
raw: true,
});
let waveOrders = Array.isArray(waveOrderRows) ? waveOrderRows : [];
@ -1851,7 +1712,7 @@ class PickService extends MainService {
warehouse_id: normalizedWarehouseId,
wave_no: targetWaveNo,
},
attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status' ],
attributes: [ 'id', 'claim_status', 'print_status' ],
raw: true,
});
waveOrders = Array.isArray(fallbackRows) ? fallbackRows : [];
@ -1864,15 +1725,8 @@ class PickService extends MainService {
}
const totalOrderCount = waveOrderIds.length;
// 拦截订单整体跳过领料:不参与领取(保持未领料),其未打印/未领料状态也不阻隔领料与拣货
const interceptedWaveOrderIds = new Set(waveOrders
.filter(item => isInterceptedOrderStatus(item && item.intercept_status))
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0));
const unclaimedOrderIds = [ ...new Set(waveOrders
.filter(item => String(item && item.claim_status || '') !== 'fin'
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
.filter(item => String(item && item.claim_status || '') !== 'fin')
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
@ -1885,7 +1739,6 @@ class PickService extends MainService {
matched_order_id: matchedOrderId,
waybill_no: waybillNo,
total_order_count: totalOrderCount,
intercepted_order_count: interceptedWaveOrderIds.size,
};
if (unclaimedOrderIds.length === 0) {
@ -1901,10 +1754,8 @@ class PickService extends MainService {
}
// 波次打印校验:存在未打印订单(print_status != fin)时禁止整波领料
// (拦截订单的未打印状态不阻隔领料)
const unprintedOrderIds = [ ...new Set(waveOrders
.filter(item => String(item && item.print_status || '') !== 'fin'
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
.filter(item => String(item && item.print_status || '') !== 'fin')
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
if (unprintedOrderIds.length > 0) {

View File

@ -65,8 +65,8 @@ class ReturnUnpackMethodService extends MainService {
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id),为空时按未知商品登记(is_recognized=0)。
* @param {string} [data.barcode] 扫描条码(仅作记录,不参与商品匹配)。
* @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id)。
* @param {string} [data.barcode] 扫描条码(stock_id 为空时按条码反查商品)。
* @param {number} [data.quantity] 数量。
* @param {string} [data.product_status] 产品状态 normal/damaged。
* @param {string} [data.remark] 备注。
@ -138,19 +138,6 @@ class ReturnUnpackMethodService extends MainService {
return this._call(() => this.service.systems.returnUnpack.submit({ id }), '提交确认失败');
}
/**
* 强制重新录制拆包视频(改,参考 order.packing.forceRecord)。
* 校验仓库录制电脑在线后重置视频状态并推送打印服务 /record/force 触发重新录制。
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @return {Promise<Object>} 统一 success 包装。
*/
async forceRecord(data = {}) {
const { id } = data;
return this._call(() => this.service.systems.returnUnpack.forceRecord({ id }), '强制录制失败');
}
/**
* 分页查询拆包单列表(查,仓库隔离自动注入)。
*
@ -205,36 +192,6 @@ class ReturnUnpackMethodService extends MainService {
);
}
/**
* 分页查询拆包录像列表(查,按拆包单维度校验仓库隔离)。
*
* @param {Object} data 请求体。
* @param {Object} [data.pagination] 分页参数。
* @param {Object} [data.where] 筛选条件(unpack_id 必填,camera_id/status 可选)。
* @param {Object} [data.sort] 排序参数。
* @return {Promise<Object>} 统一 success 包装。
*/
async videoList(data = {}) {
const { service } = this;
const { pagination, sort } = data;
const { where, whereValue } = this.prepareWhereContext(data, {});
const unpackId = Number((whereValue && whereValue.unpack_id) || 0);
return this._call(async () => {
if (!Number.isFinite(unpackId) || unpackId <= 0) {
throw service.systems.returnUnpack.createBusinessError('unpack_id 必填且必须为正整数', 400);
}
// 拆包单仓库隔离校验(不存在 404 / 跨仓库 403)
await service.systems.returnUnpack._findByIdChecked(unpackId);
return service.systems.returnUnpack.videoList(
{ ...where, unpack_id: unpackId },
pagination,
sort
);
}, '查询录像列表失败');
}
/**
* 查询拆包单详情(查)。
*

View File

@ -51,19 +51,11 @@ class WarehouseService extends MainService {
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数
* @param {Object} [data.where] 筛选条件
* @param {Object} [data.sort] 排序参数
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field)
* @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order)
* @return {Promise<Object>} 统一成功包装响应
*/
async list(data = {}) {
const { service } = this;
const { pagination } = data;
const sort = data.sort || {};
const sortParams = {
sortField: sort.sortField || sort.sort_field || 'id',
sortOrder: sort.sortOrder || sort.sort_order || 'DESC',
};
if (this.isPlainObject(data)) {
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
@ -83,7 +75,7 @@ class WarehouseService extends MainService {
},
},
});
const result = await service.systems.stockStore.getWarehouseStock(where, pagination, sortParams);
const result = await service.systems.stockStore.getWarehouseStock(where, pagination);
return this.success('ok', result);
}
@ -526,7 +518,6 @@ class WarehouseService extends MainService {
is_sn_mgmt,
is_shelf_life_mgmt,
is_batch_mgmt,
need_recheck,
prohibited_id,
brand_name,
managementFlags,
@ -569,7 +560,6 @@ class WarehouseService extends MainService {
is_sn_mgmt,
is_shelf_life_mgmt,
is_batch_mgmt,
need_recheck,
prohibited_id,
brand_name,
managementFlags,
@ -653,23 +643,6 @@ class WarehouseService extends MainService {
if (hasSku) {
result = await service.systems.stockStore.saveWarehouseStock(normalizedRow);
} else {
result = await service.systems.stockStore.createWarehouseStock(normalizedRow);
}
// 条码同步:仅当传入非空条码时写入 wms_stock_barcodes 表(未传条码则保留原有条码)
const barcodes = Array.isArray(normalizedRow.barcode) ? normalizedRow.barcode : [];
if (barcodes.length > 0) {
const stockId = (result && result.id != null) ? result.id : normalizedRow.id;
if (stockId != null) {
await service.systems.stockStore.saveWarehouseStockBarcode({
id: stockId,
barcodes,
});
}
}
if (hasSku) {
summary.updated_count += 1;
if (result && result.id != null) {
summary.updated_ids.push(result.id);
@ -677,6 +650,7 @@ class WarehouseService extends MainService {
summary.updated_ids.push(normalizedRow.id);
}
} else {
result = await service.systems.stockStore.createWarehouseStock(normalizedRow);
summary.created_count += 1;
if (result && result.id != null) {
summary.created_ids.push(result.id);
@ -763,7 +737,6 @@ class WarehouseService extends MainService {
?? goodsCode
?? '';
const storeId = pickValue([ 'store_id', 'storeId' ]) ?? this.ctx?.user?.store_id;
const needRecheckRaw = pickValue([ '是否需要复核', 'need_recheck', 'needRecheck' ]);
return {
...row,
@ -778,31 +751,12 @@ class WarehouseService extends MainService {
gross_weight: pickValue([ '毛重', 'gross_weight', 'grossWeight' ]),
tag_price: pickValue([ '标价', 'tag_price', 'tagPrice' ]),
retail_price: pickValue([ '零售价', 'retail_price', 'retailPrice' ]),
...(needRecheckRaw !== undefined && { need_recheck: this._normalizeNeedRecheckValue(needRecheckRaw) }),
barcode: this._normalizeBarcodeField(
pickValue([ '条码', 'bar_code', 'barCode', 'barcodeList', 'barcode_list', 'barcode' ])
),
};
}
/**
* 归一化「是否需要复核」字段值:需要 → Y,不需要 → N。
* 支持中文(需要/需要复核/不需要/无需复核)、Y/N、1/0、布尔值。
*
* @param {string|number|boolean} raw 原始值
* @return {string} 'Y' 或 'N'
*/
_normalizeNeedRecheckValue(raw) {
const normalized = String(raw ?? '').trim();
if ([ '需要', '需要复核', 'Y', 'y', '1' ].includes(normalized) || raw === true) {
return 'Y';
}
if ([ '不需要', '无需', '无需复核', 'N', 'n', '0' ].includes(normalized) || raw === false) {
return 'N';
}
throw new Error(`是否需要复核值不合法: ${raw},仅支持 需要/不需要`);
}
/**
* 归一化条码字段,只接受逗号分隔的字符串格式,返回去重后的条码数组。
* 与 stock.warehouse.export 导出格式对齐(导出使用逗号分隔)。

View File

@ -26,12 +26,11 @@ class StorageDeliveryService extends MainService {
}
/**
* 出库单转订单(兼容转发)。
* @param {Object} data 请求体
* @return {Promise<Object>} 转订单结果
* 出库单跳转订单占位接口(兼容转发)。
* @return {Promise<Object>} 占位失败结果
*/
async toOrder(data = {}) {
return await this.ctx.service.systemMethods.storage.stockout.toOrder(data);
async toOrder() {
return await this.ctx.service.systemMethods.storage.stockout.toOrder();
}
/**

View File

@ -349,9 +349,8 @@ class entryService extends MainService {
}
}
/**
* 入库单商品与收货单商品对照视图(system method 包装层)。
* 支持传入多个收货单ID:多个收货单明细先合并为一个整体,再与入库单做一次对照,
* 每个入库明细仅输出一行(含合并收货数量与各收货单来源明细)。
* 入库单商品与收货单商品逐行对照视图(system method 包装层)。
* 支持传入多个收货单ID进行批量对照预览。
* @param {Object} data 请求体
* @param {number} data.entry_order_id 入库单ID
* @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用)

View File

@ -13,9 +13,9 @@ class InventoryMethodService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,export,exportTaskProgress,listByStockId';
const _noNeedLog = 'list,export,exportTaskProgress,listByStockId';
const _noNeedAuth = 'list,quickPutaway,directPutaway,export,exportTaskProgress,listByStockId';
const _noNeedRight = 'list,export,exportTaskProgress';
const _noNeedLog = 'list,export,exportTaskProgress';
const _noNeedAuth = 'list,quickPutaway,export,exportTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -48,39 +48,10 @@ class InventoryMethodService extends MainService {
return this.success('ok', result);
}
/**
* 提取 stock_query 虚拟筛选条件(与订单查询一致)。
* 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。
* @param {Object} whereInput 原始 where 条件。
* @return {{ where: Object, stockQuery: string }} 清洗后的 where 与 stock_query 值。
*/
extractStockQueryVirtualFilter(whereInput = {}) {
const normalizedWhere = this.isPlainObject(whereInput)
? { ...whereInput }
: {};
const stockQueryCondition = normalizedWhere.stock_query;
delete normalizedWhere.stock_query;
if (!stockQueryCondition) {
return { where: normalizedWhere, stockQuery: '' };
}
const rawValue = this.isPlainObject(stockQueryCondition)
&& Object.prototype.hasOwnProperty.call(stockQueryCondition, 'value')
? stockQueryCondition.value
: stockQueryCondition;
const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : '';
return { where: normalizedWhere, stockQuery };
}
/**
* 库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。
* @param {Object} data 请求体
* @param {Object} [data.where] 查询条件
* @param {Object} [data.where.stock_query] 虚拟筛选字段:按商品编码(item_code)/名称(item_name)/货物编码(goods_code)/条码(barcode)/SKU ID 模糊匹配,如 { operator: 'like', value: '111' }
* @param {Object} [data.pagination] 分页参数 { page, pageSize }
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
* @param {boolean} [data.group_by_batch=false] 是否按批次查询
@ -89,26 +60,8 @@ class InventoryMethodService extends MainService {
async list(data = {}) {
const { service } = this;
const { pagination, sort, group_by_batch } = data;
const { where: cleanedWhere, stockQuery } = this.extractStockQueryVirtualFilter(data.where);
data.where = cleanedWhere;
this.prepareWhereContext(data);
const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch, stockQuery);
return this.success('ok', result);
}
/**
* 按商品查询库存明细:传入 stock_id,返回该商品在当前仓库下所有数量大于 1 的 storage 行。
* 支持两种模式:group_by_space=false 不汇总(逐条明细,含效期/预警字段,默认);
* group_by_space=true 按库位汇总数量(不含批次/效期/预警字段)。
* @param {Object} data 请求体
* @param {number} data.stock_id 商品SKU ID(必填)
* @param {boolean} [data.group_by_space=false] 是否按库位汇总
* @return {Promise<Object>} 统一 success 包装
*/
async listByStockId(data = {}) {
const { service } = this;
const groupBySpace = data.group_by_space === true || data.group_by_space === 'true';
const result = await service.systems.storage.inventory.getStorageListByStockId(data.stock_id, groupBySpace);
const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch);
return this.success('ok', result);
}
@ -125,21 +78,6 @@ class InventoryMethodService extends MainService {
const result = await service.systems.storage.inventory.quickPutaway({ receiving_id });
return this.success('ok', result);
}
/**
* 收货单直入库存(一步完成):直接写 wms_storage 库位库存并生成入库单。
* 入库单明细与收货明细一一对应,按收货明细的库位 space_id 入库。
* 要求货主配置中允许收货单直入库存,否则直接返回失败。
* @param {Object} data 请求体
* @param {number} data.receiving_id 收货单ID(必填)
* @return {Promise<Object>} 统一 success 包装,返回创建的入库单信息
*/
async directPutaway(data = {}) {
const { service } = this;
const { receiving_id } = data;
const result = await service.systems.storage.inventory.directPutaway({ receiving_id });
return this.success('ok', result);
}
/**
* 提交库存导出异步任务(入参与 list 一致,复用相同的 where/sort/group_by_batch 语义)。
*

View File

@ -82,8 +82,6 @@ class StorageStockoutService extends MainService {
const finalWhere = { [Op.and]: andConditions };
const { count, rows } = await OrderStockoutModel.findAndCountAll({
// 必须返回 id:前端行点击/详情/打印/确认等均依赖 row.id(与 receiving 等列表保持一致)
attributes: { exclude: [ 'warehouse_name' ] },
where: finalWhere,
order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]],
limit: pageSize,
@ -91,22 +89,6 @@ class StorageStockoutService extends MainService {
raw: true,
});
// 补充货主名称:store_name 快照为空时按 store_id 解析 wms_store.company_name
const storeIds = [ ...new Set(rows.map(row => Number(row.store_id)).filter(id => Number.isFinite(id) && id > 0)) ];
if (storeIds.length > 0) {
const stores = await ctx.model.Store.findAll({
where: { id: { [Op.in]: storeIds } },
attributes: [ 'id', 'company_name' ],
raw: true,
});
const nameMap = new Map(stores.map(item => [ Number(item.id), String(item.company_name || '') ]));
for (const row of rows) {
if (!row.store_name) {
row.store_name = nameMap.get(Number(row.store_id)) || '';
}
}
}
return this.success('ok', {
list: rows,
pagination: {
@ -121,309 +103,11 @@ class StorageStockoutService extends MainService {
}
/**
* 出库单转订单。
*
* 将非订单出库单(wms_order_stockout)转为正式销售订单:
* 1. 新订单 create_channel 固定为 STOCKOUT;
* 2. 释放出库单占用的库存锁定,转由新订单重新锁定;
* 3. 转单成功后原出库单置为 CANCELLED,并记录已转订单号(幂等)。
*
* 仅 CREATED / PENDING 状态的出库单允许转单;建单失败时自动补偿恢复出库单锁定。
*
* @param {Object} data 请求体
* @param {number} data.id 出库单ID(必填)
* @param {string} [data.delivery_order_code] 新订单号,不传自动生成(SK 前缀)
* @param {Object} [data.receiverInfo] 收件人信息(name/mobile/tel/province/city/area/town/detailAddress/zipCode)
* @return {Promise<Object>} 统一成功/失败包装响应
* 出库单转订单占位接口。
* @return {Promise<Object>} 统一失败包装响应
*/
async toOrder(data = {}) {
const { ctx } = this;
const id = Number(data.id || 0);
if (!id) {
return this.fail('缺少出库单ID');
}
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
if (warehouseId <= 0) {
return this.fail('缺少仓库上下文');
}
const order = await ctx.model.OrderStockout.findOne({
where: { id, warehouse_id: warehouseId, deleted_at: null },
});
if (!order) {
return this.fail('出库单不存在');
}
// 幂等:已转订单的出库单直接返回原订单信息
const currentExtendProps =
order.extend_props && typeof order.extend_props === 'object' && !Array.isArray(order.extend_props)
? order.extend_props
: {};
if (currentExtendProps.transferred_order_id) {
return this.success('出库单已转订单', {
id: order.id,
stockout_order_code: order.stockout_order_code,
order_id: currentExtendProps.transferred_order_id,
delivery_order_code: currentExtendProps.transferred_order_code || '',
});
}
if (![ 'CREATED', 'PENDING' ].includes(order.order_status)) {
return this.fail(`出库单当前状态(${order.order_status})不允许转订单`);
}
const items = await ctx.model.OrderStockoutItems.findAll({
where: { order_id: order.id },
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (!items || items.length === 0) {
return this.fail('出库单没有明细,无法转订单');
}
// 收货信息:出库单已存的 receiver_* 字段为基础,接口传入的非空 receiverInfo 字段覆盖
const storedReceiverInfo = {
company: order.receiver_company || '',
name: order.receiver_name || '',
zipCode: order.receiver_zip_code || '',
tel: order.receiver_tel || '',
mobile: order.receiver_mobile || '',
email: order.receiver_email || '',
countryCode: order.receiver_country_code || '',
province: order.receiver_province || '',
city: order.receiver_city || '',
area: order.receiver_area || '',
town: order.receiver_town || '',
detailAddress: order.receiver_detail_address || '',
};
const passedReceiverInfo = data.receiverInfo && typeof data.receiverInfo === 'object'
? data.receiverInfo
: {};
const receiverInfo = { ...storedReceiverInfo };
for (const [ key, value ] of Object.entries(passedReceiverInfo)) {
if (value !== undefined && value !== null && String(value).trim() !== '') {
receiverInfo[key] = String(value).trim();
}
}
// 收货信息必填校验:name、(tel/mobile) 其一、省市区镇详细地址,缺失禁止转订单
const missingFields = [];
if (!String(receiverInfo.name || '').trim()) {
missingFields.push('name(收件人姓名)');
}
const receiverTel = String(receiverInfo.tel || '').trim();
const receiverMobile = String(receiverInfo.mobile || '').trim();
if (!receiverTel && !receiverMobile) {
missingFields.push('tel/mobile(固定电话或移动电话至少一项)');
}
const addressFields = [
[ 'province', '省' ],
[ 'city', '市' ],
[ 'area', '区' ],
[ 'town', '镇' ],
[ 'detailAddress', '详细地址' ],
];
for (const [ key, label ] of addressFields) {
if (!String(receiverInfo[key] || '').trim()) {
missingFields.push(`${key}(${label})`);
}
}
if (missingFields.length > 0) {
return this.fail(`收货信息缺失,不能转订单:缺少 ${missingFields.join('、')}`);
}
const stockStoreService = ctx.service.systems.stockStore;
const lockMeta = {
orderType: 'QM_STOCKOUT',
orderNo: order.stockout_order_code,
orderId: order.id,
};
// 第一步:释放出库单占用的库存锁定(新订单创建时会重新锁定)
const releaseTransaction = await ctx.model.transaction();
try {
for (const item of items) {
const qty = Number(item.plan_qty) || 0;
if (qty <= 0) continue;
const releaseResult = await stockStoreService.lockItemStorages(
item.stock_id,
-qty,
releaseTransaction,
null,
{ ...lockMeta, remark: '出库单转订单释放锁定' }
);
if (!releaseResult.success) {
throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`);
}
}
await releaseTransaction.commit();
} catch (err) {
await releaseTransaction.rollback().catch(() => {});
ctx.logger.error(`[stockout.toOrder] 释放出库单锁定失败: ${err.message}`);
return this.fail(`转订单失败:${err.message}`);
}
// 第二步:创建订单(create_channel=STOCKOUT,内部重新锁定库存)
// 快递编码沿用出库单已解析的 express_code(系统快递编码),平台不传 sourcePlatformCode 走兜底平台
const deliveryOrderCode = String(data.delivery_order_code || '').trim()
|| `SK${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`;
const orderLines = items.map((item, idx) => ({
itemCode: item.item_code || '',
itemId: Number(item.item_id) || 0,
itemName: item.item_name || '',
planQty: Number(item.plan_qty) || 0,
stockId: Number(item.stock_id) || 0,
inventoryType: item.inventory_type || '',
orderLineNo: String(item.order_line_no || idx + 1),
ownerCode: item.owner_code || '',
sourceOrderCode: order.stockout_order_code,
}));
const addOrderData = {
request: {
deliveryOrder: {
deliveryOrderCode,
orderType: order.order_type || 'QTCK',
createChannel: 'STOCKOUT',
logisticsCode: order.express_code || '',
sourcePlatformCode: order.source_platform_code || '',
receiverInfo,
remark: order.remark || '',
sourceOrderCode: order.stockout_order_code,
},
orderLines: { orderLine: orderLines },
},
};
const info = {
storeId: order.store_id,
warehouseId,
appKey: (ctx.user && ctx.user.app_key) || '',
};
let addOrderResult = null;
try {
addOrderResult = await ctx.service.systems.deliveryOrder.addOrder(addOrderData, info, 'STOCKOUT');
} catch (err) {
addOrderResult = { success: false, message: err.message, data: null };
}
const orderId = addOrderResult && addOrderResult.data && addOrderResult.data.orderId;
const isDuplicate = !!(addOrderResult && addOrderResult.success && addOrderResult.message === '订单已存在');
if (!addOrderResult || !addOrderResult.success || !orderId || isDuplicate) {
// 建单失败/订单号重复:补偿恢复出库单锁定
await this._restoreStockoutLocks(stockStoreService, items, lockMeta, ctx);
return this.fail(`转订单失败:${(addOrderResult && addOrderResult.message) || '订单创建失败'}`);
}
// 第三步:标记出库单已转订单(状态推进到 TRANSFERRED,该状态下禁止一键出库)
try {
await ctx.model.OrderStockout.update(
{
order_status: 'TRANSFERRED',
sync_message: `已转订单 ${deliveryOrderCode}`,
extend_props: {
...currentExtendProps,
transferred_order_id: orderId,
transferred_order_code: deliveryOrderCode,
transferred_at: new Date(),
},
updated_at: new Date(),
},
{ where: { id: order.id } }
);
} catch (updateErr) {
// 订单已创建成功,仅出库单标记失败:记录告警,不回滚订单
ctx.logger.error(`[stockout.toOrder] 标记出库单已转失败: ${updateErr.message}`);
}
await this._writeStockoutOperationLog(
order,
'STOCKOUT_TO_ORDER',
`出库单已转订单 ${deliveryOrderCode}(order_id=${orderId}),已释放库存锁定`
);
return this.success('转订单成功', {
id: order.id,
stockout_order_code: order.stockout_order_code,
order_id: orderId,
delivery_order_code: deliveryOrderCode,
step: addOrderResult.data.step,
});
}
/**
* 转订单失败时恢复出库单库存锁定(补偿)。
* @param {Object} stockStoreService 库存服务
* @param {Array} items 出库单明细
* @param {Object} lockMeta 锁元信息
* @param {Object} ctx 请求上下文
* @return {Promise<void>} 无返回值
*/
async _restoreStockoutLocks(stockStoreService, items, lockMeta, ctx) {
const restoreTransaction = await ctx.model.transaction();
try {
for (const item of items) {
const qty = Number(item.plan_qty) || 0;
if (qty <= 0) continue;
const restoreResult = await stockStoreService.lockItemStorages(
item.stock_id,
qty,
restoreTransaction,
null,
{ ...lockMeta, remark: '出库单转订单失败恢复锁定' }
);
if (!restoreResult.success) {
throw new Error(`库存${item.stock_id}恢复锁定失败: ${restoreResult.error}`);
}
}
await restoreTransaction.commit();
} catch (err) {
await restoreTransaction.rollback().catch(() => {});
ctx.logger.error(`[stockout.toOrder] 恢复出库单锁定失败: ${err.message}`);
}
}
/**
* 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。
* @param {Object} order 出库单实例或行
* @param {string} operationCode 操作编码
* @param {string} message 日志内容
* @param {Object} [options={}] 选项,可含 transaction
* @return {Promise<void>} 无返回值
*/
async _writeStockoutOperationLog(order, operationCode, message, options = {}) {
const { ctx } = this;
const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
if (!opLogService || typeof opLogService.createOperationLogs !== 'function') {
ctx.logger.warn('[stockout] 操作日志服务不可用,跳过记录');
return;
}
const user = ctx.user || {};
try {
await opLogService.createOperationLogs([
{
businessType: 'stockout',
businessId: order.id,
operationCode,
operator: {
id: user.employees_id ?? user.id ?? null,
name: String(user.employees_name || user.real_name || user.name || 'system'),
},
extras: {
warehouseId: Number(ctx.user && ctx.user.store_id) || order.warehouse_id || null,
message,
externalLogType: 'NONE',
},
},
], { transaction: options.transaction });
} catch (err) {
ctx.logger.warn(`[stockout] 写操作日志失败: ${err.message}`);
}
async toOrder() {
return this.fail('接口暂未开放');
}
/**
@ -483,91 +167,10 @@ class StorageStockoutService extends MainService {
});
}
/**
* 查询出库单操作日志(分页)。
* 日志业务类型 business_type=stockout,business_id=出库单ID;
* 覆盖创建/审核/转订单/确认/修改/取消等操作(STOCKOUT_* 操作编码)。
* @param {Object} data 请求体
* @param {number} [data.id] 出库单ID(与 stockout_order_code 至少传一个)
* @param {string} [data.stockout_order_code] 出库单号
* @param {Object} [data.pagination] 分页对象,支持 page / pageSize(或 page_size)
* @return {Promise<Object>} 统一成功包装响应 { list, pagination }
*/
async listLogs(data = {}) {
const { ctx, service } = this;
const requestData = data && typeof data === 'object' ? data : {};
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const id = Number(requestData.id || 0);
const stockoutOrderCode = String(requestData.stockout_order_code || '').trim();
// 分页参数:兼容顶层 page/pageSize(与订单日志 order.queryOrderLogs 一致)与 pagination 对象两种写法
const pagination = requestData.pagination && typeof requestData.pagination === 'object'
? requestData.pagination
: {};
const page = requestData.page ?? pagination.page;
const pageSize = requestData.pageSize ?? pagination.pageSize ?? pagination.page_size;
if (!id && !stockoutOrderCode) {
return this.fail('id 或 stockout_order_code 至少传一个');
}
const emptyResult = {
list: [],
pagination: {
page: Number.parseInt(page, 10) || 1,
pageSize: Number.parseInt(pageSize, 10) || 20,
total: 0,
totalPages: 0,
},
};
// 定位出库单ID(日志 business_id 存的是出库单ID)
let stockoutId = id;
if (!stockoutId) {
const order = await ctx.model.OrderStockout.findOne({
where: {
stockout_order_code: stockoutOrderCode,
warehouse_id: warehouseId,
deleted_at: null,
},
attributes: [ 'id' ],
raw: true,
});
if (!order || !order.id) {
return this.success('ok', {
data: emptyResult,
code: 200,
});
}
stockoutId = Number(order.id);
}
try {
const result = await service.systems.operationLog.queryStockoutLogs({
id: stockoutId,
page,
pageSize,
warehouseId,
});
return this.success('ok', {
data: result,
code: 200,
});
} catch (e) {
// 与订单日志接口一致:查询异常时以 200 包装返回错误信息
return this.success(e.message, {
code: 200,
});
}
}
/**
* 出库单确认(直出)。
* 不改变内部库存,直接按出库单明细的计划数量确认。
* 出站同步 taobao.qimen.stockout.confirm 成功后,释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水),
* 状态才推进到 COMPLETED。
* 出站同步 taobao.qimen.stockout.confirm 成功后,状态才推进到 COMPLETED。
* 要求 express_code 已填写,否则拒绝确认。
* @param {Object} data 请求体
* @param {number} data.id 出库单ID(必填)
@ -692,56 +295,10 @@ class StorageStockoutService extends MainService {
// 第三步:根据出站结果更新状态
if (qimenSuccess) {
// 直出确认:释放出库单占用的库存锁定(QM_STOCKOUT,负数量释放并自动写 UNLOCK 流水),
// 与状态推进到 COMPLETED 在同一事务内完成,失败回滚可重试。
const finalizeTransaction = await ctx.model.transaction();
try {
let totalReleaseQty = 0;
for (const item of items) {
const qty = Number(item.plan_qty) || 0;
if (qty <= 0) continue;
const releaseResult = await ctx.service.systems.stockStore.lockItemStorages(
item.stock_id,
-qty,
finalizeTransaction,
null,
{
orderType: 'QM_STOCKOUT',
orderNo: order.stockout_order_code,
orderId: order.id,
remark: '出库单确认释放锁定',
}
);
if (!releaseResult.success) {
// 已释放过(锁定不足)视为幂等成功,避免阻断重试
const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存');
if (alreadyReleased) {
ctx.logger.warn(`[stockout.confirm] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`);
continue;
}
throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`);
}
totalReleaseQty += qty;
}
await this._writeStockoutOperationLog(
order,
'STOCKOUT_CONFIRM',
`出库单确认完成(直出),释放锁定库存 ${totalReleaseQty}`,
{ transaction: finalizeTransaction }
);
await ctx.model.OrderStockout.update(
{ order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: '', updated_at: new Date() },
{ where: { id: order.id }, transaction: finalizeTransaction }
);
await finalizeTransaction.commit();
} catch (err) {
await finalizeTransaction.rollback().catch(() => {});
ctx.logger.error(`[stockout.confirm] 释放锁定失败: ${order.stockout_order_code} - ${err.message}`);
return this.fail(`确认失败:${err.message}`);
}
await ctx.model.OrderStockout.update(
{ order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: '', updated_at: new Date() },
{ where: { id: order.id } }
);
ctx.logger.info(`[stockout.confirm] 确认完成: ${order.stockout_order_code}`);
return this.success('确认成功', {
@ -765,104 +322,6 @@ class StorageStockoutService extends MainService {
return this.fail(`出站同步失败: ${qimenMessage || '未发起出站通知'}`);
}
/**
* 出库单取消。
*
* 仅 CREATED / PENDING 状态允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,
* 写 UNLOCK 流水),状态置为 CANCELLED,并写 wms_operation_log 操作日志。
* 已转订单(TRANSFERRED)与已完成(COMPLETED)状态禁止取消。
*
* @param {Object} data 请求体
* @param {number} data.id 出库单ID(必填)
* @return {Promise<Object>} 统一成功/失败包装响应
*/
async cancel(data = {}) {
const { ctx } = this;
const id = Number(data.id || 0);
if (!id) {
return this.fail('缺少出库单ID');
}
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
if (warehouseId <= 0) {
return this.fail('缺少仓库上下文');
}
const order = await ctx.model.OrderStockout.findOne({
where: { id, warehouse_id: warehouseId, deleted_at: null },
});
if (!order) {
return this.fail('出库单不存在');
}
if (!order.canCancel || !order.canCancel()) {
return this.fail(`出库单当前状态(${order.order_status})不允许取消`);
}
const items = await ctx.model.OrderStockoutItems.findAll({
where: { order_id: order.id },
raw: true,
});
// 释放创建时占用的库存锁定 + 状态置 CANCELLED + 操作日志,同一事务
const cancelTransaction = await ctx.model.transaction();
try {
let releasedQty = 0;
for (const item of items) {
const qty = Number(item.plan_qty) || 0;
if (qty <= 0) continue;
const releaseResult = await ctx.service.systems.stockStore.lockItemStorages(
item.stock_id,
-qty,
cancelTransaction,
null,
{
orderType: 'QM_STOCKOUT',
orderNo: order.stockout_order_code,
orderId: order.id,
remark: '出库单取消释放锁定',
}
);
if (!releaseResult.success) {
// 已释放过(锁定不足)视为幂等成功,避免阻断
const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存');
if (alreadyReleased) {
ctx.logger.warn(`[stockout.cancel] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`);
continue;
}
throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`);
}
releasedQty += qty;
}
await ctx.model.OrderStockout.update(
{ order_status: 'CANCELLED', sync_message: '已取消', updated_at: new Date() },
{ where: { id: order.id }, transaction: cancelTransaction }
);
await this._writeStockoutOperationLog(
order,
'STOCKOUT_CANCEL',
`出库单已取消,释放锁定库存 ${releasedQty}`,
{ transaction: cancelTransaction }
);
await cancelTransaction.commit();
} catch (err) {
await cancelTransaction.rollback().catch(() => {});
ctx.logger.error(`[stockout.cancel] 取消失败: ${order.stockout_order_code} - ${err.message}`);
return this.fail(`取消失败:${err.message}`);
}
ctx.logger.info(`[stockout.cancel] 取消完成: ${order.stockout_order_code}`);
return this.success('取消成功', {
id: order.id,
stockout_order_code: order.stockout_order_code,
order_status: 'CANCELLED',
});
}
/**
* 更新出库单快递和运单号。
* 用于在确认前填写 express_code / waybill_code / waybill_codes。
@ -933,169 +392,6 @@ class StorageStockoutService extends MainService {
waybill_codes: order.waybill_codes,
});
}
/**
* 修改出库单信息。
*
* 可修改范围:收件人(name/tel/mobile 等)、地址(province/city/area/town/detailAddress 等)、
* 快递编码(express_code,自动解析 express_name)、来源平台(source_platform_code/name)。
* 未传入的字段不修改;快递编码与平台相关字段不传即保持原值。
*
* 限制:仅 CREATED / PENDING 状态允许修改;修改后收货信息不完整(name、(tel/mobile) 其一、
* 省市区镇详细地址缺任一)时禁止提交。
*
* @param {Object} data 请求体
* @param {number} data.id 出库单ID(必填)
* @param {string} [data.name] 收件人姓名
* @param {string} [data.tel] 固定电话
* @param {string} [data.mobile] 移动电话
* @param {string} [data.company] 公司名称
* @param {string} [data.email] 电子邮箱
* @param {string} [data.zipCode] 邮编
* @param {string} [data.countryCode] 国家二字码
* @param {string} [data.province] 省份
* @param {string} [data.city] 城市
* @param {string} [data.area] 区/县
* @param {string} [data.town] 镇/街道
* @param {string} [data.detailAddress] 详细地址
* @param {string} [data.receiver_id] 收件人证件号
* @param {string} [data.express_code] 快递公司编码(自动解析 express_name)
* @param {string} [data.source_platform_code] 来源平台编码
* @param {string} [data.source_platform_name] 来源平台名称
* @return {Promise<Object>} 统一成功/失败包装响应
*/
async updateInfo(data = {}) {
const { ctx } = this;
const id = Number(data.id || 0);
if (!id) {
return this.fail('缺少出库单ID');
}
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
if (warehouseId <= 0) {
return this.fail('缺少仓库上下文');
}
const order = await ctx.model.OrderStockout.findOne({
where: { id, warehouse_id: warehouseId, deleted_at: null },
});
if (!order) {
return this.fail('出库单不存在');
}
if (![ 'CREATED', 'PENDING' ].includes(order.order_status)) {
return this.fail(`出库单当前状态(${order.order_status})不允许修改`);
}
const updateData = { updated_at: new Date() };
const changedLabels = [];
// 收件人 / 地址字段:传入才更新,空串置 NULL
const receiverFieldMap = {
receiver_name: [ 'name', '收件人姓名' ],
receiver_tel: [ 'tel', '固定电话' ],
receiver_mobile: [ 'mobile', '移动电话' ],
receiver_company: [ 'company', '公司名称' ],
receiver_email: [ 'email', '电子邮箱' ],
receiver_zip_code: [ 'zipCode', '邮编' ],
receiver_country_code: [ 'countryCode', '国家' ],
receiver_province: [ 'province', '省份' ],
receiver_city: [ 'city', '城市' ],
receiver_area: [ 'area', '区县' ],
receiver_town: [ 'town', '镇街道' ],
receiver_detail_address: [ 'detailAddress', '详细地址' ],
receiver_id: [ 'receiver_id', '证件号' ],
};
for (const [ column, [ param, label ]] of Object.entries(receiverFieldMap)) {
if (data[param] !== undefined) {
updateData[column] = data[param] === null
? null
: String(data[param]).trim() || null;
changedLabels.push(label);
}
}
// 快递编码:传入才更新,并自动解析 express_name(与 updateExpress 同口径)
if (data.express_code !== undefined) {
const expressCode = String(data.express_code || '').trim();
if (expressCode) {
let expressName = '';
try {
const expressMap = await ctx.service.systems.setting.express.getSystemExpressMap();
const info = expressMap.get(expressCode.toUpperCase());
expressName = info ? info.name : '';
} catch (e) {
ctx.logger.warn('[updateInfo] 解析快递名称失败: ' + e.message);
}
updateData.express_code = expressCode;
updateData.express_name = expressName;
} else {
updateData.express_code = null;
updateData.express_name = null;
}
changedLabels.push('快递编码');
}
// 来源平台:传入才更新,空串置 NULL
if (data.source_platform_code !== undefined) {
updateData.source_platform_code = String(data.source_platform_code || '').trim() || null;
changedLabels.push('来源平台');
}
if (data.source_platform_name !== undefined) {
updateData.source_platform_name = String(data.source_platform_name || '').trim() || null;
if (!changedLabels.includes('来源平台')) {
changedLabels.push('来源平台');
}
}
// 修改后的收货信息完整性校验:name、(tel/mobile) 其一、省市区镇详细地址必填,缺失禁止提交
const mergedReceiver = {
name: updateData.receiver_name !== undefined ? updateData.receiver_name : order.receiver_name,
tel: updateData.receiver_tel !== undefined ? updateData.receiver_tel : order.receiver_tel,
mobile: updateData.receiver_mobile !== undefined ? updateData.receiver_mobile : order.receiver_mobile,
province: updateData.receiver_province !== undefined ? updateData.receiver_province : order.receiver_province,
city: updateData.receiver_city !== undefined ? updateData.receiver_city : order.receiver_city,
area: updateData.receiver_area !== undefined ? updateData.receiver_area : order.receiver_area,
town: updateData.receiver_town !== undefined ? updateData.receiver_town : order.receiver_town,
detailAddress: updateData.receiver_detail_address !== undefined ? updateData.receiver_detail_address : order.receiver_detail_address,
};
const missingFields = [];
if (!String(mergedReceiver.name || '').trim()) {
missingFields.push('name(收件人姓名)');
}
if (!String(mergedReceiver.tel || '').trim() && !String(mergedReceiver.mobile || '').trim()) {
missingFields.push('tel/mobile(固定电话或移动电话至少一项)');
}
const addressFields = [
[ 'province', '省' ],
[ 'city', '市' ],
[ 'area', '区' ],
[ 'town', '镇' ],
[ 'detailAddress', '详细地址' ],
];
for (const [ key, label ] of addressFields) {
if (!String(mergedReceiver[key] || '').trim()) {
missingFields.push(`${key}(${label})`);
}
}
if (missingFields.length > 0) {
return this.fail(`收货信息缺失,禁止提交:缺少 ${missingFields.join('、')}`);
}
await ctx.model.OrderStockout.update(updateData, { where: { id: order.id } });
const updated = await ctx.model.OrderStockout.findByPk(order.id, { raw: true });
if (changedLabels.length > 0) {
await this._writeStockoutOperationLog(
order,
'STOCKOUT_UPDATE_INFO',
`修改出库单信息:${changedLabels.join('、')}`
);
}
return this.success('修改成功', updated);
}
}
module.exports = StorageStockoutService;

View File

@ -29,9 +29,9 @@ class StoreWarehouseStoreService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,createUser,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity';
const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity';
const _noNeedLog = '*';
const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,createUser,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity';
const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportPrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -421,43 +421,6 @@ class StoreWarehouseStoreService extends MainService {
}
}
/**
* 为货主创建用户:按用户名查找账号,不存在则注册并随机生成密码返回,
* 两种情况统一完成货主工号绑定与货主管理员角色(id=5)授权。
*
* @param {Object} data 请求数据。
* @param {string} data.username 用户名(必填)。
* @param {number|string} data.store_id 货主 ID(必填)。
* @return {Promise<Object>} 统一响应结果。
*/
async createUser(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.createUser !== 'function') {
return this.fail('创建货主用户失败', {
code: 500,
});
}
try {
const requestData = normalizeStoreWarehousePayload(data);
const {
username,
store_id,
} = requestData;
const result = await targetService.createUser({
username,
store_id,
});
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '创建货主用户失败', {
code: Number(error.code) || 500,
});
}
}
/**
* 提交面单余额变更日志导出任务。
* 入参条件与 queryPrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。

View File

@ -416,65 +416,28 @@ class AfterSaleService extends Service {
const { ctx, app } = this;
try {
// 1. 查询订单主记录:优先按订单 id 序列表(wms_order_id_location_{warehouseId})
// 定位订单所在车道直接查对应分表,未命中再按 current → history → dispatch → outsourced
// 遍历回退,最后回退基表(存量订单)
// 1. 查询订单主记录(优先主表,再尝试工厂分表)
let order = null;
let preferredLane = null;
const factory = ctx.model.OrderDeliveryFactory;
try {
order = await ctx.model.OrderDelivery.findOne({
where: { id: orderDeliveryId },
raw: true,
});
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`);
}
if (factory && typeof factory.getCurrentModel === 'function') {
const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ];
const laneGetters = {
current: () => factory.getCurrentModel(warehouseId),
history: () => factory.getHistoryModel(warehouseId),
dispatch: () => factory.getDispatchModel(warehouseId),
outsourced: () => factory.getOutsourcedModel(warehouseId),
};
// 序列表定位优先:命中车道先查对应分表
if (!order && ctx.model.OrderDeliveryFactory) {
try {
if (typeof factory.getOrderLocation === 'function') {
const location = await factory.getOrderLocation(orderDeliveryId, warehouseId);
if (location && laneGetters[location]) {
preferredLane = String(location);
}
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 序列表定位失败: ${err.message}`);
}
const orderedLanes = preferredLane
? [ preferredLane, ...laneLabels.filter(label => label !== preferredLane) ]
: laneLabels;
for (const lane of orderedLanes) {
try {
const model = await laneGetters[lane]();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
if (factoryModel) {
order = await factoryModel.findOne({
where: { id: orderDeliveryId },
raw: true,
});
if (row) {
order = row;
break;
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 分表 ${lane} 查询失败: ${err.message}`);
}
}
}
// 分表均未命中:回退基表(存量订单)
if (!order) {
try {
order = await ctx.model.OrderDelivery.findOne({
where: { id: orderDeliveryId },
raw: true,
});
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`);
ctx.logger.warn(`[_resolveOrderDetail] 工厂模型查询失败: ${err.message}`);
}
}
@ -540,85 +503,63 @@ class AfterSaleService extends Service {
}
}
// 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询(序列表定位车道优先)
// 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询
if (orderItems.length === 0 && ctx.model.OrderItemsFactory) {
try {
const itemsFactory = ctx.model.OrderItemsFactory;
const itemsLaneLabels = [ 'current', 'history', 'dispatch' ];
const itemsLaneGetters = {
current: () => itemsFactory.getCurrentModel(warehouseId),
history: () => itemsFactory.getHistoryModel(warehouseId),
dispatch: () => itemsFactory.getDispatchModel(warehouseId),
};
const orderedItemsLanes = preferredLane && itemsLaneGetters[preferredLane]
? [ preferredLane, ...itemsLaneLabels.filter(label => label !== preferredLane) ]
: itemsLaneLabels;
let dbItems = [];
for (const lane of orderedItemsLanes) {
try {
const itemsModel = await itemsLaneGetters[lane]();
if (!itemsModel || typeof itemsModel.findAll !== 'function') continue;
const laneRows = await itemsModel.findAll({
where: { order_id: orderDeliveryId },
raw: true,
});
if (laneRows && laneRows.length > 0) {
dbItems = laneRows;
break;
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 商品明细分表 ${lane} 查询失败: ${err.message}`);
}
}
if (dbItems.length > 0) {
// 收集 stock_id 用于批量查库存详情
const stockIds = dbItems
.map(item => Number(item.stock_id))
.filter(id => Number.isInteger(id) && id > 0);
// 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性)
const stockDetailsMap = new Map();
if (stockIds.length > 0) {
try {
const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
warehouseId,
cacheTTL: 300,
});
for (const detail of details) {
stockDetailsMap.set(detail.id, detail);
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`);
}
}
orderItems = dbItems.map(item => {
const stock = stockDetailsMap.get(Number(item.stock_id)) || {};
return {
id: item.id,
order_line_no: item.order_line_no || '',
item_code: item.item_code || stock.item_code || '',
item_name: item.item_name || stock.item_name || '',
sku_property: stock.sku_property || '',
quantity: stock.quantity || 0,
locked_quantity: stock.locked_quantity || 0,
is_batch_mgmt: stock.is_batch_mgmt || 'N',
is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N',
is_images: stock.is_images || 'N',
store_id: stock.store_id || null,
packing_requirements: stock.packing_requirements || '',
stock_unit: stock.stock_unit || '',
image_url: stock.image_url || [],
barcodes: stock.barcodes || [],
plan_qty: item.plan_qty || 0,
stock_id: item.stock_id || null,
order_item_id: item.id,
order_id: orderDeliveryId,
};
const itemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
if (itemsModel) {
const dbItems = await itemsModel.findAll({
where: { order_id: orderDeliveryId },
raw: true,
});
ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`);
if (dbItems && dbItems.length > 0) {
// 收集 stock_id 用于批量查库存详情
const stockIds = dbItems
.map(item => Number(item.stock_id))
.filter(id => Number.isInteger(id) && id > 0);
// 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性)
const stockDetailsMap = new Map();
if (stockIds.length > 0) {
try {
const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
warehouseId,
cacheTTL: 300,
});
for (const detail of details) {
stockDetailsMap.set(detail.id, detail);
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`);
}
}
orderItems = dbItems.map(item => {
const stock = stockDetailsMap.get(Number(item.stock_id)) || {};
return {
id: item.id,
order_line_no: item.order_line_no || '',
item_code: item.item_code || stock.item_code || '',
item_name: item.item_name || stock.item_name || '',
sku_property: stock.sku_property || '',
quantity: stock.quantity || 0,
locked_quantity: stock.locked_quantity || 0,
is_batch_mgmt: stock.is_batch_mgmt || 'N',
is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N',
is_images: stock.is_images || 'N',
store_id: stock.store_id || null,
packing_requirements: stock.packing_requirements || '',
stock_unit: stock.stock_unit || '',
image_url: stock.image_url || [],
barcodes: stock.barcodes || [],
plan_qty: item.plan_qty || 0,
stock_id: item.stock_id || null,
order_item_id: item.id,
order_id: orderDeliveryId,
};
});
ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`);
}
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`);

View File

@ -830,10 +830,7 @@ class DeliveryOrderService extends Service {
customShopName: shopNick || '',
address: address || '',
weight: itemsInfo.total_weight || null,
// 从订单商品聚合的违禁品类型ID(StockWarehouse.prohibited_id 去重)
prohibitedTypeIds: itemsInfo && Array.isArray(itemsInfo.prohibited_type_ids)
? itemsInfo.prohibited_type_ids
: null,
prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合
}
);
@ -1306,7 +1303,7 @@ class DeliveryOrderService extends Service {
orderFlag,
sourcePlatformCode,
sourcePlatformName,
oaidOrderSourceCode,
createTime,
placeOrderTime,
payTime,
payNo,
@ -1348,7 +1345,7 @@ class DeliveryOrderService extends Service {
enableExternalExpressCode,
}, operationLogs);
const resolvedOperatorName = await this.resolveOperatorName(operatorName, createChannel, info);
const fromKey = this.normalizeOrderFromKey(info.appKey);
return {
delivery_order_code: deliveryOrderCode,
pre_delivery_order_code: preDeliveryOrderCode || '',
@ -1358,12 +1355,10 @@ class DeliveryOrderService extends Service {
order_flag: orderFlag || '',
source_platform_code: sourcePlatformCode || '',
source_platform_name: sourcePlatformName || '',
oaid_order_source_code: oaidOrderSourceCode || '',
create_channel: String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL',
sys_platform_code: platformSnapshot.sysPlatformCode,
sys_platform_name: platformSnapshot.sysPlatformName,
// 创建时间统一取服务器当前时间,不采用报文 createTime,避免被平台上报时间覆盖
create_at: new Date(),
create_at: createTime ? new Date(createTime) : new Date(),
place_order_time: placeOrderTime ? new Date(placeOrderTime) : null,
pay_time: payTime ? new Date(payTime) : null,
pay_no: payNo || sourceOrderCode || '',
@ -1410,7 +1405,7 @@ class DeliveryOrderService extends Service {
extend_props: requestExtendProps || null,
store_id: info.storeId,
warehouse_id: info.warehouseId,
from_key: fromKey,
from_key: this.normalizeOrderFromKey(info.appKey),
};
}
@ -1499,34 +1494,22 @@ class DeliveryOrderService extends Service {
errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n库存归属货主(store_id=${stockWarehouseRecord.store_id})与当前货主(store_id=${storeId})不一致,无法创建订单`);
continue;
}
} else {
} else if (!line.itemId) {
// 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景)
const findByItemCode = async () => {
if (!line.itemCode) return null;
const stockWhere = {
item_code: line.itemCode,
warehouse_id: warehouseId,
store_id: storeId,
};
if (appKey) {
stockWhere.app_key = appKey;
}
return await app.model.StockStore.findOne({ where: stockWhere, transaction });
const stockWhere = {
item_code: line.itemCode,
warehouse_id: warehouseId,
store_id: storeId,
};
if (!line.itemId) {
wms_stock = await findByItemCode();
} else {
wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction });
// 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权
if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) {
wms_stock = null;
}
// 外部渠道(奇门/开放平台)itemId 可能是平台商品标识或条码而非 WMS 主键,
// 主键查不到或跨货主时降级按 item_code 查找,避免误报“未同步推送到仓库”
if (!wms_stock) {
wms_stock = await findByItemCode();
}
if (appKey) {
stockWhere.app_key = appKey;
}
wms_stock = await app.model.StockStore.findOne({ where: stockWhere, transaction });
} else {
wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction });
// 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权
if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) {
wms_stock = null;
}
}
@ -1564,14 +1547,13 @@ class DeliveryOrderService extends Service {
// ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 =====
resolvedItems.sort((a, b) => a.stockId - b.stockId);
// ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 & 违禁品类型 =====
// ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 =====
const stockIds = [ ...new Set(resolvedItems.map(item => item.stockId).filter(Boolean)) ];
const warehouseWeightMap = new Map();
const stockProhibitedMap = new Map(); // stock_id -> 违禁品类型ID
if (stockIds.length > 0) {
const warehouseRecords = await app.model.StockWarehouse.findAll({
where: { id: stockIds },
attributes: [ 'id', 'gross_weight', 'prohibited_id' ],
attributes: [ 'id', 'gross_weight' ],
transaction,
raw: true,
});
@ -1580,10 +1562,6 @@ class DeliveryOrderService extends Service {
if (gw > 0) {
warehouseWeightMap.set(record.id, gw);
}
const prohibitedId = Number(record.prohibited_id) || 0;
if (prohibitedId > 0) {
stockProhibitedMap.set(record.id, prohibitedId);
}
}
}
@ -1727,7 +1705,6 @@ class DeliveryOrderService extends Service {
stock_quantity_map: Object.fromEntries(stockQuantityMap), // stock_id -> 数量
stock_weight_map: Object.fromEntries(stockWeightMap), // stock_id -> 单件重量
line_data: lineData, // 创建的明细数据
prohibited_type_ids: [ ...new Set(stockProhibitedMap.values()) ], // 违禁品类型ID去重数组(快递策略匹配用)
stats: { // 统计信息汇总
unique_items: stock_count,
total_items: item_total_count,
@ -1870,8 +1847,6 @@ class DeliveryOrderService extends Service {
return {
allow_storage_location: true,
order_ids: [ Number(context && context.orderId || 0) ],
// 显式携带仓库上下文,避免依赖 ctx.user(Qimen 链路无登录用户)
warehouse_id: Number(context && context.warehouseId || 0),
};
}
@ -2522,20 +2497,6 @@ class DeliveryOrderService extends Service {
const isAutoAllocateExpressEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_express);
const isAutoAllocateStorageEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage);
// 记录开关判定结果,便于排查自动分配快递/储位未触发的问题
this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 自动流程开关判定', {
warehouseId: context.warehouseId,
orderId: context.orderId,
storeId: context.storeId,
cutoffEnabled,
isCutoffActive,
needApproval,
autoAllocateExpressFlag: policyConfig && policyConfig.auto_allocate_express,
autoAllocateStorageFlag: policyConfig && policyConfig.auto_allocate_storage,
isAutoAllocateExpressEnabled,
isAutoAllocateStorageEnabled,
});
if (isAutoAllocateExpressEnabled) {
await this.runAsyncProcessStep('allocateExpress', async () => {
const request = this.buildExpressAllocateRequest(context);

View File

@ -32,29 +32,20 @@ class entryOrderService extends Service {
for (let i = 0; i < orderLine.length; i++) {
let wms_stock = null;
// ERP不处理WMS的外部商品编码
// 查找唯一键
const findByItemCode = async () => {
if (!orderLine[i].itemCode) return null;
return await app.model.StockStore.findOne({ where: {
if (!orderLine[i].itemId) {
// 查找唯一键
wms_stock = await app.model.StockStore.findOne({ where: {
item_code: orderLine[i].itemCode,
app_key: appKey,
warehouse_id: warehouseId,
store_id: storeId,
}, transaction });
};
if (!orderLine[i].itemId) {
wms_stock = await findByItemCode();
} else {
wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId, { transaction });
// 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权
if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) {
wms_stock = null;
}
// 外部渠道 itemId 可能是平台商品标识或条码而非 WMS 主键,
// 主键查不到或跨货主时降级按 item_code 查找,避免误报“未同步推送到仓库”
if (!wms_stock) {
wms_stock = await findByItemCode();
}
}
if (!wms_stock) {
errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`);

View File

@ -17,7 +17,6 @@ const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([
'delivery_order_code',
'source_platform_code',
'source_platform_name',
'oaid_order_source_code',
'sys_platform_code',
'sys_platform_name',
'order_type',

View File

@ -93,52 +93,6 @@ function isValidCainiaoTemplateUrl(templateUrl) {
const DEFAULT_CAINIAO_TEMPLATE_URL = 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948';
/**
* 将仓库ID/订单ID/业务键三段标识打包为 64 位无符号整数(Uint64)。
*
* 位宽分配("不够的补位"由左移自动补 0 完成):
* - warehouse_id:高 24 bit(hex 6 位,0x000000 ~ 0xFFFFFF)
* - order_id :中 32 bit(hex 8 位,0x00000000 ~ 0xFFFFFFFF)
* - business_key:低 8 bit (hex 2 位,0x00 ~ 0xFF)
* 合计 64 bit,拼出的 hex 固定 16 位(不足高位补 0)。
*
* 例:f425c_3948e_1 → hex 补位 0f425c0003948e01 → 1099542414161645057
*
* 纯函数(幂等):不含时间/随机因素,相同入参必然输出相同 Uint64,可安全重试。
*
* @param {number|string} warehouseId 仓库ID。
* @param {number|string} orderId 订单ID。
* @param {number|string} businessKey 业务键(1=主单号,>1=子单号)。
* @return {string} Uint64 的十进制字符串(超过 JS 安全整数 2^53,必须用字符串形式传输/序列化)。
*/
/* eslint-disable no-bitwise -- Uint64 位打包/拆解必须使用位运算 */
function toUint64(warehouseId, orderId, businessKey) {
const wh = BigInt(Number(warehouseId) || 0);
const oid = BigInt(Number(orderId) || 0);
const bk = BigInt(Number(businessKey) || 0);
if (wh < 0n || wh > 0xFFFFFFn) throw new Error(`toUint64: warehouse_id 超出 24 位范围: ${warehouseId}`);
if (oid < 0n || oid > 0xFFFFFFFFn) throw new Error(`toUint64: order_id 超出 32 位范围: ${orderId}`);
if (bk < 0n || bk > 0xFFn) throw new Error(`toUint64: business_key 超出 8 位范围: ${businessKey}`);
return ((wh << 40n) | (oid << 8n) | bk).toString();
}
/**
* 将 Uint64 反向拆解为仓库ID/订单ID/业务键(toUint64 的逆运算)。
*
* @param {string|number|bigint} value Uint64 值(十进制字符串/数字/BigInt 均可)。
* @return {{ warehouseId: number, orderId: number, businessKey: number }} 拆解结果。
*/
function fromUint64(value) {
const v = BigInt(value);
if (v < 0n || v > 0xFFFFFFFFFFFFFFFFn) throw new Error(`fromUint64: 超出 64 位范围: ${value}`);
return {
warehouseId: Number(v >> 40n),
orderId: Number((v >> 8n) & 0xFFFFFFFFn),
businessKey: Number(v & 0xFFn),
};
}
/* eslint-enable no-bitwise */
/**
* 快递平台服务类。
*
@ -749,30 +703,24 @@ class ExpressPlatformService extends MainService {
const order = order_tmp.order_delivery;
console.log('order', order);
const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {};
let plattradeno = order.oaid_order_source_code || order.source_order_codes || '';
if (listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no && plattradeno.indexOf(',') > -1) {
plattradeno = order.pay_no;
}
let playload = {
object_Id: `${order.warehouse_id.toString(16)}_${Number(order.id || 0).toString(16)}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串
orderno: `${order.warehouse_id.toString(16)}_${Number(order.id || 0).toString(16)}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
plattradeno,
tid: plattradeno,
object_Id: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串
orderno: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '',
tid:listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '',
ismultiplepieces: order.package_count > 1 ? 1 : 0,
logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '',
logistictype: expressListItem[listByWarehousePlatformCode.platform_code] || '',
providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '',
numpackage: order.package_count || '1',
Businesstype: listByWarehousePlatformCode.product_type,
Expresstype: listByWarehousePlatformCode.product_type,
ProductType: listByWarehousePlatformCode.product_type || '',
transtype: '0',
transtypecode: '1',
mainsubpaymode: '1',
businesstype: listByWarehousePlatformCode.product_type,
transtype:'0',
transtypecode:'1',
mainsubpaymode:'1',
businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS',
paymode: '1',
paymode: '1',
ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal',
ProviderID: '',
ProviderID:'',
procode: order.procode || '普通商品',
codpaymoney: order.ar_amount ?? null,
packagemoney: order.item_amount ?? null,
@ -783,6 +731,7 @@ class ExpressPlatformService extends MainService {
height: Number(order.height) || 0,
volume: Number(order.volume) || 0,
ispickup: listByWarehousePlatformCode.ispickup ?? 0,
ProductType: listByWarehousePlatformCode.product_type || '',
Sipshopid: listByWarehousePlatformCode.platform_shop_id || '',
oaid: order.oaid || '',
cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '',
@ -791,16 +740,16 @@ class ExpressPlatformService extends MainService {
brandno: listByWarehousePlatformCode.brandno || null,
needencrypt: 1,
ordertime: order.place_order_time || '',
customername: '测试',
customername:"测试",
ordersource: matchedPlatform.ordersource || '',
inputsite: order.sys_platform_code === 'XHS' ? '' : listByWarehousePlatformCode.site_code || '',
inputsite: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.site_code || '',
sitecode: listByWarehousePlatformCode.site_code || '',
shipperno: order.sys_platform_code === 'XHS' ? '' : listByWarehousePlatformCode.shipperno || '',
customercode: order.sys_platform_code === 'XHS' ? '' : listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
shipperno: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.shipperno || '',
customercode: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
sender: {
Company: listByWarehousePlatformCode.shop_name || '',
name: listByWarehousePlatformCode.sender_name || '',
phone: order.sys_platform_code === 'XHS' ? undefined : listByWarehousePlatformCode.sender_tel || '',
phone: order.sys_platform_code === 'XHS' ? undefined :listByWarehousePlatformCode.sender_tel || '',
mobile: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.sender_tel : undefined,
country: 'CN',
city: listByWarehousePlatformCode.city_name || '',
@ -829,7 +778,7 @@ class ExpressPlatformService extends MainService {
cnname: 'sp',
count: item.plan_qty || 0,
}))) || [],
// Mallmaskid: '',
//Mallmaskid: '',
template_url: listByWarehousePlatformCode.template_id || '',
labelformat: listByWarehousePlatformCode.labelformat || '',
@ -840,7 +789,7 @@ class ExpressPlatformService extends MainService {
if (Number(matchedPlatform.platid) === 673) {
playload.BizVersion = '2';
playload.brandno = listByWarehousePlatformCode.brandno === 'SF' ? listByWarehousePlatformCode.brandno : undefined;
playload.brandno = listByWarehousePlatformCode.brandno === "SF" ? listByWarehousePlatformCode.brandno : undefined;
}
if (Number(matchedPlatform.platid) === 544) {
const {
@ -892,13 +841,13 @@ class ExpressPlatformService extends MainService {
orderno,
plattradeno,
ProductType,
businesstype: ProductType,
businesstype:ProductType,
expresstype: ProductType,
logistictype,
providercode: providercode || cpcode || logistictype || '',
numpackage,
businessplat,
platcode: plattradeno,
platcode:plattradeno,
mainsubpaymode: '1',
ordertype,
businessType: businessType || ordertype || 'JH_Normal',
@ -913,7 +862,7 @@ class ExpressPlatformService extends MainService {
customername,
goods,
oaid,
customercode: logistictype === 'SF' ? undefined : customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
customercode: logistictype==="SF" ? undefined: customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
sender: {
name: senderName,
phone: senderPhoneRaw,
@ -941,11 +890,10 @@ class ExpressPlatformService extends MainService {
}
}
if (matchedPlatform.platid === 672) {
/* if (!order.source_order_codes) {
if (!order.source_order_codes) {
throw new Error('订单数据错误,缺失平台订单号');
}
*/
playload.object_Id = toUint64(order.warehouse_id, order.id, order_tmp.business_key);
playload.object_Id = order.source_order_codes.split(',')[0];
if (!order.extend_props.ewaybill_order_code) {
throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈');
}
@ -956,7 +904,7 @@ class ExpressPlatformService extends MainService {
playload.mainsubpaymode = '1';
delete playload.plattradeno;
}
playload.ProviderID = listByWarehousePlatformCode.providerid || '';
playload.ProviderID = listByWarehousePlatformCode.providerid || "";
console.log('playload', playload);
return playload;
}),
@ -1021,8 +969,8 @@ class ExpressPlatformService extends MainService {
for (const [ groupReason, groupItems ] of reasonGroups) {
const itemFailedOrders = [];
for (const failedItem of groupItems) {
const [ , order_id_hex, business_key ] = String(failedItem.orderno || '').split('_');
const orderId = parseInt(order_id_hex, 16) || 0;
const [ , order_id, business_key ] = String(failedItem.orderno || '').split('_');
const orderId = Number(order_id) || 0;
const businessKey = Number(business_key) || 0;
if (!orderId || !businessKey) continue;
@ -1065,9 +1013,8 @@ class ExpressPlatformService extends MainService {
switch (listByWarehousePlatformCode.platform_code) {
case 'KS':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
@ -1102,9 +1049,8 @@ class ExpressPlatformService extends MainService {
break;
case 'DY':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
return {
@ -1138,6 +1084,7 @@ class ExpressPlatformService extends MainService {
});
break;
case 'JD':{
const batchPrintSipshopid = String(listByWarehousePlatformCode.platform_shop_id || '0');
const batchPrintOrders = (result.results || []).map(item => ({
orderno: String(item.orderno),
logisticno: String(item.logisticno),
@ -1164,7 +1111,7 @@ class ExpressPlatformService extends MainService {
receivertel: '',
cargoname: '',
senddata: '',
// weight: '',
//weight: '',
eCustomerCode: '',
remark: '',
selleruserid: '',
@ -1204,9 +1151,8 @@ class ExpressPlatformService extends MainService {
successUpdates = (batchPrintResult && batchPrintResult.results || []).map(item => {
const objectId = String(item && item.orderno || '').trim();
const [ warehouse_id_hex, order_id_hex, business_key ] = objectId.split('_');
const [ warehouse_id_hex, order_id, business_key ] = objectId.split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = String(item && (item.logisticno || item.waybill_code) || '').trim();
const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'printdata')
? item.printdata
@ -1257,9 +1203,8 @@ class ExpressPlatformService extends MainService {
}
case 'XHS':{
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
const printInfo = item.print_info ?? item.printinfo;
return {
@ -1301,9 +1246,8 @@ class ExpressPlatformService extends MainService {
if (!objectId || objectIdParts.length < 3) {
throw new Error(`视频号取号返回 object_id 无法解析: ${objectId || JSON.stringify(item)}`);
}
const [ warehouse_id_hex, order_id_hex, business_key ] = objectIdParts;
const [ warehouse_id_hex, order_id, business_key ] = objectIdParts;
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'raw')
? item.raw
@ -1365,9 +1309,8 @@ class ExpressPlatformService extends MainService {
}
case 'PDD':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
@ -1402,9 +1345,8 @@ class ExpressPlatformService extends MainService {
case 'QT':
case 'OTHER':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_');
const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_');
const warehouse_id = parseInt(warehouse_id_hex, 16);
const order_id = parseInt(order_id_hex, 16) || 0;
const waybillCode = String(item.logisticno || item.waybill_code || '').trim();
return {
warehouse_id,
@ -1746,11 +1688,8 @@ class ExpressPlatformService extends MainService {
if (syncedOrderIds.length > 0) {
// 异步调用,不阻塞主流程
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
warehouseId,
}).catch(err => {
this.ctx.logger.error(
`[auto_sync_back] polyapi 自动同步失败: ${err.message}`
@ -1831,7 +1770,7 @@ class ExpressPlatformService extends MainService {
: [];
const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || '';
const orderDeliveryOaid = orderDelivery && orderDelivery.oaid ? String(orderDelivery.oaid).trim() : '';
const oaidTooLong = orderDeliveryOaid.indexOf('-') !== -1 || orderDeliveryOaid.length > 128;
const oaidTooLong = orderDeliveryOaid.indexOf("-") !== -1 || orderDeliveryOaid.length > 128;
const tradeOrderInfo = {
logistics_services: normalizedExtData,
@ -1855,10 +1794,10 @@ class ExpressPlatformService extends MainService {
})) || [],
goods_description: '物品',
id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`,
length: Number(orderDelivery.length || 1),
width: Number(orderDelivery.width || 1),
height: Number(orderDelivery.height || 1),
weight: Number(orderDelivery.items_weight || 1),
length:Number(orderDelivery.length || 1),
width:Number(orderDelivery.width || 1),
height:Number(orderDelivery.height || 1),
weight:Number(orderDelivery.items_weight || 1),
},
recipient: {
address: {
@ -1874,9 +1813,7 @@ class ExpressPlatformService extends MainService {
phone: recipientMobile,
oaid: oaidTooLong ? '' : orderDeliveryOaid,
caid: oaidTooLong ? orderDeliveryOaid : '',
tid: sourceOrderCodes.length > 0
? sourceOrderCodes[0]
: orderDelivery && orderDelivery.delivery_order_code || '',
tid: orderDelivery.source_order_codes,
},
user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0,
notify_extend_info: normalizedExtData,
@ -2104,11 +2041,8 @@ class ExpressPlatformService extends MainService {
if (syncedOrderIds.length > 0) {
// 异步调用,不阻塞主流程
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
warehouseId,
}).catch(err => {
this.ctx.logger.error(
`[auto_sync_back] cainiao 自动同步失败: ${err.message}`
@ -2437,7 +2371,7 @@ class ExpressPlatformService extends MainService {
object_id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`,
order_info: {
order_channels_type: 'PDD',
trade_order_list: [ `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}` ],
trade_order_list: order_tmp.order_delivery && order_tmp.order_delivery.source_order_codes ? order_tmp.order_delivery.source_order_codes.split(',') : [ order_tmp.order_delivery && order_tmp.order_delivery.delivery_order_code || '' ],
},
package_info: {
items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({
@ -2445,7 +2379,6 @@ class ExpressPlatformService extends MainService {
count: item.plan_qty,
})) || [],
id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`,
total_packages_count: order_tmp.business_key || 1,
},
recipient: {
address: {
@ -2492,9 +2425,6 @@ class ExpressPlatformService extends MainService {
},
};
console.log('拼多多平台接口构建的请求参数', JSON.stringify(pddPayload, null, 2));
await this.app.setCacheAsync('Pddquery', JSON.stringify(pddPayload), 3600);
// 这里写一个调用pdd_client的入参示例
//
//
@ -2543,8 +2473,6 @@ class ExpressPlatformService extends MainService {
data: builtRequest.requestBody,
});
await this.app.setCacheAsync('Pddresult', JSON.stringify(response), 3600);
const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data')
? response.data
: response;
@ -2813,11 +2741,8 @@ class ExpressPlatformService extends MainService {
if (syncedOrderIds.length > 0) {
// 异步调用,不阻塞主流程
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
orderIds: syncedOrderIds,
warehouseId,
}).catch(err => {
this.ctx.logger.error(
`[auto_sync_back] pdd 自动同步失败: ${err.message}`
@ -2845,8 +2770,4 @@ class ExpressPlatformService extends MainService {
}
}
// 静态挂载 Uint64 工具:供回包解析(SPH object_Id 反解)等场景复用
ExpressPlatformService.toUint64 = toUint64;
ExpressPlatformService.fromUint64 = fromUint64;
module.exports = ExpressPlatformService;

View File

@ -319,19 +319,6 @@ class operationLogService extends Service {
return await this.queryLogsByBusinessType(query, 'entry_order');
}
/**
* 查询出库单操作日志。
* @param {Object} query 查询参数。
* @param {string|number} query.id 出库单ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {number} [query.page=1] 页码。
* @param {number} [query.pageSize=20] 每页数量。
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
*/
async queryStockoutLogs(query = {}) {
return await this.queryLogsByBusinessType(query, 'stockout');
}
async getMessageDetail(data) {
const { id, type } = data;
const { ctx } = this;

View File

@ -5,7 +5,6 @@ const MainService = require('../main');
const CREATE_CHANNEL_QM = 'QM';
const CREATE_CHANNEL_MANUAL = 'MANUAL';
const CREATE_CHANNEL_API = 'API';
const CREATE_CHANNEL_STOCKOUT = 'STOCKOUT';
const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]);
const TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS = 3;
const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50;
@ -936,638 +935,6 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
};
}
/**
* 构建出库单确认回传数据(taobao.qimen.stockout.confirm / OpenAPI 回调共用)。
*
* 快递信息取订单侧实际发货信息:物流编码优先订单 sys_logistics_code → logistics_code →
* 出库单 express_code;运单号来自 wms_order_express 表(waybillCodes)。
*
* @param {Object} service 服务实例
* @param {Object} stockoutOrder 出库单主表记录(raw)
* @param {Object} orderRow 订单主表记录(raw)
* @param {Array} stockoutItems 出库单明细(raw 数组)
* @param {Array} [waybillCodes] 运单号列表
* @return {Object} 出库单确认回传请求体
*/
function buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stockoutItems, waybillCodes = []) {
const now = service.app.formatDate(new Date());
// STOCKOUT 渠道运单号只认 wms_order_express 表(分配快递号时写入),
// 不回退订单主表 express_code(该字段是面单号前置,不是完整运单号)
const normalizedWaybillCodes = (Array.isArray(waybillCodes) ? waybillCodes : [])
.map(code => String(code || '').trim())
.filter(code => !!code);
const expressCode = String(
orderRow.sys_logistics_code
|| orderRow.logistics_code
|| stockoutOrder.express_code
|| 'OTHER'
).trim();
const expressName = String(
orderRow.sys_logistics_name
|| orderRow.logistics_name
|| stockoutOrder.express_name
|| 'OTHER'
).trim();
const stockoutOrderCode = String(stockoutOrder.stockout_order_code || '').trim();
const packageCode = String(orderRow.package_code || '').trim() || stockoutOrderCode;
const orderLines = (Array.isArray(stockoutItems) ? stockoutItems : []).map(item => {
const planQty = Number(item.plan_qty) || 0;
const actualQty = Number(item.actual_qty) || planQty;
return {
orderLineNo: String(item.order_line_no || '').trim(),
ownerCode: String(item.owner_code || stockoutOrder.qimen_owner_code || '').trim(),
itemCode: String(item.item_code || '').trim(),
itemId: item.item_id,
itemName: String(item.item_name || '').trim(),
planQty,
actualQty,
inventoryType: String(item.inventory_type || 'ZP').trim(),
};
});
return {
deliveryOrder: {
totalOrderLines: Number(stockoutOrder.total_order_lines) || orderLines.length,
deliveryOrderCode: stockoutOrderCode,
deliveryOrderId: Number(stockoutOrder.id) || undefined,
warehouseCode: String(stockoutOrder.qimen_warehouse_code || '').trim(),
orderType: String(stockoutOrder.order_type || '').trim(),
status: 'DELIVERED',
outBizCode: stockoutOrderCode,
confirmType: 0,
orderConfirmTime: now,
operatorCode: '',
operatorName: '',
},
packages: {
package: normalizedWaybillCodes.map(waybillCode => ({
logisticsCode: expressCode,
logisticsName: expressName,
expressCode: waybillCode,
packageCode,
items: orderLines.map(line => ({
itemCode: line.itemCode,
itemId: line.itemId,
quantity: line.actualQty,
})),
})),
},
orderLines,
};
}
/**
* 通知外部出库单确认结果(按出库单 source_type 分流)。
*
* - QM:奇门 taobao.qimen.stockout.confirm,flag=success 视为成功;
* - API:OpenAPI 签名回调(event=stockout_completed);
* - 其他(WMS 等内部来源):无需通知外部,直接视为成功。
*
* @param {Object} service 服务实例
* @param {Object} stockoutOrder 出库单主表记录(raw)
* @param {Object} requestData 出库单确认回传请求体
* @param {Object} [context] 上下文(含 appKey)
* @return {Promise<{success: boolean, message: string}>} 通知结果
*/
async function notifyStockoutExternalInternal(service, stockoutOrder, requestData, context = {}) {
const { ctx, app } = service;
const sourceType = String(stockoutOrder.source_type || 'QM').trim().toUpperCase();
if (sourceType === 'QM') {
if (!app.qimenClient || typeof app.qimenClient.send !== 'function') {
return { success: false, message: '奇门客户端未初始化' };
}
if (!stockoutOrder.qimen_owner_code) {
return { success: false, message: '出库单缺少奇门货主编码' };
}
try {
const sendResult = await app.qimenClient.send(
'taobao.qimen.stockout.confirm',
stockoutOrder.qimen_owner_code,
requestData,
{ ctx }
);
const response = (sendResult && sendResult.xmlArray && sendResult.xmlArray.response)
? (Array.isArray(sendResult.xmlArray.response) ? sendResult.xmlArray.response[0] : sendResult.xmlArray.response)
: {};
const flag = String(response.flag || '').trim();
if (flag === 'success') {
return { success: true, message: '' };
}
return {
success: false,
message: `${response.code || ''} ${response.message || '奇门出库单确认失败'}`.trim(),
};
} catch (error) {
return { success: false, message: error.message || '奇门出库单确认异常' };
}
}
if (sourceType === 'API') {
const callbackService = ctx.service.openapi && ctx.service.openapi.callback;
const appKey = String(context.appKey || '').trim();
if (!callbackService || typeof callbackService.sendByAppKey !== 'function') {
return { success: false, message: 'OpenAPI 回调服务未初始化' };
}
if (!appKey) {
return { success: false, message: '缺少 appKey,无法回传出库单' };
}
try {
const callbackResult = await callbackService.sendByAppKey({
appKey,
event: 'stockout_completed',
data: {
stockoutOrderCode: stockoutOrder.stockout_order_code,
status: 'completed',
...requestData,
},
metadata: {
warehouseId: Number(stockoutOrder.warehouse_id) || 0,
storeId: Number(stockoutOrder.store_id) || 0,
sourceType,
},
});
if (callbackResult && callbackResult.success === true) {
return { success: true, message: '' };
}
return {
success: false,
message: String(callbackResult && callbackResult.error || 'OpenAPI 回传失败').trim(),
};
} catch (error) {
return { success: false, message: error.message || 'OpenAPI 回传异常' };
}
}
// WMS 等内部来源:无需通知外部
return { success: true, message: '' };
}
/**
* 出库单回传成功后的收尾:
* 同一事务内 ① 写回出库单快递信息并推进 COMPLETED/SUCCESS;
* ② 按订单明细扣减库存(outbound,自动释放订单锁定);③ 订单 sync_status=fin。
*
* @param {Object} service 服务实例
* @param {Object} orderModel 订单模型
* @param {Object} orderItemsModel 订单明细模型
* @param {number} orderId 订单ID
* @param {number} warehouseId 仓库ID
* @param {Object} stockoutOrder 出库单记录(raw)
* @param {Object} expressWriteback 出库单快递写回字段
* @param {Object} [orderRow] 订单记录(raw)
* @return {Promise<void>} 失败抛异常
*/
async function finalizeSuccessfulStockoutSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, stockoutOrder, expressWriteback, orderRow = null) {
const stockStoreService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.stockStore;
if (!service.ctx.model || typeof service.ctx.model.transaction !== 'function') {
throw new Error('事务能力未初始化');
}
if (!stockStoreService || typeof stockStoreService.outbound !== 'function') {
throw new Error('库存出库服务未初始化');
}
await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulStockoutSync', async transaction => {
let resolvedOrderRow = orderRow;
if (orderModel && typeof orderModel.findOne === 'function') {
resolvedOrderRow = await orderModel.findOne({
where: {
id: orderId,
warehouse_id: warehouseId,
},
attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ],
lock: transaction.LOCK.UPDATE,
raw: true,
transaction,
});
}
const stockoutUpdate = {
...expressWriteback,
order_status: 'COMPLETED',
sync_status: 'SUCCESS',
sync_message: '',
updated_at: new Date(),
};
// 防重:订单已完成同步(并发重试触发),仅补齐出库单写回后跳过扣减
if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') {
await service.ctx.model.OrderStockout.update(stockoutUpdate, {
where: { id: stockoutOrder.id },
transaction,
});
service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`);
return;
}
const freshOrderItems = await orderItemsModel.findAll({
where: { order_id: orderId },
raw: true,
transaction,
});
for (const orderItem of Array.isArray(freshOrderItems) ? freshOrderItems : []) {
const itemId = Number(orderItem && orderItem.item_id);
const quantity = resolveQimenSyncItemQuantityInternal(orderItem);
if (!Number.isFinite(itemId) || itemId <= 0 || quantity <= 0) {
continue;
}
const stockId = Number(orderItem && orderItem.stock_id) || 0;
const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, {
orderId: Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null,
orderNo: String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null,
orderItemId: Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null,
sourceOrderCodes: String(resolvedOrderRow && resolvedOrderRow.source_order_codes || '').trim() || undefined,
}, { stockId: stockId > 0 ? stockId : undefined });
if (!outboundResult || outboundResult.success !== true) {
throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim());
}
}
// 写回出库单快递信息 + 状态推进
await service.ctx.model.OrderStockout.update(stockoutUpdate, {
where: { id: stockoutOrder.id },
transaction,
});
await orderModel.update({
sync_status: 'fin',
inspection_status: 'padding',
step: 2,
order_flag: '',
updated_at: new Date(),
}, {
where: {
id: orderId,
warehouse_id: warehouseId,
status: {
[service.app.Sequelize.Op.ne]: 'cancel',
},
},
transaction,
});
});
}
/**
* 单个 STOCKOUT 订单回传处理:
* 反查出库单 → 收集订单实际快递信息 → 通知外部 → 成功后写回出库单并扣库存完成同步;
* 失败时订单 sync_status=error 并标记待处理异常,出库单 sync_status=FAILED 记录失败原因。
*
* @param {Object} service 服务实例
* @param {Object} orderModel 订单模型
* @param {Object} orderItemsModel 订单明细模型
* @param {number} orderId 订单ID
* @param {number} warehouseId 仓库ID
* @param {Object} orderRow 订单记录(raw)
* @param {Array} orderItems 订单明细(raw 数组)
* @param {Object} [context] 上下文
* @param {Array} [waybillCodes] 运单号列表
* @return {Promise<Object>} 处理结果
*/
async function processStockoutOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, orderItems, context = {}, waybillCodes = []) {
const { ctx } = service;
const deliveryOrderCode = String(orderRow && orderRow.delivery_order_code || '').trim();
const buildFailure = (message, extra = {}) => ({
order_id: orderId,
delivery_order_code: deliveryOrderCode,
status: 'failed',
message,
...extra,
});
if (!orderRow) {
return buildFailure('发货单不存在');
}
// 反查出库单:订单 source_order_codes 的首个来源单号(转订单时为出库单号),
// 兜底取订单明细 source_order_code
const sourceOrderCodes = String(orderRow.source_order_codes || '')
.split(',')
.map(code => String(code || '').trim())
.filter(code => !!code);
const sourceItem = Array.isArray(orderItems)
? orderItems.find(item => item && String(item.source_order_code || '').trim())
: null;
const itemSourceOrderCode = String(sourceItem && sourceItem.source_order_code || '').trim();
const stockoutOrderCode = String(sourceOrderCodes[0] || itemSourceOrderCode || '').trim();
if (!stockoutOrderCode) {
const message = '出库单转订单回传失败:未找到订单来源出库单号';
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
return buildFailure(message);
}
const stockoutOrder = await ctx.model.OrderStockout.findOne({
where: {
stockout_order_code: stockoutOrderCode,
warehouse_id: warehouseId,
deleted_at: null,
},
raw: true,
});
if (!stockoutOrder) {
const message = `出库单转订单回传失败:出库单(${stockoutOrderCode})不存在`;
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
return buildFailure(message);
}
// 幂等:出库单已完成同步(并发/重试场景),跳过外部通知,直接收尾
if (String(stockoutOrder.sync_status || '').trim() === 'SUCCESS') {
service.ctx.logger.info(`[syncStockoutOrders] 出库单已完成同步,跳过通知直接收尾 stockoutOrderCode=${stockoutOrderCode}`);
try {
await finalizeSuccessfulStockoutSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, stockoutOrder, {}, orderRow);
return {
order_id: orderId,
delivery_order_code: deliveryOrderCode,
status: 'success',
message: '出库单已同步,订单收尾完成',
};
} catch (error) {
const message = `出库单回传后收尾失败:${error.message}`;
await orderModel.update({
sync_status: 'error',
order_flag: message,
updated_at: new Date(),
}, {
where: { id: orderId, warehouse_id: warehouseId },
});
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
return buildFailure(message);
}
}
// 运单号校验:订单未分配运单号时无法回传出库单
// STOCKOUT 渠道运单号只认 wms_order_express 表,不回退订单主表 express_code(面单号前置)
const normalizedWaybillCodes = (Array.isArray(waybillCodes) ? waybillCodes : [])
.map(code => String(code || '').trim())
.filter(code => !!code);
if (normalizedWaybillCodes.length === 0) {
const message = '出库单转订单回传失败:订单未分配运单号';
await orderModel.update({
sync_status: 'error',
order_flag: message,
updated_at: new Date(),
}, {
where: { id: orderId, warehouse_id: warehouseId },
});
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
return buildFailure(message);
}
const stockoutItems = await ctx.model.OrderStockoutItems.findAll({
where: { order_id: stockoutOrder.id },
order: [[ 'id', 'ASC' ]],
raw: true,
});
// 快递信息写回字段(回传成功落库):物流编码/名称 + 运单号列表
const expressWriteback = {
waybill_code: normalizedWaybillCodes[0] || '',
waybill_codes: normalizedWaybillCodes,
express_code: String(
orderRow.sys_logistics_code
|| orderRow.logistics_code
|| stockoutOrder.express_code
|| ''
).trim(),
express_name: String(
orderRow.sys_logistics_name
|| orderRow.logistics_name
|| stockoutOrder.express_name
|| ''
).trim(),
};
// 通知外部(奇门 stockout.confirm / OpenAPI 回调,按出库单 source_type 分流)
const requestData = buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stockoutItems, normalizedWaybillCodes);
const notifyResult = await notifyStockoutExternalInternal(service, stockoutOrder, requestData, {
...context,
appKey: String(context.appKey || orderRow.from_key || '').trim(),
});
if (!notifyResult || notifyResult.success !== true) {
const message = `出库单转订单回传失败:${String(notifyResult && notifyResult.message || '通知外部失败').trim()}`;
await orderModel.update({
sync_status: 'error',
order_flag: message,
updated_at: new Date(),
}, {
where: { id: orderId, warehouse_id: warehouseId },
});
await ctx.model.OrderStockout.update({
sync_status: 'FAILED',
sync_message: message,
updated_at: new Date(),
}, {
where: { id: stockoutOrder.id },
});
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
return buildFailure(message);
}
try {
await finalizeSuccessfulStockoutSyncInternal(
service,
orderModel,
orderItemsModel,
orderId,
warehouseId,
stockoutOrder,
expressWriteback,
orderRow
);
} catch (error) {
const message = `出库单回传后库存扣减失败:${error.message}`;
await orderModel.update({
sync_status: 'error',
order_flag: message,
updated_at: new Date(),
}, {
where: { id: orderId, warehouse_id: warehouseId },
});
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
return buildFailure(message);
}
service.ctx.logger.info(`[syncStockoutOrders] 出库单回传成功 stockoutOrderCode=${stockoutOrderCode} orderId=${orderId}`);
return {
order_id: orderId,
delivery_order_code: deliveryOrderCode,
status: 'success',
message: '出库单回传成功',
};
}
/**
* STOCKOUT 创建渠道订单同步入口。
*
* 从待处理订单同步入口(syncOrderIds)按 create_channel 分组路由到本函数:
* 反查对应出库单,把订单实际快递编码/运单号写回出库单并通知外部
* (QM→奇门 stockout.confirm,API→OpenAPI 回调),成功后才扣减库存完成同步。
*
* @param {Object} service 服务实例
* @param {Object} groupedOrder 分组后的订单
* @param {Object} context 上下文
* @return {Promise<Object>} 同步结果
*/
async function syncStockoutOrdersInternal(service, groupedOrder = {}, context = {}) {
const orderIds = Array.isArray(groupedOrder.order_ids)
? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
: [];
const warehouseId = Number(context.warehouseId || 0);
if (orderIds.length === 0) {
return {
create_channel: CREATE_CHANNEL_STOCKOUT,
order_ids: [],
order_count: 0,
warehouse_id: warehouseId,
handler: 'syncStockoutOrders',
sync_target: 'stockout',
orders: [],
sync_results: [],
route_state: 'rejected',
status: 'failed',
message: 'STOCKOUT 同步订单不能为空',
success_count: 0,
failed_count: 0,
};
}
if (warehouseId <= 0) {
return {
create_channel: CREATE_CHANNEL_STOCKOUT,
order_ids: orderIds,
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
warehouse_id: warehouseId,
handler: 'syncStockoutOrders',
sync_target: 'stockout',
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
sync_results: [],
route_state: 'rejected',
status: 'failed',
message: '缺少仓库上下文',
success_count: 0,
failed_count: orderIds.length,
};
}
const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const { Op } = service.app.Sequelize;
const [ orderRows, orderItemRows ] = await Promise.all([
orderModel.findAll({
where: {
id: {
[Op.in]: orderIds,
},
warehouse_id: warehouseId,
},
raw: true,
}),
orderItemsModel.findAll({
where: {
order_id: {
[Op.in]: orderIds,
},
},
raw: true,
}),
]);
const orderMap = new Map();
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
if (orderRow && Number(orderRow.id) > 0) {
if (String(orderRow.sync_status || '').trim() === 'fin') {
service.ctx.logger.info(`[syncStockoutOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`);
continue;
}
orderMap.set(Number(orderRow.id), orderRow);
}
}
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds);
const itemsByOrderId = new Map();
for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) {
const itemOrderId = Number(orderItem && orderItem.order_id);
if (!Number.isFinite(itemOrderId) || itemOrderId <= 0) {
continue;
}
if (!itemsByOrderId.has(itemOrderId)) {
itemsByOrderId.set(itemOrderId, []);
}
itemsByOrderId.get(itemOrderId).push(orderItem);
}
const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id);
const uniqueOrderIds = [ ...new Set(orderIds) ];
const syncResults = [];
for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) {
const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE);
const batchResults = await Promise.all(batch.map(orderId => {
const dispatchedOrderRow = orderMap.get(orderId);
if (!dispatchedOrderRow) {
service.ctx.logger.info(`[syncStockoutOrders] 订单已过滤,跳过 orderId=${orderId}`);
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
}
return processStockoutOrderInternal(
service,
orderModel,
orderItemsModel,
orderId,
warehouseId,
dispatchedOrderRow,
itemsByOrderId.get(orderId) || [],
context,
waybillCodeMap.get(orderId)
);
}));
syncResults.push(...batchResults);
await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length);
}
const successCount = syncResults.filter(item => item.status === 'success').length;
const failedCount = syncResults.filter(item => item.status === 'failed').length;
const overallSuccess = failedCount === 0 && successCount === syncResults.length;
return {
create_channel: CREATE_CHANNEL_STOCKOUT,
order_ids: orderIds,
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
warehouse_id: warehouseId,
handler: 'syncStockoutOrders',
sync_target: 'stockout',
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
sync_results: syncResults,
route_state: overallSuccess ? 'accepted' : 'rejected',
status: overallSuccess ? 'success' : 'failed',
message: overallSuccess ? '出库单回传成功' : '出库单回传失败',
success_count: successCount,
failed_count: failedCount,
};
}
function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) {
const orderIds = Array.isArray(syncResult.order_ids)
? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
@ -2458,20 +1825,6 @@ class OrderAsyncService extends MainService {
async syncApiOrders(groupedOrder = {}, context = {}) {
return await finalizeLocalChannelOrdersInternal(this, CREATE_CHANNEL_API, groupedOrder, context, 'api');
}
/**
* STOCKOUT 创建入口处理(出库单转订单回传)。
*
* 回传时把订单实际快递编码/运单号写回出库单,并按出库单来源通知外部
* (QM→奇门 stockout.confirm,API→OpenAPI 回调),成功后才扣减库存完成同步。
*
* @param {Object} groupedOrder 分组后的订单。
* @param {Object} context 上下文。
* @return {Promise<Object>} 处理结果。
*/
async syncStockoutOrders(groupedOrder = {}, context = {}) {
return await syncStockoutOrdersInternal(this, groupedOrder, context);
}
}
module.exports = OrderAsyncService;

View File

@ -587,26 +587,12 @@ class OrderPackingService extends Service {
const updates = { end_time: finalEndTime };
// 若任务状态不是已完成(2),同步更新为已完成
const wasFinished = record.status === 2;
if (!wasFinished) {
if (record.status !== 2) {
updates.status = 2;
}
await record.update(updates);
// 任务由未结束转为已完成时,同步更新关联订单打包状态(与 workbench.finishPack 语义一致)
if (!wasFinished && updates.status === 2 && workbenchService
&& typeof workbenchService._updateOrderPackStatus === 'function') {
const isGroupTask = Number(record.pack_mode) === 2;
const taskWaveId = isGroupTask ? Number(record.wave_id || 0) : 0;
await workbenchService._updateOrderPackStatus(warehouseId, {
orderId: Number(record.order_id || 0),
waveId: taskWaveId,
packStatus: 2,
caller: 'OrderPacking.setEndTime',
});
}
return {
code: 200,
message: '结束时间设置成功',

View File

@ -543,12 +543,6 @@ class OrderPrintSystemService extends OrderBaseService {
};
}
// 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用
const waveMetaMap = new Map();
for (const waveRow of waveRows) {
waveMetaMap.set(Number(waveRow.wave_id), waveRow);
}
const hitWaveIdSet = new Set(waveRows.map(row => Number(row.wave_id)));
const missingWaveIds = normalizedWaveIds.filter(waveId => !hitWaveIdSet.has(waveId));
const hitWaveIds = normalizedWaveIds.filter(waveId => hitWaveIdSet.has(waveId));
@ -683,14 +677,11 @@ class OrderPrintSystemService extends OrderBaseService {
const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0);
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
const waveMetaRow = waveMetaMap.get(waveIdForCount) || {};
const effectiveOrderRowWithWaveIndex = {
...effectiveOrderRow,
wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0,
wave_index: waveIndex > 0 ? waveIndex : 0,
platforms_index: platformsIndex > 0 ? platformsIndex : 0,
wave_source: Number(waveMetaRow.source || 0),
wave_type: Number(waveMetaRow.wave_type || 0),
};
const storeId = Number(orderRow && orderRow.store_id || 0);
const policyConfig = policyConfigMap.get(storeId) || {};
@ -839,12 +830,6 @@ class OrderPrintSystemService extends OrderBaseService {
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds);
// 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用
const waveMetaMap = new Map();
for (const waveRow of waveRows) {
waveMetaMap.set(Number(waveRow.wave_id), waveRow);
}
const orderIdsForExpress = validOrderRows
.map(row => Number(row && row.id || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
@ -896,14 +881,11 @@ class OrderPrintSystemService extends OrderBaseService {
const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0);
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
const waveMetaRow = waveMetaMap.get(waveIdForCount) || {};
const effectiveOrderRowWithWaveIndex = {
...effectiveOrderRow,
wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0,
wave_index: waveIndex > 0 ? waveIndex : 0,
platforms_index: platformsIndex > 0 ? platformsIndex : 0,
wave_source: Number(waveMetaRow.source || 0),
wave_type: Number(waveMetaRow.wave_type || 0),
};
const storeId = Number(orderRow && orderRow.store_id || 0);
const policyConfig = policyConfigMap.get(storeId) || {};
@ -1139,12 +1121,6 @@ class OrderPrintSystemService extends OrderBaseService {
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds);
// 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用
const waveMetaMap = new Map();
for (const waveRow of waveRows) {
waveMetaMap.set(Number(waveRow.wave_id), waveRow);
}
const orderIdsForIndex = validOrderRows.map(row => Number(row.id)).filter(id => id > 0);
const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(
orderIdsForIndex, normalizedWarehouseId, validOrderWaveIds
@ -1165,14 +1141,11 @@ class OrderPrintSystemService extends OrderBaseService {
const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0);
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
const waveMetaRow = waveMetaMap.get(waveIdForCount) || {};
const effectiveOrderRowWithWaveIndex = {
...effectiveOrderRow,
wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0,
wave_index: waveIndex > 0 ? waveIndex : 0,
platforms_index: platformsIndex > 0 ? platformsIndex : 0,
wave_source: Number(waveMetaRow.source || 0),
wave_type: Number(waveMetaRow.wave_type || 0),
};
const storeId = Number(orderRow.store_id || 0);
@ -1777,7 +1750,7 @@ class OrderPrintSystemService extends OrderBaseService {
}
const querySql = `
SELECT wave_id, wave_no, source, wave_type
SELECT wave_id, wave_no
FROM wms_wave_batch
WHERE warehouse_id = :warehouseId
AND wave_id IN (:waveIds)
@ -1982,7 +1955,7 @@ class OrderPrintSystemService extends OrderBaseService {
* 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。
*
* @param {number[]} orderIds 订单 ID 列表。
* @param {number} warehouseId 仓库ID。
* @param warehouseId
* @return {Promise<Array<Object>>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、
* logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、
* warehouse_id、printinfo、signature、encryptprintinfo、ver。

View File

@ -479,14 +479,7 @@ class OrderStorageAllocationService extends MainService {
const progressCallback = typeof requestData.progress_callback === 'function'
? requestData.progress_callback
: null;
// 优先使用调用方显式传入的仓库ID(Qimen 等无登录用户上下文的链路 ctx.user 为空)
const warehouseId = toNumber(
requestData.warehouse_id
?? requestData.warehouseId
?? ctx.user?.store_id
?? ctx.user?.warehouse_id,
0
);
const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0);
const orderIds = normalizeOrderIds(requestData);
const allowStorageLocation = normalizeBooleanFlag(
requestData.allow_storage_location
@ -1568,8 +1561,7 @@ class OrderStorageAllocationService extends MainService {
* 待处理订单同步入口。
*
* 先完成订单查询、过滤与分组,再按 `create_channel` 路由到
* `orderAsync.syncQmOrders`、`orderAsync.syncManualOrders`、`orderAsync.syncApiOrders`、
* `orderAsync.syncStockoutOrders` 四个处理入口。
* `orderAsync.syncQmOrders`、`orderAsync.syncManualOrders`、`orderAsync.syncApiOrders` 三个处理入口。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 同步结果。
@ -1967,10 +1959,6 @@ class OrderStorageAllocationService extends MainService {
result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext);
} else if (createChannel === 'API') {
result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext);
} else if (createChannel === 'STOCKOUT') {
// 出库单转订单渠道:回传时把快递编码/运单号写回出库单并通知外部,
// 成功后才完成订单同步
result = await orderAsyncService.syncStockoutOrders(groupedOrder, routeContext);
} else {
result = await orderAsyncService.syncManualOrders(groupedOrder, routeContext);
}

View File

@ -9,41 +9,6 @@ const Service = require('egg').Service;
* 所有数据库交互集中在此层,供 systemMethods/returnUnpack.js 调用。
*/
class ReturnUnpackService extends Service {
/**
* 获取仓库的录制电脑 ID(带缓存)。
* 与 order_packing 一致:从 wms_print_computer 按 is_recording=true 获取。
* @param {number} warehouseId 仓库ID
* @return {Promise<number|null>} 录制电脑ID,找不到返回 null
*/
async _getRecordingComputerId(warehouseId) {
const cacheKey = `_recordingComputer_${warehouseId}`;
if (this[cacheKey] !== undefined) {
return this[cacheKey];
}
const row = await this.ctx.model.PrintComputer.findOne({
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
attributes: [ 'id' ],
raw: true,
});
this[cacheKey] = row ? row.id : null;
return this[cacheKey];
}
/**
* 构建视频完整 URL(与 order.packing 一致)。
* 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath}
* @param {number} warehouseId 仓库ID
* @param {number|null} recordingComputerId 录制电脑ID
* @param {string} videoPath 视频路径
* @return {string} 完整 URL
*/
_buildVideoUrl(warehouseId, recordingComputerId, videoPath) {
if (!videoPath || !recordingComputerId) {
return videoPath || '';
}
return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${videoPath}`;
}
/**
* 创建带业务错误码的异常对象。
*
@ -66,7 +31,7 @@ class ReturnUnpackService extends Service {
* @param {Array<number>} [params.camera_ids] 摄像头ID列表。
* @param {number} [params.return_received_id] 关联退回收到单ID。
* @param {string} [params.remark] 备注。
* @return {Promise<Object>} 开单结果,含 id、record、is_original_return、store_remark、order、order_items。
* @return {Promise<Object>} 开单结果,含 id、record、is_original_return、store_remark、order。
*/
async create({ waybill_code, camera_ids, return_received_id, remark }) {
const { ctx, app } = this;
@ -141,7 +106,6 @@ class ReturnUnpackService extends Service {
if (existing) {
// 复用已有拆包单:返回主表 + 明细 + 视频 + 原订单详情(复用 detail 查询逻辑)
const existingDetail = await this.detail(existing.id);
const existingOrder = (existingDetail.related && existingDetail.related.order) || null;
ctx.logger.info(
`[returnUnpack.create] 运单号 ${waybillCode} 3 个月内已有拆包单 id=${existing.id},直接复用返回明细`
);
@ -150,8 +114,7 @@ class ReturnUnpackService extends Service {
record: existingDetail.record,
is_original_return: Boolean(existing.order_express_id),
store_remark: String(existingDetail.record && existingDetail.record.shop_name || ''),
order: existingOrder,
order_items: existingOrder && Array.isArray(existingOrder.items) ? existingOrder.items : null,
order: (existingDetail.related && existingDetail.related.order) || null,
reused: true,
};
}
@ -277,7 +240,6 @@ class ReturnUnpackService extends Service {
is_original_return: isOriginalReturn,
store_remark: storeRemark,
order,
order_items: order && Array.isArray(order.items) ? order.items : null,
};
}
@ -548,77 +510,6 @@ class ReturnUnpackService extends Service {
};
}
/**
* 强制重新录制拆包视频:重置视频记录状态并推送打印服务强制录制。
* 参考 order.packing.forceRecord:校验仓库录制电脑在线后,将视频记录重置为
* created 并清空 video_url,再向打印服务 /record/force 推送 { unpack_id } 触发重新录制。
*
* @param {Object} params 参数。
* @param {number} params.id 拆包单ID。
* @return {Promise<Object>} 推送结果 { unpack_id, computer_id, print_service_url, print_service_request, print_service_response }。
*/
async forceRecord({ id }) {
const { ctx } = this;
// 拆包单存在性 + 仓库隔离校验(不存在 404 / 跨仓库 403)
const unpack = await this._findByIdChecked(id);
const warehouseId = Number(unpack.warehouse_id || 0);
const unpackId = Number(id);
// 1. 查找仓库的录制电脑
const recordingComputer = await ctx.model.PrintComputer.findOne({
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
raw: true,
});
if (!recordingComputer) {
throw this.createBusinessError('该仓库无录制电脑,无法强制录制', 400);
}
// 2. 检查录制电脑是否在线(与 order_packing 相同的 Redis 在线键)
const redisPrinter = ctx.app.redis.get('printer');
const onlineKey = `warehouse:${warehouseId}:printer:${recordingComputer.id}`;
const onlineInfo = await redisPrinter.get(onlineKey);
if (!onlineInfo) {
throw this.createBusinessError('该仓库录制电脑不在线,无法强制录制', 400);
}
// 3. 重置视频记录状态为 created,触发重新录制
await ctx.model.ReturnUnpackVideo.update(
{ status: 'created', video_url: '' },
{ where: { unpack_id: unpackId, deleted_at: null } }
);
// 4. 通知打印服务推送强制录制任务
const printServiceUrl = ctx.app.config.printService.url;
const requestData = { unpack_id: unpackId };
let printServiceResponse = null;
try {
const res = await ctx.curl(`${printServiceUrl}/record/force`, {
method: 'POST',
contentType: 'json',
data: requestData,
dataType: 'json',
timeout: 10000,
});
printServiceResponse = {
status: res.status,
headers: res.headers,
data: res.data,
};
} catch (err) {
ctx.logger.warn(`[returnUnpack.forceRecord] 通知打印服务强制录制 unpack_id=${unpackId} 失败: ${err.message}`);
throw this.createBusinessError(`通知打印服务失败: ${err.message}`, 500);
}
return {
unpack_id: unpackId,
computer_id: recordingComputer.id,
print_service_url: `${printServiceUrl}/record/force`,
print_service_request: requestData,
print_service_response: printServiceResponse,
};
}
/**
* 分页查询拆包单列表(仓库隔离由方法层注入 warehouse_id)。
*
@ -642,30 +533,12 @@ class ReturnUnpackService extends Service {
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: false,
include: [
{
model: ctx.model.ReturnUnpackVideo,
as: 'videos',
attributes: [ 'id', 'video_url', 'camera_id', 'status' ],
where: { deleted_at: null },
required: false,
include: [
{
model: ctx.model.Camera,
as: 'camera',
attributes: [ 'id', 'custom_name', 'channel_name' ],
required: false,
},
],
},
],
raw: true,
});
const list = [];
for (const row of rows) {
const plain = row && typeof row.toJSON === 'function' ? row.toJSON() : row;
list.push(this._flattenVideos(await this._enrichRow(plain)));
list.push(await this._enrichRow(row));
}
return {
@ -733,83 +606,6 @@ class ReturnUnpackService extends Service {
};
}
/**
* 分页查询拆包录像列表(unpack_id 维度,仓库隔离由方法层校验)。
*
* @param {Object} where 标准化 where 条件对象(unpack_id 必填)。
* @param {Object} [pagination] 分页参数。
* @param {Object} [sort] 排序参数。
* @return {Promise<Object>} { list, pagination }。
*/
async videoList(where = {}, pagination = {}, sort = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const page = Math.max(1, parseInt(pagination.page) || 1);
const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20));
const queryWhere = this._buildVideoListWhere(where, Op);
const order = this._buildVideoListOrder(sort);
const { count, rows } = await ctx.model.ReturnUnpackVideo.findAndCountAll({
where: queryWhere,
include: [
{
model: ctx.model.Camera,
as: 'camera',
required: false,
},
],
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: false,
});
// 视频地址拼接 CDN 域名(unpack_id 由方法层强制注入且已通过仓库隔离校验)
const unpackIdRaw = queryWhere.unpack_id;
const unpackId = unpackIdRaw && typeof unpackIdRaw === 'object' ? unpackIdRaw.value : unpackIdRaw;
let warehouseId = 0;
if (unpackId) {
const unpackRow = await ctx.model.ReturnUnpack.findOne({
where: { id: Number(unpackId) },
attributes: [ 'warehouse_id' ],
raw: true,
});
warehouseId = Number(unpackRow && unpackRow.warehouse_id || 0);
}
const recordingComputerId = warehouseId > 0 ? await this._getRecordingComputerId(warehouseId) : null;
const list = rows
.map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row))
.map(row => {
const camera = row.camera || {};
return {
id: row.id,
unpack_id: row.unpack_id,
video_url: this._buildVideoUrl(warehouseId, recordingComputerId, row.video_url),
status: row.status || null,
camera_id: row.camera_id || null,
camera_name: (camera.custom_name || camera.channel_name) || null,
remark: row.remark || null,
created_at: row.created_at ? app.formatDate(row.created_at) : null,
updated_at: row.updated_at ? app.formatDate(row.updated_at) : null,
};
});
return {
list,
pagination: {
page,
pageSize,
total: count,
totalPages: Math.ceil(count / pageSize),
hasPrevious: page > 1,
hasNext: page * pageSize < count,
},
};
}
/**
* 查询拆包单详情:主表 + 明细 + 视频 + 退回收到单 + 原订单详情(原单退回时)。
*
@ -947,12 +743,6 @@ class ReturnUnpackService extends Service {
raw: true,
});
// 视频地址拼接 CDN 域名(与 order.packing 对齐)
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
for (const video of videos) {
video.video_url = this._buildVideoUrl(warehouseId, recordingComputerId, video.video_url);
}
let received = null;
if (unpack.return_received_id) {
received = await ctx.model.ReturnReceived.findOne({
@ -1198,55 +988,24 @@ class ReturnUnpackService extends Service {
if (order_id && !info.trade_no) {
try {
let order = null;
const factory = ctx.model.OrderDeliveryFactory;
if (factory && typeof factory.getCurrentModel === 'function') {
const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ];
const laneGetters = {
current: () => factory.getCurrentModel(warehouse_id),
history: () => factory.getHistoryModel(warehouse_id),
dispatch: () => factory.getDispatchModel(warehouse_id),
outsourced: () => factory.getOutsourcedModel(warehouse_id),
};
// 序列表定位优先:命中车道先查对应分表,未命中按原顺序遍历回退
try {
order = await ctx.model.OrderDelivery.findOne({
where: { id: order_id },
raw: true,
});
} catch (err) {
// 主表查询失败,继续走工厂分表兜底
}
if (!order && ctx.model.OrderDeliveryFactory) {
try {
if (typeof factory.getOrderLocation === 'function') {
const location = await factory.getOrderLocation(order_id, warehouse_id);
if (location && laneGetters[location]) {
laneLabels.sort((a, b) => (a === location ? -1 : b === location ? 1 : 0));
}
const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouse_id);
if (factoryModel) {
order = await factoryModel.findOne({ where: { id: order_id }, raw: true });
}
} catch (err) {
// 定位失败忽略,保持遍历顺序
}
for (const lane of laneLabels) {
try {
const model = await laneGetters[lane]();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({ where: { id: order_id }, raw: true });
if (row) {
order = row;
break;
}
} catch (err) {
// 该表可能不存在,继续下一张
}
// 分表查询失败忽略
}
}
// 分表均未命中:回退基表(存量订单)
if (!order) {
try {
order = await ctx.model.OrderDelivery.findOne({
where: { id: order_id },
raw: true,
});
} catch (err) {
// 主表查询失败忽略
}
}
if (order) {
info.trade_no = String(order.source_order_codes || order.source_platform_code || '');
if (!info.express && order.logistics_name) info.express = String(order.logistics_name);
@ -1419,22 +1178,6 @@ class ReturnUnpackService extends Service {
record.is_original_return = Boolean(record.order_express_id);
// 视频派生字段(与 order.packing.list 对齐):记录含 videos 数组时计算
if (Array.isArray(record.videos)) {
record.has_video = record.videos.length > 0 ? 1 : 2;
record.video_enable = record.videos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2;
// 视频地址拼接 CDN 域名(与 order.packing 对齐:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path})
const warehouseId = Number(record.warehouse_id || 0);
if (warehouseId > 0) {
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
record.videos = record.videos.map(v => ({
...v,
video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url),
}));
}
}
// camera_ids 归一化为数组(MySQL JSON 列可能返回字符串)
if (record.camera_ids !== undefined && record.camera_ids !== null) {
if (typeof record.camera_ids === 'string') {
@ -1461,27 +1204,6 @@ class ReturnUnpackService extends Service {
return record;
}
/**
* 列表场景视频数组扁平化(对齐 order.packing.list 输出口径)。
* 仅输出前端需要的精简字段(id/video_url/status/camera_id/camera_name);
* detail 等场景的 videos 保持完整关联结构不变。
*
* @param {Object} row 主表记录(含 videos 关联数组)。
* @return {Object} 扁平化后的记录。
*/
_flattenVideos(row) {
if (Array.isArray(row.videos)) {
row.videos = row.videos.map(v => ({
id: v.id,
video_url: v.video_url,
status: v.status || null,
camera_id: v.camera_id || null,
camera_name: (v.camera && (v.camera.custom_name || v.camera.channel_name)) || null,
}));
}
return row;
}
/**
* 批量附加库存详情(条码/图片等)到明细行。
* 统一走 stockWarehouse.getStockDetails 通用方法(带缓存,含 barcodes/image_url/
@ -1627,30 +1349,6 @@ class ReturnUnpackService extends Service {
_buildListWhere(where = {}, Op) {
const queryWhere = {};
// has_video 筛选:1=有视频记录 2=无视频记录(口径对齐 order.packing.list)
if (where.has_video !== undefined && where.has_video !== null) {
const hasVideoValue = Number(where.has_video?.value ?? where.has_video);
if (hasVideoValue === 1 || hasVideoValue === 2) {
const existsSql = 'EXISTS (SELECT 1 FROM wms_return_unpack_video WHERE unpack_id = wms_return_unpack.id AND deleted_at IS NULL)';
const cond = hasVideoValue === 1
? this.app.Sequelize.literal(existsSql)
: this.app.Sequelize.literal(`NOT ${existsSql}`);
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), cond ];
}
}
// video_enable 筛选:1=录像可用 2=录像不可用(口径对齐 order.packing.list)
if (where.video_enable !== undefined && where.video_enable !== null) {
const videoEnableValue = Number(where.video_enable?.value ?? where.video_enable);
if (videoEnableValue === 1 || videoEnableValue === 2) {
const existsSql = "EXISTS (SELECT 1 FROM wms_return_unpack_video WHERE unpack_id = wms_return_unpack.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')";
const cond = videoEnableValue === 1
? this.app.Sequelize.literal(existsSql)
: this.app.Sequelize.literal(`NOT ${existsSql}`);
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), cond ];
}
}
const directFields = [
'warehouse_id', 'unpacker_id', 'return_received_id', 'store_id',
'order_express_id', 'order_id', 'status', 'detail_status',
@ -1705,46 +1403,6 @@ class ReturnUnpackService extends Service {
return queryWhere;
}
/**
* 构建录像列表 where 条件(unpack_id 必填等值;camera_id/status 可选等值)。
*
* @param {Object} where 标准化条件对象。
* @param {Object} Op Sequelize Op 对象。
* @return {Object} Sequelize where 条件。
*/
_buildVideoListWhere(where = {}, Op) {
const queryWhere = {};
if (where.unpack_id !== undefined && where.unpack_id !== null) {
queryWhere.unpack_id = this._resolveConditionValue(where.unpack_id, Op);
}
if (where.camera_id !== undefined && where.camera_id !== null) {
queryWhere.camera_id = this._resolveConditionValue(where.camera_id, Op);
}
if (where.status !== undefined && where.status !== null) {
queryWhere.status = this._resolveConditionValue(where.status, Op);
}
return queryWhere;
}
/**
* 录像列表排序(默认按 id 升序)。
*
* @param {Object} sort 排序参数。
* @return {Array<Array<string>>} Sequelize order 数组。
*/
_buildVideoListOrder(sort = {}) {
const sortField = sort.sortField || sort.sort_field || 'id';
const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'asc').toLowerCase();
const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC';
const allowed = new Set([ 'id', 'created_at', 'updated_at', 'camera_id' ]);
const safeSortField = allowed.has(sortField) ? sortField : 'id';
return [[ safeSortField, sortOrder ]];
}
/**
* 解析标准化条件值为 Sequelize 可用的条件对象。
*

View File

@ -292,14 +292,6 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
description: '团购打包最大时长,单位:分钟,默认 40',
min: 1,
}),
Object.freeze({
key: 'default_location_id',
name: '默认库位',
type: 'location',
default: null,
required: false,
description: '仓库未指定库位入库/上架时使用的默认库位(库位ID)',
}),
Object.freeze({
key: INTERNAL_WAVE_STRATEGY_VERSION_KEY,
name: '仓库波次策略版本号',
@ -568,47 +560,6 @@ class SettingWarehouseService extends Service {
};
}
/**
* 校验默认库位是否属于当前仓库。
*
* 传入的 default_location_id 为库位ID(wms_location_space.id),仅当该库位
* 属于当前仓库且未删除、已启用时才允许写入。
*
* @param {*} locationIdValue 待校验的库位ID。
* @param {number} warehouseId 当前仓库 ID。
* @return {Promise<void>} 无返回值。
* @throws {Error} 库位ID非法或不属于当前仓库时抛出,状态码 400。
*/
async validateDefaultLocation(locationIdValue, warehouseId) {
if (locationIdValue === undefined || locationIdValue === null || locationIdValue === '') {
return;
}
const locationId = Number(locationIdValue);
if (!Number.isInteger(locationId) || locationId <= 0) {
throw this.createError('default_location_id 必须是正整数库位ID', 400);
}
const locationModel = this.ctx && this.ctx.model && this.ctx.model.LocationSpace;
if (!locationModel || typeof locationModel.findOne !== 'function') {
return;
}
const locationSpace = await locationModel.findOne({
where: {
id: locationId,
warehouse_id: warehouseId,
is_enabled: true,
deleted_at: null,
},
attributes: [ 'id' ],
});
if (!locationSpace) {
throw this.createError(`默认库位 ${locationId} 不属于当前仓库`, 400);
}
}
/**
* 修改当前仓库设置并清理当前仓库缓存。
*
@ -638,11 +589,6 @@ class SettingWarehouseService extends Service {
throw this.createError('subject_config 参数不能为空且必须是对象', 400);
}
// 默认库位必须属于当前仓库(值为库位ID)
if (Object.prototype.hasOwnProperty.call(nextPatch, 'default_location_id')) {
await this.validateDefaultLocation(nextPatch.default_location_id, warehouseId);
}
const nextPatchForMerge = {
...nextPatch,
};

View File

@ -2218,7 +2218,6 @@ class stockStoreService extends Service {
tag_price: item.tag_price || '',
retail_price: item.retail_price || '',
gross_weight: item.gross_weight || '',
need_recheck: String(item.need_recheck || 'Y') === 'Y' ? '需要' : '不需要',
store_remask,
barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '',
quantity: item.quantity,
@ -2254,7 +2253,6 @@ class stockStoreService extends Service {
{ header: '标价', key: 'tag_price' },
{ header: '零售价', key: 'retail_price' },
{ header: '毛重', key: 'gross_weight' },
{ header: '是否需要复核', key: 'need_recheck' },
{ header: '货主', key: 'store_remask' },
{ header: '条码', key: 'barcodes' },
{ header: '库存', key: 'quantity' },
@ -2345,7 +2343,6 @@ class stockStoreService extends Service {
tag_price: item.tag_price || '',
retail_price: item.retail_price || '',
gross_weight: item.gross_weight || '',
need_recheck: String(item.need_recheck || 'Y') === 'Y' ? '需要' : '不需要',
store_remask: storeRemask,
barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '',
quantity: item.quantity,
@ -2381,7 +2378,6 @@ class stockStoreService extends Service {
{ header: '标价', key: 'tag_price' },
{ header: '零售价', key: 'retail_price' },
{ header: '毛重', key: 'gross_weight' },
{ header: '是否需要复核', key: 'need_recheck' },
{ header: '货主', key: 'store_remask' },
{ header: '条码', key: 'barcodes' },
{ header: '库存', key: 'quantity' },
@ -2534,7 +2530,7 @@ class stockStoreService extends Service {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit', 'need_recheck' ];
const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ];
const { ids, method, value } = ctx.request.body;
@ -2605,18 +2601,6 @@ class stockStoreService extends Service {
update_by: ctx.user.id || ctx.user.username,
};
} else if (method === 'need_recheck') {
// 是否需要复核:Y=需要复核,N=不需要复核
const updateValue = String(value).trim().toUpperCase();
if (![ 'Y', 'N' ].includes(updateValue)) {
return { message: '是否需要复核必须是 Y(需要复核)或 N(不需要复核)', code: 405 };
}
updateData = {
need_recheck: updateValue,
update_at: new Date(),
update_by: ctx.user.id || ctx.user.username,
};
} else if (method === 'managementFlags') {
// 管理标识是对象格式,需要更新三个独立字段
if (typeof value !== 'object') {
@ -2663,17 +2647,6 @@ class stockStoreService extends Service {
delete_at: null,
},
});
// 5.1 清除商品详情缓存(bulk update 不触发实例级 afterUpdate hook)
if (affectedRows > 0) {
const detailCacheSvc = ctx.service && ctx.service.systems && ctx.service.systems.stockWarehouse;
if (detailCacheSvc && typeof detailCacheSvc.invalidateStockDetailCache === 'function') {
await Promise.allSettled(
ids.map(stockId => detailCacheSvc.invalidateStockDetailCache(Number(stockId), warehouseId))
);
}
}
return {
message: `成功修改 ${affectedRows} 条记录`,
code: 200,
@ -3028,7 +3001,6 @@ class stockStoreService extends Service {
'is_batch_mgmt',
'is_shelf_life_mgmt',
'is_sn_mgmt',
'need_recheck',
'goods_code',
'item_code',
'item_name',
@ -3083,7 +3055,6 @@ class stockStoreService extends Service {
box_width, box_height, box_volume, box_remark, id,
box_volume_m3, boxVolumeM3,
shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days,
need_recheck,
} = data;
const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3;
const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3;
@ -3157,7 +3128,6 @@ class stockStoreService extends Service {
is_sn_mgmt: is_sn_mgmt || false,
is_shelf_life_mgmt: is_shelf_life_mgmt || false,
is_batch_mgmt: is_batch_mgmt || false,
need_recheck,
prohibited_id: prohibited_id_tmp,
brand_name,
...(managementFlags && { management_flags: managementFlags }),
@ -3210,13 +3180,6 @@ class stockStoreService extends Service {
// 7. 提交事务
await transaction.commit();
// 7.1 清除商品详情缓存(getStockDetails 缓存,bulk update 不触发实例级 afterUpdate hook)
try {
await service.systems.stockWarehouse.invalidateStockDetailCache(id, warehouseId);
} catch (cacheError) {
ctx.logger.warn(`saveWarehouseStock 清除商品详情缓存失败: ${cacheError.message}`);
}
// 8. 返回更新后的数据
return await this.getInfo({ id });
@ -3248,7 +3211,6 @@ class stockStoreService extends Service {
enable_box_spec, box_unit, quantity_per_box,
box_gross_weight, box_net_weight, box_length,
box_width, box_height, box_volume, box_remark,
need_recheck,
} = data;
// 1. 参数验证
@ -3282,7 +3244,6 @@ class stockStoreService extends Service {
is_sn_mgmt: is_sn_mgmt || false,
is_shelf_life_mgmt: is_shelf_life_mgmt || false,
is_batch_mgmt: is_batch_mgmt || false,
need_recheck: need_recheck || 'Y',
prohibited_id,
brand_name,
...(managementFlags && { management_flags: managementFlags }),
@ -3343,11 +3304,6 @@ class stockStoreService extends Service {
throw new Error('启用箱规时,每箱数量必须大于0');
}
// 是否需要复核:仅允许 Y(需要)/ N(不需要)
if (data.need_recheck !== undefined && data.need_recheck !== null && ![ 'Y', 'N' ].includes(String(data.need_recheck).trim())) {
throw new Error('need_recheck 必须是 Y(需要复核)或 N(不需要复核)');
}
// 数值类型验证
const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ];
for (const field of numericFields) {
@ -3868,38 +3824,6 @@ class stockStoreService extends Service {
return result;
});
// 批查商品图片(与 stock.warehouse.list 一致:wms_file_reference + wms_file)
if (formattedResults.length > 0) {
const stockIds = formattedResults.map(r => r.id);
const imageRows = await app.model.FileReference.findAll({
where: {
business_type: 'stock',
business_id: { [Op.in]: stockIds.map(String) },
},
include: [{
model: app.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
order: [[ 'display_order', 'ASC' ]],
raw: true,
});
const imageMap = new Map();
for (const row of imageRows) {
const sid = Number(row.business_id);
const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || '';
if (!url) continue;
if (!imageMap.has(sid)) imageMap.set(sid, []);
imageMap.get(sid).push(url);
}
for (const item of formattedResults) {
item.images = imageMap.get(item.id) || [];
}
}
// with_stock=true 时关联查询库存数据
if (with_stock && formattedResults.length > 0) {
const stockIds = formattedResults.map(r => r.id);

View File

@ -31,7 +31,7 @@ class StockWarehouseService extends Service {
* @param {Object} [options={}] 选项
* @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id)
* @param {number} [options.cacheTTL=300] 缓存过期时间(秒)
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, is_images: string, need_recheck: string, store_id: number, packing_requirements: string, stock_unit: string, image_url: string[], barcodes: Array<{id: number, barcode: string}>}>>} 商品详情列表
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, is_images: string, store_id: number, packing_requirements: string, stock_unit: string, image_url: string[], barcodes: Array<{id: number, barcode: string}>}>>} 商品详情列表
*/
async getStockDetails(stockIds, options = {}) {
const { ctx, app } = this;
@ -79,7 +79,7 @@ class StockWarehouseService extends Service {
attributes: [
'id', 'item_code', 'item_name', 'sku_property',
'quantity', 'locked_quantity', 'is_batch_mgmt',
'is_shelf_life_mgmt', 'is_images', 'need_recheck',
'is_shelf_life_mgmt', 'is_images',
'store_id', 'packing_requirements', 'stock_unit',
],
raw: true,
@ -143,7 +143,6 @@ class StockWarehouseService extends Service {
is_batch_mgmt: row.is_batch_mgmt || 'N',
is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N',
is_images: row.is_images || 'N',
need_recheck: row.need_recheck || 'Y',
store_id: row.store_id != null ? Number(row.store_id) : 0,
packing_requirements: row.packing_requirements || '',
stock_unit: row.stock_unit || '',
@ -189,10 +188,6 @@ class StockWarehouseService extends Service {
if (cached && !Array.isArray(cached.image_url)) {
cached.image_url = [];
}
// 兼容旧缓存:无 need_recheck 时补默认(需要复核)
if (cached && cached.need_recheck == null) {
cached.need_recheck = 'Y';
}
result.push(cached);
}
} else if (dbResults.has(stockId)) {

View File

@ -490,37 +490,12 @@ class EntryService extends Service {
}
}
// 批量聚合当前页入库单的商品总数量(计划数)与已入库数量
/** @type {Map<number, {total_quantity: number, received_quantity: number}>} */
const quantityMap = new Map();
if (entryOrderIds.length > 0) {
const quantityRows = await ctx.model.EntryItems.findAll({
attributes: [
'order_id',
[ Sequelize.fn('SUM', Sequelize.col('count')), 'total_quantity' ],
[ Sequelize.fn('SUM', Sequelize.col('received_quantity')), 'received_quantity' ],
],
where: { order_id: { [Op.in]: entryOrderIds } },
group: [ 'order_id' ],
raw: true,
});
for (const item of quantityRows) {
quantityMap.set(Number(item.order_id), {
total_quantity: Number(item.total_quantity) || 0,
received_quantity: Number(item.received_quantity) || 0,
});
}
}
// 为每行附加收货单绑定信息与数量汇总
// 为每行附加收货单绑定信息
const enrichedRows = rows.map(row => {
const rowJSON = row.toJSON ? row.toJSON() : row;
const bindings = receivingBindingsMap.get(row.id) || [];
const quantity = quantityMap.get(row.id) || { total_quantity: 0, received_quantity: 0 };
return {
...rowJSON,
total_quantity: quantity.total_quantity,
received_quantity: quantity.received_quantity,
receivingBindings: bindings,
hasReceiving: bindings.length > 0,
};
@ -1717,10 +1692,9 @@ class EntryService extends Service {
}
/**
* 入库单商品与收货单商品对照视图(支持多个收货单)。
* 以入库单明细为对比主体:多个收货单的明细先合并为一个整体,
* 再与入库单明细做一次对照,每个入库明细只输出一行,
* 避免多收货单时入库计划数量被重复展开。
* 入库单商品与收货单商品逐行对照视图(支持多个收货单)。
* 以入库单明细为主,按 stock_id ↔ system_product_id 匹配收货单明细,
* 返回每个收货单的匹配/未匹配/收货单多余对照结果及汇总。
*
* @param {Object} data 请求参数
* @param {number} data.entry_order_id 入库单ID
@ -1729,8 +1703,7 @@ class EntryService extends Service {
* @return {Promise<Object>} code/data/message 结构
*/
async receivingCompare(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const { ctx } = this;
const entryOrderId = Number(data.entry_order_id || 0);
const warehouseId = ctx.user.store_id;
@ -1756,53 +1729,39 @@ class EntryService extends Service {
return { code: 404, message: '入库单不存在或无权访问', data: null };
}
// 2. 查询入库单明细
// 2. 查询入库单明细(所有收货单共用)
const entryItems = await ctx.model.EntryItems.findAll({
where: { order_id: entryOrderId },
attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ],
raw: true,
});
// 3. 批量校验收货单(同仓库、未删除),无效的进入 errors
const receivingOrders = await ctx.model.Receiving.findAll({
where: {
id: { [Op.in]: receivingIds },
warehouse_id: warehouseId,
is_deleted: false,
},
attributes: [ 'id', 'receiving_number' ],
raw: true,
});
const receivingOrderMap = new Map(receivingOrders.map(row => [ Number(row.id), row ]));
// 3. 收集入库单所有 stock_id
const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ];
// 4. 对每个收货单执行对比
const comparisons = [];
const errors = [];
for (const receivingId of receivingIds) {
if (!receivingOrderMap.has(receivingId)) {
errors.push({
receiving_id: receivingId,
status: 'error',
error_code: 'RECEIVING_NOT_FOUND',
error_message: '收货单不存在或无权访问',
});
const singleResult = await this._compareSingleReceiving({
receivingId,
warehouseId,
entryOrderId,
entryOrder,
entryItems,
entryStockIds,
});
if (singleResult._error) {
errors.push(singleResult._error);
} else {
comparisons.push(singleResult);
}
}
const validReceivingIds = [ ...receivingOrderMap.keys() ];
// 4. 合并所有有效收货单的明细,再与入库单做一次对照
let receivingDetails = [];
if (validReceivingIds.length > 0) {
receivingDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: { [Op.in]: validReceivingIds } },
attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'product_name' ],
raw: true,
});
}
const merged = await this._buildMergedComparison({
warehouseId,
entryItems,
receivingDetails,
receivingOrderMap,
});
const totalReceivings = receivingIds.length;
const matchedCount = comparisons.length;
const errorCount = errors.length;
return {
code: 200,
@ -1810,64 +1769,93 @@ class EntryService extends Service {
data: {
entry_order_id: entryOrderId,
entry_order_code: entryOrder.entry_order_code,
comparison: merged.comparison,
receiving_only: merged.receivingOnly,
summary: merged.summary,
comparisons,
errors,
total_summary: {
total_receivings: receivingIds.length,
matched_count: validReceivingIds.length,
error_count: errors.length,
total_receivings: totalReceivings,
matched_count: matchedCount,
error_count: errorCount,
},
},
};
}
/**
* 将多个收货单的明细合并后,与入库单明细做一次对照。
* 每个入库明细只输出一行(matched/entry_only),匹配时合并各收货单数量,
* 并通过 receiving_sources 列出各收货单来源明细。
*
* 对单个收货单执行商品对照逻辑。
* @param {Object} params 参数
* @param {number} params.receivingId 收货单ID
* @param {number} params.warehouseId 仓库ID
* @param {number} params.entryOrderId 入库单ID
* @param {Object} params.entryOrder 入库单记录
* @param {Object[]} params.entryItems 入库单明细列表
* @param {Object[]} params.receivingDetails 已合并的收货单明细列表
* @param {Map} params.receivingOrderMap 有效收货单 Map(id → 收货单记录)
* @return {Promise<Object>} { comparison, receivingOnly, summary }
* @param {number[]} params.entryStockIds 入库单 stock_id 集合
* @return {Promise<Object>} 单个收货单的对照结果,或 { _error: ... }
*/
async _buildMergedComparison(params = {}) {
async _compareSingleReceiving(params = {}) {
const { ctx, app } = this;
const { warehouseId, entryItems, receivingDetails, receivingOrderMap } = params;
const { receivingId, warehouseId, entryItems, entryStockIds } = params;
// 校验收货单存在性与仓库匹配
const receivingOrder = await ctx.model.Receiving.findOne({
where: {
id: receivingId,
warehouse_id: warehouseId,
is_deleted: false,
},
attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ],
raw: true,
});
if (!receivingOrder) {
return {
_error: {
receiving_id: receivingId,
status: 'error',
error_code: 'RECEIVING_NOT_FOUND',
error_message: '收货单不存在或无权访问',
},
};
}
// 查询收货单明细
const receivingDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: receivingId },
attributes: [ 'id', 'system_product_id', 'actual_quantity', 'product_name' ],
raw: true,
});
// 收集所有 stock_id,批量查询商品信息
const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ];
const receivingSystemProductIds = [ ...new Set(receivingDetails.map(d => Number(d.system_product_id)).filter(Boolean)) ];
const allStockIds = [ ...new Set([ ...entryStockIds, ...receivingSystemProductIds ]) ];
const stockDetailMap = new Map();
if (allStockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(allStockIds, { warehouseId });
for (const detail of stockDetails) {
stockDetailMap.set(Number(detail.id), detail);
stockDetailMap.set(detail.id, detail);
}
}
// 仓库范围内有效的入库商品 stock_id(与原逻辑一致:仅匹配本仓库库存记录)
const validEntryStockIds = new Set(entryStockIds);
// stock_id ↔ system_product_id 映射
const stockIdToSystemProductId = new Map();
const systemProductIdToEntryStockIds = new Map();
if (entryStockIds.length > 0) {
const swRows = await ctx.model.StockWarehouse.findAll({
where: { id: { [app.Sequelize.Op.in]: entryStockIds }, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
validEntryStockIds.clear();
for (const row of swRows) {
validEntryStockIds.add(Number(row.id));
const stockId = Number(row.id);
stockIdToSystemProductId.set(stockId, stockId);
if (!systemProductIdToEntryStockIds.has(stockId)) {
systemProductIdToEntryStockIds.set(stockId, []);
}
systemProductIdToEntryStockIds.get(stockId).push(stockId);
}
}
// 查询已分配量(限定本入库单的 entry_items,避免全局绑定干扰)
const receivingDetailIds = receivingDetails.map(d => Number(d.id));
const entryItemIds = entryItems.map(ei => Number(ei.id));
const receivingDetailIds = receivingDetails.map(d => d.id);
const entryItemIds = entryItems.map(ei => ei.id);
const allocatedMap = new Map();
if (receivingDetailIds.length > 0 && entryItemIds.length > 0) {
const bindingRows = await ctx.model.InboundDirectLog.findAll({
@ -1889,67 +1877,42 @@ class EntryService extends Service {
}
}
// 按 stock_id 索引收货明细,供合并匹配
const detailsByStockId = new Map();
for (const rd of receivingDetails) {
const stockId = Number(rd.system_product_id) || 0;
if (stockId <= 0) continue;
if (!detailsByStockId.has(stockId)) {
detailsByStockId.set(stockId, []);
}
detailsByStockId.get(stockId).push(rd);
}
// 组装单个收货明细的来源信息
const buildSource = rd => {
const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null;
const allocated = allocatedMap.get(Number(rd.id)) || 0;
const quantity = Number(rd.actual_quantity) || 0;
return {
receiving_id: Number(rd.receiving_id),
receiving_number: (receivingOrderMap.get(Number(rd.receiving_id)) || {}).receiving_number || '',
receiving_detail_id: Number(rd.id),
receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '',
receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '',
receiving_actual_quantity: quantity,
receiving_allocated: allocated,
receiving_available: Math.max(0, quantity - allocated),
};
};
// 构建对照视图:以入库单明细为主,每个入库明细只输出一行
// 构建对照视图:以入库单明细为主
const comparison = [];
const matchedReceivingDetailIds = new Set();
for (const entryItem of entryItems) {
const stockId = Number(entryItem.stock_id || 0);
const systemProductId = stockIdToSystemProductId.get(stockId) || 0;
const stockDetail = stockDetailMap.get(stockId) || null;
const matchedDetails = stockId > 0 && validEntryStockIds.has(stockId)
? (detailsByStockId.get(stockId) || [])
const matchedReceiving = systemProductId > 0
? receivingDetails.filter(rd => Number(rd.system_product_id) === systemProductId)
: [];
if (matchedDetails.length > 0) {
const sources = [];
for (const rd of matchedDetails) {
matchedReceivingDetailIds.add(Number(rd.id));
sources.push(buildSource(rd));
if (matchedReceiving.length > 0) {
for (const rd of matchedReceiving) {
matchedReceivingDetailIds.add(rd.id);
const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null;
const allocated = allocatedMap.get(Number(rd.id)) || 0;
const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated);
comparison.push({
entry_item_id: Number(entryItem.id),
stock_id: stockId,
warehouse_item_code: (stockDetail && stockDetail.item_code) || '',
warehouse_item_name: (stockDetail && stockDetail.item_name) || '',
warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '',
entry_count: Number(entryItem.count) || 0,
entry_received: Number(entryItem.received_quantity) || 0,
receiving_detail_id: Number(rd.id),
receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '',
receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '',
receiving_actual_quantity: Number(rd.actual_quantity) || 0,
receiving_allocated: allocated,
receiving_available: available,
match_status: 'matched',
});
}
const mergedQuantity = sources.reduce((sum, source) => sum + source.receiving_actual_quantity, 0);
const mergedAllocated = sources.reduce((sum, source) => sum + source.receiving_allocated, 0);
comparison.push({
entry_item_id: Number(entryItem.id),
stock_id: stockId,
warehouse_item_code: (stockDetail && stockDetail.item_code) || '',
warehouse_item_name: (stockDetail && stockDetail.item_name) || '',
warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '',
entry_count: Number(entryItem.count) || 0,
entry_received: Number(entryItem.received_quantity) || 0,
match_status: 'matched',
receiving_quantity: mergedQuantity,
receiving_allocated: mergedAllocated,
receiving_available: Math.max(0, mergedQuantity - mergedAllocated),
receiving_sources: sources,
});
} else {
comparison.push({
entry_item_id: Number(entryItem.id),
@ -1959,52 +1922,69 @@ class EntryService extends Service {
warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '',
entry_count: Number(entryItem.count) || 0,
entry_received: Number(entryItem.received_quantity) || 0,
receiving_detail_id: null,
receiving_product_code: null,
receiving_product_name: null,
receiving_actual_quantity: null,
receiving_allocated: null,
receiving_available: null,
match_status: 'entry_only',
receiving_quantity: 0,
receiving_allocated: 0,
receiving_available: 0,
receiving_sources: [],
});
}
}
// 收货单中多余的商品(合并后仍未匹配到任何入库明细的收货明细,按商品合并)
const receivingOnlyMap = new Map();
// 收货单中多余的商品
const receivingOnly = [];
const receivingStockMap = new Map();
for (const rd of receivingDetails) {
if (matchedReceivingDetailIds.has(Number(rd.id))) continue;
const stockId = rd.system_product_id != null ? Number(rd.system_product_id) : null;
const source = buildSource(rd);
const key = stockId === null || Number.isNaN(stockId) ? '__none__' : String(stockId);
if (receivingOnlyMap.has(key)) {
const existing = receivingOnlyMap.get(key);
existing.receiving_actual_quantity += source.receiving_actual_quantity;
existing.receiving_allocated += source.receiving_allocated;
existing.receiving_available = Math.max(0, existing.receiving_available + source.receiving_available);
if (!existing.receiving_product_name && source.receiving_product_name) {
existing.receiving_product_name = source.receiving_product_name;
if (!matchedReceivingDetailIds.has(Number(rd.id))) {
const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null;
const stockId = rd.system_product_id != null ? Number(rd.system_product_id) : null;
const qty = Number(rd.actual_quantity) || 0;
const name = rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '';
const allocated = allocatedMap.get(Number(rd.id)) || 0;
const available = Math.max(0, qty - allocated);
if (stockId === null) {
receivingOnly.push({
receiving_product_name: name,
receiving_actual_quantity: qty,
receiving_allocated: allocated,
receiving_available: available,
});
} else if (receivingStockMap.has(stockId)) {
const existing = receivingStockMap.get(stockId);
existing.receiving_actual_quantity += qty;
existing.receiving_allocated += allocated;
existing.receiving_available += available;
if (!existing.receiving_product_name && name) {
existing.receiving_product_name = name;
}
} else {
receivingStockMap.set(stockId, {
receiving_product_name: name,
receiving_actual_quantity: qty,
receiving_allocated: allocated,
receiving_available: available,
});
}
existing.receiving_sources.push(source);
} else {
receivingOnlyMap.set(key, {
stock_id: stockId,
receiving_product_code: source.receiving_product_code,
receiving_product_name: source.receiving_product_name,
receiving_actual_quantity: source.receiving_actual_quantity,
receiving_allocated: source.receiving_allocated,
receiving_available: source.receiving_available,
receiving_sources: [ source ],
});
}
}
const receivingOnly = [ ...receivingOnlyMap.values() ];
for (const item of receivingStockMap.values()) {
item.receiving_available = Math.max(0, item.receiving_available);
receivingOnly.push(item);
}
// 汇总
const matchedItems = comparison.filter(c => c.match_status === 'matched').length;
const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length;
return {
receiving_id: receivingId,
receiving_number: receivingOrder.receiving_number,
status: 'matched',
comparison,
receivingOnly,
receiving_only: receivingOnly,
summary: {
total_entry_items: entryItems.length,
matched_items: matchedItems,

File diff suppressed because it is too large Load Diff

View File

@ -2642,21 +2642,6 @@ class ReceivingService extends Service {
}
try {
// 默认库位:优先使用仓库设置 default_location_id,未设置则兜底库位 1
let defaultSpaceId = 1;
try {
const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder;
const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function'
? await deliveryOrderService.getStoreSubjectConfig(warehouse_id)
: null;
const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0);
if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) {
defaultSpaceId = configuredLocationId;
}
} catch (error) {
ctx.logger.warn('[receiving.addDetail] 读取仓库默认库位失败,兜底库位 1: %s', error.message);
}
const defaultDetail = {
receiving_id,
product_name: '新商品',
@ -2672,7 +2657,7 @@ class ReceivingService extends Service {
production_date: null,
expiry_date: null,
remark: '',
space_id: defaultSpaceId,
space_id: 1,
creator_id,
};

View File

@ -31,7 +31,7 @@ class StockWarehouseService extends Service {
* @param {Object} [options={}] 选项
* @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id)
* @param {number} [options.cacheTTL=300] 缓存过期时间(秒)
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, image_url: string, is_images: string, need_recheck: string, store_id: number, packing_requirements: string, stock_unit: string, barcodes: Array<{id: number, barcode: string, sku_property: string}>}>>} 商品详情列表
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, image_url: string, is_images: string, store_id: number, packing_requirements: string, stock_unit: string, barcodes: Array<{id: number, barcode: string, sku_property: string}>}>>} 商品详情列表
*/
async getStockDetails(stockIds, options = {}) {
const { ctx, app } = this;
@ -77,7 +77,6 @@ class StockWarehouseService extends Service {
'id', 'item_code', 'item_name', 'sku_property',
'quantity', 'locked_quantity', 'is_batch_mgmt',
'is_shelf_life_mgmt', 'image_url', 'is_images',
'need_recheck',
'store_id', 'packing_requirements', 'stock_unit',
],
raw: true,
@ -117,7 +116,6 @@ class StockWarehouseService extends Service {
is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N',
image_url: row.image_url || '',
is_images: row.is_images || 'N',
need_recheck: row.need_recheck || 'Y',
store_id: row.store_id != null ? Number(row.store_id) : 0,
packing_requirements: row.packing_requirements || '',
stock_unit: row.stock_unit || '',
@ -155,10 +153,6 @@ class StockWarehouseService extends Service {
const cached = cacheHits.get(stockId);
// 空标记(防穿透缓存)跳过
if (cached !== null && cached !== undefined) {
// 兼容旧缓存:无 need_recheck 时补默认(需要复核)
if (cached.need_recheck == null) {
cached.need_recheck = 'Y';
}
result.push(cached);
}
} else if (dbResults.has(stockId)) {

View File

@ -407,13 +407,12 @@ class SettingStoreWarehouseService extends Service {
transaction,
}
);
} else {
await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30);
return;
}
// 清除签约策略缓存(sw_policy:{storeId}:{warehouseId}):
// 该缓存内嵌 policy_config 快照与 allowOversell 判定,策略变更(如开启允许超卖)后必须失效,
// 否则奇门推送订单会继续读取旧快照,导致超卖开关生效前仍提示库存不足。
await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30);
// 清除签约策略缓存(sw_policy:{storeId}:{warehouseId})
const relation = await this.ctx.model.StoreWarehouse.findByPk(normalizedId, {
attributes: [ 'store_id', 'warehouse_id' ],
raw: true,
@ -3276,167 +3275,6 @@ class SettingStoreWarehouseService extends Service {
throw error;
}
}
/**
* 为货主创建用户:按用户名查询账号,不存在则注册账号并返回随机生成的密码,
* 两种情况统一完成货主工号绑定与货主管理员角色(wms_role.id=5)授权,幂等执行。
* 货主审核中(wms_store.status=2)时自动转为启用(1)。
*
* @param {Object} [data={}] 请求参数。
* @param {string} data.username 用户名(必填,3-50 位字母、数字或下划线)。
* @param {number|string} data.store_id 货主 ID(必填)。
* @return {Promise<Object>} 响应对象,data 包含 account_id、username、store_id、created;
* 仅新建账号时返回 password 明文密码。
* @throws {Error} 参数缺失或格式非法时抛出 400,货主不存在时抛出 404,
* 货主管理员角色未初始化时抛出 500。
*/
async createUser(data = {}) {
const { ctx } = this;
const {
username: rawUsername,
store_id: rawStoreId,
} = data;
// 1. 校验必填参数
const username = this.normalizeText(rawUsername, 'username', 50);
if (!username) {
throw this.createError('username 参数不能为空', 400);
}
if (!/^[a-zA-Z0-9_]{3,50}$/.test(username)) {
throw this.createError('用户名格式不合法,需为 3-50 位字母、数字或下划线', 400);
}
const storeId = this.toPositiveNumber(rawStoreId, 'store_id');
// 2. 校验货主存在(同时取 status 用于后续审核中状态修正)
const store = await ctx.model.Store.findOne({
where: { id: storeId },
attributes: [ 'id', 'status' ],
});
if (!store) {
throw this.createError('货主不存在', 404);
}
// 3. 查询账号是否存在
const existingAccount = await ctx.model.Account.findOne({
where: { username },
attributes: [ 'id', 'username' ],
});
// 4. 随机生成密码(仅新建账号时使用)
const randomPassword = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '')
.slice(0, 12);
// 5. 事务内执行账号创建与授权绑定
const transaction = await ctx.model.transaction();
try {
// 5.0 货主审核中(status=2)时自动转为启用(1),store 实例在事务外查询,更新时显式传入事务
if (Number(store.status) === 2) {
await store.update({ status: 1 }, { transaction });
}
let accountId = null;
let created = false;
if (existingAccount) {
// 账号已存在:不创建、不返回密码
accountId = Number(existingAccount.id);
created = false;
} else {
// 账号不存在:复用注册服务,email/real_name 使用占位兜底
const registerResult = await ctx.service.systems.auth.user.register({
username,
password: randomPassword,
email: `${username}@placeholder.local`,
real_name: username,
}, transaction);
accountId = Number(registerResult.userId);
created = true;
}
// 6. 货主工号绑定(幂等:已存在但 status=0 时恢复为 1)
const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({
where: {
account_id: accountId,
store_id: storeId,
},
defaults: {
account_id: accountId,
store_id: storeId,
status: 1,
real_name: username,
},
transaction,
});
if (Number(employee.status) !== 1) {
await employee.update({
status: 1,
}, { transaction });
}
// 7. 确认货主管理员角色(wms_role.id=5)已初始化
const storeAdminRole = await ctx.model.Role.findByPk(5, { transaction });
if (!storeAdminRole) {
throw this.createError('货主管理员角色(id=5)未初始化', 500);
}
// 8. 授予货主管理员角色(幂等:findOrCreate)
await ctx.model.EmployeeRole.findOrCreate({
where: {
employee_id: employee.id,
role_id: 5,
},
defaults: {
employee_id: employee.id,
role_id: 5,
},
transaction,
});
await transaction.commit();
// 9. 记录操作日志(不影响业务主流程)
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: storeId,
operationCode: 'STORE_CREATE_USER',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
storeId: Number(storeId),
accountId: Number(accountId),
created,
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.createUser] 写入操作日志失败,不影响业务', logErr);
}
// 10. 组装响应:仅新建账号时返回明文密码
const resultData = {
account_id: accountId,
username,
store_id: storeId,
created,
};
if (created) {
resultData.password = randomPassword;
}
return {
code: 200,
data: resultData,
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
}
module.exports = SettingStoreWarehouseService;

View File

@ -353,8 +353,6 @@ class WorkbenchService extends Service {
const changeSummary = this._buildPackChangeSummary(packData);
const operationCode = isSandan === 1 ? 'ORDER_PACK' : 'ORDER_PACK_GROUP';
const isFinish = Number(packData && packData.status) >= 2;
const actionText = isFinish ? '打包完成' : '开始打包';
if (isSandan === 1) {
// 散单:写入单个订单操作日志
@ -365,7 +363,7 @@ class WorkbenchService extends Service {
operator,
extras: {
warehouseId,
message: `散单${actionText}:${changeSummary}`,
message: `散单打包完成:${changeSummary}`,
},
}]);
ctx.logger.info('[Workbench._writePackOperationLog] 散单操作日志已写入 orderId=%d', orderId);
@ -380,7 +378,7 @@ class WorkbenchService extends Service {
operator,
extras: {
warehouseId,
message: `${actionText}:${changeSummary}`,
message: `打包完成:${changeSummary}`,
},
}]);
return;
@ -396,13 +394,13 @@ class WorkbenchService extends Service {
operator,
extras: {
warehouseId,
message: `${actionText}(波次 ${waveNo || waveId}):${changeSummary}`,
message: `打包完成(波次 ${waveNo || waveId}):${changeSummary}`,
},
}]);
return;
}
const messagePrefix = `${isFinish ? '团购打包完成' : '团购开始打包'}(波次 ${waveNo || waveId},共${waveOrderIds.length}单):`;
const messagePrefix = `团购打包完成(波次 ${waveNo || waveId},共${waveOrderIds.length}单):`;
const payloads = waveOrderIds.map(oid => ({
businessType: 'order',
businessId: String(oid),
@ -428,75 +426,6 @@ class WorkbenchService extends Service {
}
}
/**
* 更新订单打包状态字段(散单按订单ID更新单笔,团购按波次批量更新)。
* 遍历 current + dispatch 分表,异常仅记录日志不影响主流程。
* 团购批量更新时跳过拦截订单(intercept_status 空值按 none 处理)。
*
* @param {number} warehouseId 仓库ID
* @param {Object} options
* @param {number} options.orderId 订单ID(散单使用)
* @param {number} options.waveId 波次ID(>0 时按团购批量更新)
* @param {number|string} options.packStatus 任务状态数值(1=打包中 2=已完成)
* @param {string} [options.caller] 调用方标识(仅用于日志)
* @returns {Promise<string>} 实际写入的 pack_status 值
*/
async _updateOrderPackStatus(warehouseId, { orderId, waveId, packStatus, caller = 'Workbench' }) {
const { ctx } = this;
const statusNum = parseInt(packStatus);
const orderPackStatus = statusNum >= 2 ? 'fin' : (statusNum === 1 ? 'padding' : 'fin');
const orderUpdateData = { pack_status: orderPackStatus };
const orderDeliveryFactory = ctx.model.OrderDeliveryFactory;
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
if (waveId > 0) {
// 团购:批量更新波次下所有未拦截订单
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model) continue;
const affected = await model.update(orderUpdateData, {
where: {
wave_id: waveId,
warehouse_id: warehouseId,
intercept_status: { [ctx.app.Sequelize.Op.in]: [ 'none', null ] },
},
});
if (affected[0] > 0) {
ctx.logger.info('[%s._updateOrderPackStatus] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d',
caller, waveId, orderPackStatus, entry.label, affected[0]);
}
} catch (err) {
ctx.logger.warn('[%s._updateOrderPackStatus] 更新分表 %s 失败: %s', caller, entry.label, err.message);
}
}
} else {
// 散单:按订单ID更新单个订单
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model) continue;
const affected = await model.update(orderUpdateData, {
where: { id: orderId, warehouse_id: warehouseId },
});
if (affected[0] > 0) {
ctx.logger.info('[%s._updateOrderPackStatus] 更新订单打包状态 orderId=%d pack_status=%s table=%s',
caller, orderId, orderPackStatus, entry.label);
break;
}
} catch (err) {
ctx.logger.warn('[%s._updateOrderPackStatus] 更新分表 %s 失败: %s', caller, entry.label, err.message);
}
}
}
return orderPackStatus;
}
/**
* 打包任务写入:根据发货单号查询订单并创建/更新打包任务记录
* @param {Object} params - { delivery_order_code, wave_no, warehouse_id, workbench_id, status, pack_time }
@ -672,13 +601,44 @@ class WorkbenchService extends Service {
const packTask = await ctx.model.PackTask.create(packData);
ctx.logger.info('[Workbench._packOrder] 创建打包任务 taskId=%d orderId=%d', packTask.id, orderId);
// 步骤6.5:更新订单的打包状态字段(散单按订单更新,团购按波次批量更新)
await this._updateOrderPackStatus(warehouseId, {
orderId,
waveId: isSandan === 1 ? 0 : waveId,
packStatus,
caller: 'Workbench._packOrder',
});
// 步骤6.5:更新订单的打包状态字段
const orderPackStatus = (packStatus !== undefined && parseInt(packStatus) >= 2) ? 'fin'
: (packStatus !== undefined && parseInt(packStatus) === 1) ? 'padding'
: 'fin';
const orderUpdateData = { pack_status: orderPackStatus };
if (isSandan === 1) {
// 散单:更新单个订单
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model) continue;
const affected = await model.update(orderUpdateData, {
where: { id: orderId, warehouse_id: warehouseId },
});
if (affected[0] > 0) {
ctx.logger.info('[Workbench._packOrder] 更新订单打包状态 orderId=%d pack_status=%s table=%s',
orderId, orderPackStatus, entry.label);
break;
}
} catch (_err) { continue; }
}
} else if (waveId > 0) {
// 团购:批量更新波次下所有订单(拦截订单不更新)
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model) continue;
const affected = await model.update(orderUpdateData, {
where: { wave_id: waveId, warehouse_id: warehouseId, intercept_status: 'none' },
});
if (affected[0] > 0) {
ctx.logger.info('[Workbench._packOrder] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d',
waveId, orderPackStatus, entry.label, affected[0]);
}
} catch (_err) { continue; }
}
}
// 步骤7:写入打包人员信息
const users = Array.isArray(usersParam) ? usersParam : [];
@ -884,37 +844,6 @@ class WorkbenchService extends Service {
ctx.logger.info('[Workbench._finishPack] 工作台 %d 结束打包任务 taskId=%d orderId=%d',
validWorkbenchId, lastTask.id, lastTask.order_id);
// 同步更新关联订单打包状态:散单更新单笔订单,团购批量更新波次下所有未拦截订单
const isGroupTask = Number(lastTask.pack_mode) === 2;
const taskOrderId = Number(lastTask.order_id || 0);
const taskWaveId = isGroupTask ? Number(lastTask.wave_id || 0) : 0;
await this._updateOrderPackStatus(warehouseId, {
orderId: taskOrderId,
waveId: taskWaveId,
packStatus: 2,
caller: 'Workbench._finishPack',
});
// 写入完成操作日志(团购批量写波次订单,操作人取自任务记录 operator_text)
const operatorText = String(lastTask.operator_text || '');
await this._writePackOperationLog({
warehouseId,
orderId: taskOrderId,
waveId: taskWaveId,
waveNo: lastTask.wave_no || '',
isSandan: isGroupTask ? 0 : 1,
packData: {
pack_mode: lastTask.pack_mode,
status: 2,
pack_quantity: lastTask.pack_quantity,
item_quantity: lastTask.item_quantity,
sku_count: lastTask.sku_count,
workbench_id: validWorkbenchId,
wave_no: lastTask.wave_no,
},
users: operatorText ? [{ real_name: operatorText }] : [],
});
return {
workbench_id: validWorkbenchId,
finished: true,
@ -1274,24 +1203,13 @@ class WorkbenchService extends Service {
const { order_id: orderId, waybill_code: waybillCode } = expressRecord;
// 步骤2:序列表定位优先(命中则先查对应分表),未命中按 current → dispatch 回退遍历
// 步骤2:遍历 current → dispatch 分表查找订单详情
const orderDeliveryFactory = ctx.model.OrderDeliveryFactory;
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
try {
if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId);
if (preferredLocation) {
tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (locErr) {
ctx.logger.warn('[Workbench._queryOrder] 序列表定位失败,按默认顺序遍历: %s', locErr.message);
}
let orderRow = null;
let sourceTable = null;
for (const entry of tableOrders) {
@ -1457,7 +1375,6 @@ class WorkbenchService extends Service {
wave_no: orderRow.wave_no,
post_status: orderRow.post_status,
pick_status: orderRow.pick_status,
pack_status: orderRow.pack_status,
recheck_status: orderRow.recheck_status,
outbound_status: orderRow.outbound_status,
items_count: orderRow.items_count,

View File

@ -1,254 +0,0 @@
'use strict';
/**
* wms_wave_batch.wave_no 唯一化。
*
* 背景:并发创建波次时「查当日最大序号+1」存在竞态,可能产生 wave_no 相同的多行
* (不同 wave_id、不同订单组),导致两组订单共用一个波次号。
*
* 本迁移:
* 1. 修复存量重复波次号:同一 wave_no 保留最早(wave_id 最小)一行,
* 其余行按「前缀+日期+下一个空闲序号」重新编号,并同步引用方数据
* (订单表四个车道、拣货任务波次关联表、打印记录、打包任务)的 wave_no;
* 2. 移除冗余的非唯一索引 idx_wave_no(若存在);
* 3. 新增唯一索引 uniq_wave_no(若已人工添加则跳过,保证幂等)。
*/
const TABLE_NAME = 'wms_wave_batch';
/**
* 归一化索引字段名(Sequelize 各版本返回 string 或 { attribute } 对象)。
*
* @param {Array<Object|string>} fields 索引字段列表。
* @return {Array<string>} 字段名字符串列表。
*/
function normalizeIndexFields(fields) {
return (Array.isArray(fields) ? fields : [])
.map(field => String(
typeof field === 'string' ? field : (field && (field.attribute || field.name || ''))
).trim())
.filter(Boolean);
}
/**
* 判断索引列表是否包含指定名称的非唯一/唯一 wave_no 索引。
*
* @param {Array<Object>} indexes showIndex 结果。
* @param {string} indexName 索引名称。
* @param {boolean} unique 是否唯一索引。
* @return {boolean} 是否存在。
*/
function hasWaveNoIndex(indexes, indexName, unique) {
return (Array.isArray(indexes) ? indexes : []).some(index => {
if (!index || index.name !== indexName) {
return false;
}
const fields = normalizeIndexFields(index.fields);
return fields.length === 1 && fields[0] === 'wave_no' && Boolean(index.unique) === unique;
});
}
/**
* 查询存量重复的波次号。
*
* @param {Object} queryInterface Sequelize 查询接口。
* @return {Promise<Array<{wave_no: string, cnt: number}>>} 重复波次号列表。
*/
async function fetchDuplicateWaveNos(queryInterface) {
return await queryInterface.sequelize.query(
`SELECT wave_no, COUNT(*) AS cnt
FROM ${TABLE_NAME}
GROUP BY wave_no
HAVING COUNT(*) > 1
ORDER BY wave_no ASC`,
{ type: queryInterface.sequelize.QueryTypes.SELECT }
);
}
/**
* 计算「前缀+日期」片段下下一个空闲波次号。
*
* @param {Object} queryInterface Sequelize 查询接口。
* @param {string} prefixDate 波次号前缀+日期片段(如 B20260822)。
* @return {Promise<string>} 下一个空闲波次号。
*/
async function buildNextFreeWaveNo(queryInterface, prefixDate) {
const startPos = String(prefixDate).length + 1;
const rows = await queryInterface.sequelize.query(
`SELECT IFNULL(MAX(CAST(SUBSTRING(wave_no, :startPos) AS UNSIGNED)), 0) + 1 AS seq
FROM ${TABLE_NAME}
WHERE wave_no LIKE :pattern`,
{
replacements: { startPos, pattern: `${prefixDate}%` },
type: queryInterface.sequelize.QueryTypes.SELECT,
}
);
const seq = Number(rows && rows[0] && rows[0].seq || 1);
return `${prefixDate}${String(seq).padStart(5, '0')}`;
}
/**
* 判断波次号是否已存在。
*
* @param {Object} queryInterface Sequelize 查询接口。
* @param {string} waveNo 波次号。
* @return {Promise<boolean>} 是否已存在。
*/
async function waveNoExists(queryInterface, waveNo) {
const rows = await queryInterface.sequelize.query(
`SELECT wave_id FROM ${TABLE_NAME} WHERE wave_no = :waveNo LIMIT 1`,
{ replacements: { waveNo }, type: queryInterface.sequelize.QueryTypes.SELECT }
);
return Array.isArray(rows) && rows.length > 0;
}
/**
* 更新指定表内该波次的 wave_no(表不存在时跳过)。
*
* @param {Object} queryInterface Sequelize 查询接口。
* @param {string} tableName 表名。
* @param {number} warehouseId 仓库ID。
* @param {number} waveId 波次ID。
* @param {string} waveNo 新波次号。
* @return {Promise<void>} 无返回值。
*/
async function updateTableWaveNo(queryInterface, tableName, warehouseId, waveId, waveNo) {
const checkRows = await queryInterface.sequelize.query(
`SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName`,
{ replacements: { tableName }, type: queryInterface.sequelize.QueryTypes.SELECT }
);
if (!Array.isArray(checkRows) || checkRows.length === 0) {
return;
}
await queryInterface.sequelize.query(
`UPDATE \`${tableName}\`
SET wave_no = :waveNo
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
AND wave_no <> :waveNo`,
{ replacements: { waveNo, warehouseId, waveId } }
);
}
/**
* 同步某波次被重编号后所有引用方表中的 wave_no。
*
* @param {Object} queryInterface Sequelize 查询接口。
* @param {number} warehouseId 仓库ID。
* @param {number} waveId 波次ID。
* @param {string} waveNo 新波次号。
* @return {Promise<void>} 无返回值。
*/
async function syncWaveNoReferences(queryInterface, warehouseId, waveId, waveNo) {
if (Number.isInteger(warehouseId) && warehouseId > 0) {
await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}`, warehouseId, waveId, waveNo);
await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_history`, warehouseId, waveId, waveNo);
await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_dispatch`, warehouseId, waveId, waveNo);
await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_outsourced`, warehouseId, waveId, waveNo);
}
await updateTableWaveNo(queryInterface, 'wms_wave_pick_task_wave', warehouseId, waveId, waveNo);
await updateTableWaveNo(queryInterface, 'wms_print_record', warehouseId, waveId, waveNo);
await updateTableWaveNo(queryInterface, 'wms_pack_task', warehouseId, waveId, waveNo);
}
module.exports = {
async up(queryInterface) {
// 1. 修复存量重复波次号:同一 wave_no 保留最早一行,其余重新编号
const duplicateRows = await fetchDuplicateWaveNos(queryInterface);
for (const dup of (Array.isArray(duplicateRows) ? duplicateRows : [])) {
const waveNo = String(dup && dup.wave_no || '').trim();
if (!waveNo) {
continue;
}
const rows = await queryInterface.sequelize.query(
`SELECT wave_id, warehouse_id
FROM ${TABLE_NAME}
WHERE wave_no = :waveNo
ORDER BY wave_id ASC`,
{ replacements: { waveNo }, type: queryInterface.sequelize.QueryTypes.SELECT }
);
if (!Array.isArray(rows) || rows.length <= 1) {
continue;
}
const prefixDate = waveNo.replace(/\d+$/, '');
if (!prefixDate) {
throw new Error(`波次号 ${waveNo} 无字母前缀,无法自动重编号,请人工处理`);
}
// 保留最早(wave_id 最小)的一行,其余行重新编号
for (let index = 1; index < rows.length; index += 1) {
const row = rows[index];
const waveId = Number(row && row.wave_id || 0);
const warehouseId = Number(row && row.warehouse_id || 0);
if (!Number.isInteger(waveId) || waveId <= 0) {
continue;
}
let nextWaveNo = await buildNextFreeWaveNo(queryInterface, prefixDate);
let guard = 0;
while (guard < 100 && await waveNoExists(queryInterface, nextWaveNo)) {
nextWaveNo = await buildNextFreeWaveNo(queryInterface, prefixDate);
guard += 1;
}
if (guard >= 100) {
throw new Error(`波次号 ${waveNo} 重新编号失败:无法找到空闲编号`);
}
await queryInterface.sequelize.query(
`UPDATE ${TABLE_NAME}
SET wave_no = :nextWaveNo, update_time = NOW()
WHERE wave_id = :waveId`,
{ replacements: { nextWaveNo, waveId } }
);
// 同步引用方数据
await syncWaveNoReferences(queryInterface, warehouseId, waveId, nextWaveNo);
}
}
// 2. 二次校验:修复后不应再有重复波次号
const residualRows = await fetchDuplicateWaveNos(queryInterface);
if ((Array.isArray(residualRows) ? residualRows : []).length > 0) {
const residual = residualRows.map(row => String(row && row.wave_no || '').trim()).filter(Boolean);
throw new Error(`wms_wave_batch 修复后仍存在重复波次号: ${residual.join(', ')}`);
}
// 3. 读取索引现状
const indexes = await queryInterface.showIndex(TABLE_NAME);
// 4. 移除冗余非唯一索引(若存在)
if (hasWaveNoIndex(indexes, 'idx_wave_no', false)) {
await queryInterface.removeIndex(TABLE_NAME, 'idx_wave_no');
}
// 5. 新增唯一索引(若已人工添加则跳过,保证幂等)
if (!hasWaveNoIndex(indexes, 'uniq_wave_no', true)) {
await queryInterface.addIndex(TABLE_NAME, [ 'wave_no' ], {
unique: true,
name: 'uniq_wave_no',
});
}
},
async down(queryInterface) {
const indexes = await queryInterface.showIndex(TABLE_NAME);
// 回滚:移除唯一索引
if (hasWaveNoIndex(indexes, 'uniq_wave_no', true)) {
await queryInterface.removeIndex(TABLE_NAME, 'uniq_wave_no');
}
// 回滚:恢复非唯一索引(若不存在)
if (!hasWaveNoIndex(indexes, 'idx_wave_no', false)) {
await queryInterface.addIndex(TABLE_NAME, [ 'wave_no' ], {
unique: false,
name: 'idx_wave_no',
});
}
},
};

View File

@ -1,82 +0,0 @@
'use strict';
/**
* 退回拆包录像分页列表权限迁移(returnUnpack.videoList)。
*
* 权限明细:
* 560 — returnUnpack.videoList API:退回拆包录像列表
*
* 角色授权(与查询类 546-549 一致):
* → 客服组-员工(30) → 客服组-主管(28)(客服员工及以上)
* 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理
*
* 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。
*/
const TABLE = 'wms_permission';
const ROLE_TABLE = 'wms_role';
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
/** 权限ID → 授权角色ID列表(不含通配符角色) */
const PERMISSION_ROLES = {
560: [ 30, 28 ],
};
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. 创建 API 权限记录(固定 ID 560)──
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [ 560, 'returnUnpack.videoList', null, 'returnUnpack.videoList', null, 'API:退回拆包录像列表', null, 0, 0, null, 'api', 0, 1 ] }
);
// ── 2. 角色授权注入 ──
for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) {
for (const roleId of PERMISSION_ROLES[permId]) {
const rows = await queryInterface.sequelize.query(
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
);
const record = Array.isArray(rows) ? rows[0] : null;
if (!record) {
continue;
}
// 通配符角色跳过
if (record.permissions === '*') {
continue;
}
let perms;
try {
perms = JSON.parse(record.permissions || '[]');
} catch (err) {
continue;
}
if (!Array.isArray(perms)) {
continue;
}
if (perms.includes(permId)) {
continue;
}
perms.push(permId);
perms.sort((a, b) => a - b);
await queryInterface.sequelize.query(
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
{ replacements: [ JSON.stringify(perms), roleId ] }
);
}
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE}\` WHERE id = 560`
);
},
};

View File

@ -1,17 +0,0 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_stock_warehouse', 'need_recheck', {
type: Sequelize.CHAR(1),
allowNull: false,
defaultValue: 'Y',
comment: '是否需要复核:Y=需要复核,N=不需要复核',
after: 'is_batch_mgmt',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('wms_stock_warehouse', 'need_recheck');
},
};

View File

@ -1,52 +0,0 @@
'use strict';
/**
* 新增 storage.inventory.directPutaway(收货单直入库存)API 权限记录。
*
* 幂等设计:先查询 path + type='api' 是否已存在,已存在则跳过。
*/
const TABLE = 'wms_permission';
module.exports.up = async queryInterface => {
const permissions = [
{ path: 'storage.inventory.directPutaway', meta_title: '收货单直入库存' },
];
const paths = permissions.map(p => p.path);
const placeholders = paths.map(() => '?').join(', ');
const [ rows ] = await queryInterface.sequelize.query(
`SELECT path FROM \`${TABLE}\` WHERE type = 'api' AND path IN (${placeholders})`,
{ replacements: paths }
);
const existingPaths = new Set(rows.map(r => r.path));
const toInsert = permissions.filter(p => !existingPaths.has(p.path));
if (toInsert.length > 0) {
const values = toInsert
.map(
p => `('${p.path.replace(/'/g, "\\'")}', '${p.path.replace(/'/g, "\\'")}', '${p.meta_title.replace(/'/g, "\\'")}', 'api', 1, NOW(), NOW())`
)
.join(',\n');
await queryInterface.sequelize.query(`
INSERT INTO \`${TABLE}\` (path, name, meta_title, type, status, created_at, update_at)
VALUES ${values}
`);
}
console.log(
`[Migration] wms_permission API 权限新增:共 ${permissions.length} 条,` +
`已存在 ${permissions.length - toInsert.length} 条,实际插入 ${toInsert.length} 条`
);
};
module.exports.down = async queryInterface => {
const paths = [ 'storage.inventory.directPutaway' ];
const placeholders = paths.map(() => '?').join(', ');
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE}\` WHERE type = 'api' AND path IN (${placeholders})`,
{ replacements: paths }
);
};

View File

@ -1,82 +0,0 @@
'use strict';
/**
* 退回拆包强制录制权限迁移(returnUnpack.forceRecord)。
*
* 权限明细:
* 562 — returnUnpack.forceRecord API:退回拆包强制录制
*
* 角色授权(与作业类 540-545 一致):
* → 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上)
* 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理
*
* 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。
*/
const TABLE = 'wms_permission';
const ROLE_TABLE = 'wms_role';
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
/** 权限ID → 授权角色ID列表(不含通配符角色) */
const PERMISSION_ROLES = {
562: [ 27, 26 ],
};
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. 创建 API 权限记录(固定 ID 562)──
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [ 562, 'returnUnpack.forceRecord', null, 'returnUnpack.forceRecord', null, 'API:退回拆包强制录制', null, 0, 0, null, 'api', 0, 1 ] }
);
// ── 2. 角色授权注入 ──
for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) {
for (const roleId of PERMISSION_ROLES[permId]) {
const rows = await queryInterface.sequelize.query(
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
);
const record = Array.isArray(rows) ? rows[0] : null;
if (!record) {
continue;
}
// 通配符角色跳过
if (record.permissions === '*') {
continue;
}
let perms;
try {
perms = JSON.parse(record.permissions || '[]');
} catch (err) {
continue;
}
if (!Array.isArray(perms)) {
continue;
}
if (perms.includes(permId)) {
continue;
}
perms.push(permId);
perms.sort((a, b) => a - b);
await queryInterface.sequelize.query(
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
{ replacements: [ JSON.stringify(perms), roleId ] }
);
}
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE}\` WHERE id = 562`
);
},
};

View File

@ -1,66 +0,0 @@
'use strict';
const TABLE = 'wms_order_stockout';
/**
* 为出库单主表添加收件人信息字段(对应奇门 stockout.create 报文 receiverInfo 节点)。
*
* 字段与奇门 receiverInfo 一一对应,列名统一加 receiver_ 前缀避免与订单表口径混淆。
*/
module.exports = {
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE);
const receiverColumns = [
{ name: 'receiver_company', type: Sequelize.STRING(200), comment: '收件人公司名称(receiverInfo.company)' },
{ name: 'receiver_name', type: Sequelize.STRING(50), comment: '收件人姓名(receiverInfo.name)' },
{ name: 'receiver_zip_code', type: Sequelize.STRING(50), comment: '收件人邮编(receiverInfo.zipCode)' },
{ name: 'receiver_tel', type: Sequelize.STRING(50), comment: '收件人固定电话(receiverInfo.tel)' },
{ name: 'receiver_mobile', type: Sequelize.STRING(50), comment: '收件人移动电话(receiverInfo.mobile)' },
{ name: 'receiver_email', type: Sequelize.STRING(50), comment: '收件人电子邮箱(receiverInfo.email)' },
{ name: 'receiver_country_code', type: Sequelize.STRING(50), comment: '收件人国家二字码(receiverInfo.countryCode)' },
{ name: 'receiver_province', type: Sequelize.STRING(50), comment: '收件人省份(receiverInfo.province)' },
{ name: 'receiver_city', type: Sequelize.STRING(50), comment: '收件人城市(receiverInfo.city)' },
{ name: 'receiver_area', type: Sequelize.STRING(50), comment: '收件人区域(receiverInfo.area)' },
{ name: 'receiver_town', type: Sequelize.STRING(50), comment: '收件人村镇(receiverInfo.town)' },
{ name: 'receiver_detail_address', type: Sequelize.STRING(200), comment: '收件人详细地址(receiverInfo.detailAddress)' },
{ name: 'receiver_id', type: Sequelize.STRING(50), comment: '收件人证件号(receiverInfo.id)' },
];
for (const item of receiverColumns) {
if (!columns[item.name]) {
await queryInterface.addColumn(TABLE, item.name, {
type: item.type,
allowNull: true,
comment: item.comment,
});
}
}
},
down: async queryInterface => {
const columns = await queryInterface.describeTable(TABLE);
const receiverColumnNames = [
'receiver_company',
'receiver_name',
'receiver_zip_code',
'receiver_tel',
'receiver_mobile',
'receiver_email',
'receiver_country_code',
'receiver_province',
'receiver_city',
'receiver_area',
'receiver_town',
'receiver_detail_address',
'receiver_id',
];
for (const name of receiverColumnNames) {
if (columns[name]) {
await queryInterface.removeColumn(TABLE, name);
}
}
},
};

View File

@ -1,68 +0,0 @@
'use strict';
const TABLE = 'wms_order_stockout';
/**
* 出库单补充迁移:
* 1. order_status ENUM 追加 TRANSFERRED(已转订单),转订单成功后使用该状态;
* 2. 新增平台字段 source_platform_code / source_platform_name(修改接口"平台相关"与转订单回传使用)。
*/
module.exports = {
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE);
// 1. order_status ENUM 追加 TRANSFERRED(保持默认值与原注释)
const statusType = String(columns.order_status && columns.order_status.type || '').toUpperCase();
if (statusType && !statusType.includes("'TRANSFERRED'")) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_order_stockout` MODIFY COLUMN `order_status` '
+ 'ENUM(\'CREATING\',\'CREATED\',\'PENDING\',\'COMPLETED\',\'CANCELLED\',\'TRANSFERRED\') '
+ 'NOT NULL DEFAULT \'CREATED\' '
+ 'COMMENT \'订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废, TRANSFERRED=已转订单\''
);
}
// 2. 平台字段
if (!columns.source_platform_code) {
await queryInterface.addColumn(TABLE, 'source_platform_code', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '来源平台编码(转订单时优先使用,为空时兜底平台)',
});
}
if (!columns.source_platform_name) {
await queryInterface.addColumn(TABLE, 'source_platform_name', {
type: Sequelize.STRING(200),
allowNull: true,
comment: '来源平台名称快照',
});
}
},
down: async queryInterface => {
const columns = await queryInterface.describeTable(TABLE);
// 已转订单的行先回退为已作废,再收缩 ENUM
const statusType = String(columns.order_status && columns.order_status.type || '').toUpperCase();
if (statusType && statusType.includes("'TRANSFERRED'")) {
await queryInterface.sequelize.query(
'UPDATE `wms_order_stockout` SET `order_status` = \'CANCELLED\' WHERE `order_status` = \'TRANSFERRED\''
);
await queryInterface.sequelize.query(
'ALTER TABLE `wms_order_stockout` MODIFY COLUMN `order_status` '
+ 'ENUM(\'CREATING\',\'CREATED\',\'PENDING\',\'COMPLETED\',\'CANCELLED\') '
+ 'NOT NULL DEFAULT \'CREATED\' '
+ 'COMMENT \'订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废\''
);
}
if (columns.source_platform_code) {
await queryInterface.removeColumn(TABLE, 'source_platform_code');
}
if (columns.source_platform_name) {
await queryInterface.removeColumn(TABLE, 'source_platform_name');
}
},
};

View File

@ -1,58 +0,0 @@
'use strict';
/**
* 为 storage.stockout.updateInfo 添加 API 权限并授权。
*
* 权限 ID(固定):563 — storage.stockout.updateInfo 修改出库单信息
* 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30)
*/
module.exports = {
up: async queryInterface => {
// ===== 第一步:写入权限行 =====
await queryInterface.sequelize.query(`
INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (563, 'storage.stockout.updateInfo', NULL, 'storage.stockout.updateInfo', NULL, 'API:修改出库单信息', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW())
ON DUPLICATE KEY UPDATE path='storage.stockout.updateInfo', meta_title='API:修改出库单信息', type='api'
`);
// ===== 第二步:授权给经理及各主管/客服员工角色 =====
const roleIds = [ 8, 26, 28, 29, 30 ];
for (const roleId of roleIds) {
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(563 AS UNSIGNED)),
updated_at = NOW()
WHERE id = ${roleId}
AND permissions IS NOT NULL
AND permissions != '*'
AND permissions != '[]'
AND JSON_VALID(permissions) = 1
AND JSON_CONTAINS(permissions, '563', '$') = 0
`);
}
},
down: async queryInterface => {
const roleIds = [ 8, 26, 28, 29, 30 ];
for (const roleId of roleIds) {
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = JSON_REMOVE(
permissions,
JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '563'))
),
updated_at = NOW()
WHERE id = ${roleId}
AND permissions IS NOT NULL
AND permissions != '*'
AND permissions != '[]'
`);
}
await queryInterface.sequelize.query(`
DELETE FROM wms_permission WHERE id = 563
`);
},
};

View File

@ -1,56 +0,0 @@
'use strict';
/**
* 为 storage.stockout.cancel 添加 API 权限并授权。
*
* 权限 ID(固定):564 — storage.stockout.cancel 出库单取消
* 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30)
*/
module.exports = {
up: async queryInterface => {
await queryInterface.sequelize.query(`
INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (564, 'storage.stockout.cancel', NULL, 'storage.stockout.cancel', NULL, 'API:出库单取消', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW())
ON DUPLICATE KEY UPDATE path='storage.stockout.cancel', meta_title='API:出库单取消', type='api'
`);
const roleIds = [ 8, 26, 28, 29, 30 ];
for (const roleId of roleIds) {
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(564 AS UNSIGNED)),
updated_at = NOW()
WHERE id = ${roleId}
AND permissions IS NOT NULL
AND permissions != '*'
AND permissions != '[]'
AND JSON_VALID(permissions) = 1
AND JSON_CONTAINS(permissions, '564', '$') = 0
`);
}
},
down: async queryInterface => {
const roleIds = [ 8, 26, 28, 29, 30 ];
for (const roleId of roleIds) {
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = JSON_REMOVE(
permissions,
JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '564'))
),
updated_at = NOW()
WHERE id = ${roleId}
AND permissions IS NOT NULL
AND permissions != '*'
AND permissions != '[]'
`);
}
await queryInterface.sequelize.query(`
DELETE FROM wms_permission WHERE id = 564
`);
},
};

View File

@ -1,56 +0,0 @@
'use strict';
/**
* 为 storage.stockout.listLogs 添加 API 权限并授权。
*
* 权限 ID(固定):565 — storage.stockout.listLogs 出库单操作日志查询
* 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30)
*/
module.exports = {
up: async queryInterface => {
await queryInterface.sequelize.query(`
INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (565, 'storage.stockout.listLogs', NULL, 'storage.stockout.listLogs', NULL, 'API:出库单操作日志', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW())
ON DUPLICATE KEY UPDATE path='storage.stockout.listLogs', meta_title='API:出库单操作日志', type='api'
`);
const roleIds = [ 8, 26, 28, 29, 30 ];
for (const roleId of roleIds) {
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(565 AS UNSIGNED)),
updated_at = NOW()
WHERE id = ${roleId}
AND permissions IS NOT NULL
AND permissions != '*'
AND permissions != '[]'
AND JSON_VALID(permissions) = 1
AND JSON_CONTAINS(permissions, '565', '$') = 0
`);
}
},
down: async queryInterface => {
const roleIds = [ 8, 26, 28, 29, 30 ];
for (const roleId of roleIds) {
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = JSON_REMOVE(
permissions,
JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '565'))
),
updated_at = NOW()
WHERE id = ${roleId}
AND permissions IS NOT NULL
AND permissions != '*'
AND permissions != '[]'
`);
}
await queryInterface.sequelize.query(`
DELETE FROM wms_permission WHERE id = 565
`);
},
};

View File

@ -1,50 +1,4 @@
[
{
"version": "2026.08.25-stockout-create-express-fallback-zt",
"date": "2026-08-25",
"summary": "stockout.create 快递兜底口径调整:兜底仅使用出库单兜底快递编码(policy_config.stockout_default_express_code,默认 ZT 自提),不再回退订单默认快递(default_express_code/全局 STO);快递解析改为独立实现,不再复用订单侧 resolveExpressSnapshot 兜底链。",
"methods": [
"stockout.create"
],
"notes": [
"qimenMethods/stockout.js create 快递解析重写:开启 enable_external_express_code 且传 logisticsCode 时按 wms_express_setting 映射 → 系统快递列表匹配;未传/未开启/匹配不到时取 stockout_default_express_code(为空则 'ZT'),从系统快递列表解析名称,仍不存在则编码=名称=ZT",
"app/model/store_warehouse.js POLICY_CONFIG_FIELDS:新增 stockout_default_express_code(名称:出库单默认快递,type list,default 'ZT'),getPolicyConfigFieldListWithOptions 同步注入快递选项,与 default_express_code 表现一致",
"注意:ZT 需在系统快递列表中维护(自提),否则出库单 express_code/express_name 直接落库 ZT"
],
"type": "updated",
"module": "stockout"
},
{
"version": "2026.08.25-stockout-create-receiver-info",
"date": "2026-08-25",
"summary": "stockout.create 解析 receiverInfo 落库(13 个标准字段)并接入出库单兜底快递编码:快递解析在未传 logisticsCode 或匹配不到时,优先使用货主合约配置 stockout_default_express_code(出库单兜底快递),为空再回退 default_express_code/全局 STO。",
"methods": [
"stockout.create"
],
"notes": [
"qimenMethods/stockout.js create 新增 receiverInfo 解析:company/name/zipCode/tel/mobile/email/countryCode/province/city/area/town/detailAddress/id 共 13 字段落库 receiver_* 列(空值转 NULL)",
"快递解析改为传入覆盖默认快递后的 expressPolicyConfig(default_express_code = stockout_default_express_code || default_express_code)复用 resolveExpressSnapshot 匹配链路",
"app/model/store_warehouse.js POLICY_CONFIG_FIELDS 新增 stockout_default_express_code(type list,默认空,描述:出库单未传快递编码或匹配不到时使用的兜底快递编码)",
"receiverInfo 中的 idType/idNumber 扩展字段暂不落库(数据库未建列)"
],
"type": "updated",
"module": "stockout"
},
{
"version": "2026.08.25-stockout-create-express-resolve",
"date": "2026-08-25",
"summary": "stockout.create 新增 logisticsCode 快递编码解析(简化口径):货主开启 enable_external_express_code 时按 wms_express_setting → 系统快递列表匹配,匹配不到(含未开启)一律兜底默认快递,不走订单快递策略漏斗(matchPolicy)。解析结果落库 express_code/express_name。",
"methods": [
"stockout.create"
],
"notes": [
"qimenMethods/stockout.js create 在事务外解析 deliveryOrder.logisticsCode:调 deliveryOrder.getStoreWarehousePolicyConfig 读策略开关 + deliveryOrder.resolveExpressSnapshot(编码映射+兜底,不含策略漏斗),取 sysLogisticsCode/sysLogisticsName 落库 express_code/express_name",
"解析失败仅告警不阻断建单(express_code/express_name 保持 NULL),confirm 前仍可走 storage.stockout.updateExpress 手工补填",
"注意:出库单 express_code 存系统快递编码,stockout.confirm 出站回传 logisticsCode 时直接使用该值"
],
"type": "updated",
"module": "stockout"
},
{
"version": "2026.07.01-qimen-01",
"date": "2026-07-01",

View File

@ -1,588 +1,4 @@
[
{
"version": "2026.08.26-workbench-queryOrder-pack-status",
"date": "2026-08-26",
"type": "enhanced",
"summary": "工作台 workbench.business(queryOrder) 查询订单增强:接入订单序列表(wms_order_id_location_*)优先定位分表,未命中按 current→dispatch 回退遍历;响应 order 对象新增 pack_status 字段(散单/团购均返回)。",
"methods": [
"workbench.business"
],
"notes": [
"app/service/systems/workbench.js _queryOrder 步骤2:先经 orderDeliveryFactory.getOrderLocation(orderId, warehouseId) 获取序列表位置,命中则优先查对应分表,失败/未命中保持原 current→dispatch 遍历,与 _sendWeight/waybill/order_express 等模块的序列表优先定位语义一致",
"_queryOrder 响应 order 对象新增 pack_status(none/padding/fin/error),与 pick_status/recheck_status 等状态机并列,工作台可根据打包状态判断该单是否已打包",
"备注:_packOrder 订单查找仍按 delivery_order_code 双表遍历(序列表按 id 定位,发货单号场景暂不适用)"
],
"module": "workbench"
},
{
"version": "2026.08.26-finishPack-sync-order-pack-status",
"date": "2026-08-26",
"type": "fixed",
"summary": "修复打包任务结束事件不更新订单打包状态的问题:workbench.finishPack 结束任务后同步更新关联订单 pack_status 为 fin(散单按订单更新,团购按波次批量更新未拦截订单)并写完成操作日志;order.packing.setEndTime 手动结束同样同步订单;打包操作日志文案按任务状态区分(开始打包/打包完成),不再在开始打包时误写“打包完成”。",
"methods": [],
"notes": [
"问题定位:波次 B2026082503311(团购 7 单)开始打包时 packOrder(status=1) 写入的日志前缀硬编码为“团购打包完成”,实际尾部为“任务状态: 打包中”;设备结束事件走 finishPack 仅更新 wms_pack_task(end_time/status=2),未更新订单,导致订单 pack_status 停留在 padding",
"app/service/systems/workbench.js 新增 _updateOrderPackStatus:遍历 current+dispatch 分表,散单按 order_id 更新单笔,团购按 wave_id 批量更新(intercept_status 空值按 none 处理,拦截订单跳过),异常仅记日志不影响主流程;_packOrder 步骤6.5 改为复用该方法",
"app/service/systems/workbench.js _finishPack:任务结束后按 pack_mode 判定散单/团购,调用 _updateOrderPackStatus(packStatus=2) 同步订单,并按任务记录(含 operator_text 回填操作人)写入完成操作日志",
"app/service/systems/order_packing.js setEndTime:任务由未完成转为已完成时同样调用 _updateOrderPackStatus 同步订单,与 finishPack 语义对齐",
"app/service/systems/workbench.js _writePackOperationLog:日志前缀按 status 区分——status>=2 写“打包完成”,否则写“开始打包”,保留原有字段变更描述",
"定时任务 auto_finish_pack_task 超时自动结束仅关闭任务记录、不更新订单(保持原语义,避免超时误标订单完成),如需要可在后续版本评估同步"
],
"module": "workbench"
},
{
"version": "2026.08.26-stockout-listLogs",
"date": "2026-08-26",
"type": "added",
"summary": "新增 storage.stockout.listLogs 出库单操作日志查询接口:按出库单ID或出库单号分页查询 wms_operation_log(business_type=stockout,business_id=出库单ID),覆盖转订单/确认/修改/取消等 STOCKOUT_* 操作,按创建时间倒序;配套 operationLog.queryStockoutLogs 服务方法与权限 565。",
"methods": [
"storage.stockout.listLogs"
],
"notes": [
"app/service/systemMethods/storage/stockout.js 新增 listLogs:支持 id 或 stockout_order_code 定位(出库单号先查表换ID),pagination.page/pageSize(兼容 page_size);出库单不存在返回空列表不报错;仓库上下文取 ctx.user.store_id",
"app/service/systems/operation_log.js 新增 queryStockoutLogs:复用 queryLogsByBusinessType(query, 'stockout')",
"database/migrations/20260826100000-add-stockout-listLogs-permission.js:权限 565,授权角色 8/26/28/29/30,开发库已执行",
"storage.stockout.listItems 出库单明细接口此前已存在(按 stockout_order_code/id 查 wms_order_stockout_items),本次仅补 listLogs 文档",
"实测:listLogs 按 stockout_order_code 与 id=22 均返回分页日志(STOCKOUT_TO_ORDER/STOCKOUT_UPDATE_INFO,含操作人/时间/消息/平台名),pagination.total=4 正确;注意权限迁移后短时间内用户权限上下文缓存可能未刷新导致 403,刷新后正常"
],
"module": "storage.stockout"
},
{
"version": "2026.08.26-stockout-order-sync-channel",
"date": "2026-08-26",
"type": "added",
"summary": "订单回传区分 STOCKOUT 创建渠道:待处理订单同步入口(syncOrderIds)按 create_channel 路由新增 syncStockoutOrders,回传时把订单实际快递编码/运单号写回出库单(express_code/express_name/waybill_code/waybill_codes),并按出库单来源通知外部(QM→奇门 taobao.qimen.stockout.confirm,API→OpenAPI 回调 event=stockout_completed,WMS 内部来源直接成功);通知成功后才扣减订单库存并完成同步(sync_status=fin、出库单 COMPLETED/SUCCESS),失败则订单 sync_status=error 标记待处理异常、出库单 sync_status=FAILED 记录失败原因。",
"methods": [
"order.pendingOrder.syncOrderIds"
],
"notes": [
"app/service/systems/order_async.js 新增 syncStockoutOrders/syncStockoutOrdersInternal/processStockoutOrderInternal/notifyStockoutExternalInternal/buildStockoutConfirmDataInternal/finalizeSuccessfulStockoutSyncInternal:反查出库单(订单 source_order_codes 首项或明细 source_order_code),运单号仅认 wms_order_express 表(不回退订单主表 express_code 面单前置);收尾事务内写回出库单 + 订单明细 outbound 扣库存 + sync_status=fin,SELECT FOR UPDATE 防重幂等",
"app/service/systems/order_storage_allocation.js syncOrderIds 渠道路由新增 STOCKOUT 分支(原落入 MANUAL 兜底,不通知外部)",
"出库单已 SUCCESS 的重试场景跳过重复通知,直接收尾;订单未分配运单号时回传失败并提示",
"所有回传入口(pendingOrder.syncOrderIds 异步包装、express_platform 自动同步回传)均汇聚到同一路由,改动一处覆盖全部",
"订单表无 sync_message 列:回传失败提示落在 order_flag 字段(markPendingExceptionInternal 同步置 inspection_status=error/step=3)",
"实测失败路径:测试订单 122172(TEST-SO-20260826004828-003 转单)回传奇门 stockout.confirm 返回 JST_Error,订单 sync_status=error + order_flag 提示,出库单保持 TRANSFERRED + sync_status=FAILED + sync_message 记录原因",
"实测成功路径:出库单 source_type 临时改 WMS(内部来源直接成功)触发回传,订单 sync_status=fin/order_flag 清空/step=2,出库单 COMPLETED/SUCCESS + 写回 express_code=SF/waybill_code/waybill_codes,库存 101389 quantity 100→95、locked 8→3,流水闭环 LOCK(QM_STOCKOUT)→UNLOCK(转单释放)→LOCK(DELIVERY_ORDER)→OUTBOUND(订单出库)"
],
"module": "order.pendingOrder"
},
{
"version": "2026.08.26-stockout-cancel",
"date": "2026-08-26",
"type": "added",
"summary": "新增 storage.stockout.cancel 出库单取消:仅 CREATED/PENDING 允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水)并置 CANCELLED,写 wms_operation_log 操作日志(STOCKOUT_CANCEL);TRANSFERRED/COMPLETED 禁止取消。新增权限 564 并授权。",
"methods": [
"storage.stockout.cancel"
],
"notes": [
"app/service/systemMethods/storage/stockout.js 新增 cancel:复用 lockItemStorages 负数量释放(锁定不足幂等跳过),与状态更新、操作日志同事务;仓库隔离与 confirm/updateInfo 一致",
"database/migrations/20260826093000-add-stockout-cancel-permission.js:权限 564,授权角色 8/26/28/29/30,开发库已执行",
"实测:取消测试单后 locked_quantity 101379 3→2,UNLOCK 流水(出库单取消释放锁定)与 STOCKOUT_CANCEL 操作日志均落库",
"同步更新 methods/system.json 新增 cancel 接口文档"
],
"module": "storage.stockout"
},
{
"version": "2026.08.26-stockout-operation-log",
"date": "2026-08-26",
"type": "added",
"summary": "storage.stockout 链路补写 wms_operation_log 操作日志(businessType=stockout):confirm 直出成功、toOrder 转单成功、updateInfo 修改均写操作记录;新增 updateInfo API 权限 563 并授权;修复 updateInfo 证件号参数名与出库单 ID 冲突。",
"methods": [
"storage.stockout.confirm",
"storage.stockout.toOrder",
"storage.stockout.updateInfo"
],
"notes": [
"app/service/systemMethods/storage/stockout.js 新增 _writeStockoutOperationLog(operationLog.createOperationLogs,失败仅告警不影响主流程):confirm 成功路径与状态更新同事务写 STOCKOUT_CONFIRM(含释放锁总量);toOrder 转单后写 STOCKOUT_TO_ORDER(含新订单号);updateInfo 写 STOCKOUT_UPDATE_INFO(含改动字段摘要)",
"修复:updateInfo 收件人证件号参数由 id 改为 receiver_id(原与出库单ID参数冲突,会把 data.id 误写入 receiver_id 字段)",
"database/migrations/20260826090000-add-stockout-updateInfo-permission.js:新增权限 563(storage.stockout.updateInfo),授权角色 8/26/28/29/30,开发库已执行",
"实测:updateInfo 修改后 wms_operation_log 落库(business_type=stockout、operation_code=STOCKOUT_UPDATE_INFO、operator 阿猫、message 含改动摘要)"
],
"module": "storage.stockout"
},
{
"version": "2026.08.26-stockout-confirm-release-lock",
"date": "2026-08-26",
"type": "fixed",
"summary": "storage.stockout.confirm 直出确认后释放出库单创建时占用的库存锁定:出站通知成功后,事务内逐明细 lockItemStorages(-plan_qty, orderType=QM_STOCKOUT) 释放锁定并自动写 UNLOCK 流水,与状态推进到 COMPLETED 同事务提交,失败回滚可重试;释放遇\"锁定不足\"视为幂等成功跳过。",
"methods": [
"storage.stockout.confirm"
],
"notes": [
"修复前:confirm 直出成功后 locked_quantity 一直占用(出库单无取消入口,锁只能靠转订单释放)",
"出站通知失败时锁保持、状态不变(sync_status=FAILED),重试 confirm 成功后才会释放;已释放场景(锁定不足)跳过不阻断",
"实测:本地 confirm 真实出站淘宝奇门返回 JST_Error 单号转换失败,锁保持(101379.locked=3/101389.locked=8 不变),符合设计;释放+UNLOCK 流水由 lockItemStorages 负数量链路保证"
],
"module": "storage.stockout"
},
{
"version": "2026.08.26-directPutaway-default-location",
"date": "2026-08-26",
"type": "updated",
"summary": "storage.inventory.directPutaway 默认库位改为读取仓库设置:直入库存写 wms_storage 时,收货明细 space_id 无效则使用 wms_store.subject_config.default_location_id(经 deliveryOrder.getStoreSubjectConfig 缓存优先读取),未设置时兜底库位 1。",
"methods": [
"storage.inventory.directPutaway"
],
"notes": [
"app/service/systems/storage/inventory.js directPutaway:步骤 10 写 wms_storage 的 spaceId 由硬编码 1 改为 defaultSpaceId(收货明细有库位仍按其库位),defaultSpaceId 在方法前段读取仓库设置(正整数有效才采用,否则 1),读取失败仅告警不影响入库",
"与 storage.receiving.addDetail 默认库位口径一致(仓库设置优先,兜底 1)",
"同步更新 methods/system.json directPutaway 的库位规则说明"
],
"module": "storage.inventory"
},
{
"version": "2026.08.26-receiving-addDetail-default-location",
"date": "2026-08-26",
"type": "updated",
"summary": "storage.receiving.addDetail 默认库位改为读取仓库设置:新增明细时 space_id 默认取 wms_store.subject_config.default_location_id(经 deliveryOrder.getStoreSubjectConfig 缓存优先读取),未设置时兜底库位 1;前端传入 item.space_id 时仍按传入值。",
"methods": [
"storage.receiving.addDetail"
],
"notes": [
"app/service/systems/storage/receiving.js addDetail:默认明细 space_id 由硬编码 1 改为优先读仓库设置 default_location_id(正整数有效才采用),否则兜底 1;读取失败仅告警不影响创建",
"依赖 deliveryOrder.getStoreSubjectConfig(缓存 10 分钟),saveSettings 保存仓库设置时会同步清理该缓存键",
"同步更新 methods/system.json addDetail 的 item.space_id 描述"
],
"module": "storage.receiving"
},
{
"version": "2026.08.26-warehouse-setting-default-location",
"date": "2026-08-26",
"type": "added",
"summary": "仓库设置(wms_store.subject_config)新增\"默认库位\"字段 default_location_id(type location):setting.warehouse.getFieldMeta 字段元信息新增该字段(不返回库位选项列表,库位数量大,前端按仓库搜索选择),saveSettings 传入时校验库位属于当前仓库,否则报 400 拒绝写入。",
"methods": [
"setting.warehouse.getFieldMeta",
"setting.warehouse.getSettings",
"setting.warehouse.saveSettings"
],
"notes": [
"app/service/systems/setting/warehouse.js WAREHOUSE_SETTING_FIELDS 新增 default_location_id(名称:默认库位,type location,default null,描述:仓库未指定库位入库/上架时使用的默认库位);getFieldMeta 不注入库位选项列表(库位数量大,前端按 type=location 自行按仓库搜索库位)",
"saveSettings 新增 validateDefaultLocation:传入 default_location_id 时校验其属于当前仓库,否则 400 '默认库位 {id} 不属于当前仓库';传 null/空清空",
"app/model/store.js DEFAULT_SUBJECT_CONFIG 新增 default_location_id: null;normalizeSubjectConfig 新增正整数校验分支(空值置 null)",
"同步更新 methods/system.json:getSettings 响应、saveSettings 参数补充 default_location_id 说明"
],
"module": "setting.warehouse"
},
{
"version": "2026.08.25-stockout-updateInfo-transferred",
"date": "2026-08-25",
"type": "added",
"summary": "新增 storage.stockout.updateInfo 修改出库单信息接口,并引入 TRANSFERRED 状态:转订单成功后出库单置为 TRANSFERRED(已转订单),该状态下禁止一键出库。",
"methods": [
"storage.stockout.updateInfo",
"storage.stockout.toOrder"
],
"notes": [
"storage.stockout.updateInfo:修改范围限收件人(name/tel/mobile/company/email)、地址(province/city/area/town/detailAddress/zipCode/countryCode)、快递编码(express_code,自动解析 express_name)、来源平台(source_platform_code/name),未传入不修改;仅 CREATED/PENDING 状态允许修改(400);修改后收货信息不完整(name、(tel/mobile) 其一、省市区镇详细地址)禁止提交并列出缺失字段",
"数据库迁移 20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js:order_status ENUM 追加 TRANSFERRED + 新增 source_platform_code(50)/source_platform_name(200) 列,开发库已执行并核验",
"app/model/order_stockout.js:ENUM 补 TRANSFERRED、新增两平台字段、新增 isTransferred() 辅助方法",
"storage.stockout.toOrder:转单成功后 order_status 置 TRANSFERRED(原 CANCELLED);deliveryOrder.sourcePlatformCode 优先用出库单已存平台,为空走兜底平台;confirm(一键出库)经 canConfirm 拒绝 TRANSFERRED 状态",
"同步更新 methods/system.json:新增 updateInfo 接口文档,更新 toOrder 描述与状态说明",
"实测(2026-08-26,测试单 20):正常修改 name/mobile/detailAddress + express_code=SF(自动解析 express_name=顺丰速运)+ source_platform_code 均落库,未传字段不变;detailAddress 清空被拦截(收货信息缺失,禁止提交:缺少 detailAddress(详细地址));COMPLETED 单被拦截(不允许修改);操作日志 STOCKOUT_UPDATE_INFO 含改动字段摘要(收件人姓名、移动电话、详细地址、快递编码、来源平台);测试数据已恢复原貌、日志保留"
],
"module": "storage.stockout"
},
{
"version": "2026.08.25-stockout-toOrder-receiver-validate",
"date": "2026-08-25",
"type": "fixed",
"summary": "storage.stockout.toOrder 增加收货信息必填校验与同快递建单:name、(tel/mobile) 至少一项、省市区镇详细地址缺失时拒绝转单并提示缺失字段;收货信息优先接口传入,未传回填出库单已存的 receiver_* 字段;新订单快递编码沿用出库单 express_code(相同快递),平台不传 sourcePlatformCode 走兜底平台。",
"methods": [
"storage.stockout.toOrder"
],
"notes": [
"app/service/systemMethods/storage/stockout.js toOrder:释放锁前先合并收货信息(storedReceiverInfo 从出库单 receiver_company/name/zip_code/tel/mobile/email/country_code/province/city/area/town/detail_address 回填,接口 receiverInfo 非空字段覆盖)并逐项校验,缺项返回 fail 提示缺失字段列表",
"建单参数:logisticsCode = 出库单 express_code(create 时已解析的系统快递编码),不传 sourcePlatformCode(resolvePlatformSnapshot 自动使用合约兜底平台)",
"同步更新 methods/system.json 中 storage.stockout.toOrder 的 description 与 receiverInfo 参数说明"
],
"module": "storage.stockout"
},
{
"version": "2026.08.25-stockout-receiver-info-db",
"date": "2026-08-25",
"type": "added",
"summary": "wms_order_stockout 表新增 13 个收件人字段(receiver_* 前缀),对应奇门 stockout.create 报文 receiverInfo 节点(company/name/zipCode/tel/mobile/email/countryCode/province/city/area/town/detailAddress/id),为出库单解析收件人信息与转订单回填做准备。",
"methods": [
"storage.stockout.toOrder",
"stockout.create"
],
"notes": [
"database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js 新增 13 列:receiver_company(200)/receiver_name(50)/receiver_zip_code(50)/receiver_tel(50)/receiver_mobile(50)/receiver_email(50)/receiver_country_code(50)/receiver_province(50)/receiver_city(50)/receiver_area(50)/receiver_town(50)/receiver_detail_address(200)/receiver_id(50),均允许 NULL;up/down 均带 describeTable 幂等保护",
"app/model/order_stockout.js 同步新增 13 个字段定义(remark 与 express_code 之间)",
"开发库已执行迁移并核验 SHOW COLUMNS 全部落库;生产库需在发布时按 db-migration-envs 规范执行"
],
"module": "storage.stockout"
},
{
"version": "2026.08.25-storage.stockout.toOrder",
"date": "2026-08-25",
"type": "added",
"summary": "storage.stockout.toOrder 从占位接口落地为真实实现:将非订单出库单(wms_order_stockout)转为正式销售订单,新订单 create_channel 固定为 STOCKOUT;转单时释放出库单库存锁定(QM_STOCKOUT)并转由新订单重新锁定,成功后原出库单置为 CANCELLED 并写入 extend_props.transferred_order_id(幂等,重复调用直接返回已转订单信息)。",
"methods": [
"storage.stockout.toOrder"
],
"notes": [
"app/service/systemMethods/storage/stockout.js toOrder 实现:入参 id(出库单ID,必填)、delivery_order_code(可选,不传自动生成 SK 前缀单号)、receiverInfo(可选收件人信息);校验出库单存在且 order_status 为 CREATED/PENDING(否则 400),extend_props.transferred_order_id 存在时幂等返回已转订单",
"锁转移:事务内逐明细 lockItemStorages(-plan_qty, orderType=QM_STOCKOUT) 释放出库单锁 → 调 deliveryOrder.addOrder(data, info, 'STOCKOUT') 建单并重新锁库存 → 建单失败/订单号重复时 _restoreStockoutLocks 补偿恢复锁定;建单成功后更新出库单 order_status=CANCELLED 并记录 transferred_order_id/transferred_order_code/transferred_at",
"新订单明细手工单风格传 stockId(wms_stock_warehouse.id),sourceOrderCode 写入出库单号便于追溯;create_channel=STOCKOUT 不触发 addOrder 的 API/QM 异步流程,也不会被自动同步任务推送",
"app/service/systemMethods/storage/delivery.js toOrder 兼容转发改为透传 data 参数",
"app/service/systemMethods/order/base.js CREATE_CHANNEL_LABELS 新增 STOCKOUT: '出库转单',订单工作台渠道列正确显示中文标签",
"同步更新 methods/system.json 中 storage.stockout.toOrder 接口文档"
],
"module": "storage.stockout"
},
{
"version": "2026.08.25-storeWarehouse.store.createUser",
"date": "2026-08-25",
"type": "added",
"summary": "新增 storeWarehouse.store.createUser:为货主创建用户。按用户名查询平台账号:账号不存在则自动注册并随机生成 12 位密码返回;两种情况统一完成货主工号绑定并授予货主管理员角色(wms_role.id=5)。幂等:重复调用不会重复创建账号或绑定。",
"methods": [
"storeWarehouse.store.createUser"
],
"notes": [
"app/service/systems/store_warehouse.js 新增 createUser:校验 username(必填 + 3-50 位字母数字下划线,400)与 store_id(必填正整数,400)→ 货主存在校验(404)→ 按用户名查询账号(不存在则复用 auth.user.register 注册并随机生成 12 位密码)→ 事务内 AccountStoreEmployee.findOrCreate 绑定货主工号(已存在且 status!=1 时恢复为 1)→ 校验货主管理员角色 wms_role.id=5 已初始化(缺失抛 500)→ EmployeeRole.findOrCreate 授予角色(幂等)",
"app/service/systemMethods/storeWarehouse/store.js 新增 createUser 包装方法;构造器 _noNeedRight/_noNeedAuth 白名单加入 createUser(isNeedLogin=true 需登录、isNeedAuth=false)",
"响应 data:account_id、username、store_id、created(是否本次新建账号;false 表示账号已存在仅完成授权)、password(仅 created=true 时返回 12 位随机明文密码)",
"同步更新 methods/system.json 中 storeWarehouse.store.createUser 接口文档"
],
"module": "storeWarehouse"
},
{
"version": "2026.08.25-returnUnpack.forceRecord",
"date": "2026-08-25",
"type": "added",
"summary": "新增 returnUnpack.forceRecord:强制重新录制拆包视频。参考 order.packing.forceRecord,入参 id(拆包单ID);校验仓库录制电脑(wms_print_computer is_recording=true)在线后,将 wms_return_unpack_video 视频记录重置为 created 并清空 video_url,再向打印服务 /record/force 推送 { unpack_id } 触发重新录制。",
"methods": [
"returnUnpack.forceRecord"
],
"notes": [
"app/service/systems/return_unpack.js 新增 forceRecord:_findByIdChecked 仓库隔离校验(不存在 404 / 跨仓库 403)→ 查询录制电脑(无则 400)→ Redis 在线键 warehouse:{warehouseId}:printer:{computerId} 校验在线(不在线 400)→ 重置视频状态为 created 并清空 video_url → POST {printService.url}/record/force 推送 { unpack_id }(失败抛 500 业务错误)",
"app/service/systemMethods/returnUnpack.js 新增 forceRecord 包装方法(与 submit 同层,走 _call 统一错误包装)",
"database/migrations/20260825120000-add-return-unpack-force-record-permission.js 新增权限记录 562(returnUnpack.forceRecord,API:退回拆包强制录制),授权角色与作业类 540-545 一致:仓库组-员工(27)/仓库组-主管(26)",
"同步更新 methods/system.json 中 returnUnpack.forceRecord 的接口文档"
],
"module": "returnUnpack"
},
{
"version": "2026.08.24-storage.entry-receivingCompare-merge",
"date": "2026-08-24",
"type": "fixed",
"summary": "storage.entry.receivingCompare 对比主体修正:多个收货单先合并明细,再与入库单做一次对照。原实现每个收货单各对照一遍,入库计划数量被重复展开多份,前端对比表格出现重复行。",
"methods": [
"storage.entry.receivingCompare"
],
"notes": [
"app/service/systems/storage/entry.js receivingCompare 重写:批量校验收货单后合并全部有效收货单明细,新增 _buildMergedComparison(替代 _compareSingleReceiving)输出单一对照视图",
"出参结构调整:comparisons[](按收货单拆分)改为 comparison[](合并后逐行对照,每个入库明细仅一行)+ receiving_only[] + summary;matched 行新增 receiving_quantity/receiving_allocated/receiving_available(合并值)与 receiving_sources[](各收货单来源明细),entry_only 行对应数量为 0 且 receiving_sources 为空",
"total_summary.matched_count 语义调整为有效参与对比的收货单数(原为处理成功的对照数);无效收货单仍进入 errors[]",
"同步更新 methods/system.json 中 receivingCompare 的 response 结构说明"
],
"module": "storage.entry"
},
{
"version": "2026.08.23-returnUnpack.video-url-cdn-domain",
"date": "2026-08-23",
"type": "fixed",
"summary": "修复拆包视频地址未拼接 CDN 域名的问题:returnUnpack.list / returnUnpack.detail / returnUnpack.videoList / returnUnpack.queryByWaybill 输出的 videos[].video_url 此前直接返回相对路径(如 /recordings/...),与 order.packing 输出完整 URL 的口径不一致。现在按打包侧相同规则拼接 http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path}(录制电脑从 wms_print_computer 按 is_recording=true 获取,无录制电脑时保持原始路径)。",
"methods": [
"returnUnpack.list",
"returnUnpack.detail",
"returnUnpack.videoList"
],
"notes": [
"app/service/systems/return_unpack.js 新增 _getRecordingComputerId/_buildVideoUrl(与 order_packing.js 同口径,带实例级缓存)",
"_enrichRow 视频派生块内对 videos[].video_url 拼接域名(覆盖 list/detail/submit 输出)",
"videoList 按 unpack_id 反查 warehouse_id 后拼接;queryByWaybill(inbox 查退回)的 videos 同样拼接",
"同步更新 methods/system.json 中 returnUnpack.list 与 returnUnpack.detail 的响应字段描述"
],
"module": "returnUnpack"
},
{
"version": "2026.08.23-stock.warehouse-cache-invalidate-on-update",
"date": "2026-08-23",
"type": "fixed",
"summary": "修复商品资料更新后 getStockDetails 详情缓存未清除的问题:saveWarehouseStock/handleBatchChange 使用 StockWarehouse.update 批量更新(不触发实例级 afterUpdate hook),导致 cache:stock_detail:{warehouseId}:{stockId} 旧数据在 TTL 内持续被读取(如 need_recheck 修改后复核扫描仍返回旧值)。现在两个编辑入口更新成功后显式调用 stockWarehouse.invalidateStockDetailCache 清除对应缓存。",
"methods": [
"stock.warehouse.saveWarehouseStock",
"stock.warehouse.handleBatchChange"
],
"notes": [
"app/service/systems/stock_store.js saveWarehouseStock 提交事务后调用 service.systems.stockWarehouse.invalidateStockDetailCache(id, warehouseId)(失败仅告警不阻断主流程)",
"同文件 handleBatchChange 批量更新后按 ids 批量清除详情缓存(Promise.allSettled,失败不阻断返回)",
"实证验证:更新后 Redis 缓存 key 被删除,复核扫描/统一查询立即读取到新值"
],
"module": "stock"
},
{
"version": "2026.08.23-recheckOrder.stock-need-recheck",
"date": "2026-08-23",
"type": "enhanced",
"summary": "order.recheckOrder.scanOrder / scanTask 返回报文的 stock 明细新增 need_recheck 字段(Y=需要复核,N=不需要复核,缺省 Y):散单路径 enrichOrdersWithStock 组装与团购路径 buildGroupWaveList 的 stocks 映射均透出,供前端按商品判断是否免复核。",
"methods": [
"order.recheckOrder.scanOrder",
"order.recheckOrder.scanTask"
],
"notes": [
"app/service/systemMethods/order/recheckOrder.js enrichOrdersWithStock stock 对象新增 need_recheck(取 getStockDetails 返回值,缺省 'Y')",
"同文件 buildGroupWaveList 的 stocks 映射新增 need_recheck",
"同步更新 methods/system.json 中 scanOrder 的 stock children 与 scanTask 的 stock 字段描述"
],
"module": "order"
},
{
"version": "2026.08.23-stock.warehouse-need-recheck",
"date": "2026-08-23",
"type": "enhanced",
"summary": "wms_stock_warehouse 新增 need_recheck(是否需要复核)字段:Y=需要复核(默认),N=不需要复核,非空。编辑(saveWarehouseStock/createWarehouseStock/getInfo/handleBatchChange)、导入(import 支持中文 需要/不需要 或 Y/N,缺省新建默认 Y、更新保留原值)、导出(仓库/外仓导出新增「是否需要复核」列,与导入列名对齐)全链路支持。",
"methods": [
"stock.warehouse.getInfo",
"stock.warehouse.saveWarehouseStock",
"stock.warehouse.createWarehouseStock",
"stock.warehouse.import",
"stock.warehouse.handleBatchChange",
"stock.warehouse.export",
"stock.warehouse.externalExport"
],
"notes": [
"database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js 新增迁移(CHAR(1) NOT NULL DEFAULT 'Y',comment: 是否需要复核:Y=需要复核,N=不需要复核)",
"app/model/stock_warehouse.js 新增 need_recheck 字段定义(默认 Y、非空)",
"app/service/systems/stock_store.js getInfo attributes 增加 need_recheck;saveWarehouseStock 解构/更新数据增加 need_recheck;createWarehouseStock 解构并默认 'Y';validateSaveParams 校验非 Y/N 值报错;handleBatchChange 白名单增加 need_recheck 并校验 Y/N;exportWarehouseStock/exportExternalWarehouseStock 行数据输出中文 需要/不需要 并新增「是否需要复核」导出列",
"app/service/systemMethods/stock/warehouse.js saveWarehouseStock 解构并透传 need_recheck;_normalizeWarehouseImportRow 解析「是否需要复核/need_recheck/needRecheck」列并新增 _normalizeNeedRecheckValue 归一化(需要→Y,不需要→N,非法值报错,缺省不覆盖)",
"同步更新 methods/system.json 中 getInfo/saveWarehouseStock/createWarehouseStock/import/handleBatchChange 的字段说明"
],
"module": "stock"
},
{
"version": "2026.08.23-pick.intercepted-skip-claim-pick",
"date": "2026-08-23",
"type": "fixed",
"summary": "拦截订单不再阻隔领料/拣货且不参与作业数量:pick.waveClaimScan 打印校验与领料更新跳过拦截订单(拦截未打印不阻隔领料、拦截订单不置为 claim_status=fin,响应 data 新增 intercepted_order_count);pick.query 领料前置校验仅统计非拦截未领料订单(拦截未领料不阻隔拣货,fail data 新增 intercepted_order_count);pick.createWavePickTask 新增 excludeUnclaimed 选项,普通波次(source=0)创建拣货任务计算拣货数量(order_count/任务订单/筐)时剔除未领料订单。",
"methods": [
"pick.waveClaimScan",
"pick.query",
"pick.wavePickComplete"
],
"notes": [
"app/service/systemMethods/pick.js waveClaimScan 波次订单查询 attributes 增加 intercept_status,拦截订单集合不参与 unclaimed/unprinted 统计且不参与 claim_status=fin 更新",
"app/service/systemMethods/pick.js 新增 getWaveClaimGateStats 辅助方法(统计 total/intercepted/unclaimed,unclaimed 仅计非拦截订单),query 领料门禁改用该统计",
"app/service/systemMethods/pick.js createWavePickTask 新增 params.excludeUnclaimed(默认 false):为 true 时 attributes 增加 claim_status 并剔除 claim_status != fin 订单(未领料不参与 order_count/任务订单/筐数量);query 与 wavePickComplete 对普通波次(source=0)传 excludeUnclaimed=true(wavePickComplete 波次查询 SELECT 增加 source)",
"同步更新 methods/system.json 中 pick.query 与 pick.waveClaimScan 的 description、400 错误说明与 response 字段"
],
"module": "pick"
},
{
"version": "2026.08.23-returnUnpack.list-video-fields",
"date": "2026-08-23",
"type": "enhanced",
"summary": "returnUnpack.list 对齐打包记录补齐视频字段:列表关联查询视频副表,每条记录新增 has_video(1=有视频记录/2=无)、video_enable(1=录像可用/2=不可用)派生字段与 videos 视频数组(id/video_url/status/camera_id/camera_name),并新增 has_video / video_enable 列表筛选(EXISTS 字面量,口径与 order.packing.list 一致)。",
"methods": [
"returnUnpack.list"
],
"notes": [
"app/service/systems/return_unpack.js list 改 raw:false 并 include ReturnUnpackVideo as videos(deleted_at IS NULL 过滤 + Camera 关联精简字段),行数据经 _flattenVideos 输出精简视频数组;_enrichRow 对含 videos 数组的记录派生 has_video/video_enable(create 幂等复用与 detail 返回同步受益,videos 结构不变);_buildListWhere 新增 has_video/video_enable 筛选(1/2,EXISTS/NOT EXISTS 字面量)",
"同步更新 methods/system.json 中 returnUnpack.list 的 params(where.has_video / where.video_enable)与 response list 字段说明"
],
"module": "returnUnpack"
},
{
"version": "2026.08.22-order.print-custom-area-wave-multiply-qty",
"date": "2026-08-22",
"type": "enhanced",
"summary": "面单自定义区商品明细行尾新增「波次总单数×该行商品数量」:当波次 wms_wave_batch.source=0(普通波次)且 wave_type=1 时,每条商品明细行尾追加 波次总单数 × 该行商品数量(如 500 单 × 3 件 = 1500);策略抓取波次(source=1/2)与其他波次类型不追加。",
"methods": [
"order.print.getOrderPrintData",
"order.print.getWavePlatformPrintData",
"order.print.getPrintDataByWaybillCodes"
],
"notes": [
"app/service/systems/order_print.js queryWavesByIds 查询增加 source/wave_type 字段;getWavePlatformPrintData / getOrderPrintData / getPrintDataByWaybillCodes 三条路径构建 waveMetaMap 并在订单行附加 wave_source / wave_type",
"app/lib/printer_data_builder.js buildWaybillCustomProductInfoLines 明细行构建时 waveSource=0 且 waveType=1 且 wave_total_orders>0 时行尾追加 波次总单数×qtyNumber(商品数量与乘数之间以两个空格分隔);7 个平台映射(快手/拼多多/抖音/菜鸟/小红书/视频号/京东)同步传入 waveSource/waveType",
"更新 test/app/lib/printer_data_builder_package_material.test.js:新增 T15(source=0 且 wave_type=1 行尾乘数)与 T16(source=1 不追加乘数)",
"同步更新 methods/system.json 中三个打印方法的 description"
],
"module": "order"
},
{
"version": "2026.08.22-order.print-custom-area-total-qty",
"date": "2026-08-22",
"type": "enhanced",
"summary": "面单打印自定义区首行在快递渠道名后新增「商品总数【n】」:n 优先取订单级商品总数(items_total,权威字段),其次商品明细数量累加,最后 items_count(商品种类数)兜底,避免订单 items 快照宽松文本(stock_id+数量)陈旧不完整导致数量偏差;覆盖菜鸟/京东/拼多多/抖音/快手/视频号/小红书全平台自定义区。",
"methods": [
"order.print.getOrderPrintData",
"order.print.getWavePlatformPrintData",
"order.print.getPrintDataByWaybillCodes"
],
"notes": [
"app/lib/printer_data_builder.js buildWaybillCustomProductInfoLines 头部行在快递渠道名后追加 商品总数【n】:fallbackTotalQty(items_total)>0 时优先,否则 safeItems 逐项 resolveItemQuantity 累加,再否则 fallbackItemsCount(items_count)兜底;7 个平台映射(快手/拼多多/抖音/菜鸟/小红书/视频号/京东)分别传入 fallbackTotalQty=items_total、fallbackItemsCount=items_count",
"更新 test/app/lib/printer_data_builder_package_material.test.js(T10 包材前缀断言排除商品总数标签、新增 T11 商品总数累加、T12 items_total 兜底优先、T13 items 快照宽松文本不完整时取 items_total、T14 无 items_total 时回退明细累加)与 test/app/service/systems/order_print.getWavePlatformPrintData.test.js(W023 头部行断言追加 商品总数【2】)",
"同步更新 methods/system.json 中三个打印方法的 description"
],
"module": "order"
},
{
"version": "2026.08.22-pick.query-wave-claim-gate-source0",
"date": "2026-08-22",
"type": "enhanced",
"summary": "pick.query 新增领料前置校验(仅普通波次 source=0):扫描命中普通波次时,若波次内存在未领料订单(claim_status != fin)则返回 400 并携带 action=wave_claim 提示「订单未领料,请先领料后再拣货」,阻隔开始拣货(中止拣货任务创建);已全部领料或策略抓取波次(source=1/2)不拦截。",
"methods": [
"pick.query"
],
"notes": [
"app/service/systemMethods/pick.js query 波次查询 SELECT 增加 source 字段并记录 targetWaveSource;目标波次信息校验后插入领料前置校验:source=0 时查询波次订单 claim_status,存在未领单订单 fail 400(data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、total_order_count)",
"同步更新 methods/system.json 中 pick.query 的 description 与 400 错误说明"
],
"module": "pick"
},
{
"version": "2026.08.22-stock.warehouse.import-barcode-sync",
"date": "2026-08-22",
"type": "fixed",
"summary": "修复 stock.warehouse.import 传入 barcode(条码)不生效的问题:归一化后条码未在新建/更新路径写入 wms_stock_barcodes 表。现在导入行携带非空 barcode 时,在商品创建/更新成功后调用 saveWarehouseStockBarcode 差异同步条码(未传条码则保留原有条码)。",
"methods": [
"stock.warehouse.import"
],
"notes": [
"app/service/systemMethods/stock/warehouse.js import():创建/更新成功后,若归一化 barcode 为非空数组,则按结果 id(缺省用行内 SKU)调用 systems.stockStore.saveWarehouseStockBarcode 同步到 wms_stock_barcodes 表",
"条码同步失败计入该行 fail_items,且该行不再计入成功计数,便于定位",
"未传 barcode(空数组)时不触发同步,避免误清空已有条码;barcode 格式与导出对齐(逗号分隔字符串)"
],
"module": "stock.warehouse"
},
{
"version": "2026.08.22-storage.inventory.list-filter-zero-quantity",
"date": "2026-08-22",
"type": "enhanced",
"summary": "storage.inventory.list 过滤总数量为 0 的商品或明细行:基础查询条件增加 quantity > 0,明细模式(group_by_batch=true)不再返回 quantity=0 的明细行,合并模式(group_by_batch=false)不再返回总数量为 0 的商品。storage.inventory.export 同步保持一致。",
"methods": [
"storage.inventory.list",
"storage.inventory.export"
],
"notes": [
"app/service/systems/storage/inventory.js:getInventoryList 与 exportInventoryList 的 baseWhere 均增加 { quantity: { [Op.gt]: 0 } },动态 where/stock_query 条件不受影响",
"明细模式:quantity=0 的 storage 行直接过滤;合并模式:某商品所有明细行均无正数量时分组自然消失,总量为 0 的商品不返回",
"storage.inventory.export 入参与 list 语义保持一致(导出同样过滤零量行/零量商品)"
],
"module": "storage.inventory"
},
{
"version": "2026.08.22-storage.inventory.listByStockId-group-by-space",
"date": "2026-08-22",
"type": "enhanced",
"summary": "storage.inventory.listByStockId 新增 group_by_space 双模式:false(默认,不汇总)逐条返回 quantity > 1 明细行(含批次/效期/预警字段,行为不变);true(按库位汇总)先筛 quantity > 1 明细行,再按 space_id 汇总 quantity/locked_quantity/available_quantity,返回库位级汇总行(含 batch_count、first/last_inbound_time、stock/space/store_name),不含批次与效期/预警字段。",
"methods": [
"storage.inventory.listByStockId"
],
"notes": [
"app/service/systems/storage/inventory.js:getStorageListByStockId(stockId, groupBySpace=false) 两种模式共用同一查询(先筛 quantity > 1 明细行),group_by_space=true 时用新增 _aggregateStorageRowsBySpace 按 space_id 在内存汇总(求和、批次数、最早/最晚入库时间),并保留商品/库位关联与条码图片附属信息",
"app/service/systemMethods/storage/inventory.js:listByStockId 透传 group_by_space(支持 true/'true' 布尔/字符串)",
"汇总口径:先筛 quantity > 1 的明细行再按库位求和;汇总行不返回批次与效期/库存预警字段"
],
"module": "storage.inventory"
},
{
"version": "2026.08.22-storage.inventory.store-stock-join-dedup",
"date": "2026-08-22",
"type": "fixed",
"summary": "修复库存接口按 stock_id 查询返回重复 storage 行(同 id 多条)的问题:store_stock 关联(belongsTo StoreWarehouse,按 store_id 关联)未按仓库收敛,货主在多仓库存在签约行时 JOIN 多行匹配导致同一库存行重复且 store_name 不一致。改为统一使用 StoreWarehouse.buildStoreStockInclude(按 warehouse_id + warehouse_use_status=1 收敛,命中唯一签约行)。",
"methods": [
"storage.inventory.listByStockId",
"storage.inventory.list"
],
"notes": [
"app/service/systems/storage/inventory.js:getStorageListByStockId、getInventoryList(明细模式与合并模式)三处 store_stock 嵌套 include 均改为 buildStoreStockInclude({ warehouseId, required: false, attributes: ['store_id','store_remask'] })",
"wms_store_warehouse 存在 (store_id, warehouse_id) 唯一索引,按仓库收敛后每商品至多命中一行签约关系,不再产生重复明细;合并模式下 SUM(quantity) 也不会因 JOIN 多行而翻倍",
"同时修正 storage.inventory.list 同源隐患(明细模式重复行、合并模式数量翻倍),返回结构不变"
],
"module": "storage.inventory"
},
{
"version": "2026.08.22-storage.inventory.listByStockId",
"date": "2026-08-22",
"type": "added",
"summary": "新增 storage.inventory.listByStockId 接口:传入 stock_id,返回该商品在当前仓库下所有 quantity > 1 的 wms_storage 明细行(按 id 倒序),返回结构与 storage.inventory.list 明细模式一致(含 stock 条码/图片、space 库位、货主名称及效期/库存预警字段)。",
"methods": [
"storage.inventory.listByStockId"
],
"notes": [
"app/service/systemMethods/storage/inventory.js 新增 listByStockId 包装方法,并加入 _noNeedRight/_noNeedLog/_noNeedAuth 豁免列表(与 list 一致)",
"app/service/systems/storage/inventory.js 新增 getStorageListByStockId:校验 stock_id 正整数与当前仓库上下文,where 条件 warehouse_id+stock_id+quantity>1+is_enabled=1+delete_at=null,include stock/space 与明细模式一致",
"重构 getInventoryList 明细分支:提取 _loadInventoryWarningRanges 与 _formatBatchStorageRows 复用,现有 storage.inventory.list 行为不变"
],
"module": "storage.inventory"
},
{
"version": "2026.08.21-returnUnpack.create-orderItems",
"date": "2026-08-21",
"type": "enhanced",
"summary": "returnUnpack.create 返回新增顶层 order_items 字段:原订单商品明细数组(即 order.items 的顶层透出,含 item_code/item_name/sku_property/quantity/plan_qty/barcodes/image_url 等),仅原单退回且原订单详情解析成功时返回;非原单退回或原订单详情缺失时为 null。新建与幂等复用两个分支返回结构一致。",
"methods": [
"returnUnpack.create"
],
"notes": [
"app/service/systems/return_unpack.js create:新建分支返回 order_items(order.items 为数组时透出,否则 null);幂等复用分支从 detail().related.order 提取同名字段,与 order 字段同源",
"向后兼容:仅新增顶层字段,order/record 等既有字段不变",
"同步更新 methods/system.json 中 returnUnpack.create 的 response(新增 order_items 字段说明)"
],
"module": "returnUnpack"
},
{
"version": "2026.08.21-stock.warehouse.search-return-images",
"date": "2026-08-21",
"type": "enhanced",
"summary": "stock.warehouse.search 默认模式返回数据新增 images 字段:批查 wms_file_reference(business_type=stock)+ wms_file 获取商品图片URL列表,按 display_order 升序;无图片时返回空数组。mode=\"combo\" 时不返回该字段。",
"methods": [
"stock.warehouse.search"
],
"notes": [
"app/service/systems/stock_store.js search:formattedResults 生成后批量查询 FileReference(include File.file_url,raw),按 business_id(商品ID)分组注入 item.images,与 stock.warehouse.list 图片口径一致",
"同步更新 methods/system.json 中 stock.warehouse.search 的 response 字段"
],
"module": "stock"
},
{
"version": "2026.08.21-order.pendingOrder.cloneOrder-sync-status-inherit",
"date": "2026-08-21",
"type": "enhanced",
"summary": "order.pendingOrder.cloneOrder 同步状态继承原订单:原订单已同步(sync_status=fin)时新订单直接置 fin,避免克隆后重复回传平台;原订单未同步/同步失败(padding/error)则重置为 padding 重新走同步流程。",
"methods": [
"order.pendingOrder.cloneOrder"
],
"notes": [
"app/service/systemMethods/order/pendingOrder.js cloneOrder 第 4 步 newOrderData.sync_status 按 original.sync_status 判定:fin→fin,其余→padding(RESET_FIELDS 保留 padding 兜底)",
"已同步新订单分配运单号不受 sync_status 限制(createWaybillCodePipeline 只校验 step 1/2/3/4、status、拦截、锁定、已分配运单号),但新订单 step=0 需先审核进入待处理才能分配;已同步订单分配新运单号后不会自动回传平台",
"同步更新 methods/system.json 中 cloneOrder 的 description"
],
"module": "order"
},
{
"version": "2026.08.21-order.pendingOrder.cloneOrder-storage-release-tolerant",
"date": "2026-08-21",
"type": "enhanced",
"summary": "order.pendingOrder.cloneOrder 支持克隆已同步(sync_status=fin)订单且库存释放失败不阻断:原订单已分配储位时先清除已分配库存,cancelAllocateStorage 失败降级为告警(与 cancelOrder 策略一致),克隆继续执行;残留占用保留在原订单名下,克隆新订单不重新占用库存(storage_status=none,创建过程不触发储位分配与库存锁定)。",
"methods": [
"order.pendingOrder.cloneOrder"
],
"notes": [
"app/service/systemMethods/order/pendingOrder.js cloneOrder 第 2 步:清除已分配库存失败由抛错阻断改为 ctx.logger.warn 降级,不影响克隆主流程",
"克隆新订单库存零占用(storage_status 重置 none、无自动储位分配),后续如需发货需在待处理工作台重新分配储位",
"同步更新 methods/system.json 中 cloneOrder 的 description"
],
"module": "order"
},
{
"version": "2026.08.21-order.pendingOrder.cloneOrder-unique-delivery-code",
"date": "2026-08-21",
"type": "fixed",
"summary": "修复 order.pendingOrder.cloneOrder 复制原单号导致唯一键冲突:新订单 delivery_order_code 重新生成(SYS+时间戳+随机4位,与 createOrder 同规则),原单号写入 pre_delivery_order_code 保留克隆追溯链;此前复制原单号会命中 (delivery_order_code, store_id, warehouse_id) 唯一索引,克隆报「Validation error」且原订单已被取消、新订单未创建(原订单损坏)。",
"methods": [
"order.pendingOrder.cloneOrder"
],
"notes": [
"app/service/systemMethods/order/pendingOrder.js cloneOrder:COPY_FIELDS 移除 delivery_order_code,新订单单号改为 SYS${Date.now()}${1000~9999 随机} 生成;原订单无 pre_delivery_order_code 时写入原单号保留追溯链;注释说明唯一索引约束与 UniqueConstraintError 表现",
"同步更新 methods/system.json 中 cloneOrder 的 description"
],
"module": "order"
},
{
"version": "2026.08.21-index.searchSpaces-batch-search",
"date": "2026-08-21",
@ -7150,39 +6566,5 @@
"仅文档变更,无业务代码修改"
],
"module": "storeWarehouse"
},
{
"version": "2026.08.21-storage.inventory.list-stock-query",
"date": "2026-08-21",
"type": "updated",
"summary": "storage.inventory.list 新增 where.stock_query 虚拟筛选:按商品编码/名称/货物编码/条码/SKU ID 模糊匹配库存列表",
"methods": [
"storage.inventory.list"
],
"notes": [
"与订单查询一致的 stock_query 虚拟筛选字段,如 where.stock_query = { operator: 'like', value: '111' }。",
"解析链路:stock_query → wms_stock_warehouse(item_code/item_name/goods_code/纯数字精确 id)+ wms_stock_barcodes(barcode)→ stock_id 集合 → wms_storage.stock_id IN 过滤;无匹配时返回空列表。",
"代码变更:systemMethods/storage/inventory.js#list 新增 extractStockQueryVirtualFilter(从 where 提取并移除 stock_query);systems/storage/inventory.js#getInventoryList 新增 stockQuery 参数与 resolveStockQueryToStockIds;methods/system.json 同步 where 参数文档(export 注明暂不支持 stock_query)。"
],
"module": "storage"
},
{
"version": "2026.08.24-storage.inventory.directPutaway",
"date": "2026-08-24",
"type": "added",
"summary": "新增 storage.inventory.directPutaway 接口:收货单直入库存(一步完成),直接写 wms_storage 并生成入库单",
"methods": [
"storage.inventory.directPutaway"
],
"notes": [
"新增收货单直入库存接口,与 storage.inventory.quickPutaway(转入库单,不写库存)并存,名称不交换保持兼容。",
"核心流程:校验收货单(completed + is_review=true,未作废)→ 检查货主配置 policy_config.allow_receiving_direct_putaway=1 → 过滤未入库明细(storage_status!=all)并校验全部已匹配系统商品 → 事务内锁定收货单行防并发 → 创建入库单 SCRK(order_status=COMPLETED、sync_status=SUCCESS,一步完成)→ 入库单明细与收货明细一一对应(不合并,每行 count/received_quantity=actual_quantity)→ 写入 wms_entry_order_receiving 主表级绑定 → 按 stock_id 聚合悲观行锁更新 wms_stock_warehouse 总库存并写 wms_stock_transaction(order_type=SCRK,与现有链路一致)→ 按收货明细库位 space_id 逐明细写入/累加 wms_storage 并写 wms_storage_transaction(order_type=entry_order,与现有 storage.entry.commit 链路一致)→ 逐明细写入 wms_inbound_direct_log(entry_item_id/receiving_detail_id/space_id 齐全,status=committed、inbound_type=import,与 storage.entry.commit 链路口径一致,保证 scanDetail/可用数量占用统计等读取链路数据一致)→ 回填收货明细 storage_status=all/stored_quantity 与主表 storage_status(all/partial)→ 操作日志。",
"日志全量写入:storage 变更记录(wms_storage_transaction,逐明细含 before/after 数量与锁定量)、stock 变更记录(wms_stock_transaction,按 SKU 聚合含 before/after 数量与锁定量)、stock 变更(wms_stock_warehouse 悲观行锁 increment quantity);操作日志(wms_operation_log)同时写三条:businessType=entry_order(ENTRY_ORDER_DIRECT_PUTAWAY)、businessType=storage(STORAGE_DIRECT_PUTAWAY,记录库位库存写入笔数与数量)、businessType=stock(STOCK_DIRECT_PUTAWAY,记录各 SKU 总量变更前后值摘要)。",
"库位规则:明细 space_id 有效则按其库位入库,否则回退默认库位 1;批次取收货明细 batch_number,无批次则以入库单号作为批次号;生产/效期日期取收货明细 production_date/expiry_date。",
"与 quickPutaway 的区别:directPutaway 一步直接写库存(入库单 COMPLETED),quickPutaway 仅转入库单(PENDING)不写库存,需再走 storage.entry.commit 才写库存。",
"货主开关:policy_config 新增 allow_receiving_direct_putaway(默认未开启时 400 拒绝),与 allow_receiving_quick_putaway 相互独立;app/model/store_warehouse.js 的 POLICY_CONFIG_FIELDS 白名单已补充该字段(否则模型 getter sanitizeOnly 会过滤掉该键导致开关无法读取)。",
"代码变更:app/service/systems/storage/inventory.js#directPutaway、app/service/systemMethods/storage/inventory.js#directPutaway(_noNeedAuth 新增 directPutaway)、methods/system.json 新增 method 文档、database/migrations/20260824 新增权限记录(path=storage.inventory.directPutaway)。"
],
"module": "storage"
}
]

File diff suppressed because it is too large Load Diff

View File

@ -1,173 +0,0 @@
'use strict';
/**
* 回补历史"打包完成但订单仍为打包中(padding)"的存量数据。
*
* 背景:workbench.finishPack / order_packing.setEndTime 曾只结束 wms_pack_task,
* 不更新订单 pack_status,导致大量订单停留在 padding(打包中)。
*
* 回补规则(以 wms_pack_task 为基准,status=2 视为打包已完成):
* - 团购任务(pack_mode=2):按 wave_no 批量更新对应仓库分表中
* pack_status='padding' 且未被拦截(intercept_status IN ('none', NULL))的订单 → 'fin'
* - 散单任务(pack_mode=1):按 order_id 更新单个订单(同样只改 padding 且未拦截)
* - 仅更新任务已完成(status=2)对应订单;仍在打包(status=1)或拦截中的订单不动
*
* 用法:
* node script/backfill-pack-status-fin.cjs # 预览模式:只统计不修改
* node script/backfill-pack-status-fin.cjs --apply # 实际执行
*
* 连接配置:默认 script/db-query-prod-config.js(生产库)。
*/
const path = require('path');
const { createRequire } = require('module');
const APPLY = process.argv.includes('--apply');
async function main() {
const projectRoot = path.resolve(__dirname, '..');
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
const mysql = projectRequire('mysql2/promise');
const configPath = path.join(__dirname, 'db-query-prod-config.js');
const cfg = require(configPath);
const client = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms;
if (!client) {
throw new Error(`未找到 mysql clients.wms 配置: ${configPath}`);
}
const conn = await mysql.createConnection({
host: client.host,
port: Number(client.port),
user: client.user,
password: client.password,
database: client.database,
charset: client.charset || 'utf8mb4',
timezone: 'Z',
multipleStatements: true,
});
try {
// 1. 读取所有已完成的打包任务
const [ tasks ] = await conn.query(
'SELECT warehouse_id, pack_mode, order_id, wave_no FROM wms_pack_task WHERE status = 2 AND deleted_at IS NULL'
);
const byWarehouse = new Map();
for (const t of tasks) {
const wh = Number(t.warehouse_id || 0);
if (!byWarehouse.has(wh)) byWarehouse.set(wh, { groupWaves: new Set(), singleOrders: new Set() });
const bucket = byWarehouse.get(wh);
if (Number(t.pack_mode) === 2 && t.wave_no) {
bucket.groupWaves.add(String(t.wave_no));
} else if (t.order_id) {
bucket.singleOrders.add(Number(t.order_id));
}
}
console.log(`任务统计: ${tasks.length} 条已完成任务,涉及仓库 ${byWarehouse.size} 个`);
for (const [ wh, b ] of byWarehouse.entries()) {
console.log(` 仓库 ${wh}: 团购波次 ${b.groupWaves.size} 个,散单订单 ${b.singleOrders.size} 笔`);
}
const chunk = list => {
const out = [];
for (let i = 0; i < list.length; i += 500) out.push(list.slice(i, i + 500));
return out;
};
let totalGroupAffected = 0;
let totalSingleAffected = 0;
const detail = [];
// 2. 逐仓库处理其 current / dispatch 分表
for (const [ wh, b ] of byWarehouse.entries()) {
const tables = [];
const [ tableRows ] = await conn.query('SHOW TABLES LIKE \'wms_order_delivery%\'');
const names = tableRows.map(r => Object.values(r)[0]);
for (const n of names) {
if (n.includes('_history') || n.includes('_outsourced') || n.includes('_bak')) continue;
// current 表(无后缀或带仓库后缀)与 dispatch 表都纳入
tables.push(n);
}
const waveList = [ ...b.groupWaves ];
const orderList = [ ...b.singleOrders ];
for (const tbl of tables) {
// 团购:按 wave_no 批量更新
for (const waves of chunk(waveList)) {
const waveIn = waves.map(w => conn.escape(w)).join(',');
const sql = `UPDATE ${tbl} SET pack_status = 'fin'
WHERE pack_status = 'padding'
AND intercept_status IN ('none', NULL)
AND wave_no IN (${waveIn})`;
if (APPLY) {
const [ r ] = await conn.query(sql);
if (r.affectedRows > 0) {
totalGroupAffected += r.affectedRows;
detail.push({ tbl, kind: 'group', waves: waves.length, affected: r.affectedRows });
}
} else {
const [ preview ] = await conn.query(
`SELECT COUNT(1) AS cnt FROM ${tbl}
WHERE pack_status = 'padding'
AND intercept_status IN ('none', NULL)
AND wave_no IN (${waveIn})`
);
const cnt = Number(preview[0].cnt || 0);
if (cnt > 0) {
totalGroupAffected += cnt;
detail.push({ tbl, kind: 'group', waves: waves.length, affected: cnt });
}
}
}
// 散单:按 order_id 更新
for (const orders of chunk(orderList)) {
const orderIn = orders.join(',');
if (APPLY) {
const sql = `UPDATE ${tbl} SET pack_status = 'fin'
WHERE pack_status = 'padding'
AND intercept_status IN ('none', NULL)
AND id IN (${orderIn})`;
const [ r ] = await conn.query(sql);
if (r.affectedRows > 0) {
totalSingleAffected += r.affectedRows;
detail.push({ tbl, kind: 'single', orders: orders.length, affected: r.affectedRows });
}
} else {
const [ preview ] = await conn.query(
`SELECT COUNT(1) AS cnt FROM ${tbl}
WHERE pack_status = 'padding'
AND intercept_status IN ('none', NULL)
AND id IN (${orderIn})`
);
const cnt = Number(preview[0].cnt || 0);
if (cnt > 0) {
totalSingleAffected += cnt;
detail.push({ tbl, kind: 'single', orders: orders.length, affected: cnt });
}
}
}
}
}
console.log('');
console.log(`==== ${APPLY ? '已执行' : '预览(加 --apply 执行)'} ====`);
console.log(`团购订单将更新: ${totalGroupAffected}`);
console.log(`散单订单将更新: ${totalSingleAffected}`);
console.log(`合计: ${totalGroupAffected + totalSingleAffected}`);
if (detail.length > 0) {
console.log('明细:');
for (const d of detail) console.log(` ${d.tbl} [${d.kind}] ${d.kind === 'group' ? d.waves + ' 波次' : d.orders + ' 订单'} → ${d.affected} 单`);
}
} finally {
await conn.end();
}
}
main().catch(err => {
console.error('回补脚本执行失败:', err.message);
process.exit(1);
});

View File

@ -1,73 +0,0 @@
'use strict';
/**
* 幂等补齐订单分表的 oaid_order_source_code 列。
*
* 背景:该列由订单模型(app/model/order_delivery.js)定义,分表工厂
* (order_delivery_factory.js)在首次访问某张分表时自动同步;history /
* outsourced 等长期不被访问的表可能滞后,可用本脚本提前补齐。
*
* 用法:
* 开发:node script/fix-order-oaid-column.cjs
* 生产:PowerShell 中 $env:NODE_ENV='production'; node script/fix-order-oaid-column.cjs
*
* 安全:只 ADD 缺失列(VARCHAR(50) NULL,与模型定义一致),不触碰 id /
* AUTO_INCREMENT,不修改已有列,可重复执行。
*/
(async () => {
try {
const configs = require('../database/config.js');
const env = process.env.NODE_ENV || 'development';
const cfg = configs[env];
if (!cfg) {
console.error('NO_CONFIG_FOR_ENV');
process.exit(2);
}
const mysql = require('mysql2/promise');
const conn = await mysql.createConnection({
host: cfg.host,
port: cfg.port || 3306,
user: cfg.username,
password: cfg.password,
database: cfg.database,
});
const [ tables ] = await conn.query(
`SELECT TABLE_NAME FROM information_schema.TABLES
WHERE TABLE_SCHEMA = ? AND TABLE_NAME LIKE 'wms_order_delivery\\_%'
ORDER BY TABLE_NAME`,
[ cfg.database ]
);
console.log(`环境: ${env}, 库: ${cfg.host}:${cfg.port}/${cfg.database}`);
console.log(`订单分表数量: ${tables.length}\n`);
const columnSql = 'ADD COLUMN oaid_order_source_code VARCHAR(50) NULL COMMENT \'OAID订单来源编码\'';
let added = 0;
let ok = 0;
for (const row of tables) {
const tableName = row.TABLE_NAME || row.table_name;
const [ columns ] = await conn.query(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = 'oaid_order_source_code'`,
[ cfg.database, tableName ]
);
if (columns.length === 0) {
await conn.query(`ALTER TABLE \`${tableName}\` ${columnSql}`);
console.log(`[ADD] ${tableName} 已补齐列`);
added += 1;
} else {
ok += 1;
}
}
console.log(`\n完成: 已存在 ${ok} 张, 新增 ${added} 张`);
await conn.end();
process.exit(0);
} catch (err) {
console.error('ERROR', err.message);
process.exit(3);
}
})();

View File

@ -1,23 +0,0 @@
'use strict';
const mysql = require('mysql2/promise');
(async () => {
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
// bindDetailProduct 自动写入的条码(本次测试的 TMPBC/FULLBC 前缀)
const [barcodes] = await c.query(`
SELECT id, stock_id, warehouse_id, barcode
FROM wms_stock_barcodes
WHERE barcode LIKE 'TMPBC%' OR barcode LIKE 'FULLBC%'
ORDER BY id`);
console.log('== wms_stock_barcodes 测试写入的条码(共 ' + barcodes.length + ' 行) ==');
console.log(JSON.stringify(barcodes, null, 2));
// 商品 159061/159064 上的全部条码
const [all] = await c.query(
`SELECT id, stock_id, barcode FROM wms_stock_barcodes WHERE stock_id IN (159061, 159064) ORDER BY id`
);
console.log('== 两商品全部条码 ==');
console.log(JSON.stringify(all, null, 2));
await c.end();
process.exit(0);
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,42 +0,0 @@
'use strict';
const mysql = require('mysql2/promise');
(async () => {
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
// 1. 请求日志表:本次重测 A(1530)/B(1531) 相关的接口调用日志
const [sysLogs] = await c.query(`
SELECT id, method, v, store_id, use_time, LEFT(body, 120) AS body_snip, created_at
FROM wms_system_log
WHERE body LIKE '%R20688012%' OR body LIKE '%R20688013%'
OR body LIKE '%"receiving_id":1530%' OR body LIKE '%"receiving_id":1531%'
OR body LIKE '%"ids":[1530%' OR body LIKE '%"ids":[1531%'
OR body LIKE '%"entry_order_id":387%' OR body LIKE '%"entry_order_id":388%'
ORDER BY id`);
console.log('== wms_system_log 请求日志(本次重测相关,共 ' + sysLogs.length + ' 条) ==');
console.log(JSON.stringify(sysLogs, null, 2));
// 2. 通知发送日志表(失败才写)
const [notiLogs] = await c.query(`
SELECT id, trace_id, store_id, warehouse_id, business_name, event, status, http_status, created_at
FROM wms_notification_send_log
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 2 DAY)
ORDER BY id DESC LIMIT 10`);
console.log('== wms_notification_send_log 最近两天(共 ' + notiLogs.length + ' 条) ==');
console.log(JSON.stringify(notiLogs, null, 2));
// 3. 商品资料异步补全相关(无图片/无重量时应无写入)
const [stockRow] = await c.query(
`SELECT id, is_images, gross_weight FROM wms_stock_warehouse WHERE id IN (159061, 159064)`
);
console.log('== 商品资料快照(is_images/gross_weight,验证异步补全未触发) ==');
console.log(JSON.stringify(stockRow, null, 2));
const [fileRefs] = await c.query(
`SELECT id, business_type, business_id, file_id FROM wms_file_reference WHERE business_type='stock' AND business_id IN ('159061','159064')`
);
console.log('== wms_file_reference(stock 类型,共 ' + fileRefs.length + ' 行) ==');
console.log(JSON.stringify(fileRefs, null, 2));
await c.end();
process.exit(0);
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,15 +0,0 @@
'use strict';
const mysql = require('mysql2/promise');
(async () => {
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
const [r] = await c.query(
`SELECT id, store_id, warehouse_id, warehouse_use_status,
JSON_EXTRACT(policy_config, '$.allow_receiving_direct_putaway') AS direct,
JSON_EXTRACT(policy_config, '$.allow_receiving_quick_putaway') AS quick
FROM wms_store_warehouse WHERE store_id = 1000000 AND warehouse_id = 100000`
);
console.log('store_warehouse:', JSON.stringify(r, null, 2));
const [r2] = await c.query('SELECT id, store_id, warehouse_id, status, is_review, storage_status FROM wms_receiving WHERE id IN (1521,1522,1523,1524)');
console.log('receivings:', JSON.stringify(r2, null, 2));
await c.end();
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,12 +0,0 @@
'use strict';
const mysql = require('mysql2/promise');
(async () => {
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
const [p] = await c.query("SELECT id, path, meta_title FROM wms_permission WHERE path LIKE 'storage.inventory%' AND type='api'");
console.log('perms:', JSON.stringify(p));
const [r] = await c.query('SELECT id, permissions FROM wms_role WHERE id IN (7)');
console.log('roles:', JSON.stringify(r));
const [col] = await c.query('SHOW COLUMNS FROM wms_role');
console.log('cols:', col.map(x => x.Field + ':' + x.Type).join(', '));
await c.end();
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,28 +0,0 @@
'use strict';
const mysql = require('mysql2/promise');
(async () => {
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
// 两个测试商品在 wms_storage 中的全部行
const [rows] = await c.query(`
SELECT id, warehouse_id, store_id, space_id, stock_id, batch_no, inventory_type,
quantity, locked_quantity, available_quantity,
inbound_order_no, receiving_id, entry_order_id, inbound_time
FROM wms_storage
WHERE stock_id IN (159061, 159064)
ORDER BY id`);
console.log('== wms_storage 中两个测试商品的全部行(共 ' + rows.length + ' 行) ==');
console.log(JSON.stringify(rows, null, 2));
// 两商品的库位流水(逐笔证据)
const [txns] = await c.query(`
SELECT id, order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no
FROM wms_storage_transaction
WHERE stock_id IN (159061, 159064)
ORDER BY id`);
console.log('== wms_storage_transaction 两商品逐笔流水(共 ' + txns.length + ' 条) ==');
console.log(JSON.stringify(txns, null, 2));
await c.end();
process.exit(0);
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,41 +0,0 @@
'use strict';
const mysql = require('mysql2/promise');
(async () => {
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
// 1. wms_storage 当前状态(A/B 共用的累加行)
const [storages] = await c.query(`
SELECT id, space_id, stock_id, batch_no, quantity, locked_quantity, available_quantity,
inbound_order_no, receiving_id, entry_order_id, inbound_time
FROM wms_storage WHERE id IN (408, 409)`);
console.log('== wms_storage 当前行(408/409) ==');
console.log(JSON.stringify(storages, null, 2));
// 2. wms_stock_warehouse 当前数量
const [stocks] = await c.query(`
SELECT id, item_code, quantity, locked_quantity, is_valid
FROM wms_stock_warehouse WHERE id IN (159061, 159064)`);
console.log('== wms_stock_warehouse 当前数量 ==');
console.log(JSON.stringify(stocks, null, 2));
// 3. A(入库单 387)与 B(入库单 388)各自的库位流水(证明 storage 写入)
const [storageTxns] = await c.query(`
SELECT order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no
FROM wms_storage_transaction
WHERE order_id IN (387, 388) OR order_no IN ('SCRK202608240007','SCRK202608240008')
ORDER BY id`);
console.log('== wms_storage_transaction:A(387)/B(388) 的库位流水 ==');
console.log(JSON.stringify(storageTxns, null, 2));
// 4. A/B 各自的商品流水(证明 stock_warehouse 数量变更)
const [stockTxns] = await c.query(`
SELECT order_no, transaction_type, stock_id, quantity, before_quantity, after_quantity, entry_order_id
FROM wms_stock_transaction
WHERE entry_order_id IN (387, 388) OR order_no IN ('SCRK202608240007','SCRK202608240008')
ORDER BY id`);
console.log('== wms_stock_transaction:A(387)/B(388) 的商品流水 ==');
console.log(JSON.stringify(stockTxns, null, 2));
await c.end();
process.exit(0);
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,13 +0,0 @@
'use strict';
const Redis = require('ioredis');
(async () => {
const r = new Redis({ host: '127.0.0.1', port: 6379, password: 'qwe2019', db: 10 });
const keys = await r.keys('user:info:*');
console.log('matched keys:', keys);
for (const k of keys) {
await r.del(k);
console.log('deleted:', k);
}
r.disconnect();
process.exit(0);
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,58 +0,0 @@
'use strict';
/* 临时探索脚本:查询直入/转入库单对比测试所需数据(只读) */
const mysql = require('mysql2/promise');
(async () => {
const conn = await mysql.createConnection({
host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms',
});
const [cols] = await conn.query('SHOW COLUMNS FROM wms_employee_role');
console.log('== wms_employee_role columns ==');
console.log(cols.map(c => c.Field).join(','));
const [whUsers] = await conn.query(`
SELECT a.id account_id, a.username, a.status, e.id employee_id, e.store_id warehouse_id, r.id role_id, r.role_type
FROM wms_account a
JOIN wms_account_store_employee e ON e.account_id = a.id AND e.deleted_at IS NULL
LEFT JOIN wms_employee_role er ON er.employee_id = e.id
LEFT JOIN wms_role r ON r.id = er.role_id
WHERE a.status = 1
ORDER BY e.id ASC LIMIT 8`);
console.log('== accounts ==');
console.log(JSON.stringify(whUsers, null, 2));
if (whUsers.length === 0) { await conn.end(); return; }
const whId = whUsers[0].warehouse_id;
console.log('== using warehouse_id = ' + whId + ' ==');
const [stores] = await conn.query(`
SELECT sw.store_id, sw.warehouse_use_status, sw.policy_config, s.company_name
FROM wms_store_warehouse sw JOIN wms_store s ON s.id = sw.store_id
WHERE sw.warehouse_id = ? AND sw.warehouse_use_status = 1
ORDER BY sw.id DESC LIMIT 5`, [ whId ]);
console.log('== store_warehouse contracts (warehouse=' + whId + ') ==');
console.log(JSON.stringify(stores, null, 2));
const [stocks] = await conn.query(`
SELECT sw.id, sw.item_code, sw.item_name, sw.is_batch_mgmt, sw.is_shelf_life_mgmt, sw.is_valid, sw.quantity, sw.store_id
FROM wms_stock_warehouse sw
WHERE sw.warehouse_id = ? AND sw.is_valid = 'Y' AND sw.deleted_at IS NULL
ORDER BY sw.id DESC LIMIT 8`, [ whId ]);
console.log('== stock_warehouse products ==');
console.log(JSON.stringify(stocks, null, 2));
const [spacesCols] = await conn.query('SHOW COLUMNS FROM wms_location_space');
console.log('== wms_location_space columns ==');
console.log(spacesCols.map(c => c.Field).join(','));
const [spaces] = await conn.query(`
SELECT id, space_code, custom_name, is_enabled, current_quantity
FROM wms_location_space
WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL
ORDER BY id LIMIT 8`, [ whId ]);
console.log('== location spaces ==');
console.log(JSON.stringify(spaces, null, 2));
await conn.end();
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,136 +0,0 @@
'use strict';
/**
* 批次维度对比测试(真实接口):
* 1. A 两步:批次 B-A-1 入库 10 件 → storage 建行
* 2. B 一步:批次 B-B-1 入库 10 件 → storage 建行(不同批次不互相影响)
* 3. A 两步:批次 B-A-1 再入库 5 件 → 同批次累加到 15
* 4. B 一步:批次 B-B-1 再入库 5 件 → 同批次累加到 15
* 商品 159061 / 库位 5918。测试数据不清理。
*/
const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const BASE = 'http://127.0.0.1:6060';
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
const ACCOUNT_ID = 1;
const STORE_ID = 1000000;
const STOCK_ID = 159061;
const SPACE_ID = 5918;
const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 });
async function db() {
return mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
}
async function call(method, data) {
const res = await fetch(`${BASE}/system?method=${method}&v=1&timestamp=${Date.now()}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
platform: 'web',
project: 'all',
authorization: `Bearer ${token}`,
},
body: JSON.stringify(data || {}),
});
const text = await res.text();
let parsed;
try { parsed = JSON.parse(text); } catch { parsed = text; }
return { http: res.status, body: parsed };
}
function step(name, res) {
const code = res.body && res.body.code;
const ok = res.http === 200 && res.body && res.body.flag === 'success' && (code === 200 || code === 1);
console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${code} msg=${res.body && res.body.message}`);
if (!ok) console.log(' 响应:', JSON.stringify(res.body).slice(0, 600));
return ok;
}
async function runFlow(tag, mode, batchNo, qty) {
console.log(`\n===== ${tag}:批次=${batchNo} 数量=${qty} =====`);
const conn = await db();
const [before] = await conn.query(
`SELECT quantity FROM wms_stock_warehouse WHERE id = ?`, [ STOCK_ID ]
);
// 收货单全链路
const createRes = await call('storage.receiving.create', {
store_id: STORE_ID, delivery_method: 'other', loading_method: 'with_pallet',
remark: `[批次对比-${tag}-${batchNo}]`, status: 'receiving',
});
const b = createRes.body || {};
const receivingId = (b.data && b.data.id) || b.id;
if (!step('创建收货单', createRes)) { await conn.end(); return null; }
const addRes = await call('storage.receiving.addDetail', {
receiving_id: receivingId,
item: { product_name: '批次对比测试商品', barcode: `B${Date.now()}`, actual_quantity: qty, batch_number: batchNo, space_id: SPACE_ID },
});
const addBody = addRes.body || {};
const addData = addBody.data || addBody;
const detailId = addData.selectId || (addData.details && addData.details[0] && addData.details[0].id);
if (!step('添加明细', addRes)) { await conn.end(); return null; }
if (!step('绑定商品', await call('storage.receiving.bindDetailProduct', { detail_id: detailId, system_product_id: STOCK_ID }))) { await conn.end(); return null; }
if (!step('完成收货', await call('storage.receiving.completeReceiving', { id: receivingId }))) { await conn.end(); return null; }
if (!step('审核', await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] }))) { await conn.end(); return null; }
let entryOrderId;
if (mode === 'A') {
const pRes = await call('storage.inventory.quickPutaway', { receiving_id: receivingId });
if (!step('quickPutaway', pRes)) { await conn.end(); return null; }
entryOrderId = pRes.body.data.entry_order_id;
if (!step('addItem(绑定收货明细)', await call('storage.entry.addItem', {
entry_order_id: entryOrderId,
items: [{ stock_id: STOCK_ID, quantity: qty, space_id: SPACE_ID, receiving_detail_id: detailId, allocated_quantity: qty, inbound_type: 'pda' }],
}))) { await conn.end(); return null; }
if (!step('commit', await call('storage.entry.commit', { entry_order_id: entryOrderId }))) { await conn.end(); return null; }
} else {
const dRes = await call('storage.inventory.directPutaway', { receiving_id: receivingId });
if (!step('directPutaway', dRes)) { await conn.end(); return null; }
entryOrderId = dRes.body.data.entry_order_id;
}
const [after] = await conn.query(
`SELECT quantity FROM wms_stock_warehouse WHERE id = ?`, [ STOCK_ID ]
);
console.log(` ── wms_stock_warehouse ${STOCK_ID}: ${before[0].quantity} → ${after[0].quantity}(+${qty})`);
const [storages] = await conn.query(
`SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, available_quantity, inbound_order_no, entry_order_id
FROM wms_storage WHERE stock_id = ? AND space_id = ? ORDER BY batch_no`, [ STOCK_ID, SPACE_ID ]
);
console.log(' ── wms_storage(商品 159061 / 库位 5918 全部行)──');
console.log(' ', JSON.stringify(storages));
await conn.end();
return { receivingId, entryOrderId };
}
async function main() {
await runFlow('① A-两步', 'A', 'B-A-1', 10);
await runFlow('② B-一步', 'B', 'B-B-1', 10);
await runFlow('③ A-两步(同批次累加)', 'A', 'B-A-1', 5);
await runFlow('④ B-一步(同批次累加)', 'B', 'B-B-1', 5);
const conn = await db();
const [storages] = await conn.query(
`SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, inbound_order_no, receiving_id, entry_order_id
FROM wms_storage WHERE stock_id = 159061 AND space_id = 5918 ORDER BY batch_no`
);
console.log('\n========== 最终 wms_storage 对比(商品 159061 / 库位 5918) ==========');
console.log(JSON.stringify(storages, null, 2));
const [txns] = await conn.query(
`SELECT order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type
FROM wms_storage_transaction WHERE stock_id = 159061 AND space_id = 5918 AND batch_no IN ('B-A-1','B-B-1') ORDER BY id`
);
console.log('\n========== 库位流水(批次 B-A-1 / B-B-1) ==========');
console.log(JSON.stringify(txns, null, 2));
await conn.end();
console.log('\n================ 批次对比测试结束 ================');
}
main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); });

View File

@ -1,261 +0,0 @@
'use strict';
/**
* 临时对比测试:quickPutaway(转入库单) vs directPutaway(直入库存)
* 全链路走真实接口:创建收货单 → 添加明细 → 绑定商品 → 完成收货 → 审核 → 上架。
* 测试数据不清理,保留以便核对。
* 用法:node script/tmp-test-putaway-compare.cjs
*/
const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const BASE = 'http://127.0.0.1:6060';
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
const ACCOUNT_ID = 1;
const WAREHOUSE_ID = 100000;
const STORE_ID = 1000000;
// 商品:159061 非批次非效期;159064 效期管理(非批次)
const PRODUCTS = [
{ stock_id: 159061, item_code: '20260703', qty: 30, batch_number: 'TQB1', space_id: null },
{ stock_id: 159064, item_code: '544354', qty: 7, batch_number: 'TQB2', production_date: '2026-01-01', expiry_date: '2027-01-01', space_id: null },
];
const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 });
async function db() {
return mysql.createConnection({
host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms',
});
}
async function call(method, data) {
const res = await fetch(`${BASE}/system?method=${method}&v=1&timestamp=${Date.now()}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
platform: 'web',
project: 'all',
authorization: `Bearer ${token}`,
},
body: JSON.stringify(data || {}),
});
const text = await res.text();
let parsed;
try { parsed = JSON.parse(text); } catch { parsed = text; }
return { http: res.status, body: parsed };
}
function step(name, res, extract) {
const bodyCode = res.body && res.body.code;
const ok = res.http === 200 && res.body && res.body.flag === 'success' && (bodyCode === 200 || bodyCode === 1);
let extra = '';
if (extract && res.body && res.body.data) {
try { extra = JSON.stringify(extract(res.body.data)); } catch (e) { /* ignore */ }
}
console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${bodyCode} msg=${res.body && res.body.message} ${extra}`);
return ok;
}
async function runFlow(tag, putawayMethod) {
console.log(`\n================ 流程 ${tag}(${putawayMethod}) ================`);
const conn = await db();
// 快照入库前商品总库存
const stockIds = PRODUCTS.map(p => p.stock_id);
const [beforeStock] = await conn.query(
`SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ]
);
// 1. 创建收货单
const createRes = await call('storage.receiving.create', {
store_id: STORE_ID,
delivery_method: 'other',
loading_method: 'with_pallet',
remark: `[自动对比测试-${tag}]`,
status: 'receiving',
});
const createBody = createRes.body || {};
const receivingId = createBody.data && createBody.data.id ? createBody.data.id : createBody.id;
const receivingNumber = (createBody.data && createBody.data.receiving_number) || createBody.receiving_number;
if (!step('创建收货单', createRes, () => ({ id: receivingId, receiving_number: receivingNumber }))) {
console.log(' create 响应:', JSON.stringify(createBody).slice(0, 600));
return { conn, receivingId: 0 };
}
console.log(` receiving_id=${receivingId} receiving_number=${receivingNumber}`);
// 2. 添加明细(含库位)
const detailIds = [];
for (let i = 0; i < PRODUCTS.length; i++) {
const p = PRODUCTS[i];
const addRes = await call('storage.receiving.addDetail', {
receiving_id: receivingId,
item: {
product_name: `对比测试商品${i + 1}`,
barcode: `TMPBC${Date.now()}${i}`,
actual_quantity: p.qty,
batch_number: p.batch_number,
production_date: p.production_date || null,
expiry_date: p.expiry_date || null,
space_id: p.space_id,
},
});
const addBody = addRes.body || {};
const addData = addBody.data || addBody;
const newDetailId = addData.selectId
|| (addData.details && Array.isArray(addData.details) && addData.details[0] && addData.details[0].id);
if (!step(`添加明细#${i + 1}`, addRes, () => ({ detail_id: newDetailId }))) {
console.log(' addDetail 响应:', JSON.stringify(addBody).slice(0, 600));
return { conn, receivingId };
}
detailIds.push(newDetailId);
}
// 3. 绑定系统商品
for (let i = 0; i < PRODUCTS.length; i++) {
const bindRes = await call('storage.receiving.bindDetailProduct', {
detail_id: detailIds[i],
system_product_id: PRODUCTS[i].stock_id,
});
if (!step(`绑定商品#${i + 1}`, bindRes, d => ({ detail_id: d.detail_id, system_product_id: d.system_product_id }))) return { conn, receivingId };
}
// 4. 完成收货
const completeRes = await call('storage.receiving.completeReceiving', { id: receivingId });
if (!step('完成收货', completeRes, d => ({ status: d.status || d.receiving_status }))) {
console.log(' completeReceiving 响应:', JSON.stringify(completeRes.body).slice(0, 500));
return { conn, receivingId };
}
// 5. 审核
const reviewRes = await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] });
if (!step('审核收货单', reviewRes)) {
console.log(' reviewReceiving 响应:', JSON.stringify(reviewRes.body).slice(0, 500));
return { conn, receivingId };
}
// 6. 上架
const putawayRes = await call(putawayMethod, { receiving_id: receivingId });
if (!step(`上架(${putawayMethod})`, putawayRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) {
console.log(' 上架响应:', JSON.stringify(putawayRes.body).slice(0, 800));
return { conn, receivingId };
}
// 7. 对比验证数据
const entryOrderId = putawayRes.body.data.entry_order_id;
const entryOrderCode = putawayRes.body.data.entry_order_code;
const [afterStock] = await conn.query(
`SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ]
);
console.log(' ── 商品总库存(wms_stock_warehouse)──');
for (const b of beforeStock) {
const a = afterStock.find(x => String(x.id) === String(b.id)) || { quantity: '?', locked_quantity: '?' };
console.log(` stock_id=${b.id} before=${b.quantity} after=${a.quantity} locked=${a.locked_quantity}`);
}
const [entryOrder] = await conn.query(
`SELECT id, entry_order_code, order_type, order_status, sync_status, total_order_lines FROM wms_entry_order WHERE id = ?`, [ entryOrderId ]
);
console.log(' ── 入库单(wms_entry_order)──');
console.log(' ', JSON.stringify(entryOrder[0] || null));
const [entryItems] = await conn.query(
`SELECT order_line_no, item_code, stock_id, count, received_quantity, inventory_type FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ entryOrderId ]
);
console.log(' ── 入库单明细(wms_entry_items,共 ' + entryItems.length + ' 行)──');
console.log(' ', JSON.stringify(entryItems));
const [orderReceiving] = await conn.query(
`SELECT entry_order_id, receiving_id FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ entryOrderId ]
);
console.log(' ── 绑定(wms_entry_order_receiving)──');
console.log(' ', JSON.stringify(orderReceiving));
const [receivingRow] = await conn.query(
`SELECT id, status, is_review, storage_status, detail_status FROM wms_receiving WHERE id = ?`, [ receivingId ]
);
console.log(' ── 收货单主表(wms_receiving)──');
console.log(' ', JSON.stringify(receivingRow[0] || null));
const [receivingDetails] = await conn.query(
`SELECT id, system_product_id, actual_quantity, stored_quantity, storage_status, space_id, batch_number FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ receivingId ]
);
console.log(' ── 收货明细(wms_receiving_detail)──');
console.log(' ', JSON.stringify(receivingDetails));
const [storages] = await conn.query(
`SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity,
inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date
FROM wms_storage
WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?)
ORDER BY id`, [ entryOrderId, entryOrderCode, receivingId ]
);
console.log(' ── 库位库存(wms_storage,共 ' + storages.length + ' 行)──');
console.log(' ', JSON.stringify(storages));
const [stockTxns] = await conn.query(
`SELECT transaction_type, stock_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id
FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ]
);
console.log(' ── 商品流水(wms_stock_transaction,共 ' + stockTxns.length + ' 行)──');
console.log(' ', JSON.stringify(stockTxns));
const [storageTxns] = await conn.query(
`SELECT transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no
FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ]
);
console.log(' ── 库位流水(wms_storage_transaction,共 ' + storageTxns.length + ' 行)──');
console.log(' ', JSON.stringify(storageTxns));
const [opLogs] = await conn.query(
`SELECT business_type, operation_code, business_id, operator_name, message
FROM wms_operation_log WHERE business_id = ? ORDER BY id`, [ String(entryOrderId) ]
);
console.log(' ── 操作日志(wms_operation_log,共 ' + opLogs.length + ' 行)──');
console.log(' ', JSON.stringify(opLogs));
await conn.end();
return { receivingId, entryOrderId, entryOrderCode };
}
async function main() {
const conn = await db();
// 取两个真实库位
const [spaces] = await conn.query(
`SELECT id, space_code FROM wms_location_space WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL ORDER BY id LIMIT 3`,
[ WAREHOUSE_ID ]
);
console.log('使用库位:', JSON.stringify(spaces));
PRODUCTS[0].space_id = spaces[0].id;
PRODUCTS[1].space_id = spaces[1] ? spaces[1].id : spaces[0].id;
// 开关状态:quick 已开(货主 1000000 配置为 1);direct 需开启
const [beforePolicy] = await conn.query(
`SELECT policy_config FROM wms_store_warehouse WHERE store_id = ? AND warehouse_id = ?`, [ STORE_ID, WAREHOUSE_ID ]
);
console.log('货主 policy_config:', JSON.stringify(beforePolicy[0] && beforePolicy[0].policy_config));
await conn.end();
// 流程 A:转入库单(可用 node script/tmp-test-putaway-compare.cjs A 单独跑)
if (!process.argv[2] || process.argv[2] === 'A') {
await runFlow('A-quickPutaway', 'storage.inventory.quickPutaway');
}
// 开启直入开关(测试准备,SQL 直接配置)
const conn2 = await db();
await conn2.query(
`UPDATE wms_store_warehouse SET policy_config = JSON_SET(COALESCE(policy_config,'{}'), '$.allow_receiving_direct_putaway', 1)
WHERE store_id = ? AND warehouse_id = ?`, [ STORE_ID, WAREHOUSE_ID ]
);
await conn2.end();
console.log('\n已开启 allow_receiving_direct_putaway=1(store=1000000, warehouse=100000)');
// 流程 B:直入库存
if (!process.argv[2] || process.argv[2] === 'B') {
await runFlow('B-directPutaway', 'storage.inventory.directPutaway');
}
console.log('\n================ 测试结束 ================');
}
main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); });

View File

@ -1,281 +0,0 @@
'use strict';
/**
* 临时完整对比测试:
* 流程 A(两步):storage.inventory.quickPutaway(转入库单)
* → storage.entry.addItem(导入入库,绑定收货明细)
* → storage.entry.commit(提交确认写库存)
* 流程 B(一步):storage.inventory.directPutaway(直入库存)
* 收货单链路全部走真实接口。测试数据不清理。
* 用法:node script/tmp-test-putaway-full-compare.cjs [A|B]
*/
const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const BASE = 'http://127.0.0.1:6060';
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
const ACCOUNT_ID = 1;
const WAREHOUSE_ID = 100000;
const STORE_ID = 1000000;
const PRODUCTS = [
{ stock_id: 159061, item_code: '20260703', qty: 30, batch_number: 'TQB1', space_id: null },
{ stock_id: 159064, item_code: '544354', qty: 7, batch_number: 'TQB2', production_date: '2026-01-01', expiry_date: '2027-01-01', space_id: null },
];
const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 });
async function db() {
return mysql.createConnection({
host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms',
});
}
async function call(method, data) {
const res = await fetch(`${BASE}/system?method=${method}&v=1&timestamp=${Date.now()}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
platform: 'web',
project: 'all',
authorization: `Bearer ${token}`,
},
body: JSON.stringify(data || {}),
});
const text = await res.text();
let parsed;
try { parsed = JSON.parse(text); } catch { parsed = text; }
return { http: res.status, body: parsed };
}
function step(name, res, extract) {
const bodyCode = res.body && res.body.code;
const ok = res.http === 200 && res.body && res.body.flag === 'success' && (bodyCode === 200 || bodyCode === 1);
let extra = '';
if (extract && res.body && res.body.data) {
try { extra = JSON.stringify(extract(res.body.data)); } catch (e) { /* ignore */ }
}
console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${bodyCode} msg=${res.body && res.body.message} ${extra}`);
return ok;
}
async function verifyFlow(conn, tag, receivingId, entryOrderId, entryOrderCode, beforeStock) {
const stockIds = PRODUCTS.map(p => p.stock_id);
const [afterStock] = await conn.query(
`SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ]
);
console.log(` ── [${tag}] 商品总库存(wms_stock_warehouse)──`);
for (const b of beforeStock) {
const a = afterStock.find(x => String(x.id) === String(b.id)) || { quantity: '?', locked_quantity: '?' };
console.log(` stock_id=${b.id} before=${b.quantity} after=${a.quantity} locked=${a.locked_quantity}`);
}
const [entryOrder] = await conn.query(
`SELECT id, entry_order_code, order_type, order_status, sync_status, total_order_lines FROM wms_entry_order WHERE id = ?`, [ entryOrderId ]
);
console.log(` ── [${tag}] 入库单(wms_entry_order)──`);
console.log(' ', JSON.stringify(entryOrder[0] || null));
const [entryItems] = await conn.query(
`SELECT order_line_no, item_code, stock_id, count, received_quantity, inventory_type FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ entryOrderId ]
);
console.log(` ── [${tag}] 入库单明细(wms_entry_items,共 ${entryItems.length} 行)──`);
console.log(' ', JSON.stringify(entryItems));
const [orderReceiving] = await conn.query(
`SELECT entry_order_id, receiving_id FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ entryOrderId ]
);
console.log(` ── [${tag}] 绑定(wms_entry_order_receiving)──`);
console.log(' ', JSON.stringify(orderReceiving));
const [receivingRow] = await conn.query(
`SELECT id, status, is_review, storage_status, detail_status FROM wms_receiving WHERE id = ?`, [ receivingId ]
);
console.log(` ── [${tag}] 收货单主表(wms_receiving)──`);
console.log(' ', JSON.stringify(receivingRow[0] || null));
const [receivingDetails] = await conn.query(
`SELECT id, system_product_id, actual_quantity, stored_quantity, storage_status, space_id, batch_number FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ receivingId ]
);
console.log(` ── [${tag}] 收货明细(wms_receiving_detail)──`);
console.log(' ', JSON.stringify(receivingDetails));
const [storages] = await conn.query(
`SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity,
inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date
FROM wms_storage
WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?)
ORDER BY id`, [ entryOrderId, entryOrderCode, receivingId ]
);
console.log(` ── [${tag}] 库位库存(wms_storage,共 ${storages.length} 行)──`);
console.log(' ', JSON.stringify(storages));
const [stockTxns] = await conn.query(
`SELECT transaction_type, stock_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id
FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ]
);
console.log(` ── [${tag}] 商品流水(wms_stock_transaction,共 ${stockTxns.length} 行)──`);
console.log(' ', JSON.stringify(stockTxns));
const [storageTxns] = await conn.query(
`SELECT transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no
FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ]
);
console.log(` ── [${tag}] 库位流水(wms_storage_transaction,共 ${storageTxns.length} 行)──`);
console.log(' ', JSON.stringify(storageTxns));
const [directLogs] = await conn.query(
`SELECT id, stock_id, quantity, entry_item_id, receiving_detail_id, space_id, status, inbound_type
FROM wms_inbound_direct_log WHERE entry_order_id = ? ORDER BY id`, [ entryOrderId ]
);
console.log(` ── [${tag}] 导入入库记录(wms_inbound_direct_log,共 ${directLogs.length} 行)──`);
console.log(' ', JSON.stringify(directLogs));
const [opLogs] = await conn.query(
`SELECT business_type, operation_code, operator_name, message
FROM wms_operation_log WHERE business_id = ? AND operation_code IN
('ENTRY_ORDER_QUICK_PUTAWAY','ENTRY_ORDER_DIRECT_PUTAWAY','STORAGE_DIRECT_PUTAWAY','STOCK_DIRECT_PUTAWAY','DIRECT_INBOUND_ADD','DIRECT_INBOUND_COMMIT')
ORDER BY id`, [ String(entryOrderId) ]
);
console.log(` ── [${tag}] 本流程操作日志(wms_operation_log,共 ${opLogs.length} 行)──`);
console.log(' ', JSON.stringify(opLogs));
}
async function runFlow(tag, mode) {
console.log(`\n================ 流程 ${tag}(${mode}) ================`);
const conn = await db();
const stockIds = PRODUCTS.map(p => p.stock_id);
const [beforeStock] = await conn.query(
`SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ]
);
// 收货单全链路
const createRes = await call('storage.receiving.create', {
store_id: STORE_ID,
delivery_method: 'other',
loading_method: 'with_pallet',
remark: `[完整对比测试-${tag}]`,
status: 'receiving',
});
const createBody = createRes.body || {};
const receivingId = createBody.data && createBody.data.id ? createBody.data.id : createBody.id;
const receivingNumber = (createBody.data && createBody.data.receiving_number) || createBody.receiving_number;
if (!step('创建收货单', createRes, () => ({ id: receivingId, receiving_number: receivingNumber }))) {
await conn.end(); return;
}
console.log(` receiving_id=${receivingId} receiving_number=${receivingNumber}`);
const detailIds = [];
for (let i = 0; i < PRODUCTS.length; i++) {
const p = PRODUCTS[i];
const addRes = await call('storage.receiving.addDetail', {
receiving_id: receivingId,
item: {
product_name: `完整对比测试商品${i + 1}`,
barcode: `FULLBC${Date.now()}${i}`,
actual_quantity: p.qty,
batch_number: p.batch_number,
production_date: p.production_date || null,
expiry_date: p.expiry_date || null,
space_id: p.space_id,
},
});
const addBody = addRes.body || {};
const addData = addBody.data || addBody;
const newDetailId = addData.selectId
|| (addData.details && Array.isArray(addData.details) && addData.details[0] && addData.details[0].id);
if (!step(`添加明细#${i + 1}`, addRes, () => ({ detail_id: newDetailId }))) { await conn.end(); return; }
detailIds.push(newDetailId);
}
for (let i = 0; i < PRODUCTS.length; i++) {
const bindRes = await call('storage.receiving.bindDetailProduct', {
detail_id: detailIds[i],
system_product_id: PRODUCTS[i].stock_id,
});
if (!step(`绑定商品#${i + 1}`, bindRes, d => ({ detail_id: d.detail_id, system_product_id: d.system_product_id }))) { await conn.end(); return; }
}
const completeRes = await call('storage.receiving.completeReceiving', { id: receivingId });
if (!step('完成收货', completeRes)) {
console.log(' completeReceiving 响应:', JSON.stringify(completeRes.body).slice(0, 500));
await conn.end(); return;
}
const reviewRes = await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] });
if (!step('审核收货单', reviewRes)) {
console.log(' reviewReceiving 响应:', JSON.stringify(reviewRes.body).slice(0, 500));
await conn.end(); return;
}
let entryOrderId;
let entryOrderCode;
if (mode === 'A') {
// 两步流程第一步:转入库单
const putawayRes = await call('storage.inventory.quickPutaway', { receiving_id: receivingId });
if (!step('① quickPutaway(转入库单)', putawayRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) {
console.log(' 响应:', JSON.stringify(putawayRes.body).slice(0, 600));
await conn.end(); return;
}
entryOrderId = putawayRes.body.data.entry_order_id;
entryOrderCode = putawayRes.body.data.entry_order_code;
// 两步流程第二步:导入入库(绑定收货明细 + 收货明细库位)
const addItemRes = await call('storage.entry.addItem', {
entry_order_id: entryOrderId,
items: [
{ stock_id: PRODUCTS[0].stock_id, quantity: PRODUCTS[0].qty, space_id: PRODUCTS[0].space_id, receiving_detail_id: detailIds[0], allocated_quantity: PRODUCTS[0].qty, inbound_type: 'pda' },
{ stock_id: PRODUCTS[1].stock_id, quantity: PRODUCTS[1].qty, space_id: PRODUCTS[1].space_id, receiving_detail_id: detailIds[1], allocated_quantity: PRODUCTS[1].qty, inbound_type: 'pda' },
],
});
if (!step('② storage.entry.addItem(导入入库,绑定收货明细)', addItemRes, d => ({ count: d.count, total_quantity: d.total_quantity }))) {
console.log(' 响应:', JSON.stringify(addItemRes.body).slice(0, 800));
await conn.end(); return;
}
// 两步流程第三步:提交确认写库存
const commitRes = await call('storage.entry.commit', { entry_order_id: entryOrderId });
if (!step('③ storage.entry.commit(提交确认入库)', commitRes, d => ({ success: d.success, message: d.message }))) {
console.log(' 响应:', JSON.stringify(commitRes.body).slice(0, 800));
await conn.end(); return;
}
} else {
// 一步直入
const directRes = await call('storage.inventory.directPutaway', { receiving_id: receivingId });
if (!step('① directPutaway(一步直入)', directRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) {
console.log(' 响应:', JSON.stringify(directRes.body).slice(0, 600));
await conn.end(); return;
}
entryOrderId = directRes.body.data.entry_order_id;
entryOrderCode = directRes.body.data.entry_order_code;
}
await verifyFlow(conn, tag, receivingId, entryOrderId, entryOrderCode, beforeStock);
await conn.end();
console.log(`================ 流程 ${tag} 完成:receiving=${receivingId} entry_order=${entryOrderId} ================`);
}
async function main() {
const conn = await db();
const [spaces] = await conn.query(
`SELECT id, space_code FROM wms_location_space WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL ORDER BY id LIMIT 2`,
[ WAREHOUSE_ID ]
);
console.log('使用库位:', JSON.stringify(spaces));
PRODUCTS[0].space_id = spaces[0].id;
PRODUCTS[1].space_id = spaces[1] ? spaces[1].id : spaces[0].id;
await conn.end();
const only = (process.argv[2] || '').toUpperCase();
if (!only || only === 'A') {
await runFlow('A-两步', 'A');
}
if (!only || only === 'B') {
await runFlow('B-一步', 'B');
}
console.log('\n================ 测试结束 ================');
}
main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); });

View File

@ -1,103 +0,0 @@
'use strict';
/**
* 全表核对:A 两步链路(收货单 1526 / 入库单 383) vs B 一步直入(收货单 1528 / 入库单 385)
* 覆盖 A 链路涉及的所有表(收货单阶段 + 转入库单 + 导入入库 + 提交确认)。
* 只读,不产生数据。
*/
const mysql = require('mysql2/promise');
const A = { receiving: 1526, entryOrder: 383, code: 'SCRK202608240003', detailIds: [ 2711, 2712 ] };
const B = { receiving: 1528, entryOrder: 385, code: 'SCRK202608240005', detailIds: [ 2715, 2716 ] };
(async () => {
const conn = await mysql.createConnection({
host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms',
});
const show = async (title, sql, params) => {
const [rows] = await conn.query(sql, params);
console.log(`\n===== ${title} =====`);
console.log(JSON.stringify(rows, null, 2));
};
for (const [ tag, t ] of [ [ 'A-两步', A ], [ 'B-一步', B ] ]) {
console.log(`\n########## ${tag}(receiving=${t.receiving}, entry_order=${t.entryOrder}) ##########`);
await show('1. wms_receiving 收货单主表', `
SELECT id, receiving_number, status, is_review, storage_status, detail_status, store_id, warehouse_id, total_items, total_quantity
FROM wms_receiving WHERE id = ?`, [ t.receiving ]);
await show('2. wms_receiving_detail 收货明细', `
SELECT id, receiving_id, system_product_id, actual_quantity, stored_quantity, storage_status,
space_id, batch_number, production_date, expiry_date, barcode, receiving_status
FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ t.receiving ]);
await show('3. wms_entry_order 入库单', `
SELECT id, entry_order_code, order_type, order_status, sync_status, sync_message, source_type,
total_order_lines, warehouse_id, store_id, store_name, warehouse_name, remark
FROM wms_entry_order WHERE id = ?`, [ t.entryOrder ]);
await show('4. wms_entry_items 入库明细', `
SELECT id, order_id, order_line_no, item_code, stock_id, count, received_quantity, confirm_quantity, inventory_type
FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ t.entryOrder ]);
await show('5. wms_entry_order_receiving 主表绑定', `
SELECT id, entry_order_id, receiving_id, created_at FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ t.entryOrder ]);
await show('6. wms_inbound_direct_log 导入入库记录(两步中间态)', `
SELECT id, entry_order_id, entry_order_code, stock_id, quantity, entry_item_id, receiving_detail_id, space_id, status, inbound_type, remark
FROM wms_inbound_direct_log WHERE entry_order_id = ? ORDER BY id`, [ t.entryOrder ]);
await show('7. wms_stock_warehouse 商品总库存', `
SELECT id, item_code, quantity, locked_quantity, is_valid FROM wms_stock_warehouse WHERE id IN (159061, 159064) ORDER BY id`);
await show('8. wms_storage 库位库存', `
SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity,
inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date, inbound_time
FROM wms_storage WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?) ORDER BY id`,
[ t.entryOrder, t.code, t.receiving ]);
await show('9. wms_stock_transaction 商品流水', `
SELECT id, transaction_type, stock_id, quantity, before_quantity, after_quantity,
before_locked_quantity, after_locked_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id, remark
FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ t.code, t.entryOrder ]);
await show('10. wms_storage_transaction 库位流水', `
SELECT id, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity,
before_locked_quantity, after_locked_quantity, batch_no, inventory_type, order_type, order_no, order_id
FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ t.code, t.entryOrder ]);
await show('11. wms_operation_log 本流程操作日志', `
SELECT id, business_type, business_id, operation_code, operator_name, warehouse_id, message
FROM wms_operation_log
WHERE business_id = ? AND operation_code IN
('RECEIVING_CREATE','RECEIVING_ADD_DETAIL','RECEIVING_BIND_PRODUCT','RECEIVING_COMPLETE','RECEIVING_REVIEW',
'ENTRY_ORDER_QUICK_PUTAWAY','DIRECT_INBOUND_ADD','DIRECT_INBOUND_COMMIT',
'ENTRY_ORDER_DIRECT_PUTAWAY','STORAGE_DIRECT_PUTAWAY','STOCK_DIRECT_PUTAWAY')
ORDER BY id`, [ String(t.entryOrder) ]);
await show('12. wms_operation_log 收货单维度操作日志', `
SELECT id, business_type, business_id, operation_code, operator_name, warehouse_id, message
FROM wms_operation_log WHERE business_id = ? ORDER BY id`, [ String(t.receiving) ]);
await show('13. wms_store_warehouse 货主签约与开关', `
SELECT id, store_id, warehouse_id, warehouse_use_status,
JSON_EXTRACT(policy_config, '$.allow_receiving_quick_putaway') AS quick,
JSON_EXTRACT(policy_config, '$.allow_receiving_direct_putaway') AS direct
FROM wms_store_warehouse WHERE store_id = 1000000 AND warehouse_id = 100000`);
await show('14. wms_stock_barcodes 本次绑定的条码', `
SELECT id, stock_id, warehouse_id, barcode
FROM wms_stock_barcodes
WHERE stock_id IN (159061, 159064)
AND barcode IN (SELECT barcode FROM wms_receiving_detail WHERE receiving_id = ?)
ORDER BY id`, [ t.receiving ]);
await show('15. wms_location_space 库位统计快照(入库链路不维护该统计)', `
SELECT id, space_code, current_quantity, current_sku_count, is_enabled
FROM wms_location_space WHERE id IN (5918, 5919)`);
}
await conn.end();
process.exit(0);
})().catch(e => { console.error(e); process.exit(1); });

View File

@ -1,168 +0,0 @@
'use strict';
const assert = require('node:assert/strict');
const DeliveryOrderService = require('../../../../app/service/systems/delivery_order');
/**
* 构建 addOrderLines 测试桩。
*
* @param {Object} options 可配置项。
* @param {Object} options.stockStoreRecords StockStore 桩返回值:{ byPk, byCode }。
* @return {Object} 服务实例与调用记录。
*/
function createHarness({ stockStoreRecords = {} } = {}) {
const findByPkCalls = [];
const findOneCalls = [];
const bulkCreateCalls = [];
const appLogger = {
debug() {},
info() {},
warn() {},
error() {},
};
const app = {
logger: appLogger,
getCacheAsync: async () => null,
setCacheAsync: async () => {},
delCacheAsync: async () => {},
};
const ctx = {
app,
logger: appLogger,
model: {
OrderItemsFactory: {
async getCurrentModel() {
return {
async bulkCreate(lineData) {
bulkCreateCalls.push(lineData);
return lineData;
},
};
},
},
StockStore: {
async findByPk(itemId) {
findByPkCalls.push(String(itemId));
return stockStoreRecords.byPk || null;
},
async findOne({ where } = {}) {
findOneCalls.push(where);
return stockStoreRecords.byCode || null;
},
},
StockWarehouse: {
async findAll() {
return [];
},
},
},
service: {
systems: {
stockStore: {
async getStoreWarehousePolicyByStoreAndWarehouse() {
return {};
},
async lockItemStorages() {
return { success: true };
},
},
},
},
};
app.model = ctx.model;
const service = new DeliveryOrderService(ctx);
return { service, findByPkCalls, findOneCalls, bulkCreateCalls };
}
const WMS_STOCK = {
id: 1001076,
stock_id: 154103,
store_id: 1000186,
warehouse_id: 1000028,
item_code: '6934864204356',
item_name: '黑妹炭丝护龈牙刷',
goods_code: 'A.16.006.000001',
barcode: '6934864204356',
brand_name: null,
sku_property: null,
stock_unit: null,
category_id: 0,
category_name: null,
item_type: 'ZC',
retail_price: 0,
gross_weight: 0,
net_weight: 0,
length: 0,
width: 0,
height: 0,
volume: 0,
};
const INFO = { warehouseId: 1000028, appKey: '21226717', storeId: 1000186 };
const LINE = {
itemId: '6934864204356',
itemCode: '6934864204356',
itemName: '',
planQty: 12,
orderLineNo: '0',
};
describe('test/app/service/systems/delivery_order.addOrderLines.fallback.test.js', () => {
it('itemId 非空但非 WMS 主键时,降级按 item_code 查到商品并成功创建明细', async () => {
const { service, findByPkCalls, findOneCalls, bulkCreateCalls } = createHarness({
stockStoreRecords: { byCode: WMS_STOCK },
});
const result = await service.addOrderLines([ LINE ], 7788, INFO, {});
assert.equal(result.stock_count, 1);
assert.ok(result.items_str.includes('154103+12'), `items_str=${result.items_str}`);
assert.deepEqual(findByPkCalls, [ '6934864204356' ]);
assert.equal(findOneCalls.length, 1);
assert.equal(findOneCalls[0].item_code, '6934864204356');
assert.equal(findOneCalls[0].warehouse_id, 1000028);
assert.equal(findOneCalls[0].store_id, 1000186);
assert.equal(findOneCalls[0].app_key, '21226717');
assert.equal(bulkCreateCalls.length, 1);
assert.equal(bulkCreateCalls[0][0].item_id, 1001076);
});
it('itemId 对应主键存在且同货主时,直接按主键命中,不做 item_code 降级查询', async () => {
const { service, findOneCalls } = createHarness({
stockStoreRecords: { byPk: WMS_STOCK },
});
const result = await service.addOrderLines([ LINE ], 7788, INFO, {});
assert.equal(result.stock_count, 1);
assert.equal(findOneCalls.length, 0);
});
it('主键记录跨货主且 item_code 也查不到时,报未同步推送到仓库', async () => {
const { service } = createHarness({
stockStoreRecords: { byPk: { ...WMS_STOCK, store_id: 999999 } },
});
await assert.rejects(
() => service.addOrderLines([ LINE ], 7788, INFO, {}),
/未同步推送到仓库/
);
});
it('itemId 为空时,仅按 item_code 查询(既有行为回归)', async () => {
const { service, findByPkCalls, findOneCalls } = createHarness({
stockStoreRecords: { byCode: WMS_STOCK },
});
const result = await service.addOrderLines([{ ...LINE, itemId: '' }], 7788, INFO, {});
assert.equal(result.stock_count, 1);
assert.equal(findByPkCalls.length, 0);
assert.equal(findOneCalls.length, 1);
});
});

View File

@ -27,8 +27,6 @@ function createCainiaoHarness(options = {}) {
printQuantityLogCreate: 0,
operationLogCreateOperationLogs: 0,
operationLogPayloads: [],
getContractConfigCalls: [],
syncOrderIdsCalls: [],
};
const relationRows = [
@ -57,9 +55,6 @@ function createCainiaoHarness(options = {}) {
formatDate() {
return '2026-05-24 12:00:00';
},
async setCacheAsync() {
// no-op in tests
},
},
model: {
async transaction(callback) {
@ -111,9 +106,6 @@ function createCainiaoHarness(options = {}) {
},
},
express: {
async loadExpressList() {
return [];
},
async getWaybillAsyncOrderDeliveryModel() {
return {
async update() {
@ -130,25 +122,6 @@ function createCainiaoHarness(options = {}) {
return payloads;
},
},
storeWarehouse: {
async getContractConfig(warehouseId, storeId) {
calls.getContractConfigCalls.push({ warehouseId, storeId });
if (options.contractConfig !== undefined) {
return options.contractConfig;
}
return { policy_config: { auto_sync_back: 1 } };
},
},
},
systemMethods: {
order: {
pendingOrder: {
async syncOrderIds(request) {
calls.syncOrderIdsCalls.push(request);
return { flag: 'success' };
},
},
},
},
},
state: {
@ -362,28 +335,4 @@ describe('test/app/service/systems/express_platform.cainiao.test.js', () => {
/参数错误/
);
});
it('auto_sync_back 开启且无登录用户上下文时,应以显式 warehouseId 触发订单同步回传', async () => {
const { service, calls } = createCainiaoHarness();
await service.cainiao(buildPayload());
assert.equal(calls.getContractConfigCalls.length, 1);
assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 5001 });
assert.equal(calls.syncOrderIdsCalls.length, 1);
assert.deepEqual(calls.syncOrderIdsCalls[0], {
orderIds: [ 2001 ],
warehouseId: 100000,
});
});
it('auto_sync_back 关闭时不应触发订单同步回传', async () => {
const { service, calls } = createCainiaoHarness({
contractConfig: { policy_config: { auto_sync_back: 0 } },
});
await service.cainiao(buildPayload());
assert.equal(calls.syncOrderIdsCalls.length, 0);
});
});

View File

@ -6,11 +6,9 @@ const ExpressPlatformService = require('../../../../app/service/systems/express_
/**
* 构建拼多多服务最小测试桩。
*
* @param {Object} [options={}] 测试配置。
* @param {Object} [options.contractConfig] 合约配置覆盖值。
* @return {{ service: Object, calls: Object }} 服务实例与调用记录。
*/
function createPddHarness(options = {}) {
function createPddHarness() {
const calls = {
curl: 0,
curlOptions: null,
@ -21,8 +19,6 @@ function createPddHarness(options = {}) {
storeWarehouseUpdate: 0,
printQuantityLogCreate: 0,
operationLogCreateOperationLogs: 0,
getContractConfigCalls: [],
syncOrderIdsCalls: [],
};
const ctx = {
@ -75,9 +71,6 @@ function createPddHarness(options = {}) {
service: {
systems: {
express: {
async loadExpressList() {
return [];
},
async getWaybillAsyncOrderDeliveryModel() {
return {
async update() {
@ -93,25 +86,6 @@ function createPddHarness(options = {}) {
return [];
},
},
storeWarehouse: {
async getContractConfig(warehouseId, storeId) {
calls.getContractConfigCalls.push({ warehouseId, storeId });
if (options.contractConfig !== undefined) {
return options.contractConfig;
}
return { policy_config: { auto_sync_back: 1 } };
},
},
},
systemMethods: {
order: {
pendingOrder: {
async syncOrderIds(request) {
calls.syncOrderIdsCalls.push(request);
return { flag: 'success' };
},
},
},
},
},
logger: {
@ -178,9 +152,6 @@ function buildPayload() {
express: {
PDD: 'YTO',
},
shop: {
owner_id: 'owner-1',
},
},
orders: [
{
@ -212,7 +183,7 @@ function buildPayload() {
}
describe('test/app/service/systems/express_platform.pdd.ext_data.test.js', () => {
it('should stringify object ext_data for logistics_services', async () => {
it('should stringify object ext_data for logistics_services and notify_extend_info', async () => {
const { service, calls } = createPddHarness();
const payload = buildPayload();
@ -226,33 +197,11 @@ describe('test/app/service/systems/express_platform.pdd.ext_data.test.js', () =>
const orderItem = waybillRequest.trade_order_info_dtos[0];
assert.equal(typeof orderItem.logistics_services, 'string');
assert.equal(typeof orderItem.notify_extend_info, 'string');
assert.equal(orderItem.logistics_services, JSON.stringify(payload.listByWarehousePlatformCode.ext_data));
assert.equal(orderItem.notify_extend_info, JSON.stringify(payload.listByWarehousePlatformCode.ext_data));
assert.equal(result.flag, true);
assert.equal(result.code, 0);
});
it('auto_sync_back 开启且无登录用户上下文时,应以显式 warehouseId 触发订单同步回传', async () => {
const { service, calls } = createPddHarness();
await service.pdd(buildPayload());
assert.equal(calls.getContractConfigCalls.length, 1);
assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 5001 });
assert.equal(calls.syncOrderIdsCalls.length, 1);
assert.deepEqual(calls.syncOrderIdsCalls[0], {
orderIds: [ 2001 ],
warehouseId: 100000,
});
});
it('auto_sync_back 关闭时不应触发订单同步回传', async () => {
const { service, calls } = createPddHarness({
contractConfig: { policy_config: { auto_sync_back: 0 } },
});
await service.pdd(buildPayload());
assert.equal(calls.syncOrderIdsCalls.length, 0);
});
});

View File

@ -46,8 +46,6 @@ function createPolyapiHarness(options = {}) {
printQuantityLogCreateArgsList: [],
getWaybillAsyncOrderDeliveryModel: 0,
getWaybillAsyncOrderDeliveryModelArgs: [],
getContractConfigCalls: [],
syncOrderIdsCalls: [],
callSequence: [],
};
@ -197,29 +195,26 @@ function createPolyapiHarness(options = {}) {
code: '10000',
results: [
{
orderno: '186a0_101_9101',
orderno: '100000_101_9101',
waybill_code: 'REAL-WB-101',
logisticno: 'PRE-WB-101',
printinfo: 'print-101',
signature: 'sign-101',
encryptprintinfo: 'enc-101',
issuccess: '1',
},
{
orderno: '186a0_102_9102',
orderno: '100000_102_9102',
logisticno: 'WB-102',
printinfo: 'print-102',
signature: 'sign-102',
encryptprintinfo: 'enc-102',
issuccess: '1',
},
{
orderno: '186a0_103_9103',
orderno: '100000_103_9103',
logisticno: 'WB-103',
printinfo: 'print-103',
signature: 'sign-103',
encryptprintinfo: 'enc-103',
issuccess: '1',
},
],
};
@ -240,25 +235,6 @@ function createPolyapiHarness(options = {}) {
return payload;
},
},
storeWarehouse: {
async getContractConfig(warehouseId, storeId) {
calls.getContractConfigCalls.push({ warehouseId, storeId });
if (options.contractConfig !== undefined) {
return options.contractConfig;
}
return { policy_config: { auto_sync_back: 1 } };
},
},
},
systemMethods: {
order: {
pendingOrder: {
async syncOrderIds(request) {
calls.syncOrderIdsCalls.push(request);
return { flag: 'success' };
},
},
},
},
},
};
@ -361,7 +337,7 @@ describe('test/app/service/systems/express_platform.polyapi.test.js', () => {
assert.equal(relationRows[0].print_quantity, 6);
assert.equal(relationRows[0].print_quantity_locked, 3);
assert.equal(calls.getWaybillAsyncOrderDeliveryModel, 3);
assert.deepEqual(calls.getWaybillAsyncOrderDeliveryModelArgs, [ 100000, 100000, 100000 ]);
assert.deepEqual(calls.getWaybillAsyncOrderDeliveryModelArgs, [ '100000', '100000', '100000' ]);
assert.equal(calls.operationLogArgsList[0].businessId, '101');
assert.equal(calls.requestArgs.bizcontent.orders[0].logisticno, 'REAL-WB-101');
assert.equal(calls.requestArgs.bizcontent.orders[1].logisticno, 'REAL-WB-102');
@ -459,28 +435,4 @@ describe('test/app/service/systems/express_platform.polyapi.test.js', () => {
assert.equal(result.code, 0);
assert.equal(result.message, '菠萝派平台数据处理成功');
});
it('auto_sync_back 开启且无登录用户上下文时,应以显式 warehouseId 触发订单同步回传', async () => {
const { calls, service } = createPolyapiHarness();
await service.polyapi(buildPolyapiPayload());
assert.equal(calls.getContractConfigCalls.length, 1);
assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 2001 });
assert.equal(calls.syncOrderIdsCalls.length, 1);
assert.deepEqual(calls.syncOrderIdsCalls[0], {
orderIds: [ 101, 102 ],
warehouseId: 100000,
});
});
it('auto_sync_back 关闭时不应触发订单同步回传', async () => {
const { calls, service } = createPolyapiHarness({
contractConfig: { policy_config: { auto_sync_back: 0 } },
});
await service.polyapi(buildPolyapiPayload());
assert.equal(calls.syncOrderIdsCalls.length, 0);
});
});

View File

@ -898,8 +898,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list));
assert.ok(customContent);
// 头部行:波次号 + 快递渠道名 + 商品总数【n】(无商品明细时回退 items_total/items_count)
assert.equal(customContent.data.list[0].text, 'W023 中通 商品总数【2】\r');
assert.equal(customContent.data.list[0].text, 'W023 中通\r');
});
it('should render detail lines from non-json string items', () => {