Compare commits
33 Commits
190d3cf9e5
...
731bc8e9fb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
731bc8e9fb | ||
|
|
879bfaccbe | ||
|
|
d4daa6d671 | ||
|
|
d8ffc01429 | ||
|
|
0785e7df38 | ||
|
|
fab2d9c0d1 | ||
|
|
78b46a740b | ||
|
|
1402aa3841 | ||
|
|
3401645419 | ||
|
|
ae107e5cbe | ||
|
|
e4472e2c74 | ||
|
|
9d3c6b31fd | ||
|
|
05bef9210a | ||
|
|
29b39a7add | ||
|
|
b10f8f7583 | ||
|
|
183e542d74 | ||
|
|
4223b6882a | ||
|
|
0ced089599 | ||
|
|
ee7f08b192 | ||
|
|
2e42d47302 | ||
|
|
55a6a484dc | ||
|
|
8112430c37 | ||
|
|
a123009159 | ||
|
|
d07e48c4af | ||
|
|
6094f4720d | ||
|
|
b6a9bc8f33 | ||
|
|
0fa098c188 | ||
|
|
49fb70fcbf | ||
|
|
7ba10a1e4a | ||
|
|
9743416187 | ||
|
|
6ac3441109 | ||
|
|
5cd1479a92 | ||
|
|
0717640eff |
@ -1145,6 +1145,46 @@ function resolveSubjectConfig(input) {
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 发件人相关字段集合,用于签约策略 → 仓库主体的按字段兜底。
|
||||
*/
|
||||
const SENDER_FALLBACK_FIELDS = Object.freeze([
|
||||
'sender_name',
|
||||
'sender_tel',
|
||||
'province_name',
|
||||
'city_name',
|
||||
'district_name',
|
||||
'town_name',
|
||||
'address',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 解析发件人兜底配置:签约策略 policy_config 非空值优先,空值回退仓库主体 subject_config。
|
||||
*
|
||||
* 注意:getContractConfig 会把策略默认值合并进 policy_config(发件人字段默认为空字符串),
|
||||
* 因此不能用对象浅合并(空串会覆盖 subject_config 的有效值),必须按字段回退。
|
||||
*
|
||||
* @param {Object} policyConfig 签约策略配置。
|
||||
* @param {Object} subjectConfig 仓库主体配置。
|
||||
* @return {Object} 兜底后的策略配置对象。
|
||||
*/
|
||||
function resolveSenderFallbackConfig(policyConfig, subjectConfig) {
|
||||
const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {};
|
||||
const safeSubjectConfig = isPlainObject(subjectConfig) ? subjectConfig : {};
|
||||
const merged = { ...safePolicyConfig };
|
||||
|
||||
for (const key of SENDER_FALLBACK_FIELDS) {
|
||||
if (!toTrimmedString(merged[key])) {
|
||||
const fallbackValue = toTrimmedString(safeSubjectConfig[key]);
|
||||
if (fallbackValue) {
|
||||
merged[key] = fallbackValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建基础数据中间态。
|
||||
* @param {Object} input 输入对象。
|
||||
@ -2411,6 +2451,11 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
const options = isPlainObject(input.options) ? input.options : {};
|
||||
const extraCustomLines = Array.isArray(options.extraCustomLines) ? options.extraCustomLines : [];
|
||||
const policyConfig = resolvePolicyConfig(input);
|
||||
const subjectConfig = resolveSubjectConfig(input);
|
||||
// 发件人兜底:签约策略 policy_config 非空值优先,空值回退仓库主体 subject_config。
|
||||
// 与 buildBaseData 的三级兜底语义保持一致,避免签约策略未配发件人时
|
||||
// 平台面单(快手/拼多多/抖音等)senderInfo/sender 输出为空。
|
||||
const policyConfigWithSenderFallback = resolveSenderFallbackConfig(policyConfig, subjectConfig);
|
||||
const orderExpressForCompose = isPlainObject(input.order_express)
|
||||
? { ...input.order_express }
|
||||
: {};
|
||||
@ -2500,7 +2545,7 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
policyConfigWithSenderFallback,
|
||||
cainiaoCustomControlTemplateURL,
|
||||
warnings,
|
||||
extraCustomLines
|
||||
@ -2512,7 +2557,7 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
warnings,
|
||||
policyConfig,
|
||||
policyConfigWithSenderFallback,
|
||||
customDataTemplateURL,
|
||||
extraCustomLines
|
||||
);
|
||||
@ -2522,7 +2567,7 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
policyConfigWithSenderFallback,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
@ -2531,7 +2576,7 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
policyConfigWithSenderFallback,
|
||||
extraCustomLines,
|
||||
options.customAreaBaseUrl
|
||||
);
|
||||
@ -2541,7 +2586,7 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
policyConfigWithSenderFallback,
|
||||
templateSample,
|
||||
warnings,
|
||||
extraCustomLines
|
||||
@ -2552,7 +2597,7 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
policyConfigWithSenderFallback,
|
||||
warnings,
|
||||
extraCustomLines
|
||||
);
|
||||
@ -2562,7 +2607,7 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
policyConfigWithSenderFallback,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
|
||||
141
app/model/order_b2b.js
Normal file
141
app/model/order_b2b.js
Normal file
@ -0,0 +1,141 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* B2B 订单作业明细表 Model。
|
||||
*
|
||||
* 对应数据库表 `wms_order_b2b`,与发货单(订单)分表 wms_order_delivery_% 一对一
|
||||
* (order_id 关联分表 id),记录 B2B 订单的提货作业信息:
|
||||
* 总箱数、提货车牌、备货备注、备货用时、是否提货等。
|
||||
*
|
||||
* 不分表(不按仓库分表),通过 warehouse_id/store_id 维度隔离,
|
||||
* 落表方式类似 wms_order_express(运单号表)。
|
||||
* @param {import('egg').Application} app - Egg 应用实例
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize;
|
||||
|
||||
const OrderB2b = app.model.define('wms_order_b2b', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '订单ID,关联 wms_order_delivery 分表 id',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '货主ID',
|
||||
},
|
||||
delivery_order_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '发货单号快照',
|
||||
},
|
||||
total_box_count: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '总箱数',
|
||||
},
|
||||
pickup_plate_number: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '提货车牌',
|
||||
},
|
||||
prep_remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备货备注',
|
||||
},
|
||||
prep_duration_seconds: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '备货用时(秒)',
|
||||
},
|
||||
is_picked_up: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否提货:Y=已提货 N=未提货',
|
||||
},
|
||||
is_print: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否打印:Y=已打印 N=未打印',
|
||||
},
|
||||
picked_up_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '提货时间',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_order_b2b',
|
||||
comment: 'B2B订单作业明细表',
|
||||
timestamps: false,
|
||||
indexes: [
|
||||
{
|
||||
name: 'uk_order_id',
|
||||
unique: true,
|
||||
fields: [ 'order_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_store_id',
|
||||
fields: [ 'store_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_delivery_order_code',
|
||||
fields: [ 'delivery_order_code' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_pickup_plate_number',
|
||||
fields: [ 'pickup_plate_number' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_is_picked_up',
|
||||
fields: [ 'is_picked_up' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_is_print',
|
||||
fields: [ 'is_print' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_deleted_at',
|
||||
fields: [ 'deleted_at' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return OrderB2b;
|
||||
};
|
||||
@ -282,6 +282,12 @@ module.exports = app => {
|
||||
defaultValue: 'N',
|
||||
comment: '是否紧急',
|
||||
},
|
||||
is_b2b: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否B2B:Y是 N否',
|
||||
},
|
||||
invoice_flag: {
|
||||
type: ENUM(...StatusEnum.INVOICE),
|
||||
allowNull: true,
|
||||
|
||||
@ -55,6 +55,12 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '货主ID,原单退回时回填,用于查货主备注 wms_store_warehouse.store_remask',
|
||||
},
|
||||
return_received_task_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '收件任务ID,关联 wms_return_received_task.id;默认 1=系统预设「历史收件」',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
@ -80,6 +86,7 @@ module.exports = app => {
|
||||
{ name: 'idx_scanner_id', fields: [ 'scanner_id' ] },
|
||||
{ name: 'idx_order_express_id', fields: [ 'order_express_id' ] },
|
||||
{ name: 'idx_store_id', fields: [ 'store_id' ] },
|
||||
{ name: 'idx_return_received_task_id', fields: [ 'return_received_task_id' ] },
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
70
app/model/return_received_task.js
Normal file
70
app/model/return_received_task.js
Normal file
@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 收件任务 Model(退回收件任务分组)。
|
||||
* 记录批次号、仓库ID、创建人、创建时间;主键 id 自增从 10000 开始(由迁移设置 AUTO_INCREMENT)。
|
||||
* @param {Object} app Egg.js Application 实例。
|
||||
* @return {Object} Sequelize Model 定义。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const ReturnReceivedTask = app.model.define('return_received_task', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID(自增从10000开始)',
|
||||
},
|
||||
batch_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '批次号',
|
||||
},
|
||||
title: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '标题(任务名称,如系统预设「历史收件」)',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
creator_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '创建人账户ID',
|
||||
},
|
||||
creator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '创建人名称快照',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_return_received_task',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
// 表无 deleted_at 列,必须显式关闭全局 define 的 paranoid 默认值,
|
||||
// 否则 findAll/findOne 会拼出 deleted_at 字段导致 Unknown column 报错
|
||||
paranoid: false,
|
||||
comment: '收件任务表(批次号、仓库ID、创建人、创建时间)',
|
||||
});
|
||||
|
||||
return ReturnReceivedTask;
|
||||
};
|
||||
@ -91,8 +91,8 @@ module.exports = app => {
|
||||
{ name: 'idx_check_id', fields: [ 'check_id' ] },
|
||||
{ name: 'idx_warehouse_stock', fields: [ 'warehouse_id', 'stock_id' ] },
|
||||
{ name: 'idx_stock_id', fields: [ 'stock_id' ] },
|
||||
{ name: 'uk_check_stock', unique: true, fields: [ 'check_id', 'stock_id' ] },
|
||||
{ name: 'uk_check_location', unique: true, fields: [ 'check_id', 'location_code' ] },
|
||||
{ name: 'uk_check_stock_location', unique: true, fields: [ 'check_id', 'stock_id', 'location_id' ] },
|
||||
{ name: 'idx_check_location', fields: [ 'check_id', 'location_code' ] },
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@ -10,7 +10,7 @@
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize;
|
||||
const { BIGINT, STRING, INTEGER, DATE, BOOLEAN } = app.Sequelize;
|
||||
|
||||
const StockCheckRecord = app.model.define('wms_stock_check_record', {
|
||||
id: {
|
||||
@ -49,6 +49,12 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '未知商品名称快照(缺省为条码);已知商品为空',
|
||||
},
|
||||
is_empty: {
|
||||
type: BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
comment: '是否空库位标记(true=确认库位为空,stock_id/barcode/item_name 均为空、quantity=0)',
|
||||
},
|
||||
location_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
|
||||
@ -107,6 +107,9 @@ module.exports = {
|
||||
empty_count: result ? result.empty_count : 0,
|
||||
closed_count: result ? result.closed_count : 0,
|
||||
pending_confirm_count: result ? result.pending_confirm_count : 0,
|
||||
unbound_count: result ? result.unbound_count : 0,
|
||||
misread_count: result ? result.misread_count : 0,
|
||||
probe_failed_count: result ? result.probe_failed_count : 0,
|
||||
warehouse_ids: result ? result.warehouse_ids : [],
|
||||
closed_waves: result ? result.closed_waves : [],
|
||||
};
|
||||
@ -115,7 +118,10 @@ module.exports = {
|
||||
|
||||
ctx.logger.info(
|
||||
`[sync-finished-wave-batch] 本轮完成 closed=${result ? result.closed_count : 0} candidate=${result ? result.candidate_count : 0}`
|
||||
+ ` pendingConfirm=${result ? result.pending_confirm_count : 0} warehouses=${result ? result.warehouse_ids.length : 0}`
|
||||
+ ` pendingConfirm=${result ? result.pending_confirm_count : 0}`
|
||||
+ ` unbound=${result ? result.unbound_count : 0} misread=${result ? result.misread_count : 0}`
|
||||
+ ` probeFailed=${result ? result.probe_failed_count : 0}`
|
||||
+ ` warehouses=${result ? result.warehouse_ids.length : 0}`
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
@ -4,7 +4,7 @@ const Service = require('egg').Service;
|
||||
|
||||
const apiLogSink = require('../lib/api_log_sink');
|
||||
|
||||
const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other', 'workerstation', 'workstation' ]);
|
||||
const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other', 'tv', 'workerstation', 'workstation' ]);
|
||||
// project: all=全部, warehouse=仓库, store=货主, tms=物流
|
||||
const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 'scm', 'other' ]);
|
||||
|
||||
|
||||
@ -1052,7 +1052,7 @@ function formatTbWaybillSearchResponse(responseData, expressNameMap = {}) {
|
||||
* 因此将通配符改为显式清单:本清单之外的新方法默认记录系统日志,
|
||||
* 新增方法如需免日志须在此登记。
|
||||
*/
|
||||
const INDEX_NO_NEED_LOG_METHODS = 'fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getCOSUploadConfig,getImages,uploadSuccessNotify,recognizeLicensePlate,ReferenceFile,getMessageDetail,test,getI18nMessage,putI18nCollect,extractModule,tryAutoTranslateNewKeys,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,ensureShopPrintPlatformExists,buildShopPrintPlatformInclude,getShopList,requestPddWaybillSearch,requestPddStdTemplates,requestTbWaybillSearch,requestTbCainiaoStdTemplates,requestPolyStdTemplates,getShopExpressList,getCainiaoStfTemplates,normalizeTemplatePlatformCode,normalizeTemplateExpressCode,getExpressPlatformFieldName,getTemplateAllowedExpressCodeSet,filterPrintPlatformTemplateResponseData,getPrintPlatformTemplateCacheKey,requestPrintPlatformTemplateList,resolvePddTemplateWpCodeCandidates,requestPddTemplateSourceList,getPrintPlatformTemplateList,isPlatformOauthReservationDuplicateError,getPlatformOauthReservationCodePrefix,hasPlatformOauthReservationCodePrefix,normalizePlatformOauthReservationCode,generatePlatformOauthReservationCode,createPlatformOauthReservation,getPlatformOauthLink,listenPlatformOauthBind,loginToIm,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,parseWechatBadgeCode,queryUserByWechatBadge';
|
||||
const INDEX_NO_NEED_LOG_METHODS = 'fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getCOSUploadConfig,getImages,uploadSuccessNotify,recognizeLicensePlate,ReferenceFile,getMessageDetail,test,getI18nMessage,putI18nCollect,extractModule,tryAutoTranslateNewKeys,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,ensureShopPrintPlatformExists,buildShopPrintPlatformInclude,getShopList,requestPddWaybillSearch,requestPddStdTemplates,requestTbWaybillSearch,requestTbCainiaoStdTemplates,requestPolyStdTemplates,getShopExpressList,getCainiaoStfTemplates,normalizeTemplatePlatformCode,normalizeTemplateExpressCode,getExpressPlatformFieldName,getTemplateAllowedExpressCodeSet,filterPrintPlatformTemplateResponseData,getPrintPlatformTemplateCacheKey,requestPrintPlatformTemplateList,resolvePddTemplateWpCodeCandidates,requestPddTemplateSourceList,getPrintPlatformTemplateList,isPlatformOauthReservationDuplicateError,getPlatformOauthReservationCodePrefix,hasPlatformOauthReservationCodePrefix,normalizePlatformOauthReservationCode,generatePlatformOauthReservationCode,createPlatformOauthReservation,getPlatformOauthLink,listenPlatformOauthBind,loginToIm,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,parseWechatBadgeCode,queryUserByWechatBadge';
|
||||
|
||||
class indexService extends MainService {
|
||||
/**
|
||||
@ -1063,9 +1063,9 @@ class indexService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedLog = INDEX_NO_NEED_LOG_METHODS;
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
async fastWhereTree(data) {
|
||||
@ -1084,6 +1084,55 @@ class indexService extends MainService {
|
||||
const result = await service.systems.store.loadWarehouses();
|
||||
return this.success('ok', { warehouses: result, code: 200 });
|
||||
}
|
||||
/**
|
||||
* 获取仓库面板数据。
|
||||
*
|
||||
* 最后更新时间一般由外部驱动;缓存有最后更新时间时按增量返回:
|
||||
* is_change=false 时返回空 data(节约流量),is_change=true 时输出缓存数据;
|
||||
* 缓存中没有最后更新时间时才查库拉取数据并兜底设置最后更新时间。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @param {number|string} [data.last_change_at] 最后一次更改的时间戳(Unix 秒),force=false 时必填
|
||||
* @param {boolean|number|string} [data.force] 首次拉取兼容入参(true/1/'true'),当前仅影响 last_change_at 是否可缺省
|
||||
* @return {Promise<Object>} 返回 { is_change, last_change_at, data },其中 is_change=false 时 data 为空对象
|
||||
*/
|
||||
async getWarehousePanelData(data = {}) {
|
||||
const { ctx, service } = this;
|
||||
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null;
|
||||
if (!warehouseId) {
|
||||
return this.fail('缺少仓库上下文');
|
||||
}
|
||||
|
||||
const force = data.force === true || data.force === 'true' || data.force === 1;
|
||||
|
||||
const rawLast = data && data.last_change_at;
|
||||
let lastChangeAt = 0;
|
||||
if (force) {
|
||||
// 首次拉取可不传时间戳,缺省视为 0;若传入则仍做格式校验
|
||||
if (rawLast !== undefined && rawLast !== null && String(rawLast).trim() !== '') {
|
||||
lastChangeAt = Number(rawLast);
|
||||
if (!Number.isFinite(lastChangeAt) || lastChangeAt < 0) {
|
||||
return this.fail('参数错误:last_change_at 必须为数字时间戳');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (rawLast === undefined || rawLast === null || String(rawLast).trim() === '') {
|
||||
return this.fail('参数错误:last_change_at 不能为空');
|
||||
}
|
||||
lastChangeAt = Number(rawLast);
|
||||
if (!Number.isFinite(lastChangeAt) || lastChangeAt < 0) {
|
||||
return this.fail('参数错误:last_change_at 必须为数字时间戳');
|
||||
}
|
||||
}
|
||||
|
||||
const result = await service.systems.warehousePanel.getPanelData(warehouseId, { force, lastChangeAt });
|
||||
return this.success('ok', {
|
||||
is_change: result.is_change,
|
||||
last_change_at: result.last_change_at,
|
||||
data: result.data,
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
async loadExpressInterfaces(data = {}) {
|
||||
const { service } = this;
|
||||
const { systemExpressCode } = data;
|
||||
|
||||
@ -46,7 +46,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = [
|
||||
'wave_scan_result',
|
||||
'post_status', 'storage_status', 'pick_status', 'pack_status',
|
||||
'inspection_status', 'print_status', 'confirm_print_status', 'claim_status',
|
||||
'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status',
|
||||
'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status', 'recheck_time',
|
||||
'create_channel',
|
||||
'store_id',
|
||||
];
|
||||
|
||||
@ -13,12 +13,107 @@ class OrderIndexService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill';
|
||||
const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill';
|
||||
const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill';
|
||||
const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b';
|
||||
const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b';
|
||||
const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单转 B2B 订单。
|
||||
*
|
||||
* 仅限待处理表中未打印、未锁定、未拦截的订单;不符合条件跳过。
|
||||
* 事务内:订单表 is_b2b 置 Y + 写入 wms_order_b2b 作业明细,提交后写操作日志。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<number|string>|number|string} [data.ids] 订单ID集合(优先)。
|
||||
* @param {Array<number|string>|number|string} [data.order_ids] 订单ID集合别名。
|
||||
* @param {Array<number|string>|number|string} [data.orderIds] 订单ID集合别名。
|
||||
* @param {number|string} [data.id] 订单ID单值别名。
|
||||
* @param {number|string} [data.order_id] 订单ID单值别名。
|
||||
* @param {number|string} [data.orderId] 订单ID单值别名。
|
||||
* @return {Promise<Object>} 统一成功包装响应(data 含 converted/skipped/not_found 分流结果)。
|
||||
*/
|
||||
async convertToB2b(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const rawIds = requestData.ids !== undefined ? requestData.ids
|
||||
: requestData.order_ids !== undefined ? requestData.order_ids
|
||||
: requestData.orderIds !== undefined ? requestData.orderIds
|
||||
: requestData.id !== undefined ? requestData.id
|
||||
: requestData.order_id !== undefined ? requestData.order_id
|
||||
: requestData.orderId;
|
||||
const orderIds = [ ...new Set(
|
||||
(Array.isArray(rawIds) ? rawIds : [ rawIds ])
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isInteger(item) && item > 0)
|
||||
) ];
|
||||
if (orderIds.length === 0) {
|
||||
return this.fail('订单ID不能为空', {}, 400);
|
||||
}
|
||||
if (orderIds.length > 200) {
|
||||
return this.fail('单次最多转换 200 个订单', {}, 400);
|
||||
}
|
||||
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const operator = this.getOrderLogOperator();
|
||||
|
||||
const result = await this.service.systems.orderB2b.convertOrdersToB2b({
|
||||
warehouseId,
|
||||
orderIds,
|
||||
operator,
|
||||
});
|
||||
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消 B2B 出库:订单流转回正常订单。
|
||||
*
|
||||
* 仅限待处理表中 is_b2b=Y 且未打印、未锁定、未拦截、B2B 面单未打印的订单;
|
||||
* 不符合条件跳过。事务内:订单表 is_b2b 置回 N + B2B 作业明细软删除,
|
||||
* 提交后写操作日志。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<number|string>|number|string} [data.ids] 订单ID集合(优先)。
|
||||
* @param {Array<number|string>|number|string} [data.order_ids] 订单ID集合别名。
|
||||
* @param {Array<number|string>|number|string} [data.orderIds] 订单ID集合别名。
|
||||
* @param {number|string} [data.id] 订单ID单值别名。
|
||||
* @param {number|string} [data.order_id] 订单ID单值别名。
|
||||
* @param {number|string} [data.orderId] 订单ID单值别名。
|
||||
* @return {Promise<Object>} 统一成功包装响应(data 含 canceled/skipped/not_found 分流结果)。
|
||||
*/
|
||||
async cancelB2b(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const rawIds = requestData.ids !== undefined ? requestData.ids
|
||||
: requestData.order_ids !== undefined ? requestData.order_ids
|
||||
: requestData.orderIds !== undefined ? requestData.orderIds
|
||||
: requestData.id !== undefined ? requestData.id
|
||||
: requestData.order_id !== undefined ? requestData.order_id
|
||||
: requestData.orderId;
|
||||
const orderIds = [ ...new Set(
|
||||
(Array.isArray(rawIds) ? rawIds : [ rawIds ])
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isInteger(item) && item > 0)
|
||||
) ];
|
||||
if (orderIds.length === 0) {
|
||||
return this.fail('订单ID不能为空', {}, 400);
|
||||
}
|
||||
if (orderIds.length > 200) {
|
||||
return this.fail('单次最多取消 200 个订单', {}, 400);
|
||||
}
|
||||
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const operator = this.getOrderLogOperator();
|
||||
|
||||
const result = await this.service.systems.orderB2b.cancelOrdersB2b({
|
||||
warehouseId,
|
||||
orderIds,
|
||||
operator,
|
||||
});
|
||||
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交订单导出任务。
|
||||
*
|
||||
|
||||
@ -986,6 +986,8 @@ class WaveService extends OrderBaseService {
|
||||
intercept_status: 'none',
|
||||
lock_status: 'none',
|
||||
wave_id: 0,
|
||||
// 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行)
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
};
|
||||
|
||||
const itemPartType = String(structure.item_part_type || '').trim();
|
||||
@ -2913,6 +2915,8 @@ class WaveService extends OrderBaseService {
|
||||
intercept_status: 'none',
|
||||
lock_status: 'none',
|
||||
wave_id: 0,
|
||||
// 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行)
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
};
|
||||
|
||||
if (storeId > 0) {
|
||||
@ -3167,6 +3171,8 @@ class WaveService extends OrderBaseService {
|
||||
intercept_status: 'none',
|
||||
lock_status: 'none',
|
||||
wave_id: 0,
|
||||
// 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行)
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
};
|
||||
|
||||
if (storeId > 0) {
|
||||
@ -3431,6 +3437,8 @@ class WaveService extends OrderBaseService {
|
||||
intercept_status: 'none',
|
||||
lock_status: 'none',
|
||||
wave_id: 0,
|
||||
// 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行)
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
};
|
||||
|
||||
if (storeId > 0) {
|
||||
@ -3734,6 +3742,7 @@ class WaveService extends OrderBaseService {
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
AND (o.is_b2b IS NULL OR o.is_b2b = 'N')
|
||||
WHERE m.warehouse_id = :warehouseId
|
||||
AND m.strategy_id = :strategyId
|
||||
ORDER BY o.id ASC
|
||||
@ -3975,6 +3984,7 @@ class WaveService extends OrderBaseService {
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
AND (o.is_b2b IS NULL OR o.is_b2b = 'N')
|
||||
INNER JOIN (
|
||||
SELECT
|
||||
src.items_hash AS structure_key${groupKeyExtra},
|
||||
@ -3990,6 +4000,7 @@ class WaveService extends OrderBaseService {
|
||||
AND src.outbound_status != 'padding'
|
||||
AND src.intercept_status = 'none'
|
||||
AND src.lock_status = 'none'
|
||||
AND (src.is_b2b IS NULL OR src.is_b2b = 'N')
|
||||
GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''}
|
||||
) same_structure
|
||||
ON same_structure.structure_key = o.items_hash${joinKeyExtra}
|
||||
@ -4077,6 +4088,7 @@ class WaveService extends OrderBaseService {
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
AND (o.is_b2b IS NULL OR o.is_b2b = 'N')
|
||||
INNER JOIN (
|
||||
SELECT
|
||||
src.items_hash AS structure_key${groupKeyExtra},
|
||||
@ -4092,6 +4104,7 @@ class WaveService extends OrderBaseService {
|
||||
AND src.outbound_status != 'padding'
|
||||
AND src.intercept_status = 'none'
|
||||
AND src.lock_status = 'none'
|
||||
AND (src.is_b2b IS NULL OR src.is_b2b = 'N')
|
||||
GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''}
|
||||
) same_structure
|
||||
ON same_structure.structure_key = o.items_hash${joinKeyExtra}
|
||||
@ -6943,6 +6956,8 @@ class WaveService extends OrderBaseService {
|
||||
intercept_status: 'none',
|
||||
lock_status: 'none',
|
||||
print_status: { [Op.ne]: 'fin' },
|
||||
// 波次策略扫描不扫描 B2B 订单(NULL 视为非 B2B,兼容存量行)
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
};
|
||||
|
||||
if (!forceRescan) {
|
||||
@ -7502,6 +7517,7 @@ class WaveService extends OrderBaseService {
|
||||
intercept_status: 'none',
|
||||
lock_status: 'none',
|
||||
print_status: { [Op.ne]: 'fin' },
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
[Op.or]: [
|
||||
{ wave_strategy_version: { [Op.ne]: currentVersion } },
|
||||
{ wave_strategy_version: { [Op.is]: null } },
|
||||
@ -8188,6 +8204,8 @@ class WaveService extends OrderBaseService {
|
||||
step: { [Op.in]: [ 1, 2, 3 ] },
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: { [Op.ne]: 'padding' },
|
||||
// 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行)
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
[Op.or]: candidateWhereList,
|
||||
},
|
||||
raw: true,
|
||||
@ -8276,7 +8294,7 @@ class WaveService extends OrderBaseService {
|
||||
|
||||
try {
|
||||
const orderRows = await orderModel.findAll({
|
||||
attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name', 'intercept_status', 'lock_status' ],
|
||||
attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name', 'intercept_status', 'lock_status', 'is_b2b' ],
|
||||
where: {
|
||||
id: { [Op.in]: normalizedIds },
|
||||
},
|
||||
@ -8305,6 +8323,12 @@ class WaveService extends OrderBaseService {
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ]
|
||||
.sort((a, b) => a - b);
|
||||
// B2B 订单不参与波次抓取(NULL 视为非 B2B,兼容存量行)
|
||||
const excludedB2bOrderIds = [ ...new Set(normalizedOrderRows
|
||||
.filter(row => String(row && row.is_b2b || '').trim() === 'Y')
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ]
|
||||
.sort((a, b) => a - b);
|
||||
|
||||
const fetchableRows = normalizedOrderRows.filter(row => {
|
||||
const orderId = Number(row && row.id || 0);
|
||||
@ -8328,6 +8352,11 @@ class WaveService extends OrderBaseService {
|
||||
return false;
|
||||
}
|
||||
|
||||
// B2B 订单不允许抓取波次
|
||||
if (String(row && row.is_b2b || '').trim() === 'Y') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
@ -8349,6 +8378,7 @@ class WaveService extends OrderBaseService {
|
||||
excluded_existing_wave_order_ids: excludedExistingWaveOrderIds,
|
||||
excluded_intercepted_order_ids: excludedInterceptedOrderIds,
|
||||
excluded_locked_order_ids: excludedLockedOrderIds,
|
||||
excluded_b2b_order_ids: excludedB2bOrderIds,
|
||||
skipped_order_ids: skippedOrderIds,
|
||||
not_found_order_ids: notFoundOrderIds,
|
||||
});
|
||||
@ -8467,6 +8497,7 @@ class WaveService extends OrderBaseService {
|
||||
excluded_existing_wave_order_ids: excludedExistingWaveOrderIds,
|
||||
excluded_intercepted_order_ids: excludedInterceptedOrderIds,
|
||||
excluded_locked_order_ids: excludedLockedOrderIds,
|
||||
excluded_b2b_order_ids: excludedB2bOrderIds,
|
||||
skipped_order_ids: skippedOrderIds,
|
||||
not_found_order_ids: notFoundOrderIds,
|
||||
});
|
||||
@ -10259,7 +10290,8 @@ class WaveService extends OrderBaseService {
|
||||
/**
|
||||
* 执行批次分配快递号后台任务。
|
||||
*
|
||||
* 任务仅负责提交分配请求到快递分配流水线,实际分配过程由快递服务异步处理。
|
||||
* 任务会等待快递分配流水线中所有批次真正完成分配(awaitTasks=true)后
|
||||
* 才写入 success 状态,避免进度接口在分配尚未完成时提前返回完成。
|
||||
*
|
||||
* @param {Object} params 任务参数。
|
||||
* @param {string} params.taskId 任务ID。
|
||||
@ -10494,7 +10526,13 @@ class WaveService extends OrderBaseService {
|
||||
totalOrderCount: normalizedOrders.length,
|
||||
sampleOrderIds: normalizedOrders.slice(0, 20).map(item => Number(item && item.order_id || 0)).filter(Boolean),
|
||||
});
|
||||
const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(normalizedOrders);
|
||||
// awaitTasks=true:等待所有批次真正分配完成后再返回,避免任务被提前标记 success。
|
||||
// warehouseId 显式传入:后台任务运行在 setImmediate 异步上下文中,ctx.user 可能已失效,
|
||||
// 防止 getCurrentWarehouseId() 返回 0 导致跨仓/无效仓查询。
|
||||
const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(normalizedOrders, {
|
||||
awaitTasks: true,
|
||||
warehouseId,
|
||||
});
|
||||
const durationMs = Date.now() - startTime;
|
||||
|
||||
this.ctx.logger.info('[wave.batchAllocateExpress] 快递号分配流水线执行完成', {
|
||||
@ -11851,6 +11889,7 @@ class WaveService extends OrderBaseService {
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
AND (o.is_b2b IS NULL OR o.is_b2b = 'N')
|
||||
AND (:createdBefore IS NULL OR o.create_at < :createdBefore)
|
||||
INNER JOIN (
|
||||
SELECT
|
||||
@ -11867,6 +11906,7 @@ class WaveService extends OrderBaseService {
|
||||
AND src.outbound_status != 'padding'
|
||||
AND src.intercept_status = 'none'
|
||||
AND src.lock_status = 'none'
|
||||
AND (src.is_b2b IS NULL OR src.is_b2b = 'N')
|
||||
GROUP BY ${structureExpr('src')}${groupKeyExtra}
|
||||
) same_structure
|
||||
ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra}
|
||||
@ -12145,6 +12185,8 @@ class WaveService extends OrderBaseService {
|
||||
step: { [Op.ne]: 0 },
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: { [Op.ne]: 'padding' },
|
||||
// 尾部兜底:候选筛选后再次排除 B2B 订单(NULL 视为非 B2B,兼容存量行)
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
@ -12395,6 +12437,7 @@ class WaveService extends OrderBaseService {
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
AND (o.is_b2b IS NULL OR o.is_b2b = 'N')
|
||||
AND ${structureExpr('o')} IN (:structureKeys)${expressCondition}
|
||||
ORDER BY o.id ASC
|
||||
`, {
|
||||
|
||||
@ -51,11 +51,17 @@ class ReturnReceivedMethodService extends MainService {
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} data.waybill_code 退回收件运单号。
|
||||
* @param {string} [data.remark] 备注。
|
||||
* @param {number|string} [data.return_received_task_id] 收件任务ID,不传默认 1(系统预设「历史收件」);
|
||||
* 兼容旧字段 receiving_task_id(新字段优先)。
|
||||
* @return {Promise<Object>} 统一 success 包装。
|
||||
*/
|
||||
async create(data = {}) {
|
||||
const { waybill_code, remark } = data;
|
||||
return this._call(() => this.service.systems.returnReceived.create({ waybill_code, remark }), '扫码登记失败');
|
||||
const { waybill_code, remark, return_received_task_id, receiving_task_id } = data;
|
||||
// 新字段 return_received_task_id 优先,兼容旧字段 receiving_task_id
|
||||
const taskId = return_received_task_id !== undefined && return_received_task_id !== null && return_received_task_id !== ''
|
||||
? return_received_task_id
|
||||
: receiving_task_id;
|
||||
return this._call(() => this.service.systems.returnReceived.create({ waybill_code, remark, return_received_task_id: taskId }), '扫码登记失败');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
166
app/service/systemMethods/returnReceivedTask.js
Normal file
166
app/service/systemMethods/returnReceivedTask.js
Normal file
@ -0,0 +1,166 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 系统方法层:returnReceivedTask(收件任务模块接口包装层,退回收件任务分组)。
|
||||
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,
|
||||
* 将具体业务逻辑下沉到 systems.returnReceivedTask 中。
|
||||
*
|
||||
* 权限口径:create/delete 需要登录、免 API 权限校验(无需 wms_permission 记录);
|
||||
* 仓库与创建人均由服务端从登录上下文自动注入,禁止前端传入。
|
||||
*/
|
||||
class ReturnReceivedTaskMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
// 免登录方法列表:空(全部需要登录)
|
||||
const _noNeedLogin = '';
|
||||
// 免权限方法列表:create/delete/batchDelete/list 免 API 权限校验(仅需登录)
|
||||
const _noNeedRight = 'create,delete,batchDelete,list';
|
||||
// 免日志方法列表:list(查询类不记录操作日志)
|
||||
const _noNeedLog = 'list';
|
||||
// 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期)
|
||||
const _noNeedAuth = '';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一调用收件任务业务服务,并捕获业务错误码。
|
||||
*
|
||||
* @param {Function} fn 业务调用函数。
|
||||
* @param {string} fallbackMessage 兜底错误文案。
|
||||
* @return {Promise<Object>} 统一 success/fail 包装。
|
||||
*/
|
||||
async _call(fn, fallbackMessage) {
|
||||
try {
|
||||
const result = await fn();
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
const code = Number(error && error.code);
|
||||
if (Number.isInteger(code) && code >= 400 && code < 600) {
|
||||
return this.fail(error.message || fallbackMessage, {}, code);
|
||||
}
|
||||
this.ctx.logger.error(`[returnReceivedTask] ${fallbackMessage}: ${error && error.message ? error.message : error}`);
|
||||
return this.fail('服务器内部错误', {}, 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建收件任务(增)。
|
||||
* warehouse_id / creator_id / creator_name 由服务端从当前登录上下文自动注入,前端无需传递;
|
||||
* 批次号一律由服务端自动生成(RT+YYYYMMDD+5位序号,参考波次号取号机制),不接收外部输入。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.title] 标题(任务名称)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回新建的收件任务行。
|
||||
*/
|
||||
async create(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
|
||||
const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
|
||||
const { title } = data || {};
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.returnReceivedTask.create({
|
||||
warehouseId,
|
||||
title,
|
||||
creatorId,
|
||||
creatorName,
|
||||
}),
|
||||
'创建收件任务失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询收件任务列表(查)。
|
||||
* warehouse_id 由服务端从当前登录上下文自动注入(含系统级任务 warehouse_id=0),禁止前端传入。
|
||||
* 搜索关键词 where.quickWhere:在 title(标题)/batch_no(编号)/creator_name(创建人)三个字段中模糊匹配
|
||||
* (OR 关系);title/batch_no/creator_name 也支持 {operator,value} 标准结构(like/eq/in 等)。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Object} [data.where] 筛选条件(含 has_register:是否有登记,true/false)。
|
||||
* @param {Object} [data.pagination] 分页参数。
|
||||
* @param {Object} [data.sort] 排序参数(sortField: id/batch_no/created_at/updated_at,默认 id desc)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回 { list, pagination }。
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const { service } = this;
|
||||
const { pagination, sort } = data;
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 仓库隔离:由服务端从当前上下文自动注入(含系统级任务 warehouse_id=0),禁止前端传入
|
||||
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
|
||||
const enforcedWhere = { ...where };
|
||||
if (warehouseId > 0) {
|
||||
enforcedWhere.warehouse_id = { operator: 'in', value: [ 0, warehouseId ] };
|
||||
}
|
||||
|
||||
return this._call(
|
||||
() => service.systems.returnReceivedTask.list(enforcedWhere, pagination, sort, warehouseId),
|
||||
'查询列表失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除收件任务(删,硬删除)。
|
||||
* 逐条分流:不存在/系统预设(id=1)/非本仓库/已有收件登记的任务计入 skipped_ids 不报错;
|
||||
* 其余硬删除并清理缓存。warehouse_id 由服务端从当前登录上下文自动注入,前端无需传递。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<number>|number} data.ids 收件任务ID(数组或单值,单次上限 200)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回
|
||||
* { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。
|
||||
*/
|
||||
async batchDelete(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { ids } = data || {};
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.returnReceivedTask.batchDelete({ warehouseId, ids }),
|
||||
'批量删除收件任务失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除收件任务(删,硬删除)。
|
||||
* 兼容两种入参:
|
||||
* - ids(数组或单值):批量删除,逐条分流,不存在/系统预设/非本仓库/已有登记的任务
|
||||
* 计入 skipped_ids 不报错,返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids };
|
||||
* - id(单值):单值删除,不满足条件抛 404/409。
|
||||
* warehouse_id 由服务端从当前登录上下文自动注入,前端无需传递。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<number>|number} [data.ids] 收件任务ID(数组或单值,单次上限 200,优先于 id)。
|
||||
* @param {number|string} [data.id] 收件任务ID(单值删除)。
|
||||
* @return {Promise<Object>} 统一包装:单值删除返回 { id, deleted };
|
||||
* 批量删除返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { id, ids } = data || {};
|
||||
|
||||
// 批量删除:传 ids 时走批量分流语义
|
||||
if (ids !== undefined && ids !== null) {
|
||||
return this._call(
|
||||
() => this.service.systems.returnReceivedTask.batchDelete({ warehouseId, ids }),
|
||||
'批量删除收件任务失败'
|
||||
);
|
||||
}
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.returnReceivedTask.delete(id, warehouseId),
|
||||
'删除收件任务失败'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReturnReceivedTaskMethodService;
|
||||
@ -3,7 +3,7 @@
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 系统方法层:returnWaybill(运单退回登记模块接口包装层)。
|
||||
* 系统方法层:returnWaybill(未退登记模块接口包装层)。
|
||||
* 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑,
|
||||
* 将具体业务逻辑下沉到 systems.return_waybill 中。
|
||||
*/
|
||||
@ -22,7 +22,7 @@ class ReturnWaybillMethodService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一调用运单退回登记业务服务,并捕获业务错误码。
|
||||
* 统一调用未退登记业务服务,并捕获业务错误码。
|
||||
*
|
||||
* @param {Function} fn 业务调用函数。
|
||||
* @param {string} fallbackMessage 兜底错误文案。
|
||||
@ -43,7 +43,7 @@ class ReturnWaybillMethodService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单退回登记(增)。
|
||||
* 未退登记(增)。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} data.waybill_code 运单号。
|
||||
|
||||
@ -8,8 +8,8 @@ const STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
/** 单次导出任务允许的最大盘点任务数量 */
|
||||
const STOCK_CHECK_EXPORT_MAX_TASK_IDS = 50;
|
||||
|
||||
/** 全部 20 个 method 名(免权限/免鉴权清单共用) */
|
||||
const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,report,recordList,recordDelete,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate';
|
||||
/** 全部 24 个 method 名(免权限/免鉴权清单共用) */
|
||||
const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,workDataSpaceDetails,workDataDetail,report,markEmpty,recordList,recordDelete,recheckClearLocation,finish,submit,cancel,audit,batchDelete,export,exportDetail,exportTaskProgress,patternList,patternCreate';
|
||||
|
||||
/**
|
||||
* 系统方法层:stock.check(库存盘点模块接口包装层)。
|
||||
@ -24,7 +24,7 @@ class StockCheckMethodService extends MainService {
|
||||
// 免权限方法列表:全部 20 个方法免 API 权限校验(与 stock/transaction.js 口径一致)
|
||||
const _noNeedRight = ALL_METHOD_NAMES;
|
||||
// 免日志方法列表:查询类与导出类不记录操作日志(recordDelete/patternCreate 为写操作,保留操作日志)
|
||||
const _noNeedLog = 'list,detail,result,workData,recordList,export,exportTaskProgress,patternList';
|
||||
const _noNeedLog = 'list,detail,result,workData,workDataSpaceDetails,workDataDetail,recordList,export,exportDetail,exportTaskProgress,patternList';
|
||||
// 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致)
|
||||
const _noNeedAuth = ALL_METHOD_NAMES;
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
@ -32,22 +32,24 @@ class StockCheckMethodService extends MainService {
|
||||
|
||||
/**
|
||||
* 统一调用库存盘点业务服务,并捕获业务错误码。
|
||||
* 成功/失败均按统一 data 层封装:{ flag, code, message, data },
|
||||
* 与项目 toSuccess/toFailure 常规口径一致(业务数据整体放入 data)。
|
||||
*
|
||||
* @param {Function} fn 业务调用函数。
|
||||
* @param {string} fallbackMessage 兜底错误文案。
|
||||
* @return {Promise<Object>} 统一 success/fail 包装。
|
||||
* @return {Promise<Object>} 统一 { flag, code, message, data } 包装。
|
||||
*/
|
||||
async _call(fn, fallbackMessage) {
|
||||
try {
|
||||
const result = await fn();
|
||||
return this.success('ok', result);
|
||||
return { flag: 'success', code: 1, message: 'ok', data: result };
|
||||
} catch (error) {
|
||||
const code = Number(error && error.code);
|
||||
if (Number.isInteger(code) && code >= 400 && code < 600) {
|
||||
return this.fail(error.message || fallbackMessage, {}, code);
|
||||
return { flag: 'failure', code, message: error.message || fallbackMessage, data: null };
|
||||
}
|
||||
this.ctx.logger.error(`[stock.check] ${fallbackMessage}: ${error && error.message ? error.message : error}`);
|
||||
return this.fail('服务器内部错误', {}, 500);
|
||||
return { flag: 'failure', code: 500, message: '服务器内部错误', data: null };
|
||||
}
|
||||
}
|
||||
|
||||
@ -282,15 +284,16 @@ class StockCheckMethodService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取盘点任务明细(任务范围行:商品或库位)。
|
||||
* 只返回范围行,不包含盘点作业聚合与作业记录(作业聚合见 result;
|
||||
* 作业记录的 barcode/item_name/images 口径见 result/recordList)。
|
||||
* 拉取盘点任务详情(只返回任务本身信息)。
|
||||
* 不返回明细范围行(明细范围行/盘点结果请调用 result)、作业记录(recordList)
|
||||
* 与盘点作业数据(workData)。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回 { check, rows, total };
|
||||
* rows 每条为纯范围行字段:id/check_id/warehouse_id/scope_type/stock_id/location_id/
|
||||
* location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回 { check };
|
||||
* check 为盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/
|
||||
* start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/
|
||||
* remark/created_at/updated_at)。
|
||||
*/
|
||||
async detail(data = {}) {
|
||||
const { ctx } = this;
|
||||
@ -329,30 +332,114 @@ class StockCheckMethodService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取盘点作业数据(单接口三视图,view 入参驱动)。
|
||||
* 拉取盘点作业数据(视图由任务类型与 is_goods 驱动)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||||
* 视图规则:任务范围为库位(type=location/all)时一律按库位视图返回(无视 view/is_goods);
|
||||
* 任务范围为商品(type=goods/store)时默认聚合库位视图(space),
|
||||
* 仅传入 is_goods=true 时按商品视图(goods)返回。
|
||||
* 分页:data.pagination.{page,pageSize}(与 stock.check.list 口径一致,
|
||||
* 未传或非法时默认 page=1、pageSize=20,上限 200);
|
||||
* 响应 rows 为当前页行、total 为全部行数,并返回 page/pageSize。
|
||||
* 不返回任务主表信息(check)——任务信息请调用 stock.check.detail;
|
||||
* 响应返回 view(服务端实际解析出的视图类型 location/goods/space),供调用方判断 rows 行结构。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @param {string} data.view 视图类型:location/goods/space。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回 { check, rows, total };rows 结构按 view 不同:
|
||||
* @param {boolean} [data.is_goods] 商品任务是否按商品视图返回(true=goods);
|
||||
* 缺省 false=聚合库位视图(space);库位任务无视该参数(兼容 isGoods 驼峰写法)。
|
||||
* @param {string} [data.keyword] 关键字(仅库位任务 location 视图生效):按行
|
||||
* location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后返回;非库位任务忽略。
|
||||
* @param {boolean} [data.only_abnormal] 只看未盘和差异(可选,向后兼容新增,兼容 onlyAbnormal 驼峰写法):
|
||||
* 过滤在 keyword 之后、分页切片之前完成,三视图均生效——location 视图仅保留 status=unchecked
|
||||
* 或含未知商品记录(has_unknown=true)的行;goods 视图仅保留未盘行(locations 均无 record_ids)
|
||||
* 或明盘差异行(is_diff=1,盲盘无数量字段仅按未盘过滤);space 视图按行内 goods 子项过滤
|
||||
* (status=unchecked 或明盘 checked_quantity≠system_quantity),过滤后 goods 为空的行整体移除。
|
||||
* @param {Object} [data.pagination] 分页配置 { page, pageSize }。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回 { view, rows, total, page, pageSize };rows 结构按视图不同:
|
||||
* location=库位结构(任务库位范围行为列表,行内挂 goods/unknown 作业记录子列表);
|
||||
* goods=商品结构(任务商品范围行为列表,行内挂按库位聚合的 locations 作业记录,
|
||||
* 明盘返回数量与差异,盲盘不返回数量字段);
|
||||
* space=商品结构(任务商品所在库位为列表,按拣货路径排序,行内挂该库位的任务商品,
|
||||
* space=聚合库位结构(任务商品所在库位为列表,按拣货路径排序,行内挂该库位的任务商品,
|
||||
* 明盘返回账面/实盘数量,盲盘不返回数量字段)。
|
||||
*/
|
||||
async workData(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { id, view } = data || {};
|
||||
const {
|
||||
id,
|
||||
is_goods: isGoodsSnake,
|
||||
isGoods: isGoodsCamel,
|
||||
keyword,
|
||||
pagination,
|
||||
only_abnormal: onlyAbnormalSnake,
|
||||
onlyAbnormal: onlyAbnormalCamel,
|
||||
} = data || {};
|
||||
const isGoods = isGoodsSnake !== undefined ? isGoodsSnake : isGoodsCamel;
|
||||
const onlyAbnormal = onlyAbnormalSnake !== undefined ? onlyAbnormalSnake : onlyAbnormalCamel;
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.workData({ warehouseId, id, view }),
|
||||
() => this.service.systems.stockCheck.workData({ warehouseId, id, isGoods, keyword, pagination, onlyAbnormal }),
|
||||
'拉取盘点作业数据失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取盘点作业数据(space 视图分页版)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/space_code/custom_barcode/custom_name/goods,
|
||||
* goods 行含 detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/
|
||||
* record_ids,明盘另含 system_quantity/checked_quantity,status=checked/unchecked);
|
||||
* 传入 location_id 时只返回该库位行(total=1),不传时按分页返回全部库位行。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @param {number} [data.location_id] 库位ID(兼容 locationId 驼峰写法)。
|
||||
* @param {Object} [data.pagination] 分页配置 { page, pageSize }。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回 { view:'space', rows, total, page, pageSize }。
|
||||
*/
|
||||
async workDataSpaceDetails(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const {
|
||||
id,
|
||||
location_id: locationIdSnake,
|
||||
locationId: locationIdCamel,
|
||||
pagination,
|
||||
} = data || {};
|
||||
const locationId = locationIdSnake !== undefined ? locationIdSnake : locationIdCamel;
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.workDataSpaceDetails({ warehouseId, id, locationId, pagination }),
|
||||
'拉取盘点作业数据失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取单条盘点明细的作业数据(workData 单行版)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||||
* 按明细范围类型分流,均返回单行对象(与对应视图单行结构一致):
|
||||
* 库位明细(scope_type=location)行结构同 workData location 视图单行
|
||||
* (detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/
|
||||
* checked_at/checkers/goods);商品明细(scope_type=goods)行结构同 workData goods 视图行
|
||||
* (detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/locations,
|
||||
* 明盘含 system_quantity/checked_quantity/diff_quantity/is_diff,盲盘不含数量字段)。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.detail_id 盘点明细ID(库位范围行或商品范围行;兼容 detailId 驼峰写法)。
|
||||
* @return {Promise<Object>} 统一 success 包装,data 为单行作业数据(结构随明细范围类型)。
|
||||
*/
|
||||
async workDataDetail(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { detail_id: detailIdSnake, detailId: detailIdCamel } = data || {};
|
||||
const detailId = detailIdSnake !== undefined ? detailIdSnake : detailIdCamel;
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.workDataDetail({ warehouseId, detailId }),
|
||||
'拉取盘点明细作业数据失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 盘点作业上报(覆盖式)。
|
||||
* 同明细 + 同商品 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增;
|
||||
@ -376,7 +463,16 @@ class StockCheckMethodService extends MainService {
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const checkerId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
|
||||
const checkerName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
|
||||
const { id, detail_id: detailId, location, quantity, stock_id: stockId, barcode, item_name: itemName } = data || {};
|
||||
const {
|
||||
id,
|
||||
detail_id: detailId,
|
||||
location,
|
||||
quantity,
|
||||
stock_id: stockId,
|
||||
barcode,
|
||||
item_name: itemName,
|
||||
is_empty: isEmpty,
|
||||
} = data || {};
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.report({
|
||||
@ -388,6 +484,7 @@ class StockCheckMethodService extends MainService {
|
||||
stockId,
|
||||
barcode,
|
||||
itemName,
|
||||
is_empty: isEmpty,
|
||||
checkerId,
|
||||
checkerName,
|
||||
}),
|
||||
@ -395,6 +492,37 @@ class StockCheckMethodService extends MainService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记库位为空(库位盘点模式专属)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location/all)时允许,
|
||||
* 非库位任务报 400;状态仅 approved/checking;明细必须属于本任务且为库位范围行。
|
||||
* 行为与 report(is_empty=true) 一致:写/更新空标记记录、清除该明细商品记录、重算汇总。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @param {number} data.detail_id 库位明细ID。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回
|
||||
* { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。
|
||||
*/
|
||||
async markEmpty(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const checkerId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
|
||||
const checkerName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
|
||||
const { id, detail_id: detailId } = data || {};
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.markEmpty({
|
||||
warehouseId,
|
||||
id,
|
||||
detailId,
|
||||
checkerId,
|
||||
checkerName,
|
||||
}),
|
||||
'标记空库位失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取盘点作业记录列表。
|
||||
* 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;按记录 id 倒序,返回分页结果。
|
||||
@ -424,30 +552,69 @@ class StockCheckMethodService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除盘点作业记录。
|
||||
* 批量删除盘点作业记录(按行清除盘点信息)。
|
||||
* 仅主表状态 approved/checking 允许删除;删除后重算盘点进度汇总,主表状态不回退。
|
||||
* 查不到的记录 ID 计入 skipped_ids 不报错;deleted_ids/skipped_ids 保持入参顺序。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @param {number} data.record_id 作业记录ID(兼容 recordId 写法)。
|
||||
* @param {number} [data.recordId] 作业记录ID(驼峰别名)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回 { record_id, deleted, ...summary }。
|
||||
* @param {Array<number>|number} data.record_ids 作业记录ID数组(单次上限 200;
|
||||
* 兼容 recordIds 驼峰写法;兼容旧版单值 record_id 写法,单值自动转数组)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回
|
||||
* { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status };
|
||||
* 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版
|
||||
* { record_id, deleted, ...summary } 变更为上述结构。
|
||||
*/
|
||||
async recordDelete(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { id, record_id: recordIdRaw, recordId: recordIdAlias } = data || {};
|
||||
const recordId = recordIdRaw !== undefined && recordIdRaw !== null && recordIdRaw !== ''
|
||||
? recordIdRaw
|
||||
: recordIdAlias;
|
||||
const {
|
||||
id,
|
||||
record_ids: recordIdsRaw,
|
||||
recordIds: recordIdsArrayAlias,
|
||||
recordId: recordIdSingleAlias,
|
||||
record_id: recordIdSingleSnake,
|
||||
} = data || {};
|
||||
const recordIds = recordIdsRaw !== undefined
|
||||
? recordIdsRaw
|
||||
: (recordIdsArrayAlias !== undefined
|
||||
? recordIdsArrayAlias
|
||||
: (recordIdSingleAlias !== undefined ? recordIdSingleAlias : recordIdSingleSnake));
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.recordDelete({
|
||||
warehouseId,
|
||||
id,
|
||||
recordId,
|
||||
recordIds,
|
||||
}),
|
||||
'删除盘点作业记录失败'
|
||||
'批量删除盘点作业记录失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。
|
||||
* 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),该库位回到未盘;
|
||||
* 仅任务范围为库位(type=location/all)且状态 approved/checking 时允许,非库位任务报 400。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @param {number} data.location_id 库位ID(wms_location_space.id;兼容 locationId 驼峰写法)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回
|
||||
* { detail_id, location_id, deleted_count, total_items, checked_items, diff_items, detail_status }。
|
||||
*/
|
||||
async recheckClearLocation(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { id, location_id: locationIdRaw, locationId: locationIdAlias } = data || {};
|
||||
const locationId = locationIdRaw !== undefined ? locationIdRaw : locationIdAlias;
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.recheckClearLocation({
|
||||
warehouseId,
|
||||
id,
|
||||
locationId,
|
||||
}),
|
||||
'重盘清除库位失败'
|
||||
);
|
||||
}
|
||||
|
||||
@ -646,6 +813,102 @@ class StockCheckMethodService extends MainService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交盘点明细导出任务(单任务,按盘点范围分流)。
|
||||
* 异步执行:商品范围任务固定两个 Sheet——Sheet1「汇总和差异」(每商品一行:账面快照合计/实盘合计/差异/差异类型盘盈|盘亏)+ Sheet2「库位明细」(库位编码/数量/条码/商品名称);
|
||||
* 库位范围任务 Sheet「盘点明细」(库位/商品/盘点数量)→ ExcelJS 流式写入 → COS 上传。
|
||||
* 进度通过 Redis 缓存追踪,立即返回任务ID;进度查询复用 exportTaskProgress。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回任务ID。
|
||||
*/
|
||||
async exportDetail(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { id } = data || {};
|
||||
|
||||
const checkId = Number(id);
|
||||
if (!Number.isInteger(checkId) || checkId <= 0) {
|
||||
return this.fail('盘点任务ID不能为空', {}, 400);
|
||||
}
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 5,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await this.service.systems.stockCheck.exportCheckDetail({
|
||||
warehouseId,
|
||||
id: checkId,
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress,
|
||||
current_count: safeProgress.currentCount || 0,
|
||||
total_count: safeProgress.totalCount || 0,
|
||||
message: safeProgress.message || '导出任务执行中',
|
||||
result: safeProgress.result || null,
|
||||
error: '',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
current_count: result.current_count || 0,
|
||||
total_count: result.total_count || 0,
|
||||
message: '导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询盘点任务导出进度。
|
||||
*
|
||||
|
||||
@ -228,12 +228,26 @@ class StockReportMethodService extends MainService {
|
||||
sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder,
|
||||
};
|
||||
|
||||
const onProgress = async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress,
|
||||
current_count: safeProgress.currentCount ?? safeProgress.current_count ?? 0,
|
||||
total_count: safeProgress.totalCount ?? safeProgress.total_count ?? 0,
|
||||
message: safeProgress.message || '导出任务执行中',
|
||||
result: safeProgress.result || null,
|
||||
error: '',
|
||||
});
|
||||
};
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
progress: 5,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
@ -241,7 +255,7 @@ class StockReportMethodService extends MainService {
|
||||
|
||||
const result = await service.systems.storage.report.export(
|
||||
startTime, endTime, false, warehouseIds,
|
||||
sortOption, exportMode, 'store', stockIds, keyword
|
||||
sortOption, exportMode, 'store', stockIds, keyword, onProgress
|
||||
);
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
@ -338,18 +352,35 @@ class StockReportMethodService extends MainService {
|
||||
sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder,
|
||||
};
|
||||
|
||||
const onProgress = async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress,
|
||||
current_count: safeProgress.currentCount ?? safeProgress.current_count ?? 0,
|
||||
total_count: safeProgress.totalCount ?? safeProgress.total_count ?? 0,
|
||||
message: safeProgress.message || '导出任务执行中',
|
||||
result: safeProgress.result || null,
|
||||
error: '',
|
||||
});
|
||||
};
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
progress: 5,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption, exportMode, 'warehouse', stockIds, keyword);
|
||||
const result = await service.systems.storage.report.export(
|
||||
startTime, endTime, bySpace, storeIds, sortOption, exportMode,
|
||||
'warehouse', stockIds, keyword, onProgress
|
||||
);
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
@ -480,10 +511,16 @@ class StockReportMethodService extends MainService {
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const normalizeCount = value => {
|
||||
const numericValue = Number(value);
|
||||
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
|
||||
};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||||
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
|
||||
current_count: normalizeCount(safePayload.current_count),
|
||||
total_count: normalizeCount(safePayload.total_count),
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
|
||||
@ -740,6 +740,101 @@ class ExcelService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传已经生成到本地临时目录的 Excel 文件(供流式生成场景复用上传链路)。
|
||||
* 与 generateAndUpload 的区别:文件由调用方(如 ExcelJS.stream.WorkbookWriter)落盘,
|
||||
* 这里只负责归一化文件名、构建上传 key、流式上传与可选的落库记录。
|
||||
* @param {Object} options 参数
|
||||
* @param {string} options.filePath 本地文件绝对路径
|
||||
* @param {string} [options.filename] 原始文件名
|
||||
* @param {string} [options.dir='exports/excel'] 上传目录
|
||||
* @param {string} [options.key] 自定义上传 key(优先于 dir)
|
||||
* @param {string} [options.category='document'] 文件分类
|
||||
* @param {boolean} [options.saveRecord=false] 是否落库记录
|
||||
* @param {string} [options.businessType] 业务类型(落库记录用)
|
||||
* @param {string} [options.businessId] 业务ID(落库记录用)
|
||||
* @param {string} [options.uploaderDept] 上传部门(落库记录用)
|
||||
* @param {string|number} [options.expireTime] 过期时间(落库记录用)
|
||||
* @param {number} [options.expireDays] 过期天数(落库记录用)
|
||||
* @param {Function} [options.onProgress] 上传进度回调
|
||||
* @return {Promise<Object>} 上传结果(含 filename/fileKey/size/contentType 与 uploadFile 返回值)
|
||||
*/
|
||||
async uploadExistingFile({
|
||||
filePath,
|
||||
filename = 'export.xlsx',
|
||||
dir = 'exports/excel',
|
||||
key,
|
||||
category = 'document',
|
||||
saveRecord = false,
|
||||
businessType,
|
||||
businessId,
|
||||
uploaderDept,
|
||||
expireTime,
|
||||
expireDays,
|
||||
onProgress,
|
||||
...options
|
||||
} = {}) {
|
||||
const uploadService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.upload;
|
||||
|
||||
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
|
||||
throw new Error('上传服务不可用,无法上传 Excel 文件');
|
||||
}
|
||||
|
||||
if (typeof filePath !== 'string' || !filePath) {
|
||||
throw new Error('filePath 不能为空');
|
||||
}
|
||||
|
||||
const bookType = String(options.bookType || path.extname(filename).replace('.', '') || 'xlsx').toLowerCase();
|
||||
const safeFilename = this.sanitizeFilename(filename, `.${bookType}`);
|
||||
const contentType = this.getContentType(bookType);
|
||||
const stat = await fs.promises.stat(filePath);
|
||||
const uploadKey = this.buildUploadKey(safeFilename, { dir, key });
|
||||
const uploadStream = fs.createReadStream(filePath);
|
||||
|
||||
uploadStream.filename = safeFilename;
|
||||
uploadStream.mimeType = contentType;
|
||||
uploadStream.fileSize = stat.size;
|
||||
|
||||
const uploadResult = await uploadService.uploadFile(uploadStream, {
|
||||
key: uploadKey,
|
||||
category,
|
||||
mimetype: 'xls,xlsx,csv',
|
||||
onProgress,
|
||||
});
|
||||
|
||||
let fileRecord = null;
|
||||
if ((saveRecord || businessType || businessId) && typeof uploadService.uploadSuccessNotify === 'function') {
|
||||
const recordResult = await uploadService.uploadSuccessNotify({
|
||||
url: uploadResult.fileName,
|
||||
fileKey: uploadResult.fileName,
|
||||
fileName: safeFilename,
|
||||
name: safeFilename,
|
||||
fileSize: stat.size,
|
||||
size: stat.size,
|
||||
fileType: category,
|
||||
mimeType: contentType,
|
||||
type: category,
|
||||
category,
|
||||
businessType,
|
||||
businessId,
|
||||
uploaderDept,
|
||||
expireTime,
|
||||
expireDays,
|
||||
});
|
||||
|
||||
fileRecord = recordResult && (recordResult.data || recordResult);
|
||||
}
|
||||
|
||||
return {
|
||||
filename: safeFilename,
|
||||
fileKey: uploadResult.fileName,
|
||||
size: stat.size,
|
||||
contentType,
|
||||
...uploadResult,
|
||||
fileRecord,
|
||||
};
|
||||
}
|
||||
|
||||
async sendFile({ ctx = this.ctx, filename = 'export.xlsx', ...options } = {}) {
|
||||
if (!ctx) {
|
||||
throw new Error('ctx 不存在,无法输出下载响应');
|
||||
|
||||
429
app/service/systems/order_b2b.js
Normal file
429
app/service/systems/order_b2b.js
Normal file
@ -0,0 +1,429 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/** 订单转 B2B 操作码 */
|
||||
const ORDER_B2B_CONVERT_OPERATION_CODE = 'ORDER_B2B_CONVERT';
|
||||
/** 取消 B2B(流转回正常订单)操作码 */
|
||||
const ORDER_B2B_CANCEL_OPERATION_CODE = 'ORDER_B2B_CANCEL';
|
||||
/** 单次转换订单数上限 */
|
||||
const ORDER_B2B_CONVERT_BATCH_LIMIT = 200;
|
||||
|
||||
/**
|
||||
* B2B 订单业务服务。
|
||||
*
|
||||
* 负责订单转 B2B(wms_order_delivery.is_b2b 置 Y + wms_order_b2b 作业明细落表)。
|
||||
*/
|
||||
class OrderB2bService extends Service {
|
||||
/**
|
||||
* 将待处理订单批量转为 B2B 订单。
|
||||
*
|
||||
* 仅限待处理表(current 分表)中未打印、未锁定、未拦截的订单;
|
||||
* 不符合条件的订单跳过(计入 skipped),不报错。事务内完成
|
||||
* is_b2b 置 Y 与 wms_order_b2b 明细写入;操作日志在事务提交后写入。
|
||||
*
|
||||
* @param {Object} params 转换参数。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @param {Array<number>} params.orderIds 订单ID数组。
|
||||
* @param {Object|null} [params.operator=null] 操作人 { id, name }。
|
||||
* @return {Promise<Object>} { converted_order_ids, converted_count, skipped_order_ids,
|
||||
* skipped_count, skipped_reasons, not_found_order_ids }
|
||||
*/
|
||||
async convertOrdersToB2b(params = {}) {
|
||||
const { ctx, app } = this;
|
||||
const normalizedWarehouseId = Number(params && params.warehouseId || 0);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw new Error('未识别到当前仓库上下文');
|
||||
}
|
||||
|
||||
const rawIds = params && params.orderIds;
|
||||
const normalizedOrderIds = [ ...new Set(
|
||||
(Array.isArray(rawIds) ? rawIds : [ rawIds ])
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isInteger(item) && item > 0)
|
||||
) ];
|
||||
if (normalizedOrderIds.length === 0) {
|
||||
throw new Error('订单ID不能为空');
|
||||
}
|
||||
if (normalizedOrderIds.length > ORDER_B2B_CONVERT_BATCH_LIMIT) {
|
||||
throw new Error(`单次最多转换 ${ORDER_B2B_CONVERT_BATCH_LIMIT} 个订单`);
|
||||
}
|
||||
|
||||
const operator = params && params.operator && typeof params.operator === 'object'
|
||||
? params.operator
|
||||
: null;
|
||||
const { Op } = app.Sequelize;
|
||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(normalizedWarehouseId);
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
const convertedRows = [];
|
||||
const skippedReasons = [];
|
||||
let notFoundOrderIds = [];
|
||||
|
||||
try {
|
||||
const lockRows = await orderModel.findAll({
|
||||
attributes: [
|
||||
'id', 'delivery_order_code', 'store_id', 'step',
|
||||
'print_status', 'lock_status', 'intercept_status', 'is_b2b',
|
||||
],
|
||||
where: {
|
||||
id: { [Op.in]: normalizedOrderIds },
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const rowMap = new Map((Array.isArray(lockRows) ? lockRows : []).map(row => [ Number(row && row.id || 0), row ]));
|
||||
notFoundOrderIds = normalizedOrderIds.filter(orderId => !rowMap.has(orderId));
|
||||
|
||||
for (const orderId of normalizedOrderIds) {
|
||||
const row = rowMap.get(orderId);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const skipReason = this.resolveConvertSkipReason(row);
|
||||
if (skipReason) {
|
||||
skippedReasons.push({
|
||||
order_id: orderId,
|
||||
delivery_order_code: String(row.delivery_order_code || '').trim(),
|
||||
reason: skipReason,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
convertedRows.push(row);
|
||||
}
|
||||
|
||||
if (convertedRows.length > 0) {
|
||||
const convertedOrderIds = convertedRows.map(row => Number(row.id));
|
||||
const now = new Date();
|
||||
|
||||
await orderModel.update(
|
||||
{ is_b2b: 'Y', updated_at: now },
|
||||
{
|
||||
where: {
|
||||
id: { [Op.in]: convertedOrderIds },
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
// 写入 B2B 作业明细(uk_order_id 唯一):
|
||||
// 首次转换创建新行;二次转换(存在历史软删除行)恢复同一行并重置作业字段
|
||||
const b2bModel = ctx.model.OrderB2b;
|
||||
for (const row of convertedRows) {
|
||||
const orderId = Number(row.id);
|
||||
const baseFields = {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
store_id: Number(row.store_id || 0) > 0 ? Number(row.store_id) : null,
|
||||
delivery_order_code: String(row.delivery_order_code || '').trim(),
|
||||
updated_at: now,
|
||||
};
|
||||
const existing = await b2bModel.findOne({
|
||||
where: { order_id: orderId },
|
||||
paranoid: false,
|
||||
transaction,
|
||||
});
|
||||
if (existing) {
|
||||
// 恢复历史行并重置作业字段(取消 B2B 后的旧作业数据不再有效)
|
||||
await existing.update({
|
||||
deleted_at: null,
|
||||
total_box_count: 0,
|
||||
pickup_plate_number: null,
|
||||
prep_remark: null,
|
||||
prep_duration_seconds: 0,
|
||||
is_picked_up: 'N',
|
||||
picked_up_at: null,
|
||||
is_print: 'N',
|
||||
...baseFields,
|
||||
}, { transaction, paranoid: false });
|
||||
} else {
|
||||
await b2bModel.create({
|
||||
order_id: orderId,
|
||||
...baseFields,
|
||||
created_at: now,
|
||||
}, { transaction });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
|
||||
// 操作日志在事务提交后写入,失败不影响主流程
|
||||
for (const row of convertedRows) {
|
||||
try {
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: Number(row.id),
|
||||
operationCode: ORDER_B2B_CONVERT_OPERATION_CODE,
|
||||
operationAction: 'UPDATE',
|
||||
changeSummary: '订单转为B2B订单',
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderId: Number(row.id),
|
||||
orderNo: String(row.delivery_order_code || '').trim(),
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[orderB2b.convertOrdersToB2b] 写入操作日志失败,不影响业务, orderId=${row.id}, error=${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const skippedOrderIds = [ ...new Set(skippedReasons.map(item => item.order_id)) ];
|
||||
return {
|
||||
converted_order_ids: [ ...new Set(convertedRows.map(row => Number(row.id))) ],
|
||||
converted_count: convertedRows.length,
|
||||
skipped_order_ids: skippedOrderIds,
|
||||
skipped_count: skippedOrderIds.length,
|
||||
skipped_reasons: skippedReasons,
|
||||
not_found_order_ids: notFoundOrderIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断订单是否满足转 B2B 条件,返回跳过原因;可转换时返回空串。
|
||||
*
|
||||
* 条件:待处理(step != 0)、未打印(print_status != fin)、
|
||||
* 未锁定(lock_status = none)、未拦截(intercept_status = none)、未转 B2B(is_b2b != Y)。
|
||||
*
|
||||
* @param {Object} row 订单行。
|
||||
* @return {string} 跳过原因,可转换返回空字符串。
|
||||
*/
|
||||
resolveConvertSkipReason(row = {}) {
|
||||
if (Number(row && row.step || 0) === 0) {
|
||||
return '订单待审核,不允许转B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.print_status || '').trim() === 'fin') {
|
||||
return '订单已打印,不允许转B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.lock_status || 'none').trim() !== 'none') {
|
||||
return '订单已锁定,不允许转B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.intercept_status || 'none').trim() !== 'none') {
|
||||
return '订单已拦截,不允许转B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.is_b2b || '').trim() === 'Y') {
|
||||
return '订单已是B2B订单';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消 B2B 出库:将 B2B 订单流转回正常订单。
|
||||
*
|
||||
* 仅限待处理表(current 分表)中 is_b2b=Y 且未打印、未锁定、未拦截、
|
||||
* B2B 面单未打印(wms_order_b2b.is_print=N)的订单;不符合条件的订单跳过,
|
||||
* 不报错。事务内完成 is_b2b 置回 N 与 B2B 作业明细软删除;
|
||||
* 操作日志在事务提交后写入。
|
||||
*
|
||||
* @param {Object} params 取消参数。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @param {Array<number>} params.orderIds 订单ID数组。
|
||||
* @param {Object|null} [params.operator=null] 操作人 { id, name }。
|
||||
* @return {Promise<Object>} { canceled_order_ids, canceled_count, skipped_order_ids,
|
||||
* skipped_count, skipped_reasons, not_found_order_ids }
|
||||
*/
|
||||
async cancelOrdersB2b(params = {}) {
|
||||
const { ctx, app } = this;
|
||||
const normalizedWarehouseId = Number(params && params.warehouseId || 0);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw new Error('未识别到当前仓库上下文');
|
||||
}
|
||||
|
||||
const rawIds = params && params.orderIds;
|
||||
const normalizedOrderIds = [ ...new Set(
|
||||
(Array.isArray(rawIds) ? rawIds : [ rawIds ])
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isInteger(item) && item > 0)
|
||||
) ];
|
||||
if (normalizedOrderIds.length === 0) {
|
||||
throw new Error('订单ID不能为空');
|
||||
}
|
||||
if (normalizedOrderIds.length > ORDER_B2B_CONVERT_BATCH_LIMIT) {
|
||||
throw new Error(`单次最多取消 ${ORDER_B2B_CONVERT_BATCH_LIMIT} 个订单`);
|
||||
}
|
||||
|
||||
const operator = params && params.operator && typeof params.operator === 'object'
|
||||
? params.operator
|
||||
: null;
|
||||
const { Op } = app.Sequelize;
|
||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(normalizedWarehouseId);
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
const canceledRows = [];
|
||||
const skippedReasons = [];
|
||||
let notFoundOrderIds = [];
|
||||
|
||||
try {
|
||||
const lockRows = await orderModel.findAll({
|
||||
attributes: [
|
||||
'id', 'delivery_order_code', 'store_id', 'step',
|
||||
'print_status', 'lock_status', 'intercept_status', 'is_b2b',
|
||||
],
|
||||
where: {
|
||||
id: { [Op.in]: normalizedOrderIds },
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const rowMap = new Map((Array.isArray(lockRows) ? lockRows : []).map(row => [ Number(row && row.id || 0), row ]));
|
||||
notFoundOrderIds = normalizedOrderIds.filter(orderId => !rowMap.has(orderId));
|
||||
|
||||
// B2B 作业明细打印状态(is_print):已打印 B2B 面单的订单不允许取消
|
||||
const b2bRows = await ctx.model.OrderB2b.findAll({
|
||||
where: {
|
||||
order_id: { [Op.in]: normalizedOrderIds },
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'order_id', 'is_print' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const b2bPrintMap = new Map((Array.isArray(b2bRows) ? b2bRows : [])
|
||||
.map(row => [ Number(row && row.order_id || 0), String(row && row.is_print || 'N').trim() ]));
|
||||
|
||||
for (const orderId of normalizedOrderIds) {
|
||||
const row = rowMap.get(orderId);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const skipReason = this.resolveCancelSkipReason(row, b2bPrintMap.get(orderId));
|
||||
if (skipReason) {
|
||||
skippedReasons.push({
|
||||
order_id: orderId,
|
||||
delivery_order_code: String(row.delivery_order_code || '').trim(),
|
||||
reason: skipReason,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
canceledRows.push(row);
|
||||
}
|
||||
|
||||
if (canceledRows.length > 0) {
|
||||
const canceledOrderIds = canceledRows.map(row => Number(row.id));
|
||||
const now = new Date();
|
||||
|
||||
await orderModel.update(
|
||||
{ is_b2b: 'N', updated_at: now },
|
||||
{
|
||||
where: {
|
||||
id: { [Op.in]: canceledOrderIds },
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
// B2B 作业明细软删除(保留历史)
|
||||
await ctx.model.OrderB2b.update(
|
||||
{ deleted_at: now, updated_at: now },
|
||||
{
|
||||
where: {
|
||||
order_id: { [Op.in]: canceledOrderIds },
|
||||
deleted_at: null,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
|
||||
// 操作日志在事务提交后写入,失败不影响主流程
|
||||
for (const row of canceledRows) {
|
||||
try {
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: Number(row.id),
|
||||
operationCode: ORDER_B2B_CANCEL_OPERATION_CODE,
|
||||
operationAction: 'UPDATE',
|
||||
changeSummary: '取消B2B出库,订单流转回正常订单',
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderId: Number(row.id),
|
||||
orderNo: String(row.delivery_order_code || '').trim(),
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[orderB2b.cancelOrdersB2b] 写入操作日志失败,不影响业务, orderId=${row.id}, error=${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const skippedOrderIds = [ ...new Set(skippedReasons.map(item => item.order_id)) ];
|
||||
return {
|
||||
canceled_order_ids: [ ...new Set(canceledRows.map(row => Number(row.id))) ],
|
||||
canceled_count: canceledRows.length,
|
||||
skipped_order_ids: skippedOrderIds,
|
||||
skipped_count: skippedOrderIds.length,
|
||||
skipped_reasons: skippedReasons,
|
||||
not_found_order_ids: notFoundOrderIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 B2B 订单是否满足取消条件,返回跳过原因;可取消时返回空串。
|
||||
*
|
||||
* 条件:待处理(step != 0)、是 B2B(is_b2b = Y)、未打印(print_status != fin)、
|
||||
* 未锁定(lock_status = none)、未拦截(intercept_status = none)、
|
||||
* B2B 面单未打印(is_print != Y)。
|
||||
*
|
||||
* @param {Object} row 订单行。
|
||||
* @param {string} b2bIsPrint B2B 作业明细打印状态(无明细行时为空串,视为未打印)。
|
||||
* @return {string} 跳过原因,可取消返回空字符串。
|
||||
*/
|
||||
resolveCancelSkipReason(row = {}, b2bIsPrint = '') {
|
||||
if (Number(row && row.step || 0) === 0) {
|
||||
return '订单待审核,不允许取消B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.is_b2b || '').trim() !== 'Y') {
|
||||
return '订单不是B2B订单';
|
||||
}
|
||||
|
||||
if (String(row && row.print_status || '').trim() === 'fin') {
|
||||
return '订单已打印,不允许取消B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.lock_status || 'none').trim() !== 'none') {
|
||||
return '订单已锁定,不允许取消B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.intercept_status || 'none').trim() !== 'none') {
|
||||
return '订单已拦截,不允许取消B2B';
|
||||
}
|
||||
|
||||
if (String(b2bIsPrint || '').trim() === 'Y') {
|
||||
return 'B2B面单已打印,不允许取消B2B';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderB2bService;
|
||||
@ -52,8 +52,8 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([
|
||||
{ header: '包材编码', key: 'package_material_code', width: 20 },
|
||||
{ header: '包材名称', key: 'package_material_name', width: 20 },
|
||||
{ header: '分配时间', key: 'waybill_allocated_at', width: 20 },
|
||||
{ header: '商品种数', key: 'items_count', width: 12 },
|
||||
{ header: '商品件数', key: 'items_total', width: 12 },
|
||||
{ header: '订单商品总类数', key: 'items_count', width: 16 },
|
||||
{ header: '订单商品总数', key: 'items_total', width: 16 },
|
||||
{ header: '商品重量', key: 'items_weight', width: 12 },
|
||||
{ header: '称重重量(g)', key: 'weighing_weight', width: 14 },
|
||||
{ header: '订单金额', key: 'total_amount', width: 14 },
|
||||
@ -64,6 +64,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([
|
||||
{ header: '出库状态', key: 'outbound_status', width: 14 },
|
||||
{ header: '复核状态', key: 'inspection_status', width: 14 },
|
||||
{ header: '复核完成状态', key: 'recheck_status', width: 16 },
|
||||
{ header: '复核时间', key: 'recheck_time', width: 20 },
|
||||
{ header: '配货状态', key: 'post_status', width: 14 },
|
||||
{ header: '打包状态', key: 'pack_status', width: 14 },
|
||||
{ header: '备注', key: 'remark', width: 30 },
|
||||
@ -103,8 +104,8 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([
|
||||
{ header: '包材编码', key: 'package_material_code', width: 20 },
|
||||
{ header: '包材名称', key: 'package_material_name', width: 20 },
|
||||
{ header: '分配时间', key: 'waybill_allocated_at', width: 20 },
|
||||
{ header: '商品种数', key: 'items_count', width: 12 },
|
||||
{ header: '商品件数', key: 'items_total', width: 12 },
|
||||
{ header: '订单商品总类数', key: 'items_count', width: 16 },
|
||||
{ header: '订单商品总数', key: 'items_total', width: 16 },
|
||||
{ header: '商品重量', key: 'items_weight', width: 12 },
|
||||
{ header: '称重重量(g)', key: 'weighing_weight', width: 14 },
|
||||
{ header: '订单金额', key: 'total_amount', width: 14 },
|
||||
@ -115,6 +116,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([
|
||||
{ header: '出库状态', key: 'outbound_status', width: 14 },
|
||||
{ header: '复核状态', key: 'inspection_status', width: 14 },
|
||||
{ header: '复核完成状态', key: 'recheck_status', width: 16 },
|
||||
{ header: '复核时间', key: 'recheck_time', width: 20 },
|
||||
{ header: '配货状态', key: 'post_status', width: 14 },
|
||||
{ header: '打包状态', key: 'pack_status', width: 14 },
|
||||
{ header: '备注', key: 'remark', width: 30 },
|
||||
@ -379,7 +381,7 @@ class OrderExportService extends OrderBaseService {
|
||||
|
||||
/**
|
||||
* 映射订单导出数据行。
|
||||
* - waybill 模式:按运单号展开,每个运单一组;商品种数/件数仅主单号行体现,子单号行置 0。
|
||||
* - waybill 模式:按运单号展开,每个运单一组;商品总类数/商品总数仅主单号行体现,子单号行置 0。
|
||||
* - item 模式:按商品明细展开,每个商品一行;运单信息汇总填充。
|
||||
* @param {Object} orderRow 订单行。
|
||||
* @param {Object} [context] 导出上下文,包含批量查询的辅助数据。
|
||||
@ -480,6 +482,7 @@ class OrderExportService extends OrderBaseService {
|
||||
outbound_status: translateStatus('outbound_status', safeOrderRow.outbound_status),
|
||||
inspection_status: translateStatus('inspection_status', safeOrderRow.inspection_status),
|
||||
recheck_status: translateStatus('recheck_status', safeOrderRow.recheck_status),
|
||||
recheck_time: formatDateSafe(safeOrderRow.recheck_time),
|
||||
post_status: translateStatus('post_status', safeOrderRow.post_status),
|
||||
pack_status: translateStatus('pack_status', safeOrderRow.pack_status),
|
||||
archive_time: formatDateSafe(safeOrderRow.archive_time),
|
||||
@ -562,7 +565,7 @@ class OrderExportService extends OrderBaseService {
|
||||
return {
|
||||
...commonFields,
|
||||
items_detail: this.normalizeExportCellValue(itemsDetail),
|
||||
// 商品种数/件数为订单级数据,仅主单号行体现;子单号行置 0,避免与主单号重复
|
||||
// 商品总类数/商品总数为订单级数据,仅主单号行体现;子单号行置 0,避免与主单号重复
|
||||
items_count: isMainWaybill ? commonFields.items_count : 0,
|
||||
items_total: isMainWaybill ? commonFields.items_total : 0,
|
||||
waybill_code: exp.waybill_code || '',
|
||||
|
||||
@ -47,8 +47,8 @@ const FIELDS = Object.freeze([
|
||||
{ key: 'package_material_code', label: '包材编码', type: 'string' },
|
||||
{ key: 'package_material_name', label: '包材名称', type: 'string' },
|
||||
{ key: 'waybill_allocated_at', label: '分配时间', type: 'string' },
|
||||
{ key: 'items_count', label: '商品种数', type: 'string' },
|
||||
{ key: 'items_total', label: '商品件数', type: 'string' },
|
||||
{ key: 'items_count', label: '订单商品总类数', type: 'string' },
|
||||
{ key: 'items_total', label: '订单商品总数', type: 'string' },
|
||||
{ key: 'items_weight', label: '商品重量', type: 'string' },
|
||||
{ key: 'weighing_weight', label: '称重重量(g)', type: 'string' },
|
||||
{ key: 'total_amount', label: '订单金额', type: 'string' },
|
||||
|
||||
@ -11,6 +11,13 @@ const Service = require('egg').Service;
|
||||
/** 退回收到导出分页拉取大小 */
|
||||
const RETURN_RECEIVED_EXPORT_PAGE_SIZE = 500;
|
||||
|
||||
/** 收件任务缓存键前缀(任务ID → 任务元信息) */
|
||||
const RETURN_RECEIVED_TASK_CACHE_KEY_PREFIX = 'return_received_task:';
|
||||
/** 收件任务缓存过期秒数(10 分钟) */
|
||||
const RETURN_RECEIVED_TASK_CACHE_TTL_SECONDS = 600;
|
||||
/** 系统预设「历史收件」任务ID(未传任务ID时的默认值) */
|
||||
const DEFAULT_RETURN_RECEIVED_TASK_ID = 1;
|
||||
|
||||
/**
|
||||
* 退回收到模块业务逻辑层。
|
||||
* 负责 wms_return_received 的增删查,以及原单反查、货主备注、30 日幂等等核心操作。
|
||||
@ -37,9 +44,10 @@ class ReturnReceivedService extends Service {
|
||||
* @param {Object} params 登记参数。
|
||||
* @param {string} params.waybill_code 退回收件运单号。
|
||||
* @param {string} [params.remark] 备注。
|
||||
* @param {number|string} [params.return_received_task_id] 收件任务ID,不传默认 1(系统预设「历史收件」)。
|
||||
* @return {Promise<Object>} 登记结果,含 record、is_original_return、store_remark、is_urgent、duplicated。
|
||||
*/
|
||||
async create({ waybill_code, remark }) {
|
||||
async create({ waybill_code, remark, return_received_task_id }) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
@ -62,6 +70,9 @@ class ReturnReceivedService extends Service {
|
||||
throw this.createBusinessError('缺少扫描人员工号上下文', 400);
|
||||
}
|
||||
|
||||
// 收件任务ID校验(缓存优先,未命中穿透数据库建立缓存)
|
||||
const returnReceivedTaskId = await this._validateReturnReceivedTask(return_received_task_id, warehouseId);
|
||||
|
||||
// 30 日幂等窗口:同仓库 + 同单号,扫描日期在最近 30 天内则视为重复
|
||||
const now = new Date();
|
||||
const thirtyDaysAgo = new Date(now.getTime());
|
||||
@ -150,6 +161,7 @@ class ReturnReceivedService extends Service {
|
||||
order_express_id: orderExpressId,
|
||||
order_id: orderId,
|
||||
store_id: storeId,
|
||||
return_received_task_id: returnReceivedTaskId,
|
||||
remark: remark ? String(remark).slice(0, 500) : null,
|
||||
});
|
||||
|
||||
@ -189,6 +201,59 @@ class ReturnReceivedService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验收件任务ID(缓存优先,未命中穿透数据库建立缓存)。
|
||||
*
|
||||
* 规则:
|
||||
* 1. 未传任务ID时默认 1(系统预设「历史收件」);
|
||||
* 2. 任务ID必须为正整数;
|
||||
* 3. 缓存键 return_received_task:{id} 命中直接使用;未命中查 wms_return_received_task,
|
||||
* 存在则写缓存(TTL 10 分钟),不存在报错;
|
||||
* 4. 任务必须属于当前仓库或系统级(warehouse_id=0)。
|
||||
*
|
||||
* @param {number|string|undefined} rawTaskId 入参任务ID。
|
||||
* @param {number} warehouseId 当前仓库ID。
|
||||
* @return {Promise<number>} 校验通过的任务ID。
|
||||
*/
|
||||
async _validateReturnReceivedTask(rawTaskId, warehouseId) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
const taskId = rawTaskId === undefined || rawTaskId === null || rawTaskId === ''
|
||||
? DEFAULT_RETURN_RECEIVED_TASK_ID
|
||||
: Number(rawTaskId);
|
||||
|
||||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||||
throw this.createBusinessError('收件任务ID不合法', 400);
|
||||
}
|
||||
|
||||
const cacheKey = RETURN_RECEIVED_TASK_CACHE_KEY_PREFIX + taskId;
|
||||
let task = await app.getCacheAsync(cacheKey);
|
||||
if (!task) {
|
||||
// 缓存未命中:穿透数据库查询并建立缓存
|
||||
task = await ctx.model.ReturnReceivedTask.findOne({
|
||||
where: { id: taskId },
|
||||
attributes: [ 'id', 'warehouse_id', 'title' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!task) {
|
||||
throw this.createBusinessError(`收件任务不存在: ${taskId}`, 400);
|
||||
}
|
||||
await app.setCacheAsync(cacheKey, {
|
||||
id: Number(task.id),
|
||||
warehouse_id: Number(task.warehouse_id || 0),
|
||||
title: String(task.title || ''),
|
||||
}, RETURN_RECEIVED_TASK_CACHE_TTL_SECONDS);
|
||||
}
|
||||
|
||||
// 仓库归属校验:系统级(warehouse_id=0)或当前仓库任务才允许使用
|
||||
const taskWarehouseId = Number(task.warehouse_id || 0);
|
||||
if (taskWarehouseId !== 0 && taskWarehouseId !== Number(warehouseId)) {
|
||||
throw this.createBusinessError('收件任务不属于当前仓库', 400);
|
||||
}
|
||||
|
||||
return taskId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断运单是否存在退回查询记录(加急标记判定口径)。
|
||||
* 判定标准:wms_return_query_log 中存在 warehouse_id = 当前仓库 且 waybill_code = 登记运单号(精确匹配)的记录。
|
||||
@ -924,6 +989,7 @@ class ReturnReceivedService extends Service {
|
||||
const directFields = [
|
||||
'warehouse_id', 'scanner_id', 'store_id', 'order_express_id', 'order_id',
|
||||
'waybill_code', 'scan_date', 'created_at', 'updated_at', 'scanner_name',
|
||||
'return_received_task_id',
|
||||
];
|
||||
|
||||
for (const field of directFields) {
|
||||
|
||||
535
app/service/systems/return_received_task.js
Normal file
535
app/service/systems/return_received_task.js
Normal file
@ -0,0 +1,535 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/** 批次号前缀(RT=Return(Received) Task) */
|
||||
const BATCH_NO_PREFIX = 'RT';
|
||||
/** 批次号当日序号位宽(5 位补零) */
|
||||
const BATCH_NO_SEQUENCE_WIDTH = 5;
|
||||
/** 序列表业务类型(wms_number_sequence.biz_type,全局维度 warehouse_id=0) */
|
||||
const BATCH_NO_BIZ_TYPE = 'return_received_task_batch_no';
|
||||
|
||||
/**
|
||||
* 收件任务模块业务逻辑层(退回收件任务分组)。
|
||||
* 负责 wms_return_received_task(收件任务表)的创建与删除。
|
||||
* 所有数据库交互集中在此层,供 systemMethods/returnReceivedTask.js 调用。
|
||||
*/
|
||||
class ReturnReceivedTaskService extends Service {
|
||||
/**
|
||||
* 创建带业务错误码的异常对象。
|
||||
* @param {string} message 错误信息。
|
||||
* @param {number} [code=400] 业务错误码。
|
||||
* @return {Error} 包含 code 的异常对象。
|
||||
*/
|
||||
createBusinessError(message, code = 400) {
|
||||
const error = new Error(`${message}`);
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建收件任务。
|
||||
* 仓库与创建人均由方法层从登录上下文注入,前端不传;
|
||||
* 批次号一律由服务端自动生成(RT+YYYYMMDD+5位序号,参考波次号取号机制),
|
||||
* 不接收外部输入。
|
||||
*
|
||||
* @param {Object} params 创建参数。
|
||||
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
|
||||
* @param {string} [params.title] 标题(任务名称),缺省为空串。
|
||||
* @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。
|
||||
* @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。
|
||||
* @return {Promise<Object>} 新建的收件任务行(时间字段为格式化字符串)。
|
||||
* @throws {Error} 参数非法时抛出业务错误(错误码 400)。
|
||||
*/
|
||||
async create({ warehouseId, title, creatorId, creatorName }) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw this.createBusinessError('无法获取当前仓库上下文');
|
||||
}
|
||||
|
||||
const normalizedTitle = title ? String(title).trim() : '';
|
||||
if (normalizedTitle.length > 100) {
|
||||
throw this.createBusinessError('标题过长(最多100字符)');
|
||||
}
|
||||
|
||||
const record = await ctx.model.ReturnReceivedTask.create({
|
||||
batch_no: await this.generateBatchNo(),
|
||||
title: normalizedTitle,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
creator_id: creatorId ? Number(creatorId) : 0,
|
||||
creator_name: creatorName ? String(creatorName).trim() : '',
|
||||
});
|
||||
|
||||
const row = record.get({ plain: true });
|
||||
return {
|
||||
...row,
|
||||
created_at: row.created_at ? app.formatDate(row.created_at, 'YYYY-MM-DD HH:mm:ss') : '',
|
||||
updated_at: row.updated_at ? app.formatDate(row.updated_at, 'YYYY-MM-DD HH:mm:ss') : '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询收件任务列表(仓库隔离由方法层注入 warehouse_id,系统级任务 warehouse_id=0 一并可见)。
|
||||
*
|
||||
* 搜索关键词(where 直接传字符串默认模糊匹配,也支持 {operator, value} 标准结构):
|
||||
* title(标题)、batch_no(编号)、creator_name(创建人)。
|
||||
* 其他字段:id/creator_id/warehouse_id 等值或 in、created_at/updated_at 范围;
|
||||
* has_register(是否有登记):true=仅看有登记任务,false=仅看无登记任务(按 wms_return_received 引用判定)。
|
||||
*
|
||||
* @param {Object} where 标准化 where 条件对象。
|
||||
* @param {Object} [pagination] 分页参数。
|
||||
* @param {number} [pagination.page=1] 页码。
|
||||
* @param {number} [pagination.pageSize=20] 每页数量。
|
||||
* @param {Object} [sort] 排序参数。
|
||||
* @param {string} [sort.sortField] 排序字段。
|
||||
* @param {string} [sort.sortOrder] 排序顺序(asc/desc)。
|
||||
* @param {number} [warehouseId=0] 当前仓库ID(由方法层从上下文注入)。
|
||||
* 用于把登记数量与「是否有登记」统计限定在当前仓库:系统级任务(如「历史收件」id=1)
|
||||
* 被各仓库共用,register_count/has_register 只统计当前仓库的登记行,避免跨仓。
|
||||
* @return {Promise<Object>} { list: Array, pagination: Object },
|
||||
* list 每行含 register_count(该任务在当前仓库下的退回收件登记数量,无登记为 0)。
|
||||
*/
|
||||
async list(where = {}, pagination = {}, sort = {}, warehouseId = 0) {
|
||||
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 normalizedWarehouseId = Number(warehouseId);
|
||||
const statWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0;
|
||||
|
||||
const queryWhere = this._buildTaskListWhere(where, Op, statWarehouseId);
|
||||
const order = this._buildTaskListOrder(sort);
|
||||
|
||||
const { count, rows } = await ctx.model.ReturnReceivedTask.findAndCountAll({
|
||||
where: queryWhere,
|
||||
order,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 任务登记数量:按任务ID分组统计当前仓库的登记行数(一次分组查询,避免系统级任务跨仓统计)
|
||||
const taskIds = rows.map(row => Number(row.id)).filter(id => id > 0);
|
||||
const registerCountMap = new Map();
|
||||
if (taskIds.length > 0) {
|
||||
const statWhere = { return_received_task_id: { [Op.in]: taskIds } };
|
||||
if (statWarehouseId > 0) {
|
||||
statWhere.warehouse_id = statWarehouseId;
|
||||
}
|
||||
const statRows = await ctx.model.ReturnReceived.findAll({
|
||||
attributes: [
|
||||
'return_received_task_id',
|
||||
[ app.Sequelize.fn('COUNT', app.Sequelize.col('return_received_task_id')), 'register_count' ],
|
||||
],
|
||||
where: statWhere,
|
||||
group: [ 'return_received_task_id' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const stat of statRows) {
|
||||
registerCountMap.set(Number(stat.return_received_task_id), Number(stat.register_count || 0));
|
||||
}
|
||||
}
|
||||
|
||||
const list = rows.map(row => ({
|
||||
...row,
|
||||
register_count: registerCountMap.get(Number(row.id)) || 0,
|
||||
created_at: row.created_at ? app.formatDate(row.created_at, 'YYYY-MM-DD HH:mm:ss') : '',
|
||||
updated_at: row.updated_at ? app.formatDate(row.updated_at, 'YYYY-MM-DD HH:mm:ss') : '',
|
||||
}));
|
||||
|
||||
return {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: count,
|
||||
totalPages: Math.ceil(count / pageSize),
|
||||
hasPrevious: page > 1,
|
||||
hasNext: page * pageSize < count,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据标准化 where 条件构建收件任务列表查询条件。
|
||||
*
|
||||
* @param {Object} where 标准化 where 条件对象。
|
||||
* @param {Object} Op Sequelize Op 对象。
|
||||
* @param {number} [warehouseId=0] 当前仓库ID(has_register 判定按当前仓库过滤,避免跨仓)。
|
||||
* @return {Object} Sequelize where 条件。
|
||||
*/
|
||||
_buildTaskListWhere(where = {}, Op, warehouseId = 0) {
|
||||
const { app } = this;
|
||||
const queryWhere = {};
|
||||
|
||||
// 搜索关键词字段:标题/编号/创建人,支持 {operator,value} 标准结构(like 模糊/eq 精确等)
|
||||
for (const field of [ 'title', 'batch_no', 'creator_name' ]) {
|
||||
const raw = where[field];
|
||||
if (raw === undefined || raw === null) {
|
||||
continue;
|
||||
}
|
||||
queryWhere[field] = this._resolveTaskConditionValue(raw, Op);
|
||||
}
|
||||
|
||||
// 快捷搜索关键词:在 title/batch_no/creator_name 三个字段中 OR 模糊匹配
|
||||
if (where.quickWhere !== undefined && where.quickWhere !== null) {
|
||||
const quickRaw = this._extractTaskConditionValue(where.quickWhere);
|
||||
const quickValue = this._extractTaskConditionValue(quickRaw);
|
||||
if (quickValue !== undefined && quickValue !== null && String(quickValue).trim() !== '') {
|
||||
const likePattern = { [Op.like]: `%${String(quickValue).trim()}%` };
|
||||
queryWhere[Op.or] = [
|
||||
{ title: likePattern },
|
||||
{ batch_no: likePattern },
|
||||
{ creator_name: likePattern },
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 是否有登记(派生筛选):true=仅看有登记的任务,false=仅看无登记的任务;按当前仓库过滤,避免跨仓
|
||||
if (where.has_register !== undefined && where.has_register !== null) {
|
||||
const hasValue = this._extractTaskConditionValue(where.has_register);
|
||||
const flag = hasValue === true || hasValue === 1 || hasValue === '1' || hasValue === 'true';
|
||||
const registerSubSql = warehouseId > 0
|
||||
? `(SELECT DISTINCT return_received_task_id FROM wms_return_received WHERE warehouse_id = ${Number(warehouseId)})`
|
||||
: '(SELECT DISTINCT return_received_task_id FROM wms_return_received)';
|
||||
queryWhere.id = flag
|
||||
? { [Op.in]: app.Sequelize.literal(registerSubSql) }
|
||||
: { [Op.notIn]: app.Sequelize.literal(registerSubSql) };
|
||||
}
|
||||
|
||||
// 数值字段:等值/in/范围
|
||||
for (const field of [ 'id', 'creator_id', 'warehouse_id' ]) {
|
||||
if (where[field] !== undefined && where[field] !== null) {
|
||||
queryWhere[field] = this._resolveTaskConditionValue(where[field], Op);
|
||||
}
|
||||
}
|
||||
|
||||
// 时间字段
|
||||
for (const field of [ 'created_at', 'updated_at' ]) {
|
||||
if (where[field] !== undefined && where[field] !== null) {
|
||||
queryWhere[field] = this._resolveTaskConditionValue(where[field], Op);
|
||||
}
|
||||
}
|
||||
|
||||
return queryWhere;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析标准化条件值为 Sequelize 可用的条件对象。
|
||||
*
|
||||
* @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。
|
||||
* @param {Object} Op Sequelize Op 对象。
|
||||
* @return {*} Sequelize 条件。
|
||||
*/
|
||||
_resolveTaskConditionValue(condition, Op) {
|
||||
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
|
||||
const operator = condition.operator;
|
||||
const value = condition.value;
|
||||
|
||||
if (!operator) {
|
||||
return value;
|
||||
}
|
||||
|
||||
switch (operator) {
|
||||
case 'eq':
|
||||
return value;
|
||||
case 'ne':
|
||||
return { [Op.ne]: value };
|
||||
case 'in':
|
||||
return { [Op.in]: Array.isArray(value) ? value : [ value ] };
|
||||
case 'notin':
|
||||
return { [Op.notIn]: Array.isArray(value) ? value : [ value ] };
|
||||
case 'like':
|
||||
return { [Op.like]: `%${value}%` };
|
||||
case 'gt':
|
||||
return { [Op.gt]: value };
|
||||
case 'gte':
|
||||
return { [Op.gte]: value };
|
||||
case 'lt':
|
||||
return { [Op.lt]: value };
|
||||
case 'lte':
|
||||
return { [Op.lte]: value };
|
||||
case 'between':
|
||||
return { [Op.between]: Array.isArray(value) ? value : [ value ] };
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return condition;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 sort 参数构建 Sequelize 排序数组。
|
||||
*
|
||||
* @param {Object} sort 排序参数。
|
||||
* @return {Array<Array<string>>} Sequelize order 数组。
|
||||
*/
|
||||
_buildTaskListOrder(sort = {}) {
|
||||
const sortField = sort.sortField || sort.sort_field || 'id';
|
||||
const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase();
|
||||
const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC';
|
||||
|
||||
const allowedSortFields = new Set([ 'id', 'batch_no', 'created_at', 'updated_at' ]);
|
||||
const safeSortField = allowedSortFields.has(sortField) ? sortField : 'id';
|
||||
|
||||
return [[ safeSortField, sortOrder ]];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从条件对象中提取原始 value。
|
||||
*
|
||||
* @param {*} condition 标准化条件。
|
||||
* @return {*} 原始值。
|
||||
*/
|
||||
_extractTaskConditionValue(condition) {
|
||||
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
|
||||
if ('value' in condition) {
|
||||
return condition.value;
|
||||
}
|
||||
}
|
||||
return condition;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期片段(YYYYMMDD)。
|
||||
*
|
||||
* @return {string} 当前日期片段。
|
||||
*/
|
||||
getCurrentDatePart() {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getDate()).padStart(2, '0');
|
||||
return `${year}${month}${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成收件任务批次号(原子取号,参考波次号 getNextWaveNoSequence 口径)。
|
||||
*
|
||||
* 格式:RT + YYYYMMDD + 5位序号(如 RT2026100500001)。
|
||||
* 基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date
|
||||
* 串行化并发事务,biz_type=return_received_task_batch_no,全局维度 warehouse_id=0),
|
||||
* 并对齐当日主表已有最大序号(历史编号不跳号);
|
||||
* upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq,
|
||||
* 避免 REPEATABLE READ 快照读读到旧值。
|
||||
*
|
||||
* @return {Promise<string>} 批次号。
|
||||
*/
|
||||
async generateBatchNo() {
|
||||
const { ctx } = this;
|
||||
const datePart = this.getCurrentDatePart();
|
||||
const pattern = `${BATCH_NO_PREFIX}${datePart}%`;
|
||||
const prefixDatePartLength = BATCH_NO_PREFIX.length + datePart.length;
|
||||
|
||||
// 历史对齐种子:当日主表已有最大序号(无则为 0)
|
||||
const seedRows = await ctx.model.query(
|
||||
`SELECT IFNULL(MAX(CAST(SUBSTRING(batch_no, :startPos) AS UNSIGNED)), 0) AS max_seq
|
||||
FROM wms_return_received_task
|
||||
WHERE batch_no LIKE :pattern`,
|
||||
{
|
||||
replacements: {
|
||||
pattern,
|
||||
startPos: prefixDatePartLength + 1,
|
||||
},
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq || 0);
|
||||
|
||||
// 原子取号:全局维度(warehouse_id=0)按「业务类型+日期」递增,唯一键串行化并发事务
|
||||
await ctx.model.query(
|
||||
`INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at)
|
||||
VALUES (0, :bizType, :datePart, :seed + 1, NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`,
|
||||
{
|
||||
replacements: {
|
||||
bizType: BATCH_NO_BIZ_TYPE,
|
||||
datePart,
|
||||
seed,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化),
|
||||
// FOR UPDATE 返回最新提交版本,不受旧快照影响
|
||||
const seqRows = await ctx.model.query(
|
||||
`SELECT current_seq
|
||||
FROM wms_number_sequence
|
||||
WHERE warehouse_id = 0 AND biz_type = :bizType AND date_part = :datePart
|
||||
FOR UPDATE`,
|
||||
{
|
||||
replacements: {
|
||||
bizType: BATCH_NO_BIZ_TYPE,
|
||||
datePart,
|
||||
},
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
const sequence = Number(seqRows && seqRows[0] && seqRows[0].current_seq || 0);
|
||||
const safeSequence = Number.isInteger(sequence) && sequence > 0 ? sequence : 1;
|
||||
|
||||
return `${BATCH_NO_PREFIX}${datePart}${String(safeSequence).padStart(BATCH_NO_SEQUENCE_WIDTH, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除收件任务(硬删除)。
|
||||
*
|
||||
* 规则(逐条分流,不整体报错):
|
||||
* 1. 任务不存在、系统预设(id=1「历史收件」)、非当前仓库任务 → 计入 skipped_ids;
|
||||
* 2. 任务下已有收件登记(wms_return_received.return_received_task_id 引用)→ 409 口径计入 skipped_ids;
|
||||
* 3. 其余任务硬删除,并清理任务缓存 return_received_task:{id}。
|
||||
*
|
||||
* @param {Object} params 批量删除参数。
|
||||
* @param {number} params.warehouseId 当前仓库ID(由方法层从上下文注入)。
|
||||
* @param {Array<number>|number} params.ids 收件任务ID(数组或单个数值,单次上限 200)。
|
||||
* @return {Promise<Object>} { total, deleted_count, skipped_count, deleted_ids, skipped_ids },
|
||||
* deleted_ids/skipped_ids 保持入参顺序。
|
||||
* @throws {Error} 仓库上下文缺失、ids 为空或超过上限时抛出业务错误(错误码 400)。
|
||||
*/
|
||||
async batchDelete(params = {}) {
|
||||
const { warehouseId, ids } = params;
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw this.createBusinessError('无法获取当前仓库上下文');
|
||||
}
|
||||
|
||||
// ids 归一化:单值转数组、去重、只保留正整数
|
||||
const idSource = Array.isArray(ids) ? ids : [ ids ];
|
||||
const numericIds = [ ...new Set(idSource.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ];
|
||||
if (numericIds.length === 0) {
|
||||
throw this.createBusinessError('ids 不能为空');
|
||||
}
|
||||
if (numericIds.length > 200) {
|
||||
throw this.createBusinessError('单次最多删除 200 个收件任务');
|
||||
}
|
||||
|
||||
// 查询任务(不限定仓库,便于区分「不存在/系统预设/无权」三种跳过原因)
|
||||
const taskRows = await ctx.model.ReturnReceivedTask.findAll({
|
||||
where: { id: { [Op.in]: numericIds } },
|
||||
attributes: [ 'id', 'warehouse_id', 'title' ],
|
||||
raw: true,
|
||||
});
|
||||
const taskMap = new Map(taskRows.map(row => [ Number(row.id), row ]));
|
||||
|
||||
// 登记引用计数(本仓库口径一致:普通任务登记都在本仓库)
|
||||
const usedRows = await ctx.model.ReturnReceived.findAll({
|
||||
attributes: [
|
||||
'return_received_task_id',
|
||||
[ app.Sequelize.fn('COUNT', app.Sequelize.col('return_received_task_id')), 'register_count' ],
|
||||
],
|
||||
where: { return_received_task_id: { [Op.in]: numericIds } },
|
||||
group: [ 'return_received_task_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const usedCountMap = new Map();
|
||||
for (const stat of usedRows) {
|
||||
usedCountMap.set(Number(stat.return_received_task_id), Number(stat.register_count || 0));
|
||||
}
|
||||
|
||||
// 逐条分流(保持入参顺序)
|
||||
const deletedIds = [];
|
||||
const skippedIds = [];
|
||||
for (const taskId of numericIds) {
|
||||
const row = taskMap.get(taskId);
|
||||
if (!row) {
|
||||
skippedIds.push(taskId);
|
||||
continue;
|
||||
}
|
||||
if (Number(row.id) === 1) {
|
||||
skippedIds.push(taskId); // 系统预设不可删除
|
||||
continue;
|
||||
}
|
||||
if (Number(row.warehouse_id) !== normalizedWarehouseId) {
|
||||
skippedIds.push(taskId); // 非本仓库无权操作
|
||||
continue;
|
||||
}
|
||||
if ((usedCountMap.get(taskId) || 0) > 0) {
|
||||
skippedIds.push(taskId); // 已有收件登记不可删除
|
||||
continue;
|
||||
}
|
||||
deletedIds.push(taskId);
|
||||
}
|
||||
|
||||
if (deletedIds.length > 0) {
|
||||
await ctx.model.ReturnReceivedTask.destroy({ where: { id: { [Op.in]: deletedIds } } });
|
||||
|
||||
// 清理任务缓存(登记校验缓存 return_received_task:{id})
|
||||
for (const taskId of deletedIds) {
|
||||
await app.delCacheAsync(`return_received_task:${taskId}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
total: numericIds.length,
|
||||
deleted_count: deletedIds.length,
|
||||
skipped_count: skippedIds.length,
|
||||
deleted_ids: deletedIds,
|
||||
skipped_ids: skippedIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除单个收件任务(兼容入口,硬删除)。
|
||||
* 单值语义与批量删除一致:不满足删除条件时抛出对应业务错误(不静默跳过)。
|
||||
*
|
||||
* @param {number|string} taskId 收件任务ID。
|
||||
* @param {number} warehouseId 当前仓库ID(由方法层从上下文注入)。
|
||||
* @return {Promise<Object>} { id, deleted: true }。
|
||||
*/
|
||||
async delete(taskId, warehouseId) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
const normalizedId = Number(taskId);
|
||||
if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
|
||||
throw this.createBusinessError('收件任务ID不合法');
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw this.createBusinessError('无法获取当前仓库上下文');
|
||||
}
|
||||
|
||||
const task = await ctx.model.ReturnReceivedTask.findOne({
|
||||
where: { id: normalizedId },
|
||||
attributes: [ 'id', 'warehouse_id', 'title' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!task) {
|
||||
throw this.createBusinessError('收件任务不存在', 404);
|
||||
}
|
||||
|
||||
// 系统预设「历史收件」不可删除
|
||||
if (Number(task.id) === 1) {
|
||||
throw this.createBusinessError('系统预设任务不可删除', 404);
|
||||
}
|
||||
|
||||
// 归属校验:任务必须属于当前仓库
|
||||
if (Number(task.warehouse_id) !== normalizedWarehouseId) {
|
||||
throw this.createBusinessError('收件任务不存在或无权操作', 404);
|
||||
}
|
||||
|
||||
// 已有登记不可删除
|
||||
const usedCount = await ctx.model.ReturnReceived.count({
|
||||
where: { return_received_task_id: normalizedId },
|
||||
});
|
||||
if (usedCount > 0) {
|
||||
throw this.createBusinessError('该任务已有收件登记,无法删除', 409);
|
||||
}
|
||||
|
||||
await ctx.model.ReturnReceivedTask.destroy({ where: { id: normalizedId } });
|
||||
|
||||
// 清理任务缓存(登记校验缓存 return_received_task:{id})
|
||||
await app.delCacheAsync(`return_received_task:${normalizedId}`);
|
||||
|
||||
return { id: normalizedId, deleted: true };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReturnReceivedTaskService;
|
||||
@ -3,8 +3,8 @@
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* 运单退回登记模块业务逻辑层。
|
||||
* 复用 wms_return_query_log 表,提供「货主 + 运单号」退回登记的增删查改。
|
||||
* 未退登记模块业务逻辑层。
|
||||
* 复用 wms_return_query_log 表,提供「货主 + 运单号」未退登记的增删查改。
|
||||
* 所有数据库交互集中在此层,供 systemMethods/returnWaybill.js 调用。
|
||||
*/
|
||||
class ReturnWaybillService extends Service {
|
||||
@ -22,7 +22,7 @@ class ReturnWaybillService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单退回登记(增)。入参:运单号 + 货主ID。
|
||||
* 未退登记(增)。入参:运单号 + 货主ID。
|
||||
* 同 warehouse_id + store_id + waybill_code 已存在时返回已有记录(幂等)。
|
||||
*
|
||||
* @param {Object} params 登记参数。
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -209,7 +209,10 @@ class StockoutOrderService extends MainService {
|
||||
orderLineNo: line.orderLineNo,
|
||||
ownerCode: line.ownerCode,
|
||||
itemCode: line.itemCode,
|
||||
itemId: line.itemId,
|
||||
// item_id 统一写入实际匹配到的 StockStore 主键 id(纯数字),
|
||||
// 避免调用方把「编码+名称」等非数字值放进 itemId 时写入 BIGINT 列
|
||||
// 触发 MySQL 严格模式报错(与 entry_order 建单口径一致)
|
||||
itemId: wmsStock.id,
|
||||
itemName: line.itemName,
|
||||
planQty,
|
||||
inventoryType: line.inventoryType,
|
||||
|
||||
@ -1,6 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const Service = require('egg').Service;
|
||||
const ExcelJS = require('exceljs');
|
||||
|
||||
/**
|
||||
* 将输入转换为时间戳。
|
||||
@ -614,9 +618,10 @@ class StorageReportService extends Service {
|
||||
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||||
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤)
|
||||
* @param {string} [keyword=''] 商品关键字(模糊匹配)
|
||||
* @param {Function} [onProgress=null] 进度回调:async ({ status, progress, currentCount, totalCount, message, result }) => void
|
||||
* @return {Promise<Object>} excel 上传结果
|
||||
*/
|
||||
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '') {
|
||||
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '', onProgress = null) {
|
||||
const { ctx, app } = this;
|
||||
const isStoreMode = searchMode === 'store';
|
||||
// 导出必须全量:显式传大分页,避免默认分页(pageSize=20)截断汇总与明细白名单
|
||||
@ -692,70 +697,29 @@ class StorageReportService extends Service {
|
||||
const detailReceivingIdSelectSql = isBySpace ? 'NULL AS receiving_id' : 't.receiving_id';
|
||||
const detailEntryOrderIdSelectSql = isBySpace ? 'NULL AS entry_order_id' : 't.entry_order_id';
|
||||
|
||||
const detailRows = await ctx.model.query(`
|
||||
SELECT
|
||||
t.id,
|
||||
t.created_at,
|
||||
t.transaction_type,
|
||||
t.store_id,
|
||||
t.warehouse_id,
|
||||
t.stock_id,
|
||||
${detailSpaceSelectSql},
|
||||
t.quantity,
|
||||
t.before_quantity,
|
||||
t.after_quantity,
|
||||
t.before_locked_quantity,
|
||||
t.after_locked_quantity,
|
||||
t.batch_no,
|
||||
${detailInventoryTypeSelectSql},
|
||||
t.order_type,
|
||||
t.order_no,
|
||||
t.order_id,
|
||||
${detailReceivingIdSelectSql},
|
||||
${detailEntryOrderIdSelectSql},
|
||||
t.operator_name,
|
||||
t.remark
|
||||
FROM ${detailTransactionTable} t
|
||||
WHERE ${whereClauses.join(' AND ')}
|
||||
ORDER BY t.created_at ASC, t.id ASC
|
||||
`, {
|
||||
replacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
const progressHandler = typeof onProgress === 'function' ? onProgress : async () => {};
|
||||
|
||||
const safeDetailRows = Array.isArray(detailRows) ? detailRows : [];
|
||||
const detailStockIds = [ ...new Set(safeDetailRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const detailStoreIds = [ ...new Set(safeDetailRows.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const detailSpaceIds = [ ...new Set(safeDetailRows.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const detailEntryOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.entry_order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const detailOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
|
||||
const summaryStoreIds = [ ...new Set(summaryList.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const summarySpaceIds = isBySpace
|
||||
? [ ...new Set(summaryList.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ]
|
||||
: [];
|
||||
|
||||
// 货主模式:从流水明细按订单ID收集所属仓库,用于运单查询强制同仓校验
|
||||
const detailOrderWarehouseMap = new Map();
|
||||
for (const item of safeDetailRows) {
|
||||
const orderId = Number(item.order_id);
|
||||
const rowWarehouseId = Number(item.warehouse_id);
|
||||
if (Number.isInteger(orderId) && orderId > 0 && Number.isInteger(rowWarehouseId) && rowWarehouseId > 0) {
|
||||
detailOrderWarehouseMap.set(orderId, rowWarehouseId);
|
||||
// 明细总数:仅用于进度展示,COUNT 一次(秒级)
|
||||
const totalCountRows = await ctx.model.query(
|
||||
`SELECT COUNT(*) AS cnt FROM ${detailTransactionTable} t WHERE ${whereClauses.join(' AND ')}`,
|
||||
{
|
||||
replacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
}
|
||||
);
|
||||
const detailTotalCount = Array.isArray(totalCountRows) && totalCountRows.length > 0
|
||||
? Number(totalCountRows[0].cnt)
|
||||
: 0;
|
||||
|
||||
const maps = await this.loadReportReferenceMaps({
|
||||
stockIds: [ ...new Set([ ...summaryStockIds, ...detailStockIds ]) ],
|
||||
storeIds: [ ...new Set([ ...summaryStoreIds, ...detailStoreIds ]) ],
|
||||
spaceIds: [ ...new Set([ ...summarySpaceIds, ...detailSpaceIds ]) ],
|
||||
includeBarcode: true,
|
||||
entryOrderIds: detailEntryOrderIds,
|
||||
orderIds: detailOrderIds,
|
||||
warehouseId,
|
||||
orderWarehouseMap: detailOrderWarehouseMap,
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: detailTotalCount > 0 ? 5 : 90,
|
||||
currentCount: 0,
|
||||
totalCount: detailTotalCount,
|
||||
message: detailTotalCount > 0 ? `已命中 ${detailTotalCount} 条变更记录,开始导出` : '未命中变更记录,开始生成文件',
|
||||
});
|
||||
|
||||
// 汇总 sheet 数据(汇总量小,全内存构建)
|
||||
const summaryColumns = [
|
||||
{ header: '开始时间', key: 'start_time' },
|
||||
{ header: '结束时间', key: 'end_time' },
|
||||
@ -802,58 +766,6 @@ class StorageReportService extends Service {
|
||||
end_total: toNumber(item.end_total),
|
||||
}));
|
||||
|
||||
const detailSheetRows = safeDetailRows.map(item => {
|
||||
const stockId = toNumber(item.stock_id);
|
||||
const storeId = toNumber(item.store_id);
|
||||
const stock = maps.stockMap.get(stockId) || {};
|
||||
const store = maps.storeMap.get(storeId) || {};
|
||||
const barcodeSet = maps.barcodeMap.get(stockId);
|
||||
|
||||
const entryOrderId = toNumber(item.entry_order_id);
|
||||
const entryOrder = entryOrderId > 0 ? (maps.entryOrderMap.get(entryOrderId) || {}) : {};
|
||||
const isQimenEntry = entryOrder.source_type === 'QM';
|
||||
|
||||
const orderId = toNumber(item.order_id);
|
||||
const orderDelivery = orderId > 0 ? (maps.orderDeliveryMap.get(orderId) || {}) : {};
|
||||
const waybillCode = maps.orderExpressMap.get(orderId) || '';
|
||||
|
||||
// 运单号:出库取 order_express.waybill_code,入库取 entry_order.express_code
|
||||
const generalWaybillNo = waybillCode
|
||||
|| (entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : '');
|
||||
|
||||
return {
|
||||
created_at: formatDateTime(item.created_at),
|
||||
transaction_type: formatTransactionType(item.transaction_type),
|
||||
store_id: storeId,
|
||||
store_name: store.company_name || '',
|
||||
store_remask: maps.storeWarehouseMap.get(storeId) || '',
|
||||
stock_id: stockId,
|
||||
item_code: stock.item_code || '',
|
||||
item_name: stock.item_name || '',
|
||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||
quantity: toNumber(item.quantity),
|
||||
before_quantity: toNumber(item.before_quantity),
|
||||
after_quantity: toNumber(item.after_quantity),
|
||||
before_locked_quantity: toNumber(item.before_locked_quantity),
|
||||
after_locked_quantity: toNumber(item.after_locked_quantity),
|
||||
batch_no: item.batch_no || '',
|
||||
inventory_type: item.inventory_type || '',
|
||||
order_type: item.order_type || '',
|
||||
order_no: item.order_no || '',
|
||||
order_id: orderId,
|
||||
receiving_id: toNumber(item.receiving_id),
|
||||
entry_order_id: entryOrderId,
|
||||
operator_name: item.operator_name || '',
|
||||
remark: item.remark || '',
|
||||
// 新增字段
|
||||
qimen_entry_order_code: isQimenEntry ? String(entryOrder.entry_order_code || '').trim() : '',
|
||||
platform_trade_no: String(orderDelivery.source_order_codes || item.order_no || '').trim(),
|
||||
entry_order_waybill_no: entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : '',
|
||||
entry_order_express_company: entryOrderId > 0 ? String(entryOrder.logistics_name || '').trim() : '',
|
||||
waybill_no: String(generalWaybillNo || '').trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const detailColumns = [
|
||||
{ header: '时间', key: 'created_at' },
|
||||
{ header: '类型', key: 'transaction_type' },
|
||||
@ -884,23 +796,221 @@ class StorageReportService extends Service {
|
||||
{ header: '备注', key: 'remark' },
|
||||
];
|
||||
|
||||
return await ctx.service.systems.excel.generateAndUpload({
|
||||
filename: this.buildExportFilename(startTime, endTime),
|
||||
dir: `exports/storage/report/${warehouseId || storeId || 'common'}`,
|
||||
category: 'document',
|
||||
sheets: [
|
||||
{
|
||||
name: '汇总',
|
||||
columns: summaryColumns,
|
||||
rows: summarySheetRows,
|
||||
},
|
||||
{
|
||||
name: '变更记录',
|
||||
columns: detailColumns,
|
||||
rows: detailSheetRows,
|
||||
},
|
||||
],
|
||||
});
|
||||
// 明细游标分页:按主键 id 升序分批拉取(id 自增序≈插入序),
|
||||
// 流式写入 ExcelJS stream,避免一次性把全部明细与单元格留在内存。
|
||||
const detailBatchSize = 5000;
|
||||
const filename = this.buildExportFilename(startTime, endTime);
|
||||
let tempDir = null;
|
||||
let workbook = null;
|
||||
let currentCount = 0;
|
||||
let cursorId = 0;
|
||||
|
||||
try {
|
||||
tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'wms-stock-report-export-'));
|
||||
const filePath = path.join(tempDir, filename);
|
||||
workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||||
filename: filePath,
|
||||
useStyles: false,
|
||||
useSharedStrings: false,
|
||||
});
|
||||
|
||||
const summaryWorksheet = workbook.addWorksheet('汇总');
|
||||
summaryWorksheet.columns = summaryColumns.map(column => ({ header: column.header, key: column.key }));
|
||||
for (const row of summarySheetRows) {
|
||||
summaryWorksheet.addRow(row);
|
||||
}
|
||||
summaryWorksheet.commit();
|
||||
|
||||
const detailWorksheet = workbook.addWorksheet('变更记录');
|
||||
detailWorksheet.columns = detailColumns.map(column => ({ header: column.header, key: column.key }));
|
||||
|
||||
for (;;) {
|
||||
const batchReplacements = { ...replacements, cursorId };
|
||||
const batchWhereClauses = [ ...whereClauses, 't.id > :cursorId' ];
|
||||
const batchRows = await ctx.model.query(`
|
||||
SELECT
|
||||
t.id,
|
||||
t.created_at,
|
||||
t.transaction_type,
|
||||
t.store_id,
|
||||
t.warehouse_id,
|
||||
t.stock_id,
|
||||
${detailSpaceSelectSql},
|
||||
t.quantity,
|
||||
t.before_quantity,
|
||||
t.after_quantity,
|
||||
t.before_locked_quantity,
|
||||
t.after_locked_quantity,
|
||||
t.batch_no,
|
||||
${detailInventoryTypeSelectSql},
|
||||
t.order_type,
|
||||
t.order_no,
|
||||
t.order_id,
|
||||
${detailReceivingIdSelectSql},
|
||||
${detailEntryOrderIdSelectSql},
|
||||
t.operator_name,
|
||||
t.remark
|
||||
FROM ${detailTransactionTable} t
|
||||
WHERE ${batchWhereClauses.join(' AND ')}
|
||||
ORDER BY t.id ASC
|
||||
LIMIT ${detailBatchSize}
|
||||
`, {
|
||||
replacements: batchReplacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
|
||||
const safeBatchRows = Array.isArray(batchRows) ? batchRows : [];
|
||||
if (safeBatchRows.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
// 本批富化:仅针对本批涉及的商品/货主/库位/入库单/订单加载映射
|
||||
const batchStockIds = [ ...new Set(safeBatchRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const batchStoreIds = [ ...new Set(safeBatchRows.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const batchSpaceIds = [ ...new Set(safeBatchRows.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const batchEntryOrderIds = [ ...new Set(safeBatchRows.map(item => Number(item.entry_order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const batchOrderIds = [ ...new Set(safeBatchRows.map(item => Number(item.order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
|
||||
// 货主模式:从流水明细按订单ID收集所属仓库,用于运单查询强制同仓校验
|
||||
const batchOrderWarehouseMap = new Map();
|
||||
for (const item of safeBatchRows) {
|
||||
const orderId = Number(item.order_id);
|
||||
const rowWarehouseId = Number(item.warehouse_id);
|
||||
if (Number.isInteger(orderId) && orderId > 0 && Number.isInteger(rowWarehouseId) && rowWarehouseId > 0) {
|
||||
batchOrderWarehouseMap.set(orderId, rowWarehouseId);
|
||||
}
|
||||
}
|
||||
|
||||
const maps = await this.loadReportReferenceMaps({
|
||||
stockIds: batchStockIds,
|
||||
storeIds: batchStoreIds,
|
||||
spaceIds: batchSpaceIds,
|
||||
includeBarcode: true,
|
||||
entryOrderIds: batchEntryOrderIds,
|
||||
orderIds: batchOrderIds,
|
||||
warehouseId,
|
||||
orderWarehouseMap: batchOrderWarehouseMap,
|
||||
});
|
||||
|
||||
let lastRow = null;
|
||||
for (const item of safeBatchRows) {
|
||||
const exportRow = this.buildDetailExportRow(item, maps);
|
||||
lastRow = detailWorksheet.addRow(exportRow);
|
||||
currentCount += 1;
|
||||
const rowId = Number(item.id);
|
||||
if (Number.isInteger(rowId) && rowId > cursorId) {
|
||||
cursorId = rowId;
|
||||
}
|
||||
}
|
||||
// 行级 commit:仅 flush 到当前批次末行(worksheet.commit 是终态,不能在中间调用)
|
||||
if (lastRow) {
|
||||
lastRow.commit();
|
||||
}
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: detailTotalCount > 0
|
||||
? Math.min(95, Math.max(5, Math.round(5 + (currentCount / detailTotalCount) * 90)))
|
||||
: 95,
|
||||
currentCount,
|
||||
totalCount: detailTotalCount,
|
||||
message: detailTotalCount > 0 ? `已完成 ${currentCount}/${detailTotalCount} 条变更记录` : '变更记录生成完成',
|
||||
});
|
||||
|
||||
// 本批不满一页说明已到末尾,避免再发一次空查询
|
||||
if (safeBatchRows.length < detailBatchSize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
detailWorksheet.commit();
|
||||
await workbook.commit();
|
||||
|
||||
const uploadResult = await ctx.service.systems.excel.uploadExistingFile({
|
||||
filePath,
|
||||
filename,
|
||||
dir: `exports/storage/report/${warehouseId || storeId || 'common'}`,
|
||||
category: 'document',
|
||||
});
|
||||
|
||||
await progressHandler({
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
currentCount,
|
||||
totalCount: detailTotalCount,
|
||||
message: '导出任务完成',
|
||||
result: uploadResult,
|
||||
});
|
||||
|
||||
return uploadResult;
|
||||
} catch (error) {
|
||||
if (workbook && workbook.stream && typeof workbook.stream.destroy === 'function') {
|
||||
workbook.stream.destroy();
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
await fs.promises.rm(tempDir, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一条流水明细行映射为导出 sheet 行。
|
||||
* @param {Object} item 流水明细行
|
||||
* @param {Object} maps 名称映射集合(loadReportReferenceMaps 返回值)
|
||||
* @return {Object} 导出 sheet 行
|
||||
*/
|
||||
buildDetailExportRow(item, maps = {}) {
|
||||
const stockId = toNumber(item.stock_id);
|
||||
const storeId = toNumber(item.store_id);
|
||||
const stock = maps.stockMap && maps.stockMap.get(stockId) || {};
|
||||
const store = maps.storeMap && maps.storeMap.get(storeId) || {};
|
||||
const barcodeSet = maps.barcodeMap ? maps.barcodeMap.get(stockId) : null;
|
||||
|
||||
const entryOrderId = toNumber(item.entry_order_id);
|
||||
const entryOrder = entryOrderId > 0 && maps.entryOrderMap ? (maps.entryOrderMap.get(entryOrderId) || {}) : {};
|
||||
const isQimenEntry = entryOrder.source_type === 'QM';
|
||||
|
||||
const orderId = toNumber(item.order_id);
|
||||
const orderDelivery = orderId > 0 && maps.orderDeliveryMap ? (maps.orderDeliveryMap.get(orderId) || {}) : {};
|
||||
const waybillCode = maps.orderExpressMap ? (maps.orderExpressMap.get(orderId) || '') : '';
|
||||
|
||||
// 运单号:出库取 order_express.waybill_code,入库取 entry_order.express_code
|
||||
const generalWaybillNo = waybillCode
|
||||
|| (entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : '');
|
||||
|
||||
return {
|
||||
created_at: formatDateTime(item.created_at),
|
||||
transaction_type: formatTransactionType(item.transaction_type),
|
||||
store_id: storeId,
|
||||
store_name: store.company_name || '',
|
||||
store_remask: maps.storeWarehouseMap ? (maps.storeWarehouseMap.get(storeId) || '') : '',
|
||||
stock_id: stockId,
|
||||
item_code: stock.item_code || '',
|
||||
item_name: stock.item_name || '',
|
||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||
quantity: toNumber(item.quantity),
|
||||
before_quantity: toNumber(item.before_quantity),
|
||||
after_quantity: toNumber(item.after_quantity),
|
||||
before_locked_quantity: toNumber(item.before_locked_quantity),
|
||||
after_locked_quantity: toNumber(item.after_locked_quantity),
|
||||
batch_no: item.batch_no || '',
|
||||
inventory_type: item.inventory_type || '',
|
||||
order_type: item.order_type || '',
|
||||
order_no: item.order_no || '',
|
||||
order_id: orderId,
|
||||
receiving_id: toNumber(item.receiving_id),
|
||||
entry_order_id: entryOrderId,
|
||||
operator_name: item.operator_name || '',
|
||||
remark: item.remark || '',
|
||||
// 新增字段
|
||||
qimen_entry_order_code: isQimenEntry ? String(entryOrder.entry_order_code || '').trim() : '',
|
||||
platform_trade_no: String(orderDelivery.source_order_codes || item.order_no || '').trim(),
|
||||
entry_order_waybill_no: entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : '',
|
||||
entry_order_express_company: entryOrderId > 0 ? String(entryOrder.logistics_name || '').trim() : '',
|
||||
waybill_no: String(generalWaybillNo || '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
702
app/service/systems/warehouse_panel.js
Normal file
702
app/service/systems/warehouse_panel.js
Normal file
@ -0,0 +1,702 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
// 面板数据缓存 TTL(秒):缓存期内直接复用;过期视为无最后更新时间,重新聚合并兜底设置
|
||||
const PANEL_CACHE_TTL_SECONDS = 300;
|
||||
// 缓存键前缀(按仓库存储:{prefix}:lastChangeAt:{warehouseId})
|
||||
const PANEL_CACHE_KEY_PREFIX = 'index:warehousePanel';
|
||||
|
||||
// 订单履约链路环节定义(每环节按未/已两个数值输出;field 为订单分表状态字段)
|
||||
const FULFILLMENT_STAGES = [
|
||||
{ key: 'alloc', icon: 'alloc', undone: '未分配', done: '已分配', field: 'post_status' },
|
||||
{ key: 'print', icon: 'print', undone: '未打印', done: '已打印', field: 'print_status' },
|
||||
{ key: 'pick', icon: 'pick', undone: '未拣货', done: '已拣货', field: 'pick_status' },
|
||||
{ key: 'recheck', icon: 'recheck', undone: '未复核', done: '已复核', field: 'recheck_status' },
|
||||
{ key: 'pack', icon: 'pack', undone: '未打包', done: '已打包', field: 'pack_status' },
|
||||
{ key: 'ship', icon: 'ship', undone: '待出库', done: '已出库', field: 'outbound_status' },
|
||||
];
|
||||
|
||||
// 今日订单趋势固定横轴(08:00-18:00 共 11 点)
|
||||
const TREND_HOURS = [ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ];
|
||||
|
||||
// 拣货任务活跃状态(排除 9=已取消)
|
||||
const PICK_TASK_ACTIVE_STATUSES = [ 0, 1, 2, 3 ];
|
||||
|
||||
class WarehousePanelService extends Service {
|
||||
/**
|
||||
* 面板缓存键(按仓库存储)。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getPanelCacheKey(warehouseId) {
|
||||
return `${PANEL_CACHE_KEY_PREFIX}:lastChangeAt:${warehouseId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取面板数据。
|
||||
*
|
||||
* 最后更新时间一般由外部驱动(业务数据变化时写入缓存键的 last_change_at);
|
||||
* 本方法仅在缓存中没有最后更新时间时,才查库拉取数据并兜底设置最后更新时间。
|
||||
*
|
||||
* 拉取逻辑:
|
||||
* - 缓存有最后更新时间:is_change=false(传入时间戳不小于缓存时间戳)时返回空 data(节约流量);
|
||||
* is_change=true 时优先输出缓存数据;缓存无数据(外部只驱动了时间戳)则查库补数据并保留外部时间戳;
|
||||
* - 缓存无最后更新时间(未命中/过期):查库拉数据并设置最后更新时间。
|
||||
*
|
||||
* is_change 语义:传入时间戳小于缓存最后更改时间戳时为 true。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {Object} [options] 选项
|
||||
* @param {number} [options.lastChangeAt=0] 客户端持有的最后更改时间戳
|
||||
* @return {Promise<Object>} 组装后的面板数据(含 title/fulfillment/stageOverview 等数据块)
|
||||
*/
|
||||
async getPanelData(warehouseId, options = {}) {
|
||||
const lastChangeAt = Number(options.lastChangeAt || 0);
|
||||
|
||||
const cacheKey = this.getPanelCacheKey(warehouseId);
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
|
||||
// 缓存有最后更新时间
|
||||
if (cached && cached.last_change_at) {
|
||||
const cachedTs = Number(cached.last_change_at);
|
||||
const isChange = lastChangeAt < cachedTs;
|
||||
|
||||
// 未变化:空 data 节约流量,不查库
|
||||
if (!isChange) {
|
||||
return { is_change: false, last_change_at: cachedTs, data: {} };
|
||||
}
|
||||
|
||||
// 已有缓存数据:直接输出,不查库
|
||||
if (cached.data) {
|
||||
return { is_change: true, last_change_at: cachedTs, data: cached.data };
|
||||
}
|
||||
|
||||
// 外部只驱动了最后更新时间(无缓存数据):查库拉数据补入缓存,保留外部时间戳
|
||||
const data = await this.buildPanelData(warehouseId);
|
||||
await this.app.setCacheAsync(cacheKey, { last_change_at: cachedTs, data }, PANEL_CACHE_TTL_SECONDS);
|
||||
return { is_change: true, last_change_at: cachedTs, data };
|
||||
}
|
||||
|
||||
// 缓存无最后更新时间:查库拉数据并设置最后更新时间
|
||||
const data = await this.buildPanelData(warehouseId);
|
||||
const nowTs = Math.floor(Date.now() / 1000);
|
||||
await this.app.setCacheAsync(cacheKey, { last_change_at: nowTs, data }, PANEL_CACHE_TTL_SECONDS);
|
||||
return { is_change: true, last_change_at: nowTs, data };
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合全部面板数据块。
|
||||
*
|
||||
* 各数据块独立容错:单块查询失败时该块返回 null(前端按字段缺失处理),不影响其他块。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @return {Promise<Object>} 组装后的面板数据(含 title/fulfillment/stageOverview 等数据块)
|
||||
*/
|
||||
async buildPanelData(warehouseId) {
|
||||
const { ctx } = this;
|
||||
const { model } = ctx;
|
||||
const { Op } = this.app.Sequelize;
|
||||
|
||||
const now = new Date();
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const tomorrowStart = new Date(todayStart.getTime() + 86400000);
|
||||
|
||||
const factory = model.OrderDeliveryFactory;
|
||||
const [ currentModel, dispatchModel ] = await Promise.all([
|
||||
factory.getCurrentModel(warehouseId),
|
||||
factory.getDispatchModel(warehouseId),
|
||||
]);
|
||||
const currentTableName = currentModel.getTableName();
|
||||
const dispatchTableName = dispatchModel.getTableName();
|
||||
|
||||
const pendingBase = {
|
||||
step: { [Op.in]: [ 1, 2, 3 ] },
|
||||
outbound_status: { [Op.ne]: 'padding' },
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
};
|
||||
|
||||
const blocks = await Promise.all([
|
||||
this.queryFulfillment(currentModel, pendingBase).catch(error => this.logBlockError('fulfillment', error)),
|
||||
this.queryStageOverview(warehouseId, currentModel, pendingBase, todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('stageOverview', error)),
|
||||
this.queryB2b(currentModel, dispatchModel, todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('b2b', error)),
|
||||
this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, [ 1, 5 ], todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('groupPicking', error)),
|
||||
this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, [ 2, 3, 4 ], todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('scatterPicking', error)),
|
||||
this.queryPackingPersonal(warehouseId, todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('packingRank', error)),
|
||||
this.queryTrend(currentModel, pendingBase, todayStart)
|
||||
.catch(error => this.logBlockError('trend', error)),
|
||||
this.queryWeeklyIntercept(currentModel, dispatchModel, todayStart)
|
||||
.catch(error => this.logBlockError('weeklyEfficiency', error)),
|
||||
]);
|
||||
|
||||
const [ fulfillment, stageOverview, b2b, groupPicking, scatterPicking, packingRank, trend, weeklyEfficiency ] = blocks;
|
||||
|
||||
const data = {
|
||||
title: ctx.user?.store_name || '',
|
||||
fulfillment,
|
||||
stageOverview,
|
||||
b2b,
|
||||
groupPicking,
|
||||
scatterPicking,
|
||||
packingRank,
|
||||
trend,
|
||||
weeklyEfficiency,
|
||||
};
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录数据块聚合失败日志(返回 null,前端按字段缺失处理)。
|
||||
*
|
||||
* @param {string} blockName 数据块名
|
||||
* @param {Error} error 异常
|
||||
* @return {null} 恒返回 null(调用方将对应数据块置空)
|
||||
*/
|
||||
logBlockError(blockName, error) {
|
||||
const logger = this.ctx.logger;
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn(`[WarehousePanel] 数据块聚合失败,已跳过: ${blockName}`, error.message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单履约链路:6 个环节 × 未/已 + 分母。
|
||||
*
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} pendingBase 待处理基础过滤
|
||||
* @return {Promise<Object>} { total, items }
|
||||
*/
|
||||
async queryFulfillment(currentModel, pendingBase) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
|
||||
const totalCountPromise = currentModel.count({ where: pendingBase });
|
||||
const stageCounts = await Promise.all(FULFILLMENT_STAGES.map(async stage => {
|
||||
const undone = await currentModel.count({
|
||||
where: {
|
||||
...pendingBase,
|
||||
[Op.or]: [
|
||||
{ [stage.field]: { [Op.ne]: 'fin' } },
|
||||
{ [stage.field]: { [Op.is]: null } },
|
||||
],
|
||||
},
|
||||
});
|
||||
const done = await currentModel.count({
|
||||
where: { ...pendingBase, [stage.field]: 'fin' },
|
||||
});
|
||||
return { undone, done };
|
||||
}));
|
||||
|
||||
const total = await totalCountPromise;
|
||||
const items = [];
|
||||
FULFILLMENT_STAGES.forEach((stage, index) => {
|
||||
const counts = stageCounts[index] || { undone: 0, done: 0 };
|
||||
items.push({ label: stage.undone, icon: stage.icon, value: counts.undone || 0 });
|
||||
items.push({ label: stage.done, icon: stage.icon, value: counts.done || 0 });
|
||||
});
|
||||
|
||||
return { total: total || 0, items };
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一条 count 原生 SQL 并返回计数。
|
||||
*
|
||||
* @param {string} sql SQL 文本
|
||||
* @param {Object} replacements 替换参数
|
||||
* @return {Promise<number>} 计数结果
|
||||
*/
|
||||
async countSql(sql, replacements) {
|
||||
const rows = await this.ctx.model.query(sql, {
|
||||
replacements,
|
||||
type: this.ctx.model.QueryTypes.SELECT,
|
||||
});
|
||||
const first = Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
|
||||
return Number(first && first.cnt || 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 作业环节概览:总量 + 拦截 + 5 张环节卡(缺数据源的字段不写入)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} pendingBase 待处理基础过滤
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { totalOrders, interceptOrders, stages }
|
||||
*/
|
||||
async queryStageOverview(warehouseId, currentModel, pendingBase, todayStart, tomorrowStart) {
|
||||
const { model } = this.ctx;
|
||||
const { Op } = this.app.Sequelize;
|
||||
const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart };
|
||||
|
||||
const [
|
||||
totalPending,
|
||||
todayOutbound,
|
||||
interceptOrders,
|
||||
receivingToday,
|
||||
receivingDoing,
|
||||
shelfDoing,
|
||||
pickToday,
|
||||
pickDoing,
|
||||
pickAbnormal,
|
||||
recheckToday,
|
||||
recheckDoing,
|
||||
recheckAbnormal,
|
||||
packToday,
|
||||
packDoing,
|
||||
packAbnormal,
|
||||
] = await Promise.all([
|
||||
currentModel.count({ where: pendingBase }),
|
||||
currentModel.count({
|
||||
where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: todayRange },
|
||||
}),
|
||||
currentModel.count({
|
||||
where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } },
|
||||
}),
|
||||
model.Receiving.count({ where: { warehouse_id: warehouseId, created_at: todayRange } }),
|
||||
model.Receiving.count({ where: { warehouse_id: warehouseId, status: 'receiving' } }),
|
||||
model.Receiving.count({
|
||||
where: { warehouse_id: warehouseId, storage_status: { [Op.in]: [ 'waiting', 'partial' ] } },
|
||||
}),
|
||||
this.countSql(
|
||||
`SELECT COUNT(*) AS cnt FROM wms_wave_pick_task
|
||||
WHERE warehouse_id = :warehouseId AND status IN (:statuses)
|
||||
AND finish_time >= :start AND finish_time < :end`,
|
||||
{ warehouseId, statuses: [ 2, 3 ], start: todayStart, end: tomorrowStart }
|
||||
),
|
||||
this.countSql(
|
||||
`SELECT COUNT(*) AS cnt FROM wms_wave_pick_task
|
||||
WHERE warehouse_id = :warehouseId AND status = 1`,
|
||||
{ warehouseId }
|
||||
),
|
||||
currentModel.count({ where: { ...pendingBase, pick_status: 'error' } }),
|
||||
currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }),
|
||||
model.WaveBatch.count({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
recheck_start_time: { [Op.not]: null },
|
||||
wave_status: { [Op.in]: [ 3, 4 ] },
|
||||
},
|
||||
}),
|
||||
currentModel.count({ where: { ...pendingBase, recheck_status: 'error' } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, create_time: todayRange } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, status: 1 } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, status: 3 } }),
|
||||
]);
|
||||
|
||||
const stages = [
|
||||
{
|
||||
key: 'receiving',
|
||||
name: '收货',
|
||||
icon: 'car',
|
||||
tone: 'green',
|
||||
today: receivingToday,
|
||||
doing: receivingDoing,
|
||||
},
|
||||
{
|
||||
key: 'shelf',
|
||||
name: '上架',
|
||||
icon: 'rack',
|
||||
tone: 'amber',
|
||||
doing: shelfDoing,
|
||||
},
|
||||
{
|
||||
key: 'pick',
|
||||
name: '拣货',
|
||||
icon: 'cart',
|
||||
tone: 'blue',
|
||||
today: pickToday,
|
||||
doing: pickDoing,
|
||||
abnormal: pickAbnormal,
|
||||
},
|
||||
{
|
||||
key: 'recheck',
|
||||
name: '复核',
|
||||
icon: 'scan',
|
||||
tone: 'violet',
|
||||
today: recheckToday,
|
||||
doing: recheckDoing,
|
||||
abnormal: recheckAbnormal,
|
||||
},
|
||||
{
|
||||
key: 'pack',
|
||||
name: '打包',
|
||||
icon: 'box',
|
||||
tone: 'cyan',
|
||||
today: packToday,
|
||||
doing: packDoing,
|
||||
abnormal: packAbnormal,
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
totalOrders: totalPending + todayOutbound,
|
||||
interceptOrders,
|
||||
stages,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* B2B 今日出库统计(常用表 + 配送表双表聚合)。
|
||||
*
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} dispatchModel 配送分表模型
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { orders, goods, sku }
|
||||
*/
|
||||
async queryB2b(currentModel, dispatchModel, todayStart, tomorrowStart) {
|
||||
const { Op, fn, col, literal } = this.app.Sequelize;
|
||||
const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart };
|
||||
const where = {
|
||||
is_b2b: 'Y',
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
delivery_time: todayRange,
|
||||
};
|
||||
const attrs = [
|
||||
[ fn('COUNT', literal('*')), 'orders' ],
|
||||
[ fn('SUM', col('items_total')), 'goods' ],
|
||||
[ fn('SUM', col('items_count')), 'sku' ],
|
||||
];
|
||||
|
||||
const [ currentAgg, dispatchAgg ] = await Promise.all([
|
||||
currentModel.findOne({ attributes: attrs, where, raw: true }),
|
||||
dispatchModel.findOne({ attributes: attrs, where, raw: true }),
|
||||
]);
|
||||
|
||||
return {
|
||||
orders: Number(currentAgg?.orders || 0) + Number(dispatchAgg?.orders || 0),
|
||||
goods: Number(currentAgg?.goods || 0) + Number(dispatchAgg?.goods || 0),
|
||||
sku: Number(currentAgg?.sku || 0) + Number(dispatchAgg?.sku || 0),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 拣货统计块(团购 pick_mode=1,5;散单 pick_mode=2,3,4)。
|
||||
*
|
||||
* 窗口:今日创建(create_time 今日)且未取消的任务;
|
||||
* orders/wave 取任务快照(order_count/wave_count);
|
||||
* goods/sku 经 wms_wave_pick_task_order 关联订单分表快照(items_total/items_count)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {string} currentTableName 常用分表名
|
||||
* @param {string} dispatchTableName 配送分表名
|
||||
* @param {Array<number>} pickModes 拣货模式集合
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { orders, goods, sku, wave, top }
|
||||
*/
|
||||
async queryPickingBlock(warehouseId, currentTableName, dispatchTableName, pickModes, todayStart, tomorrowStart) {
|
||||
const { model } = this.ctx;
|
||||
const { QueryTypes } = model;
|
||||
|
||||
const replacements = {
|
||||
warehouseId,
|
||||
pickModes,
|
||||
activeStatuses: PICK_TASK_ACTIVE_STATUSES,
|
||||
start: todayStart,
|
||||
end: tomorrowStart,
|
||||
};
|
||||
|
||||
const taskWindowWhere = `
|
||||
t.warehouse_id = :warehouseId AND t.pick_mode IN (:pickModes)
|
||||
AND t.create_time >= :start AND t.create_time < :end
|
||||
AND t.status IN (:activeStatuses)
|
||||
`;
|
||||
|
||||
const [ summaryRows, topRows ] = await Promise.all([
|
||||
model.query(`
|
||||
SELECT COUNT(*) AS task_count, COALESCE(SUM(order_count), 0) AS orders, COALESCE(SUM(wave_count), 0) AS waves
|
||||
FROM wms_wave_pick_task t
|
||||
WHERE ${taskWindowWhere}
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(`
|
||||
SELECT t.pick_user_id AS user_id, t.pick_user_name AS name,
|
||||
COALESCE(SUM(t.order_count), 0) AS orders, COALESCE(SUM(t.wave_count), 0) AS waves
|
||||
FROM wms_wave_pick_task t
|
||||
WHERE ${taskWindowWhere}
|
||||
GROUP BY t.pick_user_id, t.pick_user_name
|
||||
ORDER BY orders DESC
|
||||
LIMIT 5
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const [ goodsSkuRows, topGoodsSkuRows ] = await this.queryPickingGoodsSku(
|
||||
currentTableName, dispatchTableName, taskWindowWhere, replacements
|
||||
);
|
||||
|
||||
const summary = Array.isArray(summaryRows) && summaryRows.length > 0 ? summaryRows[0] : {};
|
||||
const topGoodsSkuMap = new Map();
|
||||
(topGoodsSkuRows || []).forEach(row => {
|
||||
topGoodsSkuMap.set(String(row.user_id), { goods: Number(row.goods || 0), sku: Number(row.sku || 0) });
|
||||
});
|
||||
|
||||
const top = (topRows || []).map((row, index) => {
|
||||
const goodsSku = topGoodsSkuMap.get(String(row.user_id)) || { goods: 0, sku: 0 };
|
||||
return {
|
||||
rank: index + 1,
|
||||
name: row.name || '',
|
||||
orders: Number(row.orders || 0),
|
||||
goods: goodsSku.goods,
|
||||
sku: goodsSku.sku,
|
||||
wave: Number(row.waves || 0),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
orders: Number(summary.orders || 0),
|
||||
goods: Number(goodsSkuRows.goods || 0),
|
||||
sku: Number(goodsSkuRows.sku || 0),
|
||||
wave: Number(summary.waves || 0),
|
||||
top,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询拣货任务的 goods/sku(总量 + 按人分组),经任务订单关联表 join 订单分表。
|
||||
*
|
||||
* @param {string} currentTableName 常用分表名
|
||||
* @param {string} dispatchTableName 配送分表名
|
||||
* @param {string} taskWindowWhere 任务窗口 where 片段
|
||||
* @param {Object} replacements 替换参数
|
||||
* @return {Promise<Array<Object>>} [ 总量行, top 行数组 ]
|
||||
*/
|
||||
async queryPickingGoodsSku(currentTableName, dispatchTableName, taskWindowWhere, replacements) {
|
||||
const { model } = this.ctx;
|
||||
const { QueryTypes } = model;
|
||||
|
||||
const goodsSkuSelect = `
|
||||
SELECT COALESCE(SUM(od.items_total), 0) AS goods, COALESCE(SUM(od.items_count), 0) AS sku
|
||||
FROM wms_wave_pick_task t
|
||||
JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id
|
||||
JOIN \`${currentTableName}\` od ON od.id = pto.order_id AND od.status != 'cancel'
|
||||
WHERE ${taskWindowWhere}
|
||||
`;
|
||||
const goodsSkuSelectDispatch = goodsSkuSelect.replace(`\`${currentTableName}\``, `\`${dispatchTableName}\``);
|
||||
|
||||
const [ currentRows, dispatchRows ] = await Promise.all([
|
||||
model.query(goodsSkuSelect, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(goodsSkuSelectDispatch, { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const current = Array.isArray(currentRows) && currentRows.length > 0 ? currentRows[0] : {};
|
||||
const dispatch = Array.isArray(dispatchRows) && dispatchRows.length > 0 ? dispatchRows[0] : {};
|
||||
const totalGoodsSku = {
|
||||
goods: Number(current.goods || 0) + Number(dispatch.goods || 0),
|
||||
sku: Number(current.sku || 0) + Number(dispatch.sku || 0),
|
||||
};
|
||||
|
||||
const topGoodsSkuSelect = `
|
||||
SELECT t.pick_user_id AS user_id, COALESCE(SUM(od.items_total), 0) AS goods, COALESCE(SUM(od.items_count), 0) AS sku
|
||||
FROM wms_wave_pick_task t
|
||||
JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id
|
||||
JOIN \`${currentTableName}\` od ON od.id = pto.order_id AND od.status != 'cancel'
|
||||
WHERE ${taskWindowWhere}
|
||||
GROUP BY t.pick_user_id
|
||||
`;
|
||||
const topGoodsSkuSelectDispatch = topGoodsSkuSelect.replace(`\`${currentTableName}\``, `\`${dispatchTableName}\``);
|
||||
|
||||
const [ topCurrentRows, topDispatchRows ] = await Promise.all([
|
||||
model.query(topGoodsSkuSelect, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(topGoodsSkuSelectDispatch, { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const topGoodsSkuMap = new Map();
|
||||
[ ...(topCurrentRows || []), ...(topDispatchRows || []) ].forEach(row => {
|
||||
const key = String(row.user_id);
|
||||
const prev = topGoodsSkuMap.get(key) || { goods: 0, sku: 0 };
|
||||
topGoodsSkuMap.set(key, {
|
||||
goods: prev.goods + Number(row.goods || 0),
|
||||
sku: prev.sku + Number(row.sku || 0),
|
||||
});
|
||||
});
|
||||
|
||||
return [ totalGoodsSku, [ ...topGoodsSkuMap.entries() ].map(([ user_id, item ]) => ({ user_id, ...item })) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 打包个人排名(散单+团购任务合并,按打包员姓名聚合)。
|
||||
*
|
||||
* 口径:今日创建(create_time 今日)且非异常(status != 3)的任务;
|
||||
* 团购任务多人打包时同一任务计入多人(不折算)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { orders, goods, sku, wave, top }
|
||||
*/
|
||||
async queryPackingPersonal(warehouseId, todayStart, tomorrowStart) {
|
||||
const { model } = this.ctx;
|
||||
const { QueryTypes } = model;
|
||||
|
||||
const replacements = { warehouseId, start: todayStart, end: tomorrowStart };
|
||||
const taskWindowWhere = `
|
||||
pt.warehouse_id = :warehouseId AND pt.create_time >= :start AND pt.create_time < :end
|
||||
AND pt.status != 3 AND pt.deleted_at IS NULL
|
||||
`;
|
||||
|
||||
const [ summaryRows, topRows ] = await Promise.all([
|
||||
model.query(`
|
||||
SELECT COUNT(*) AS orders, COALESCE(SUM(pt.item_quantity), 0) AS goods,
|
||||
COALESCE(SUM(pt.sku_count), 0) AS sku,
|
||||
COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave
|
||||
FROM wms_pack_task pt
|
||||
WHERE ${taskWindowWhere}
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(`
|
||||
SELECT pp.account_name AS name, COUNT(*) AS orders, COALESCE(SUM(pt.item_quantity), 0) AS goods,
|
||||
COALESCE(SUM(pt.sku_count), 0) AS sku,
|
||||
COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave
|
||||
FROM wms_pack_task pt
|
||||
JOIN wms_pack_task_packer pp ON pp.pack_task_id = pt.id AND pp.deleted_at IS NULL
|
||||
WHERE ${taskWindowWhere}
|
||||
GROUP BY pp.account_name
|
||||
ORDER BY orders DESC
|
||||
LIMIT 5
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const summary = Array.isArray(summaryRows) && summaryRows.length > 0 ? summaryRows[0] : {};
|
||||
const top = (topRows || []).map((row, index) => ({
|
||||
rank: index + 1,
|
||||
name: row.name || '',
|
||||
orders: Number(row.orders || 0),
|
||||
goods: Number(row.goods || 0),
|
||||
sku: Number(row.sku || 0),
|
||||
wave: Number(row.wave || 0),
|
||||
}));
|
||||
|
||||
return {
|
||||
orders: Number(summary.orders || 0),
|
||||
goods: Number(summary.goods || 0),
|
||||
sku: Number(summary.sku || 0),
|
||||
wave: Number(summary.wave || 0),
|
||||
top,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 今日订单实时趋势(固定 08:00-18:00 共 11 点,按小时补零)。
|
||||
*
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} pendingBase 待处理基础过滤
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @return {Promise<Object>} { max, points }
|
||||
*/
|
||||
async queryTrend(currentModel, pendingBase, todayStart) {
|
||||
const { Op, fn, col, literal } = this.app.Sequelize;
|
||||
const now = new Date();
|
||||
|
||||
const rows = await currentModel.findAll({
|
||||
attributes: [
|
||||
[ fn('HOUR', col('create_at')), 'hour' ],
|
||||
[ fn('COUNT', literal('*')), 'count' ],
|
||||
],
|
||||
where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: now } },
|
||||
group: [ 'hour' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const hourMap = new Map();
|
||||
(rows || []).forEach(row => {
|
||||
hourMap.set(Number(row.hour), Number(row.count || 0));
|
||||
});
|
||||
|
||||
const points = TREND_HOURS.map(hour => ({
|
||||
label: `${String(hour).padStart(2, '0')}:00`,
|
||||
value: hourMap.get(hour) || 0,
|
||||
}));
|
||||
const peak = points.reduce((maxValue, point) => Math.max(maxValue, point.value), 0);
|
||||
const max = Math.max(Math.ceil(peak / 10) * 10, 10);
|
||||
|
||||
return { max, points };
|
||||
}
|
||||
|
||||
/**
|
||||
* 近 7 日拦截量按天统计(时间锚点:intercept_time,为空时回落 create_at)。
|
||||
*
|
||||
* 吞吐量(throughput)口径未定义,暂不输出;仅输出 days[].intercept。
|
||||
*
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} dispatchModel 配送分表模型
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @return {Promise<Object>} { days }
|
||||
*/
|
||||
async queryWeeklyIntercept(currentModel, dispatchModel, todayStart) {
|
||||
const { Op, fn, col, literal } = this.app.Sequelize;
|
||||
const sevenDaysAgo = new Date(todayStart.getTime() - 6 * 86400000);
|
||||
const tomorrowStart = new Date(todayStart.getTime() + 86400000);
|
||||
const anchor = fn('COALESCE', col('intercept_time'), col('create_at'));
|
||||
const where = {
|
||||
[Op.and]: [
|
||||
{ intercept_status: { [Op.not]: null, [Op.ne]: 'none' } },
|
||||
this.app.Sequelize.where(anchor, { [Op.gte]: sevenDaysAgo, [Op.lt]: tomorrowStart }),
|
||||
],
|
||||
};
|
||||
const attributes = [
|
||||
[ fn('DATE', anchor), 'day' ],
|
||||
[ fn('COUNT', literal('*')), 'count' ],
|
||||
];
|
||||
|
||||
const [ currentRows, dispatchRows ] = await Promise.all([
|
||||
currentModel.findAll({ attributes, where, group: [ 'day' ], raw: true }),
|
||||
dispatchModel.findAll({ attributes, where, group: [ 'day' ], raw: true }),
|
||||
]);
|
||||
|
||||
const dayMap = new Map();
|
||||
[ ...(currentRows || []), ...(dispatchRows || []) ].forEach(row => {
|
||||
const dayKey = this.normalizeDayKey(row.day);
|
||||
if (!dayKey) {
|
||||
return;
|
||||
}
|
||||
dayMap.set(dayKey, (dayMap.get(dayKey) || 0) + Number(row.count || 0));
|
||||
});
|
||||
|
||||
const days = [];
|
||||
for (let offset = 6; offset >= 0; offset--) {
|
||||
const day = new Date(todayStart.getTime() - offset * 86400000);
|
||||
const dayKey = this.formatDateKey(day);
|
||||
const label = `${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`;
|
||||
days.push({ label, intercept: dayMap.get(dayKey) || 0 });
|
||||
}
|
||||
|
||||
return { days };
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化日期分组键(DATE() 结果可能为 Date 对象或 'YYYY-MM-DD' 字符串)。
|
||||
*
|
||||
* @param {*} value 分组值
|
||||
* @return {string} 'YYYY-MM-DD'
|
||||
*/
|
||||
normalizeDayKey(value) {
|
||||
if (!value) {
|
||||
return '';
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return this.formatDateKey(value);
|
||||
}
|
||||
const text = String(value);
|
||||
return text.length >= 10 ? text.slice(0, 10) : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化为本地日期键 'YYYY-MM-DD'。
|
||||
*
|
||||
* @param {Date} date 日期
|
||||
* @return {string} 'YYYY-MM-DD'
|
||||
*/
|
||||
formatDateKey(date) {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehousePanelService;
|
||||
@ -7,8 +7,14 @@ const MainService = require('../main');
|
||||
const ACTIVE_WAVE_STATUSES = [ 0, 1 ];
|
||||
// 终结态:复核完成(与 recheckOrder 复核完成路径一致,使波次从 batchList 中自然消失)
|
||||
const CLOSED_WAVE_STATUS = 5;
|
||||
// 创建不足该分钟数的波次不参与自动终结,避免与创建事务并发误判
|
||||
const WAVE_MIN_AGE_MINUTES = 5;
|
||||
// 创建不足该分钟数的波次不参与自动终结,避免与创建事务并发误判。
|
||||
// 2026-10-09 事故:PDA 策略抓取建波(B2026100900660,07:04:04)后订单绑定延迟至 07:16:37
|
||||
// (窗口约 12 分钟),5 分钟门槛不够,波次在建波与订单绑定之间被误判为空而终结。
|
||||
// 提至 30 分钟,覆盖正常建波+绑定流程(含慢事务、请求重试、流程中断后补做)的窗口。
|
||||
const WAVE_MIN_AGE_MINUTES = 30;
|
||||
// 判空抽样核对条数:订单表判空但索引表仍有行的波次,按索引指向的订单抽样核对订单表
|
||||
// 是否存在这些行,用于识别「读偏」(分表重建/复制期间订单表读到半成品空表)。
|
||||
const WAVE_INDEX_PROBE_LIMIT = 50;
|
||||
// 单次 SQL IN 列表的波次数量上限
|
||||
const WAVE_ID_BATCH_SIZE = 500;
|
||||
// 判空二次确认:同一波次需连续两轮(间隔不小于该毫秒数)都判定为空,才允许终结。
|
||||
@ -92,7 +98,7 @@ class WaveBatchClosureService extends MainService {
|
||||
FROM wms_wave_batch
|
||||
WHERE wave_status IN (:waveStatuses)
|
||||
AND total_orders > 0
|
||||
AND create_time < (NOW() - INTERVAL ${WAVE_MIN_AGE_MINUTES} MINUTE)`,
|
||||
AND create_time < (UTC_TIMESTAMP() - INTERVAL ${WAVE_MIN_AGE_MINUTES} MINUTE)`,
|
||||
{
|
||||
replacements: { waveStatuses: ACTIVE_WAVE_STATUSES },
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
@ -121,6 +127,9 @@ class WaveBatchClosureService extends MainService {
|
||||
|
||||
const warehouseIds = Array.from(warehouseWaveMap.keys());
|
||||
const emptyWaves = [];
|
||||
const unboundWaves = [];
|
||||
const misreadWaves = [];
|
||||
const probeFailedWaves = [];
|
||||
|
||||
for (const warehouseId of warehouseIds) {
|
||||
const waves = warehouseWaveMap.get(warehouseId);
|
||||
@ -170,9 +179,91 @@ class WaveBatchClosureService extends MainService {
|
||||
continue;
|
||||
}
|
||||
|
||||
const finishedWaves = waves.filter(item => !existingWaveIds.has(item.waveId));
|
||||
if (finishedWaves.length > 0) {
|
||||
emptyWaves.push(...finishedWaves);
|
||||
// 交叉校验波次索引表:订单绑定与索引重建同事务,索引行是「订单曾绑定过」的强信号。
|
||||
// 订单表判空但索引非空 → 可能是正常离表(发货迁移不删索引),也可能是读偏,
|
||||
// 由后续抽样核对区分;订单表与索引表双空 → 订单从未绑定(建波中间态)或全量清空异常。
|
||||
const indexedWaveIds = new Set();
|
||||
let indexQueryFailed = false;
|
||||
for (let offset = 0; offset < waves.length; offset += WAVE_ID_BATCH_SIZE) {
|
||||
const batchWaves = waves.slice(offset, offset + WAVE_ID_BATCH_SIZE);
|
||||
const batchWaveIds = batchWaves.map(item => item.waveId);
|
||||
try {
|
||||
const indexRows = await ctx.model.query(
|
||||
`SELECT DISTINCT wave_id
|
||||
FROM wms_order_wave_index
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id IN (:waveIds)`,
|
||||
{
|
||||
replacements: {
|
||||
warehouseId,
|
||||
waveIds: batchWaveIds,
|
||||
},
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
for (const row of (Array.isArray(indexRows) ? indexRows : [])) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
if (Number.isInteger(waveId) && waveId > 0) {
|
||||
indexedWaveIds.add(waveId);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
indexQueryFailed = true;
|
||||
ctx.logger.warn(`[wave-batch-closure] 查询仓库 ${warehouseId} 波次索引表失败,跳过该仓库: ${error.message}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (indexQueryFailed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 分类判定
|
||||
for (const item of waves) {
|
||||
const { waveId } = item;
|
||||
if (existingWaveIds.has(waveId)) {
|
||||
continue; // 待处理表仍有订单,正常活动波次
|
||||
}
|
||||
if (!indexedWaveIds.has(waveId)) {
|
||||
// 订单表与索引表双空:订单从未绑定(建波与绑定之间的中间态)或全量清空异常,
|
||||
// 一律不自动终结(宁可漏关,不可误关),交由人工/后续流程处理。
|
||||
unboundWaves.push(item);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 订单表空但索引仍有行:抽样核对索引指向的订单是否真的已离开订单表。
|
||||
// 注意 MySQL 不支持 IN (SELECT ... LIMIT n),此处用 JOIN 派生表(FROM 子句 LIMIT 合法)。
|
||||
let probeCount = null;
|
||||
try {
|
||||
const probeRows = await ctx.model.query(
|
||||
`SELECT COUNT(*) AS probe_count
|
||||
FROM ${currentTableName} o
|
||||
INNER JOIN (
|
||||
SELECT order_id
|
||||
FROM wms_order_wave_index
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id = :waveId
|
||||
LIMIT ${WAVE_INDEX_PROBE_LIMIT}
|
||||
) idx ON idx.order_id = o.id`,
|
||||
{
|
||||
replacements: { warehouseId, waveId },
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
probeCount = Number(Array.isArray(probeRows) && probeRows[0] && probeRows[0].probe_count || 0);
|
||||
} catch (error) {
|
||||
probeFailedWaves.push(item);
|
||||
ctx.logger.warn(`[wave-batch-closure] 仓库 ${warehouseId} 波次 ${waveId} 索引抽样核对失败,本轮不终结: ${error.message}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Number.isFinite(probeCount) && probeCount > 0) {
|
||||
// 索引指向的订单仍存在于待处理表:判空属于读偏(分表重建/复制等),不终结
|
||||
misreadWaves.push(item);
|
||||
} else {
|
||||
emptyWaves.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -219,8 +310,8 @@ class WaveBatchClosureService extends MainService {
|
||||
`UPDATE wms_wave_batch
|
||||
SET wave_status = :closedStatus,
|
||||
processed_orders = total_orders,
|
||||
check_time = NOW(),
|
||||
update_time = NOW()
|
||||
check_time = UTC_TIMESTAMP(),
|
||||
update_time = UTC_TIMESTAMP()
|
||||
WHERE wave_id IN (:waveIds)
|
||||
AND wave_status IN (:waveStatuses)
|
||||
AND total_orders > 0`,
|
||||
@ -247,22 +338,52 @@ class WaveBatchClosureService extends MainService {
|
||||
pending_confirm_count: pendingConfirmWaves.length,
|
||||
pending_confirm_wave_ids: pendingConfirmWaves.map(item => item.waveId),
|
||||
empty_wave_ids: emptyWaves.map(item => item.waveId),
|
||||
unbound_count: unboundWaves.length,
|
||||
unbound_wave_ids: unboundWaves.map(item => item.waveId),
|
||||
misread_count: misreadWaves.length,
|
||||
misread_wave_ids: misreadWaves.map(item => item.waveId),
|
||||
probe_failed_count: probeFailedWaves.length,
|
||||
probe_failed_wave_ids: probeFailedWaves.map(item => item.waveId),
|
||||
warehouse_ids: warehouseIds,
|
||||
closed_waves: confirmedWaves,
|
||||
duration_ms: Date.now() - startedAt,
|
||||
};
|
||||
|
||||
if (confirmedWaves.length > 0 || pendingConfirmWaves.length > 0) {
|
||||
if (unboundWaves.length > 0) {
|
||||
ctx.logger.warn(
|
||||
`[wave-batch-closure] ${unboundWaves.length} 个波次订单表与索引表双空(疑似建波未完成或全量清空异常),`
|
||||
+ `不自动终结: ${formatWaveIdListForLog(unboundWaves.map(item => item.waveId))}`
|
||||
);
|
||||
}
|
||||
if (misreadWaves.length > 0) {
|
||||
ctx.logger.warn(
|
||||
`[wave-batch-closure] ${misreadWaves.length} 个波次判空与索引抽样核对不一致(疑似读偏),`
|
||||
+ `不自动终结: ${formatWaveIdListForLog(misreadWaves.map(item => item.waveId))}`
|
||||
);
|
||||
}
|
||||
|
||||
if (confirmedWaves.length > 0 || pendingConfirmWaves.length > 0
|
||||
|| unboundWaves.length > 0 || misreadWaves.length > 0 || probeFailedWaves.length > 0) {
|
||||
const pendingSuffix = pendingConfirmWaves.length > 0
|
||||
? ` pendingWaves=${formatWaveIdListForLog(result.pending_confirm_wave_ids)}`
|
||||
: '';
|
||||
const confirmedSuffix = confirmedWaveIds.length > 0
|
||||
? ` waves=${formatWaveIdListForLog(confirmedWaveIds)}`
|
||||
: '';
|
||||
const unboundSuffix = unboundWaves.length > 0
|
||||
? ` unbound=${unboundWaves.length}`
|
||||
: '';
|
||||
const misreadSuffix = misreadWaves.length > 0
|
||||
? ` misread=${misreadWaves.length}`
|
||||
: '';
|
||||
const probeFailedSuffix = probeFailedWaves.length > 0
|
||||
? ` probeFailed=${probeFailedWaves.length}`
|
||||
: '';
|
||||
ctx.logger.info(
|
||||
`[wave-batch-closure] 波次终结结果 dryRun=${dryRun} candidate=${candidateCount}`
|
||||
+ ` confirmed=${confirmedWaves.length} closedRows=${result.closed_count}`
|
||||
+ ` pendingConfirm=${pendingConfirmWaves.length}${pendingSuffix}${confirmedSuffix}`
|
||||
+ `${unboundSuffix}${misreadSuffix}${probeFailedSuffix}`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -147,6 +147,54 @@ class WaybillService extends MainService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析主单号筛选条件(单值 / 数组 / 标准 where 对象),返回对应订单ID列表。
|
||||
* 先按主单号(business_key=1)在 wms_order_express 中定位 order_id,调用方再据此查询订单下所有运单(主+子)。
|
||||
*
|
||||
* @param {*} mainWaybillCode 主单号条件值(字符串 / 字符串数组 / {operator,value} 标准化对象)。
|
||||
* @param {number} warehouseId 仓库ID(仓库隔离)。
|
||||
* @return {Promise<{empty: boolean, orderIds: number[]}>} empty=true 表示所有主单号均不存在,调用方应直接返回空结果;orderIds 去重后的订单ID列表。
|
||||
*/
|
||||
async resolveMainWaybillOrderIds(mainWaybillCode, warehouseId) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const codes = (Array.isArray(mainWaybillCode) ? mainWaybillCode : [ mainWaybillCode ])
|
||||
.map(code => (code === undefined || code === null ? '' : String(code).trim()))
|
||||
.filter(code => code !== '');
|
||||
|
||||
if (codes.length === 0) {
|
||||
return { empty: false, orderIds: [] };
|
||||
}
|
||||
|
||||
const mainRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
waybill_code: { [Op.in]: codes },
|
||||
business_key: 1,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!mainRecords || mainRecords.length === 0) {
|
||||
return { empty: true, orderIds: [] };
|
||||
}
|
||||
|
||||
const orderIds = [];
|
||||
for (const record of mainRecords) {
|
||||
const orderId = Number(record.order_id);
|
||||
if (Number.isFinite(orderId) && !orderIds.includes(orderId)) {
|
||||
orderIds.push(orderId);
|
||||
}
|
||||
}
|
||||
if (orderIds.length === 0) {
|
||||
return { empty: true, orderIds: [] };
|
||||
}
|
||||
|
||||
return { empty: false, orderIds };
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单列表查询(仓库侧)。
|
||||
* 按仓库维度查询运单号列表,支持分页、多条件筛选、排序。
|
||||
@ -154,7 +202,7 @@ class WaybillService extends MainService {
|
||||
* 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。
|
||||
*
|
||||
* @param {Object} [options={}] 查询参数。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode(字符串模糊匹配 / 字符串数组精确匹配)/ mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode(字符串模糊匹配 / 字符串数组精确匹配)/ mainWaybillCode(字符串 / 字符串数组精确匹配,数组时返回多个主单对应订单下的运单)/ orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。
|
||||
* @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。
|
||||
* @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。
|
||||
* @return {Promise<Object>} 运单列表与分页信息 { list, pagination }。
|
||||
@ -198,28 +246,20 @@ class WaybillService extends MainService {
|
||||
// 构建查询条件
|
||||
const queryWhere = { warehouse_id: warehouseId };
|
||||
|
||||
// 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单
|
||||
const mainWaybillCode = val(where.mainWaybillCode);
|
||||
if (mainWaybillCode && String(mainWaybillCode).trim()) {
|
||||
const mainCode = String(mainWaybillCode).trim();
|
||||
const mainRecord = await ctx.model.OrderExpress.findOne({
|
||||
where: {
|
||||
waybill_code: mainCode,
|
||||
business_key: 1,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (mainRecord) {
|
||||
queryWhere.order_id = mainRecord.order_id;
|
||||
} else {
|
||||
// 主单号不存在,直接返回空结果
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page, pageSize, total: 0, totalPages: 0 },
|
||||
};
|
||||
}
|
||||
// 主单号查询:先通过主单号(支持单值/数组)定位 order_id,再查这些订单下所有运单(主+子)
|
||||
const mainResolved = await this.resolveMainWaybillOrderIds(val(where.mainWaybillCode), warehouseId);
|
||||
if (mainResolved.empty) {
|
||||
// 主单号均不存在,直接返回空结果
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page, pageSize, total: 0, totalPages: 0 },
|
||||
};
|
||||
}
|
||||
if (mainResolved.orderIds.length > 0) {
|
||||
// 单主单保持标量 order_id(向后兼容),多主单使用 Op.in
|
||||
queryWhere.order_id = mainResolved.orderIds.length === 1
|
||||
? mainResolved.orderIds[0]
|
||||
: { [Op.in]: mainResolved.orderIds };
|
||||
}
|
||||
|
||||
// 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like)
|
||||
@ -741,27 +781,19 @@ class WaybillService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
// 主单号查询
|
||||
const mainWaybillCodeExport = val(where.mainWaybillCode);
|
||||
if (mainWaybillCodeExport && String(mainWaybillCodeExport).trim()) {
|
||||
const mainCode = String(mainWaybillCodeExport).trim();
|
||||
const mainRecord = await ctx.model.OrderExpress.findOne({
|
||||
where: {
|
||||
waybill_code: mainCode,
|
||||
business_key: 1,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (mainRecord) {
|
||||
queryWhere.order_id = mainRecord.order_id;
|
||||
} else {
|
||||
if (typeof onProgress === 'function') {
|
||||
await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } });
|
||||
}
|
||||
return { list: [], current_count: 0, total_count: 0, url: '' };
|
||||
// 主单号查询(支持单值/数组,与 list 保持一致)
|
||||
const mainResolvedExport = await this.resolveMainWaybillOrderIds(val(where.mainWaybillCode), warehouseId);
|
||||
if (mainResolvedExport.empty) {
|
||||
if (typeof onProgress === 'function') {
|
||||
await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } });
|
||||
}
|
||||
return { list: [], current_count: 0, total_count: 0, url: '' };
|
||||
}
|
||||
if (mainResolvedExport.orderIds.length > 0) {
|
||||
// 单主单保持标量 order_id(向后兼容),多主单使用 Op.in
|
||||
queryWhere.order_id = mainResolvedExport.orderIds.length === 1
|
||||
? mainResolvedExport.orderIds[0]
|
||||
: { [Op.in]: mainResolvedExport.orderIds };
|
||||
}
|
||||
|
||||
// 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like),与 list 保持一致
|
||||
|
||||
@ -255,6 +255,8 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
}
|
||||
```
|
||||
|
||||
> `where.mainWaybillCode` 支持字符串或字符串数组:`"SF1234567890"`(单主单)或 `["SF1234567890", "SF0987654321"]`(多主单,按 `IN` 精确匹配)。上例以单值展示。
|
||||
|
||||
#### 参数说明
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
@ -262,7 +264,7 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
| `pagination` | `object` | ✗ | 分页参数 `{ page, pageSize }`,默认 page=1, pageSize=20 |
|
||||
| `where` | `object` | ✗ | 筛选条件,所有字段均为可选 |
|
||||
| `where.waybillCode` | `string` | ✗ | 运单号(模糊搜索) |
|
||||
| `where.mainWaybillCode` | `string` | ✗ | **主单号**(精确匹配)。先通过主单号定位 `order_id`,再返回该订单下所有运单(主+子)。与 `waybillCode` 互斥,同时传入时 `mainWaybillCode` 优先 |
|
||||
| `where.mainWaybillCode` | `string \| string[]` | ✗ | **主单号**(精确匹配,2026-10-04 起支持数组)。单值:先通过主单号定位 `order_id`,再返回该订单下所有运单(主+子);数组:按 `Op.in` 匹配多个主单号,返回这些主单对应订单下的全部运单。与 `waybillCode` 同时传入时按 AND 叠加,不做互斥优先级处理。空数组/全空值不加该条件;主单号均不存在时直接返回空列表 |
|
||||
| `where.waybillType` | `string` | ✗ | 🆕 **运单类型**:`"main"`/`"1"`=主单号(`business_key=1`),`"child"`/`"2"`=子单号(`business_key>1`) |
|
||||
| `where.orderId` | `number` | ✗ | 订单ID(等值) |
|
||||
| `where.orderNo` | `string` | ✗ | ⛔ **暂不可用**:订单号(待快照字段 `delivery_order_code` 落库后启用 LIKE 模糊搜索) |
|
||||
@ -367,7 +369,7 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
|
||||
1. **仓库隔离**:自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定,`ctx.user.store_id` 即为当前用户所属仓库ID)。所有查询 WHERE 条件自动追加 `warehouse_id`,不可由前端入参覆盖
|
||||
2. **主单号关联查询**:每条运单记录通过 SELF JOIN(`t1.order_id = t2.order_id AND t2.business_key = 1`)获取主单号 `main_waybill_code`。当 `business_key = 1` 时,主单号就是自身 `waybill_code`;当 `business_key > 1` 时,需要 JOIN 获取主单号
|
||||
3. **按主单号入参查询**:当 `where.mainWaybillCode` 传入时,先通过主单号 `waybill_code` 定位 `order_id`(`WHERE waybill_code = ? AND business_key = 1`),再 `WHERE order_id = ?` 返回该订单下所有运单(主+子)
|
||||
3. **按主单号入参查询**:当 `where.mainWaybillCode` 传入时,先通过主单号 `waybill_code` 定位 `order_id`,再返回该订单下所有运单(主+子)。**支持单值 / 数组**(2026-10-04):单值保持 `WHERE waybill_code = ? AND business_key = 1 AND warehouse_id = ?` → `WHERE order_id = ?`(标量,向后兼容);数组按 `WHERE waybill_code IN (?, ?) AND business_key = 1 AND warehouse_id = ?` → `WHERE order_id IN (?, ?)`(去重后 `Op.in`),返回多个主单对应订单下的全部运单;元素自动 trim 并过滤空值,全部主单号不存在时直接返回空列表,空数组/全空值数组不添加该条件
|
||||
4. **按物流接口ID查询**:直接 `WHERE logistics_interface_id = ?`,等值匹配
|
||||
5. **订单号模糊搜索**:当 `where.orderNo` 或 `where.keyword` 匹配到非纯数字运单号时,需要 JOIN 订单表(current/history/dispatch)进行 `delivery_order_code LIKE` 匹配
|
||||
6. **打印次数**:通过子查询或 LEFT JOIN + GROUP BY `express_print_record.express_no = waybill_code` 聚合
|
||||
@ -609,7 +611,7 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
|---|------|------|------|------|
|
||||
| — | `warehouse_id` | — | = | ✅ 自动注入 |
|
||||
| 1 | `waybillCode` | string | LIKE | ✅ |
|
||||
| 2 | `mainWaybillCode` | string | 精确→order_id | ✅ |
|
||||
| 2 | `mainWaybillCode` | string \| string[] | 精确→order_id(数组 Op.in) | ✅ 🆕 |
|
||||
| 3 | `waybillType` | string | `main/1`→bk=1, `child/2`→bk>1 | ✅ 🆕 |
|
||||
| 4 | `orderId` | number | = | ✅ |
|
||||
| 5 | `orderNo` | string | LIKE | ⛔ 待快照 |
|
||||
|
||||
@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 库存盘点作业记录表支持空库位标记(库位盘点模式:确认库位为空时上报一条特殊记录):
|
||||
*
|
||||
* wms_stock_check_record 新增 is_empty(TINYINT(1) NOT NULL DEFAULT 0):
|
||||
* - is_empty=1 的记录表示「确认该库位为空」:stock_id=NULL、barcode=NULL、item_name=NULL、quantity=0;
|
||||
* - 与商品记录互斥(应用层保证):标记空时删除该明细下商品记录;上报商品时删除该明细下空记录;
|
||||
* - 空记录按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新(唯一索引不约束 NULL 行)。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_stock_check_record';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
await queryInterface.sequelize.query(`
|
||||
ALTER TABLE \`${TABLE_NAME}\`
|
||||
ADD COLUMN \`is_empty\` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否空库位标记(1=确认为空,stock_id/barcode/item_name 均为空、quantity=0)' AFTER \`item_name\`
|
||||
`);
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'is_empty');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,47 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 商品盘点明细按「商品 + 库位」拆行(商品任务必须按库位盘点):
|
||||
*
|
||||
* wms_stock_check_detail:
|
||||
* 1. 唯一索引 uk_check_stock(check_id, stock_id) 变更为 uk_check_stock_location(check_id, stock_id, location_id),
|
||||
* 允许同一商品在该任务下按多个库存库位拆成多行(location_id 均为 NULL 的旧行不受唯一约束,MySQL NULL 语义)。
|
||||
* 2. 唯一索引 uk_check_location(check_id, location_code) 放宽为普通索引 idx_check_location:
|
||||
* 商品拆行后同一任务同一库位可能对应多个商品行(location_code 相同),唯一约束不再成立;
|
||||
* 库位明细行(scope_type=location)幂等由应用层查重保证。
|
||||
* 3. 商品明细行(scope_type=goods)将写入其库存库位快照(location_id/location_code/system_quantity=该库位账面),
|
||||
* 应用层保证同商品重复添加整体跳过(幂等口径不变)。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_stock_check_detail';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
await queryInterface.sequelize.query(`
|
||||
ALTER TABLE \`${TABLE_NAME}\`
|
||||
DROP INDEX \`uk_check_stock\`,
|
||||
DROP INDEX \`uk_check_location\`,
|
||||
ADD UNIQUE INDEX \`uk_check_stock_location\` (\`check_id\`, \`stock_id\`, \`location_id\`),
|
||||
ADD INDEX \`idx_check_location\` (\`check_id\`, \`location_code\`)
|
||||
`);
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
// 回退前清理同 (check_id, stock_id) 的多行重复(保留最小 id),保证恢复唯一索引不失败;
|
||||
// 同任务同库位的多商品行(拆行产生)一并清理(保留最小 id),恢复 uk_check_location 不失败
|
||||
await queryInterface.sequelize.query(`
|
||||
DELETE d1 FROM \`${TABLE_NAME}\` d1
|
||||
INNER JOIN \`${TABLE_NAME}\` d2
|
||||
ON d1.check_id = d2.check_id
|
||||
AND ((d1.stock_id = d2.stock_id) OR (d1.location_code = d2.location_code))
|
||||
AND d1.id > d2.id
|
||||
`);
|
||||
await queryInterface.sequelize.query(`
|
||||
ALTER TABLE \`${TABLE_NAME}\`
|
||||
DROP INDEX \`uk_check_stock_location\`,
|
||||
DROP INDEX \`idx_check_location\`,
|
||||
ADD UNIQUE INDEX \`uk_check_stock\` (\`check_id\`, \`stock_id\`),
|
||||
ADD UNIQUE INDEX \`uk_check_location\` (\`check_id\`, \`location_code\`)
|
||||
`);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建收件任务表 wms_receiving_task。
|
||||
*
|
||||
* 字段:批次号 batch_no、仓库ID warehouse_id(数据隔离维度)、
|
||||
* 创建人 creator_id/creator_name、创建时间 created_at。
|
||||
* 主键 id 自增从 10000 开始(建表后设置 AUTO_INCREMENT = 10000)。
|
||||
*
|
||||
* 索引:
|
||||
* idx_warehouse_id(按仓库查询)
|
||||
* idx_batch_no(按批次号查询)
|
||||
* idx_creator_id(按创建人查询)
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_receiving_task';
|
||||
const AUTO_INCREMENT_START = 10000;
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, DATE } = Sequelize;
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID(自增从10000开始)',
|
||||
},
|
||||
batch_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '批次号',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
creator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '创建人账户ID',
|
||||
},
|
||||
creator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '创建人名称快照',
|
||||
},
|
||||
created_at: { type: DATE, allowNull: false, comment: '创建时间' },
|
||||
updated_at: { type: DATE, allowNull: false, comment: '更新时间' },
|
||||
});
|
||||
|
||||
// 自增ID从 10000 开始
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE ${TABLE_NAME} AUTO_INCREMENT = ${AUTO_INCREMENT_START}`
|
||||
);
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'batch_no' ], { name: 'idx_batch_no' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'creator_id' ], { name: 'idx_creator_id' });
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,48 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 收件任务表补「标题」字段,并播种系统预设行(幂等)。
|
||||
*
|
||||
* - addColumn title(标题,NOT NULL 默认空串)
|
||||
* - 幂等插入系统预设:id=1、warehouse_id=0、title='历史收件',
|
||||
* 用于处理历史(旧流程)收货任务;batch_no 同步填 '历史收件',creator_id=0(系统)。
|
||||
*
|
||||
* 显式插入 id=1 不会影响 AUTO_INCREMENT=10000 的水位(1 < 10000)。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_receiving_task';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { STRING } = Sequelize;
|
||||
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!tableInfo.title) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'title', {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '标题(任务名称,如系统预设「历史收件」)',
|
||||
});
|
||||
}
|
||||
|
||||
const { sequelize } = queryInterface;
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT id FROM `' + TABLE_NAME + '` WHERE id = 1 LIMIT 1'
|
||||
);
|
||||
if (!rows || rows.length === 0) {
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + TABLE_NAME + '` (id, batch_no, warehouse_id, creator_id, creator_name, title, created_at, updated_at) VALUES (1, :b, 0, 0, :c, :t, NOW(), NOW())',
|
||||
{ replacements: { b: '历史收件', c: '系统', t: '历史收件' } }
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
await sequelize.query(
|
||||
'DELETE FROM `' + TABLE_NAME + '` WHERE id = 1 AND warehouse_id = 0'
|
||||
);
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'title');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,47 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 收件登记表 wms_return_received 增加收件任务ID。
|
||||
*
|
||||
* - addColumn receiving_task_id(BIGINT UNSIGNED NOT NULL DEFAULT 1,关联 wms_receiving_task.id)
|
||||
* - 回填:所有现有行 receiving_task_id 统一更新为 1(即系统预设「历史收件」任务)
|
||||
* - 索引 idx_receiving_task_id(按收件任务查询)
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_return_received';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT } = Sequelize;
|
||||
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!tableInfo.receiving_task_id) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'receiving_task_id', {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '收件任务ID,关联 wms_receiving_task.id;默认 1=系统预设「历史收件」',
|
||||
});
|
||||
}
|
||||
|
||||
// 显式回填:所有现有行统一为 1(系统预设「历史收件」任务)
|
||||
await queryInterface.sequelize.query(
|
||||
'UPDATE `' + TABLE_NAME + '` SET receiving_task_id = 1 WHERE receiving_task_id IS NULL OR receiving_task_id = 0'
|
||||
);
|
||||
|
||||
const indexes = await queryInterface.showIndex(TABLE_NAME);
|
||||
const hasIndex = (indexes || []).some(i => i.name === 'idx_receiving_task_id');
|
||||
if (!hasIndex) {
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'receiving_task_id' ], { name: 'idx_receiving_task_id' });
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const indexes = await queryInterface.showIndex(TABLE_NAME);
|
||||
const hasIndex = (indexes || []).some(i => i.name === 'idx_receiving_task_id');
|
||||
if (hasIndex) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_receiving_task_id');
|
||||
}
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'receiving_task_id');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,78 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 收件任务表与关联字段改名(对齐 return_received 退回收件命名体系)。
|
||||
*
|
||||
* - 表 wms_receiving_task 重命名为 wms_return_received_task
|
||||
* - wms_return_received.receiving_task_id 列改名为 return_received_task_id
|
||||
* - 索引 idx_receiving_task_id 改名为 idx_return_received_task_id
|
||||
*
|
||||
* 说明:仅改名,不改数据类型/默认值/数据;列改名后索引保留,先删旧索引再
|
||||
* CHANGE COLUMN 再重建新索引,保证索引名与列名一致。
|
||||
*/
|
||||
|
||||
const TASK_TABLE_OLD = 'wms_receiving_task';
|
||||
const TASK_TABLE_NEW = 'wms_return_received_task';
|
||||
const REGISTER_TABLE = 'wms_return_received';
|
||||
const COLUMN_OLD = 'receiving_task_id';
|
||||
const COLUMN_NEW = 'return_received_task_id';
|
||||
const INDEX_OLD = 'idx_receiving_task_id';
|
||||
const INDEX_NEW = 'idx_return_received_task_id';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
|
||||
// 1. 表重命名
|
||||
await sequelize.query(
|
||||
`RENAME TABLE \`${TASK_TABLE_OLD}\` TO \`${TASK_TABLE_NEW}\``
|
||||
);
|
||||
|
||||
// 2. 登记表列改名(先删旧索引,CHANGE COLUMN 后重建新索引)
|
||||
const indexes = await queryInterface.showIndex(REGISTER_TABLE);
|
||||
const hasOldIndex = (indexes || []).some(i => i.name === INDEX_OLD);
|
||||
if (hasOldIndex) {
|
||||
await queryInterface.removeIndex(REGISTER_TABLE, INDEX_OLD);
|
||||
}
|
||||
|
||||
const tableInfo = await queryInterface.describeTable(REGISTER_TABLE);
|
||||
if (tableInfo[COLUMN_OLD]) {
|
||||
await sequelize.query(
|
||||
`ALTER TABLE \`${REGISTER_TABLE}\` CHANGE COLUMN \`${COLUMN_OLD}\` \`${COLUMN_NEW}\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 1 COMMENT '收件任务ID,关联 wms_return_received_task.id;默认 1=系统预设「历史收件」'`
|
||||
);
|
||||
}
|
||||
|
||||
const indexesAfter = await queryInterface.showIndex(REGISTER_TABLE);
|
||||
const hasNewIndex = (indexesAfter || []).some(i => i.name === INDEX_NEW);
|
||||
if (!hasNewIndex) {
|
||||
await queryInterface.addIndex(REGISTER_TABLE, [ COLUMN_NEW ], { name: INDEX_NEW });
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
|
||||
const indexes = await queryInterface.showIndex(REGISTER_TABLE);
|
||||
const hasNewIndex = (indexes || []).some(i => i.name === INDEX_NEW);
|
||||
if (hasNewIndex) {
|
||||
await queryInterface.removeIndex(REGISTER_TABLE, INDEX_NEW);
|
||||
}
|
||||
|
||||
const tableInfo = await queryInterface.describeTable(REGISTER_TABLE);
|
||||
if (tableInfo[COLUMN_NEW]) {
|
||||
await sequelize.query(
|
||||
`ALTER TABLE \`${REGISTER_TABLE}\` CHANGE COLUMN \`${COLUMN_NEW}\` \`${COLUMN_OLD}\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 1 COMMENT '收件任务ID,关联 wms_receiving_task.id;默认 1=系统预设「历史收件」'`
|
||||
);
|
||||
}
|
||||
|
||||
const indexesAfter = await queryInterface.showIndex(REGISTER_TABLE);
|
||||
const hasOldIndex = (indexesAfter || []).some(i => i.name === INDEX_OLD);
|
||||
if (!hasOldIndex) {
|
||||
await queryInterface.addIndex(REGISTER_TABLE, [ COLUMN_OLD ], { name: INDEX_OLD });
|
||||
}
|
||||
|
||||
await sequelize.query(
|
||||
`RENAME TABLE \`${TASK_TABLE_NEW}\` TO \`${TASK_TABLE_OLD}\``
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 数据菜单下新增 web_pages 子菜单「退件记录」(id=640),并授权客服员工及以上角色。
|
||||
*
|
||||
* 权限明细:
|
||||
* 640 — ReturnRecord(web_pages 菜单,parent_id=16 数据)
|
||||
*
|
||||
* 角色授权(系统预设角色,不含通配符角色):
|
||||
* 640 → 客服组-员工(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 = {
|
||||
640: [ 30, 28 ],
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
// ── 1. 创建 web_pages 菜单权限(固定 ID,parent_id=16 数据)──
|
||||
await queryInterface.sequelize.query(
|
||||
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
|
||||
{ replacements: [ 640, 'ReturnRecord', '@/views/data/returnrecord/index', 'ReturnRecord', null, '退件记录', null, 0, 0, 16, 'web_pages', 1, 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 = 640`
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 移除 returnwaybill / returnReceived / returnUnpack 前端页面权限。
|
||||
*
|
||||
* - wms_permission:删除 web_pages 类型页面记录 530(returnReceived)、
|
||||
* 550(returnUnpack)、556(returnwaybill)
|
||||
* - wms_role:从所有非通配符角色的 permissions 数组中移除这三个 id
|
||||
* (通配符角色 permissions='*' 自动拥有所有权限,无需处理)
|
||||
*
|
||||
* 注意:仅移除前端页面权限,API 权限(returnReceived.create 等 type=api)保留。
|
||||
*/
|
||||
|
||||
const TABLE = 'wms_permission';
|
||||
const ROLE_TABLE = 'wms_role';
|
||||
const PAGE_PERMISSION_IDS = [ 530, 550, 556 ];
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
// ── 1. 删除 web_pages 页面权限记录 ──
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM \`${TABLE}\` WHERE type = 'web_pages' AND id IN (:ids)`,
|
||||
{ replacements: { ids: PAGE_PERMISSION_IDS } }
|
||||
);
|
||||
|
||||
// ── 2. 从非通配符角色 permissions 数组中移除 ──
|
||||
const roles = await queryInterface.sequelize.query(
|
||||
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE permissions IS NOT NULL AND permissions <> '' AND permissions <> '*'`,
|
||||
{ type: queryInterface.sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
for (const role of roles) {
|
||||
let perms;
|
||||
try {
|
||||
perms = JSON.parse(role.permissions || '[]');
|
||||
} catch (err) {
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(perms)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filtered = perms.filter(id => !PAGE_PERMISSION_IDS.includes(Number(id)));
|
||||
if (filtered.length === perms.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
|
||||
{ replacements: [ JSON.stringify(filtered), role.id ] }
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
// 恢复页面权限记录(角色数组不做恢复,回滚由后续授权迁移补充)
|
||||
await queryInterface.sequelize.query(
|
||||
`INSERT IGNORE INTO \`${TABLE}\` (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) VALUES
|
||||
(530, 'returnReceived', '@/views/express/returnReceived/index', 'returnReceived', NULL, '快递收件', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW()),
|
||||
(550, 'returnUnpack', '@/views/express/returnUnpack/index', 'returnUnpack', NULL, '快递拆包', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW()),
|
||||
(556, 'returnwaybill', '@/views/express/returnwaybill/index', 'returnwaybill', NULL, '运单退回', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW())`
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 权限名称修正:「运单退回登记」→「未退登记」。
|
||||
*
|
||||
* 仅改 API 权限显示名称(meta_title),path/name(方法路由)保持不变:
|
||||
* 551 — API:未退登记
|
||||
* 552 — API:未退登记修改
|
||||
* 553 — API:未退登记列表
|
||||
* 554 — API:未退登记详情
|
||||
* 555 — API:未退登记删除
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
'UPDATE `wms_permission` SET meta_title = REPLACE(meta_title, :oldName, :newName) WHERE id IN (551, 552, 553, 554, 555)',
|
||||
{ replacements: { oldName: '运单退回登记', newName: '未退登记' } }
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
'UPDATE `wms_permission` SET meta_title = REPLACE(meta_title, :newName, :oldName) WHERE id IN (551, 552, 553, 554, 555)',
|
||||
{ replacements: { oldName: '运单退回登记', newName: '未退登记' } }
|
||||
);
|
||||
},
|
||||
};
|
||||
113
database/migrations/20261008193000-create-wms-order-b2b.js
Normal file
113
database/migrations/20261008193000-create-wms-order-b2b.js
Normal file
@ -0,0 +1,113 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建 B2B 订单作业明细表 wms_order_b2b。
|
||||
*
|
||||
* 与发货单(订单)主表 wms_order_delivery 分表一对一(order_id 关联分表 id,uk_order_id 唯一),
|
||||
* 不分表(单表全量),通过 warehouse_id/store_id 做数据隔离与检索维度,
|
||||
* 类似 wms_order_express(运单号表)的落表方式。
|
||||
*
|
||||
* 字段:
|
||||
* order_id 订单ID(关联 wms_order_delivery 分表 id,唯一)
|
||||
* warehouse_id / store_id 仓库/货主维度
|
||||
* delivery_order_code 发货单号快照(便于按单号检索)
|
||||
* total_box_count 总箱数
|
||||
* pickup_plate_number 提货车牌
|
||||
* prep_remark 备货备注
|
||||
* prep_duration_seconds 备货用时(秒)
|
||||
* is_picked_up 是否提货(Y/N)
|
||||
* picked_up_at 提货时间
|
||||
* created_at / updated_at / deleted_at 审计与软删除
|
||||
*
|
||||
* 索引:
|
||||
* uk_order_id(order_id 唯一)
|
||||
* idx_warehouse_id / idx_store_id / idx_delivery_order_code
|
||||
* idx_pickup_plate_number / idx_is_picked_up / idx_deleted_at
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_b2b';
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, INTEGER, ENUM, DATE } = Sequelize;
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '订单ID,关联 wms_order_delivery 分表 id',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '货主ID',
|
||||
},
|
||||
delivery_order_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '发货单号快照',
|
||||
},
|
||||
total_box_count: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '总箱数',
|
||||
},
|
||||
pickup_plate_number: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '提货车牌',
|
||||
},
|
||||
prep_remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备货备注',
|
||||
},
|
||||
prep_duration_seconds: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '备货用时(秒)',
|
||||
},
|
||||
is_picked_up: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否提货:Y=已提货 N=未提货',
|
||||
},
|
||||
picked_up_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '提货时间',
|
||||
},
|
||||
created_at: { type: DATE, allowNull: false, comment: '创建时间' },
|
||||
updated_at: { type: DATE, allowNull: false, comment: '更新时间' },
|
||||
deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' },
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'order_id' ], { unique: true, name: 'uk_order_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: 'idx_store_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'delivery_order_code' ], { name: 'idx_delivery_order_code' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'pickup_plate_number' ], { name: 'idx_pickup_plate_number' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'is_picked_up' ], { name: 'idx_is_picked_up' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' });
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单基表 wms_order_delivery 增加 is_b2b 列(是否B2B,默认 N)。
|
||||
*
|
||||
* 分表(wms_order_delivery_%)列由 order_delivery_factory 惰性同步补齐
|
||||
* (首次访问分表时 describeTable 比对 + 单条 ALTER,带自增水位保护),
|
||||
* 本迁移只补基表列,保持基表与分表结构一致。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_delivery';
|
||||
const COLUMN_NAME = 'is_b2b';
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { ENUM } = Sequelize;
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否B2B:Y是 N否',
|
||||
});
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* B2B 订单作业明细表 wms_order_b2b 增加 is_print 列(是否打印,默认 N)。
|
||||
*
|
||||
* 字段:is_print ENUM('Y','N') NOT NULL DEFAULT 'N'(N=未打印 Y=已打印)。
|
||||
* 索引:idx_is_print(按打印状态筛选)。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_b2b';
|
||||
const COLUMN_NAME = 'is_print';
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { ENUM } = Sequelize;
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否打印:Y=已打印 N=未打印',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_NAME, [ COLUMN_NAME ], { name: 'idx_is_print' });
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_is_print');
|
||||
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
|
||||
},
|
||||
};
|
||||
@ -172,8 +172,8 @@ report.generate(method 层,异步任务,入参 report_id)
|
||||
| `package_material_code` | 包材编码 |
|
||||
| `package_material_name` | 包材名称 |
|
||||
| `waybill_allocated_at` | 分配时间 |
|
||||
| `items_count` | 商品种数 |
|
||||
| `items_total` | 商品件数 |
|
||||
| `items_count` | 订单商品总类数 |
|
||||
| `items_total` | 订单商品总数 |
|
||||
| `items_weight` | 商品重量 |
|
||||
| `weighing_weight` | 称重重量(g) |
|
||||
| `total_amount` | 订单金额 |
|
||||
|
||||
@ -1,4 +1,20 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.10.08-qimen-stockout-item-id-normalize",
|
||||
"date": "2026-10-08",
|
||||
"type": "updated",
|
||||
"module": "stockout",
|
||||
"summary": "qimen stockout.create 明细 item_id 落库口径修正:统一写入实际匹配到的 StockStore 数字主键 id,修复调用方把「编码+名称」拼接串放进 itemId(同时 itemCode 可精确匹配)时写入 BIGINT 列触发 MySQL 严格模式 1366(Incorrect integer value for column item_id)导致建单失败的问题;与 entryorder.create 建单口径对齐。",
|
||||
"methods": [
|
||||
"stockout.create"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/stockout_order.js#create 校验循环 items.push:itemId 由 line.itemId 改为 wmsStock.id(StockStore 主键,纯数字);itemCode/itemName 仍落报文原值,stockId 仍为 wmsStock.stock_id",
|
||||
"回传影响:stockout 确认回传(order_async.js buildStockoutConfirmDataInternal)itemId 改为 StockStore 主键 id,符合奇门 itemId=「仓储系统商品ID」语义,与入库单确认回传口径一致",
|
||||
"生产案例:2026-10-08 10:09 奇门 stockout.create(app_key=23204092)报 Incorrect integer value: LB006小光兔灵感五色眼影盘#01情懒落日 for column item_id,调用方 itemId/itemCode/itemName 三字段均为拼接串,系统按 itemCode 匹配到 StockStore(stock_id=162580)但落库仍用报文原值",
|
||||
"验证:test/temp_test_stockout_itemid_normalize.js(非数字 itemId + itemCode 降级匹配 → 建单成功且 item_id=StockStore 主键;数字主键回归通过),5/5 PASS"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.12-qimen-order-cancel-rk-entry-order-support",
|
||||
"date": "2026-09-12",
|
||||
|
||||
@ -1,4 +1,570 @@
|
||||
[
|
||||
{
|
||||
"version": "0.3.262",
|
||||
"date": "2026-10-10",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.result 无作业记录时返回明细范围行(盘点前/待提交后台查看明细专用,不再作为盘点作业数据提供)(0.3.261 → 0.3.262)",
|
||||
"methods": [
|
||||
"stock.check.result"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:result 在无作业记录(如待提交/盘点前)时 rows 直接返回 wms_stock_check_detail 明细范围行(原始行,不聚合),total=明细行数——本接口仅展示盘点前/盘点后后台查看明细使用,不再作为盘点作业数据提供(盘点作业数据见 stock.check.workData);有作业记录时保持原聚合口径不变(商品范围按商品合并、库位范围按库位行)。",
|
||||
"代码依据:app/service/systems/stock_check.js#result(records.length===0 分支直接返回明细行);回归测试调整 3 用例(盘点前/待提交两用例新断言明细范围行口径;addDetail 与 recordDelete 用例同步改为断言明细范围行),stock_check 全量 235 用例通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.result 一条(description/response.rows/notes 补充无作业记录时返回明细范围行口径);根版本 0.3.261 → 0.3.262、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 24 条 method 未改动(stock.check 分组仍为 25 条)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.261",
|
||||
"date": "2026-10-10",
|
||||
"type": "added",
|
||||
"summary": "新增 stock.check.exportDetail 盘点明细导出接口(异步,按盘点范围分流:商品盘点固定两 sheet——汇总和差异 + 库位/数量/条码/商品名称;库位盘点简化)",
|
||||
"methods": [
|
||||
"stock.check.exportDetail"
|
||||
],
|
||||
"notes": [
|
||||
"接口:stock.check.exportDetail,入参 id(盘点任务ID,必填);异步执行,立即返回 task_id,进度查询复用 stock.check.exportTaskProgress。",
|
||||
"商品盘点固定两个 Sheet:Sheet1「汇总和差异」每商品一行(盘点单号/商品编码/商品名称/规格/账面数量(明细行 system_quantity 快照合计,提交审核时刷新)/盘点数量/差异数量/差异类型(盘盈|盘亏,无差异或未盘留空);未知商品追加在末尾(无账面、差异=实盘=盘盈);Sheet2「库位明细」每商品每库位一行(库位编码/数量(实盘,未盘 0)/条码(wms_stock_barcodes 第一条)/商品名称)。",
|
||||
"库位盘点:Sheet「盘点明细」作业记录口径(库位编码/商品编码/商品名称/盘点数量),未知商品编码=扫描条码、空库位标记商品为空数量 0。",
|
||||
"迭代记录:首版按 mode 二选一(location 单 sheet / summary 两 sheet),用户纠正为商品盘点固定两 sheet(汇总和差异 + 库位明细精简列),mode 入参已移除;随后纠正「库位明细」按作业记录(wms_stock_check_record)一行一条实际盘点记录导出(不再按快照库位展开/合并无库位组);补充库位编码列显示覆盖(custom_name → custom_barcode → space_code);最后汇总和差异 sheet 增加「条码」列(wms_stock_barcodes 第一条,未知商品商品编码列即扫描条码、条码列留空)。",
|
||||
"代码依据:app/service/systems/stock_check.js#exportCheckDetail/#_generateAndUploadCheckDetailExcel(商品范围复用 result 的商品合并聚合;新增 StockBarcode 条码查询)/#_uploadExportExcelFile(原 _generateAndUploadStockCheckExcel 上传段抽为公共方法,两处导出一致复用)+ app/service/systemMethods/stock/check.js#exportDetail(ALL_METHOD_NAMES/_noNeedLog 已加入);回归测试 3 用例(商品两 sheet 回读断言/库位任务/方法层异步轮询至 success),stock_check 全量 235 用例通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.exportDetail 一条(位于 stock.check.export 之后,分组由 24 条增至 25 条);根版本 0.3.260 → 0.3.261、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 24 条 method 未改动。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.260",
|
||||
"date": "2026-10-10",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.submit 商品范围任务提交审核时刷新明细行账面快照(提交即快照,提交时点账面;不新增表、主表不额外写快照)(0.3.259 → 0.3.260)",
|
||||
"methods": [
|
||||
"stock.check.submit"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:商品范围任务(scope_type=goods)提交审核时把各明细行 system_quantity 刷新为该库位当时账面 SUM(available_quantity+locked_quantity)(库存记录不存在按 0),保证 result/差异对比使用提交时点的账面(添加明细到提交之间库存变动以提交时点为准,与 result 商品范围聚合的库位账面快照同源);明细表本身已按「商品+库位」完整记录快照,主表不额外写快照(scope_snapshot 保持 null);快照失败则提交失败(提交即快照);驳回(rejected)后重新提交会重新刷新;库位范围任务(scope_type=location)账面实时查 wms_storage,不处理。",
|
||||
"存储方案:无需新表、无迁移——明细表已有 system_quantity 快照列(按「商品+库位」拆行),提交时直接刷新即可。",
|
||||
"代码依据:app/service/systems/stock_check.js#submit(缺库位校验后、置 submitted 前调用)/#_refreshGoodsBookSnapshotOnSubmit(新增);回归测试两用例(商品任务提交后明细行快照刷新为提交时账面、主表 scope_snapshot 保持 null,库存临时 +100 后 finally 恢复;库位范围任务提交明细行 system_quantity 保持 0),stock_check 全量 231 用例通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.submit 一条(description/notes 补提交时刷新明细行账面快照语义);根版本 0.3.259 → 0.3.260、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 23 条 method 未改动(stock.check 分组仍为 24 条)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.259",
|
||||
"date": "2026-10-10",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.result 商品范围按商品聚合输出(一个商品一行,多个库位明细行合并),行内 locations 输出各库位账面快照与实盘;主表计数同步商品口径(0.3.258 → 0.3.259)",
|
||||
"methods": [
|
||||
"stock.check.result",
|
||||
"stock.check.detail"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:按商品盘点(scope_type=goods)不再按库位拆行输出——result 商品范围按 stock_id 合并(一行一商品),行含 system_quantity(账面快照合计=各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照)与 locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }]:system_quantity 为该库位账面快照、quantity 为该库位实盘合计(未盘为 0),仅作业记录存在而快照不存在的库位追加在末尾且 system_quantity=0);行级 checked_quantity/diff_quantity/is_diff/status 按合并后的商品口径计算;主表计数 total_items/checked_items/diff_items 响应口径以聚合行为准(total_items=行数、checked_items=已盘行数、diff_items=差异行数)。",
|
||||
"同步改动:主表 total_items 商品范围改为按商品计数(addDetail/detailDelete/patternCreate/_countScopeSummary);_recalcCheckSummary 的 checked_items/diff_items 与 finish/_calcQuantityDiffSummary 的盘盈盘亏汇总(detail profit/loss 同口径)均改为商品范围按商品聚合;detail 描述同步。",
|
||||
"代码依据:app/service/systems/stock_check.js#result/#_buildDetailAggregations(新增 _formatMergedGoodsAggregationRow 商品合并格式化器,_formatDetailAggregationRow 仅保留库位行)、#_countScopeSummary(新增)、#_recalcCheckSummary、#finish、#_calcQuantityDiffSummary;回归测试新增「多库位商品合并为一行」用例(全部库位上报、差异=实盘合计-账面快照合计),stock_check 全量 229 用例通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.result(description/response.rows/notes 同步商品范围合并口径)与 stock.check.detail(description 盘盈盘亏口径短语同步)两条;根版本 0.3.258 → 0.3.259、updatedAt 2026-10-09 → 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 24 条)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.258",
|
||||
"date": "2026-10-09",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData / workDataSpaceDetails 空间视图库位排序修正:仅按库位拣货顺序 pick_sequence 升序排序,pick_priority 与库位 id 均不参与(同值保持库位查询顺序)(0.3.257 → 0.3.258)",
|
||||
"methods": [
|
||||
"stock.check.workData",
|
||||
"stock.check.workDataSpaceDetails"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:space 视图库位排序在 0.3.257(对齐拣货模块 sort_by,pick_sequence 升序 + pick_priority 升序 + 库位 id 兜底)基础上修正为仅按库位拣货顺序排序——pick_sequence 升序,pick_priority 与库位 id 均不参与排序(同值保持库位查询顺序,依赖 Array.sort 稳定排序);行内 goods 排序与分页/过滤行为不变;goods 视图 locations 排序不受影响。",
|
||||
"代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows(sortedLocations 比较函数简化为仅 pick_sequence 差值;两处 LocationSpace 查询 attributes 移除 pick_priority;JSDoc 与 workData 方法注释同步);回归测试排序用例改造为两阶段(pick_sequence 升序 + pick_priority 双向设置均不影响顺序),stock_check 全量 228 用例通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataSpaceDetails 两条(description/notes 同步排序口径);根版本 0.3.257 → 0.3.258、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 24 条)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.257",
|
||||
"date": "2026-10-09",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData / workDataSpaceDetails 空间视图库位排序对齐拣货模块:pick_priority 由降序改为升序(与拣货模块 sort_by [ pick_sequence, pick_priority, space_id, item_code ] 一致)(0.3.256 → 0.3.257)",
|
||||
"methods": [
|
||||
"stock.check.workData",
|
||||
"stock.check.workDataSpaceDetails"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:space 视图库位排序规则由「pick_sequence 升序、pick_priority 降序、同值按库位 id 升序兜底」改为「pick_sequence 升序、pick_priority 升序、同值按库位 id 升序兜底」,与拣货模块(app/service/systems/pick.js sort_by 声明:[ pick_sequence, pick_priority, space_id, item_code ])排序规则一致,保证盘点作业顺序与拣货路径一致;goods 视图 locations 排序不受影响。",
|
||||
"代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows(sortedLocations 比较函数 priorityDiff 改为 left - right 升序;JSDoc 与 workData 方法注释同步);回归测试新增 space 视图排序用例(pick_sequence 升序 + pick_priority 升序两阶段断言,旧降序实现下第二阶段会失败),stock_check 全量 228 用例通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataSpaceDetails 两条(description/notes 同步排序口径);根版本 0.3.256 → 0.3.257、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 24 条)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.256",
|
||||
"date": "2026-10-09",
|
||||
"type": "updated",
|
||||
"summary": "index.getWarehousePanelData is_change=false 时返回空 data 节约流量(传入时间戳未过期时不查库不输出数据;is_change=true 时仍优先输出缓存数据)(0.3.255 → 0.3.256)",
|
||||
"methods": [
|
||||
"index.getWarehousePanelData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/warehouse_panel.js#getPanelData(缓存有最后更新时间时先算 isChange,false 直接返回 { is_change: false, last_change_at, data: {} } 不查库;true 时缓存有 data 直出、无 data 查库补数据保留外部时间戳;无最后更新时间仍查库+设置);app/service/systemMethods/index.js 注释同步;ESLint 0 错误;临时验证脚本 17 用例全 PASS(新增未变化空 data 不查库用例)。",
|
||||
"文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(description/response.data/notes 同步空 data 语义);根版本 0.3.255 → 0.3.256、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.255",
|
||||
"date": "2026-10-09",
|
||||
"type": "updated",
|
||||
"summary": "index.getWarehousePanelData 拉取逻辑改为外部驱动:缓存有最后更新时间且有数据直接输出;有最后时间无数据(外部只驱动时间戳)查库补数据并保留外部时间戳;无最后时间才查库并设置最后更新时间;缓存 TTL 10 秒 → 300 秒(0.3.254 → 0.3.255)",
|
||||
"methods": [
|
||||
"index.getWarehousePanelData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/warehouse_panel.js#getPanelData(三段式拉取逻辑:命中直出 / 有外部时间戳无数据查库补 data 保留外部 ts / 无时间戳查库+设置 nowTs;PANEL_CACHE_TTL_SECONDS=300);app/service/systemMethods/index.js 注释同步(force 仅影响 last_change_at 是否可缺省);ESLint 0 错误;临时验证脚本 16 用例全 PASS(新增外部驱动时间戳查库补数据用例,断言保留外部时间戳 1800000000 且写缓存值一致)。",
|
||||
"文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.is_change/last_change_at 描述与 notes 缓存语义同步外部驱动);根版本 0.3.254 → 0.3.255、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.254",
|
||||
"date": "2026-10-09",
|
||||
"type": "updated",
|
||||
"summary": "index.getWarehousePanelData data 填充有数据源的字段(title/fulfillment/stageOverview/b2b/groupPicking/scatterPicking/packingRank.personal/trend/weeklyEfficiency.intercept),无数据源的字段暂不输出;缓存值升级为 { last_change_at, data }(TTL 10 秒,过期重算)(0.3.253 → 0.3.254)",
|
||||
"methods": [
|
||||
"index.getWarehousePanelData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:新增 app/service/systems/warehouse_panel.js(WarehousePanelService:getPanelData 增量判定与缓存、buildPanelData 8 个数据块并行聚合且单块容错、queryFulfillment/queryStageOverview/queryB2b/queryPickingBlock/queryPickingGoodsSku/queryPackingPersonal/queryTrend/queryWeeklyIntercept);app/service/systemMethods/index.js#getWarehousePanelData 改为参数校验后调用 systems 层(原 getWarehousePanelLastChangeCacheKey 移入 systems 层);ESLint 0 错误;临时逻辑脚本 15 用例全 PASS;真实库(127.0.0.1:3307)只读 SQL 验证仓库 100000/1000028 共 90 条查询全部可执行。",
|
||||
"文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.data 描述补充已输出字段、notes 补充缓存语义/口径/未输出字段清单);根版本 0.3.253 → 0.3.254、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.253",
|
||||
"date": "2026-10-09",
|
||||
"type": "updated",
|
||||
"summary": "index.getWarehousePanelData 响应新增 last_change_at(服务端最后更改时间戳,缓存未命中时为 0),供前端保存并作为下次轮询入参回传(0.3.252 → 0.3.253)",
|
||||
"methods": [
|
||||
"index.getWarehousePanelData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/index.js#getWarehousePanelData(读取缓存后 cachedAt 有效时返回其值,否则返回 0;is_change 判定逻辑不变);ESLint 0 错误,临时验证脚本 13 用例全 PASS(新增 last_change_at 断言:命中缓存返回缓存值、未命中返回 0)。",
|
||||
"文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response 新增 last_change_at;description/notes 同步);根版本 0.3.252 → 0.3.253、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.252",
|
||||
"date": "2026-10-09",
|
||||
"type": "updated",
|
||||
"summary": "index.getWarehousePanelData 新增 force 入参(可选):首次拉取传 true 时 is_change 强制为 true 且 last_change_at 可缺省(0.3.251 → 0.3.252)",
|
||||
"methods": [
|
||||
"index.getWarehousePanelData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/index.js#getWarehousePanelData(force 解析兼容 true/'true'/1;force=true 时 last_change_at 缺省视为 0,传了仍做格式校验;is_change = force || (传入时间戳 < 缓存最后更改时间戳));ESLint 0 错误,临时验证脚本 13 用例全 PASS(含 force=true 缺省时间戳、force=1、force='true'、force=false 缺省时间戳仍报参数错误)。",
|
||||
"文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(params 新增 force、last_change_at 的 required 由 true 改为 false 并同步说明;description/response/notes 同步);根版本 0.3.251 → 0.3.252、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.251",
|
||||
"date": "2026-10-09",
|
||||
"type": "added",
|
||||
"summary": "基础模块新增 index.getWarehousePanelData 仓库面板数据接口:按仓库增量变更检测,入参 last_change_at 小于缓存最后更改时间戳时返回 is_change=true,data 暂为空(0.3.250 → 0.3.251)",
|
||||
"methods": [
|
||||
"index.getWarehousePanelData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/index.js#getWarehousePanelData + #getWarehousePanelLastChangeCacheKey;缓存键 index:warehousePanel:lastChangeAt:{warehouseId}(按仓库存储,通过 getCacheAsync 读取);需要登录(isNeedLogin=true),免权限/免鉴权/免系统日志,ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=index 基础模块分组新增 1 条 method(插在 index.loadWarehouses 之后);根版本 0.3.250 → 0.3.251、updatedAt 2026-10-06 → 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.250",
|
||||
"date": "2026-10-06",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData 新增 only_abnormal 入参(可选,兼容 onlyAbnormal 驼峰写法):只看未盘和差异——过滤在 keyword 之后、分页切片之前完成,三视图均生效(location 视图按行 status=unchecked 或 has_unknown 保留;goods 视图按未盘行或明盘 is_diff=1 保留,盲盘仅按未盘;space 视图按行内 goods 子项过滤 status=unchecked 或明盘数量差异、空行整体移除;total 为过滤后行数)(0.3.249 → 0.3.250)",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:stock.check.workData params 新增 only_abnormal(boolean,body,可选,向后兼容,兼容 onlyAbnormal 驼峰写法;未传或非 true(false/0/空串/缺省)不过滤)——过滤在 keyword 之后、分页切片之前完成(与 keyword 叠加,keyword 先过滤、only_abnormal 后过滤;total 为过滤后行数),三视图均生效:①location 视图仅保留 status=unchecked(未盘)或 has_unknown=true(含未知商品记录,未知商品无账面、差异=实盘-0=盘盈视为差异)的行,空库位标记(is_empty)后 status=checked 视为已盘点、不保留;②goods 视图仅保留未盘行(locations 均无 record_ids,即无任何作业记录)或明盘差异行(is_diff=1),盲盘(mode=blind)无数量字段仅按未盘过滤(已盘行全部移除);③space 视图按行内 goods 子项过滤(保留 status=unchecked 子项,明盘另保留 checked_quantity≠system_quantity 的数量差异子项,system_quantity 口径=可用+锁定),过滤后 goods 为空的行整体移除。",
|
||||
"代码依据:app/service/systemMethods/stock/check.js#workData(only_abnormal/onlyAbnormal 蛇形驼峰兼容与透传)+ app/service/systems/stock_check.js#workData(abnormalRequested=onlyAbnormal===true||'true'||1,keywordFilteredRows 后调用 _filterAbnormalWorkRows(resolvedView, rows, check.mode!=='blind'),再分页切片;新增 _filterAbnormalWorkRows 私有方法按视图过滤);回归测试新增 5 用例(location/goods 明盘/space 明盘/space 盲盘/keyword 叠加)全部通过、workData 相关 43 用例通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 only_abnormal、description/response.rows/response.total/notes 同步过滤口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.249 → 0.3.250、updatedAt 保持 2026-10-06;methods/changes/system.json 新增本条(插入数组首位);其余 23 条 method 未改动(stock.check 分组仍为 24 条)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.249",
|
||||
"date": "2026-10-06",
|
||||
"type": "updated",
|
||||
"summary": "盘点账面口径全量统一为可用+锁定(SUM(available_quantity+locked_quantity)):result 库位行/空标记盘亏、report 重算、finish 差异汇总、detail 盘盈盘亏汇总、addDetail 拆行快照(0.3.248 → 0.3.249)",
|
||||
"methods": [
|
||||
"stock.check.workData",
|
||||
"stock.check.workDataDetail",
|
||||
"stock.check.workDataSpaceDetails",
|
||||
"stock.check.result",
|
||||
"stock.check.report",
|
||||
"stock.check.finish",
|
||||
"stock.check.detail",
|
||||
"stock.check.addDetail"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:全部盘点账面口径统一为 wms_storage SUM(available_quantity+locked_quantity)(=可用+锁定)——①result 库位行 stocks 账面与空库位标记盘亏(_buildDetailAggregations/_formatDetailAggregationRow);②report 重算 diff_items 的库位行按商品账面与空标记库位账面(_recalcCheckSummary);③finish 差异汇总复用 _recalcCheckSummary 口径;④detail profit_total/loss_total 汇总复用同口径;⑤addDetail 按库位拆行写入的明细快照 system_quantity=该库位库存 SUM(可用+锁定);与盘点作业视图(workData/workDataDetail/workDataSpaceDetails,0.3.248 已改)完全一致。商品行差异仍以明细账面快照(system_quantity 列)对比。",
|
||||
"代码依据:app/service/systems/stock_check.js#_recalcCheckSummary/#_buildDetailAggregations/#_formatDetailAggregationRow/#addDetail(attributes 全部改为 literal('SUM(available_quantity + locked_quantity)'));回归测试 222/222 通过、ESLint 0 错误(测试 helper fetchStorageQuantity/拆行断言/多库位拆行用例同步改口径)。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 8 条 method(workData/workDataDetail/workDataSpaceDetails/result/report/finish/detail/addDetail 的 description/notes 同步库位账面=可用+锁定口径);根版本 0.3.248 → 0.3.249、updatedAt 2026-10-05 → 2026-10-06;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 23 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.248",
|
||||
"date": "2026-10-05",
|
||||
"type": "updated",
|
||||
"summary": "盘点作业数据接口(stock.check.workData/workDataDetail/workDataSpaceDetails)库位账面改为可用+锁定(SUM(available_quantity+locked_quantity))并新增 locked_quantity 锁定数量字段(0.3.247 → 0.3.248)",
|
||||
"methods": [
|
||||
"stock.check.workData",
|
||||
"stock.check.workDataDetail",
|
||||
"stock.check.workDataSpaceDetails"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:goods 视图 locations 各项与 space 视图 goods 子项的库位账面 system_quantity 由 wms_storage SUM(quantity) 改为 SUM(available_quantity+locked_quantity)(=可用+锁定),并新增 locked_quantity(该库位锁定数量,SUM(locked_quantity));盘点数量 quantity/checked_quantity 口径不变;盲盘仍不返回任何数量字段。",
|
||||
"代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows/#_buildSpaceWorkRows(Storage 查询 attributes 增加 literal('SUM(available_quantity + locked_quantity)') 与 fn('SUM', col('locked_quantity')));result/report/finish 的差异汇总口径不变(仍按 quantity 与明细快照);回归测试 222/222 通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData、stock.check.workDataDetail 与 stock.check.workDataSpaceDetails 三条(description/response.rows/notes 同步库位账面=可用+锁定口径与 locked_quantity 字段);根版本 0.3.247 → 0.3.248、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 20 条 method 未改动(stock.check 分组仍为 23 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.247",
|
||||
"date": "2026-10-05",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData / workDataDetail 的 goods 视图明盘库位同时输出账面数量(system_quantity)与盘点数量(quantity)两个字段(0.3.246 → 0.3.247)",
|
||||
"methods": [
|
||||
"stock.check.workData",
|
||||
"stock.check.workDataDetail"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:goods 视图明盘(mode=open)每库位由单一 quantity(实盘合计)改为同时输出 system_quantity(该库位账面数量,wms_storage 该库位 SUM(quantity),无库存记录库位为 0)与 quantity(该库位盘点数量=实盘合计,未盘库位为 0)两字段区分开;盲盘仍不返回任何数量字段。",
|
||||
"代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows(Storage 查询 attributes 增加 fn('SUM', col('quantity')) 按 stock+space 分组汇总,构建 stockId→spaceCode→账面数量映射;buildLocationItem 明盘输出双数量字段);行级 checked_quantity 仍为 locations.quantity 合计、diff/is_diff 仅存在作业记录的行计算(口径不变);回归测试 222/222 通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataDetail 两条(description/response.rows/notes 同步明盘库位双数量字段口径);根版本 0.3.246 → 0.3.247、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 23 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.246",
|
||||
"date": "2026-10-05",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData / workDataDetail 的 goods 视图 locations 改为商品所在全部库位列表(明盘显示库位+数量、盲盘只显示库位;未盘行不误显盘亏差异)(0.3.245 → 0.3.246)",
|
||||
"methods": [
|
||||
"stock.check.workData",
|
||||
"stock.check.workDataDetail"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:_buildGoodsWorkRows 的 locations 由「仅已盘库位(按首条记录 id 升序)」改为「商品所在全部库位列表」——基础库位取自 wms_storage(任务 stock_id 集合 + is_enabled=1 未删除,DISTINCT space_id)经库位表取 space_code 并按拣货路径排序(pick_sequence 升序、pick_priority 降序、库位 id 升序兜底);无库存但已有作业记录的库位按首条记录 id 升序追加在末尾;空库位(location_code 空)组仍排在最后;未盘库位输出空信息(checked_at/checker_name=null、record_ids/images 空数组、明盘 quantity=0)。",
|
||||
"差异口径:明盘 checked_quantity=locations 各库位 quantity 合计(未盘行恒 0);diff_quantity/is_diff 仅对存在作业记录(detailRecords.length>0)的行计算,未盘行恒 0(避免未盘行误显盘亏差异——此前 locations 非空导致未盘行 diff_quantity=0-账面为负);盲盘仍不返回任何数量字段。",
|
||||
"代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows(workData 与 workDataDetail goods 明细分支复用同一构建函数);回归测试 222/222 通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataDetail 两条(description/response.rows/notes 同步 goods 视图 locations 商品所在全部库位列表口径);根版本 0.3.245 → 0.3.246、updatedAt 2026-10-04 → 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 23 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.245",
|
||||
"date": "2026-10-04",
|
||||
"type": "added",
|
||||
"summary": "新增 stock.check.workDataDetail 盘点明细单行作业数据接口(workData 单行版,仅库位任务明细):入参 detail_id(库位范围行,兼容 detailId 驼峰),返回统一 success 包装、data 为单行作业数据(结构与 workData location 视图单行一致);仅任务状态 approved/checking 可拉取(0.3.244 → 0.3.245)",
|
||||
"methods": [
|
||||
"stock.check.workDataDetail"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:ALL_METHOD_NAMES 新增 workDataDetail(22→23)、_noNeedLog 查询类清单新增 workDataDetail;方法层 stock.check.workDataDetail 兼容 detail_id/detailId 驼峰写法、warehouse_id 服务端自动注入;系统层仅库位任务明细(scope_type=location)支持,返回结构与 workData location 视图单行一致(detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/checked_at/checkers/goods)。",
|
||||
"校验口径:detail_id 非正整数 400『盘点明细ID不能为空』;明细不存在 400『盘点明细不存在』;scope_type 非 location 400『仅库位任务明细支持拉取单行作业数据』;任务不存在 400『盘点任务不存在』;任务状态非 approved/checking 400 拒绝(与 stock.check.workData 同口径)。",
|
||||
"代码依据:app/service/systemMethods/stock/check.js#workDataDetail + app/service/systems/stock_check.js#workDataDetail(复用 _buildLocationWorkRows);回归测试 216/216 通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workDataDetail 一条(位于 stock.check.workData 之后);根版本 0.3.244 → 0.3.245、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组由 22 条增至 23 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local)与生产库(WMS_DB_TARGET=production)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.244",
|
||||
"date": "2026-10-04",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData 新增 keyword 入参(可选,向后兼容):仅库位任务(location 视图)按行 location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后再分页(0.3.243 → 0.3.244)",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:params 新增 keyword(string,可选,向后兼容)——先分流:仅库位任务(type=location/all,即服务端解析视图为 location)生效;生效时按 location 视图行字段 location_code(优先明细快照,缺失回退库位表 space_code)与 location_name(custom_name 兜底 space_code)做模糊匹配(contains、不区分大小写)过滤任务明细后再分页返回;非库位任务(goods/store,space/goods 视图)忽略该参数;keyword 为空/纯空白视为未传不过滤。",
|
||||
"分页口径:过滤在分页切片之前完成,total 为过滤后的行数,rows 为过滤后的当前页行(分页仍按 pagination.{page,pageSize} 切片,与既有口径一致)。",
|
||||
"代码依据:app/service/systemMethods/stock/check.js#workData(包装层透传 keyword)+ app/service/systems/stock_check.js#workData(normalizedKeyword=String(keyword||\"\").trim().toLowerCase(),resolvedView===\"location\" 且非空时按 location_code/location_name includes 过滤);回归测试 214/214 通过、ESLint 0 错误。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 keyword、description/response.rows/response.total 同步过滤口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.243 → 0.3.244、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库与生产库(import 当前 system.json → export 往返校验);生产库此前停留在 0.3.240,本次回填一并同步 0.3.241(detail 精简)、0.3.242(workData 返回 view)、0.3.243(waybill 主单号数组)三批累积差异。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.243",
|
||||
"date": "2026-10-04",
|
||||
"type": "updated",
|
||||
"summary": "waybill.warehouse.list/export 的 where.mainWaybillCode 支持字符串数组(多主单号精确匹配,Op.in 定位 order_id 集合,0.3.242 → 0.3.243)",
|
||||
"methods": [
|
||||
"waybill.warehouse.list",
|
||||
"waybill.warehouse.export"
|
||||
],
|
||||
"notes": [
|
||||
"变更内容:where.mainWaybillCode 由「仅字符串单值」扩展为「字符串 | 字符串数组」;数组时按 Op.in 精确匹配多个主单号,先定位 order_id 集合,再返回/导出这些订单下的全部运单(主+子)。单值行为完全不变(order_id 条件仍为标量)。",
|
||||
"边界:数组元素自动 trim 并过滤空值;全部不存在时直接返回空结果(list 空列表 / export total_count=0);空数组或全空值数组不添加该筛选条件;与 waybillCode 同时传入时按 AND 叠加。仓库隔离(warehouse_id = ctx.user.store_id)不受影响。",
|
||||
"文档修正:原描述「与 waybillCode 互斥,同时传入时 mainWaybillCode 优先」与实际实现不符(实现为 AND 叠加),本次一并更正。",
|
||||
"代码依据:app/service/systems/waybill.js#resolveMainWaybillOrderIds(list/export 共用);回归测试 test/app/service/systems/waybill.warehouse.mainWaybillCode.in.test.js。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(import 当前 system.json)并 export 往返校验;生产库需另行同步。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.03-stock-check-workdata-view-only",
|
||||
"date": "2026-10-03",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData 不返回任务主表信息 check,改为返回 view(解析后的视图类型 location/goods/space);任务信息统一由 stock.check.detail 返回",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/stock_check.js#workData 返回体由 { check, rows, total, page, pageSize } 改为 { view, rows, total, page, pageSize }(check 仍内部查询用于视图解析/盲盘明盘/状态守卫;view=resolvedView);app/service/systemMethods/stock/check.js#workData 仅同步 JSDoc(行为不变,仍统一 success/failure 包装)。",
|
||||
"测试同步:test/app/service/systems/stock_check.test.js(workData 用例移除 data.check.* 断言、新增「响应键集合为 page/pageSize/rows/total/view」「三视图 view 断言(location/goods/space、库位任务无视 is_goods、is_goods 非 true 走 space)」「方法层不返回 check 且 view=goods」;盲盘/明盘模式断言改由 findCheckRow 从库表核对);真实库集成测试 213/213 通过、ESLint 0 错误。",
|
||||
"兼容性影响:响应 data 移除 check 字段(破坏性变更)、新增 view 字段;rows/total/page/pageSize 与 location/goods/space 三视图结构、明盘盲盘数量控制、状态限制均不变;前端如需任务主表信息改调 stock.check.detail,如需判断行结构可直接读取 view,无需再自行按任务类型/is_goods 推导。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response(data.children 以 view 替换 check)/notes 同步;headers/params/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.241 → 0.3.242、updatedAt 保持 2026-10-03;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,需另行同步回填开发库与生产库(import 当前 system.json → export 往返校验),保持库与文件一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.03-stock-check-detail-task-only",
|
||||
"date": "2026-10-03",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.detail 精简为只返回任务本身信息({ check }),不再返回明细范围行 rows 与 total(明细范围行/盘点结果改由 stock.check.result 返回)",
|
||||
"methods": [
|
||||
"stock.check.detail"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/stock_check.js#detail 改为仅返回 { check: _formatCheckRow(check) }(删除明细表查询、rows/total 与商品行 stock 挂载);同步删除已无引用的 _formatDetailScopeRow;app/service/systemMethods/stock/check.js#detail 仅同步 JSDoc(行为不变,仍统一 success/failure 包装)。",
|
||||
"测试同步:test/app/service/systems/stock_check.test.js(helper detailCheck 改为「detail 取 check + 直查明细表补 rows」,新增 detail 只返回 { check } 与 400 边界用例,方法层 detail 用例改写,删除原「detail 纯范围行」5 条用例与已无引用的字段常量);真实库集成测试 213/213 通过、ESLint 0 错误。",
|
||||
"兼容性影响:响应 data 由 { check, rows, total } 变更为 { check },为破坏性变更;调用方如需明细范围行/盘点结果改调 stock.check.result(返回 { check, rows, total }),作业记录改调 stock.check.recordList,盘点作业数据改调 stock.check.workData。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.detail 一条(description/response(data.children 仅保留 check)/notes 同步;headers/params/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.240 → 0.3.241、updatedAt 2026-10-02 → 2026-10-03;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,需另行同步回填开发库与生产库(import 当前 system.json → export 往返校验),保持库与文件一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-recordList-goods-mount-align-workData",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.recordList 商品信息挂载对齐 workData:已知商品(stock_id 有值)item_code/item_name/spec 批量取自 stockWarehouse.getStockDetails(带缓存,未命中回退明细表商品快照),新增 store_id(商品货主ID)/store_name(货主名,经 _resolveStoreNameMap 解析)、barcode 兜底商品条码(getStockDetails.barcodes[0],无则保留记录原始条码);未知商品(stock_id 为空)item_code=扫描条码兜底、item_name=名称快照兜底条码、spec/store_id/store_name=null、barcode=扫描条码;保留记录表全字段不变、images 仍为作业记录照片(FileReference business_type=stock_check_record)、location_code 空串统一返回 null 不变——向后兼容,仅新增列。代码已改并测试通过 215/215、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.recordList"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/stock_check.js#recordList(rows 记录表全字段不变 + 商品信息挂载:已知商品 stockDetailMap 由 ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }) 带缓存批量取,item_code/item_name/spec 优先 getStockDetails、未命中回退明细表 wms_stock_check_detail 商品快照;store_id=Number(stockDetail.store_id)(无则 null)、store_name 经 _resolveStoreNameMap(storeIds, warehouseId) 解析;barcode=stockDetail.barcodes[0].barcode(无则保留记录原始条码);未知商品 isUnknownGoods=true:item_code=扫描条码(barcode 空则 null)、item_name=名称快照兜底条码、spec/store_id/store_name=null、barcode=扫描条码;location_code 空串归一 null 不变;images 经 _attachRecordImages 挂载 FileReference business_type=stock_check_record 不变)。本次代码已改并测试通过 215/215、ESLint 0 错误。",
|
||||
"影响面:向后兼容(仅新增 spec/store_id/store_name 三列与 barcode 商品条码兜底),记录表全字段与 item_code/item_name 原有兜底口径保留;未知商品新增 spec/store_id/store_name 为 null;location_code 空串返回 null 不变;images 仍为作业记录照片。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.recordList 一条(description/response.rows 补新增字段 spec/store_id/store_name 与 barcode 兜底口径(对齐 workData)、说明保留记录全字段;notes 补「商品信息挂载对齐 workData」说明);headers/params/errors/isNeedAuth/isNeedLogin 不变;根版本 0.3.239 → 0.3.240、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-work-data-record-photos",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData 三视图作业照片挂载与 record_ids 输出:location 视图 goods 子项 images 由「商品主图 stockDetail.image_url」改为「作业记录照片 record.images」(_attachRecordImages 挂载 FileReference business_type=stock_check_record,与 result/recordList 口径一致;未知商品子项 images 维持记录照片不变);goods 视图(is_goods=true)locations 聚合项新增 images(该库位该商品全部记录的作业照片扁平去重)与 record_ids(该库位该商品全部作业记录 ID,按记录 id 升序);space 视图 goods 子项 images 由商品主图改为该商品在该库位的作业照片聚合(扁平去重)并新增 record_ids(该商品在该库位全部作业记录 ID);行级/未盘项无记录时 images/record_ids 为空数组。record_ids 供前端编辑/移除记录(recordDelete 批量删除、recheckClearLocation 重盘清除库位),location 视图单条 record_id 直接定位不变。代码已改并测试通过 214/214、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/stock_check.js#_buildLocationWorkRows(已知商品子项 images 由商品主图改为 record.images 作业记录照片,未知商品子项维持记录照片)+ #_buildGoodsWorkRows(locations 聚合项新增 record_ids(按记录 id 升序)与 images(该库位该商品全部记录照片扁平去重),行级 images 仍为 stockDetail.image_url)+ #_buildSpaceWorkRows(goods 子项 images 由商品主图改为该商品在该库位的作业照片聚合(扁平去重),新增 record_ids)+ #_attachRecordImages(FileReference business_type=stock_check_record,与 result/recordList 口径一致)。本次代码已改并测试通过 214/214、ESLint 0 错误。",
|
||||
"影响面:images 由商品主图变为作业照片(location 视图已知商品子项、space 视图 goods 子项);goods 视图行级 images 仍为商品主图;goods locations 项与 space goods 项新增 record_ids(供前端编辑/移除记录:stock.check.recordDelete 批量删除、stock.check.recheckClearLocation 重盘清除库位);location 视图单条 record_id 直接定位不变;行级/未盘项无记录时 images/record_ids 为空数组;其余字段与分页/状态限制口径不变。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步三视图作业照片挂载与 record_ids 输出口径);headers/params/errors/isNeedAuth/isNeedLogin 不变;根版本 0.3.238 → 0.3.239、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-goods-detail-split-by-location",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "盘点模块「商品任务必须按库位盘点」改造:商品明细按「商品+库位」拆行——addDetail/patternCreate 商品路径(_addGoodsDetailRows)按商品在仓库的启用库存库位(wms_storage is_enabled=1,按 space_id 分组 SUM)拆行,每个「商品+库位」生成一条 scope_type=goods 明细行(location_id/location_code 绑定库存库位、system_quantity=该库位库存 SUM),一个商品多个库位多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细(商品任务必须按库位盘点);同商品重复添加整体跳过(幂等口径不变);added/total_items 为拆分明细行数。detail 商品行 location_id/location_code 非空(15 字段结构不变)。submit「存在缺少库位的盘点明细,无法提交审核」校验不再限定 scope_type=location:全部明细行(库位型与商品型)location_id 为空或 location_code 为空/空串均拦截。配套数据库迁移 20261002170000(已在开发/生产执行):uk_check_stock(check_id,stock_id) → uk_check_stock_location(check_id,stock_id,location_id);uk_check_location 唯一约束放宽为普通索引 idx_check_location(库位行幂等由应用层查重保证)。代码已改并测试通过 213/213、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.addDetail",
|
||||
"stock.check.detail",
|
||||
"stock.check.submit",
|
||||
"stock.check.patternCreate",
|
||||
"stock.check.addLocationDetail"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows(Storage.findAll where warehouse_id+stock_id in+is_enabled=1、attributes SUM(quantity)、group=[stock_id, space_id];LocationSpace 按 id 取 space_code 快照;货主校验与同商品整体跳过沿用;无启用库存库位商品 → invalidStockIds;每个「商品+库位」生成 scope_type=goods 行 location_id/location_code/system_quantity=该库位 SUM)+ #addDetail(added=toCreate.length、total_items 重算)+ #submit(count where check_id+(location_id 为空或 location_code 为空/空串),不再限定 scope_type=location)+ #detail/_formatDetailScopeRow(15 字段结构不变,商品行 location 有值)+ #patternCreate(pattern.type==='goods' 调 _addGoodsDetailRows)。本次代码已改并测试通过 213/213、ESLint 0 错误。",
|
||||
"迁移说明:database/migrations/20261002170000-split-goods-detail-by-location.js(已在开发库与生产库执行)——wms_stock_check_detail 唯一索引 uk_check_stock(check_id, stock_id) 变更为 uk_check_stock_location(check_id, stock_id, location_id)(商品拆行后同任务同商品可多行);uk_check_location(check_id, location_code) 唯一约束放宽为普通索引 idx_check_location(商品拆行后同任务同库位可有多个商品行,库位行幂等由应用层查重保证)。",
|
||||
"影响面:商品明细行数=商品×启用库存库位数(不再一商品一行);system_quantity 语义由商品全仓账面变为该「商品+库位」库存 SUM;无启用库存库位的商品无法加入盘点(addDetail 记入 invalid_stock_ids、patternCreate 不产生明细行);detail 商品行 location_id/location_code 由 null 变为绑定库存库位;submit 缺库位校验覆盖全部明细行(商品行与库位行)。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.addDetail:description/params/response/notes 补商品拆行口径(拆多行、无库存库位 invalid、system_quantity=该库位账面、added=拆分行数);stock.check.detail:description/response.rows/notes 商品行 location_id/location_code 绑定库存库位;stock.check.submit:description/notes 缺库位校验改为覆盖全部明细行;stock.check.patternCreate:description/notes 补 goods 定式按库存库位拆行;stock.check.addLocationDetail:notes 幂等索引口径同步 uk_check_location 唯一约束放宽为普通索引 idx_check_location);根版本 0.3.237 → 0.3.238、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动(stock.check 分组仍为 22 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-submit-missing-location-guard",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.submit 新增提交校验:库位范围明细(scope_type=location)缺少库位(location_id 为空或 location_code 为空/空串)的明细行存在时抛 400「存在缺少库位的盘点明细,无法提交审核」——脏数据防御,正常流程 addDetail/addLocationDetail 不会产生此类明细;原有校验(状态非 created/rejected 不允许提交审核、total_items<=0 无明细行拒绝)不变。代码已改并测试通过 211/211、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.submit"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/stock_check.js#submit——校验顺序:任务ID 为空→400「盘点任务ID不能为空」;任务不存在→400「盘点任务不存在」;状态非 created/rejected→400「当前状态(xx)不允许提交审核」;total_items<=0→400「盘点任务还没有明细行,无法提交审核」;新增库位缺库位校验:StockCheckDetail.count where check_id+scope_type=location+(location_id 为空或 location_code 为空/空串)>0→400「存在缺少库位的盘点明细,无法提交审核」(脏数据防御,正常流程 addDetail/addLocationDetail 不会产生此类明细)。本次代码已改并测试通过 211/211、ESLint 0 错误。",
|
||||
"影响面:前端无需改动——该校验仅拦截脏数据(手工/历史遗留缺库位明细),正常盘点流程不受影响;原有校验顺序不变。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.submit 一条(errors 400 补「存在缺少库位的盘点明细,无法提交审核」、description/notes 补该校验口径);根版本 0.3.236 → 0.3.237、updatedAt 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-record-delete-batch-recheck-clear-location",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "盘点模块两项改动:① stock.check.recordDelete 由旧版单值删除升级为批量删除(与 detailDelete 批量口径一致)——入参 record_ids 数组(单次上限 200,兼容 recordIds 驼峰数组、recordId 单数驼峰、record_id 单值旧写法,单值自动转数组);响应由 { record_id, deleted, total_items, checked_items, diff_items, detail_status } 变更为 { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status }(deleted_ids/skipped_ids 保持入参顺序,查不到的记录计入 skipped_ids 不报错,旧版「作业记录不存在或不属于该盘点任务」400 不再返回);② 新增 stock.check.recheckClearLocation 重盘清除库位——传任务ID+库位ID,清除该库位范围内明细(scope_type=location)的全部作业记录(含空库位标记)、该库位回到未盘,仅库位范围任务(type=location/all)且状态 approved/checking 可用,删除后清理图片引用、重算汇总(主表状态不回退)、写 STOCK_CHECK_CLEAR_LOCATION 日志;ALL_METHOD_NAMES 由 21 个增至 22 个(加入 recheckClearLocation,位于 recordDelete 之后)。代码已改并测试通过 210/210、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.recordDelete",
|
||||
"stock.check.recheckClearLocation"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/stock/check.js#recordDelete(record_ids 兼容 recordIds/recordId/record_id,单值自动转数组)+ app/service/systems/stock_check.js#recordDelete(校验顺序:任务ID 为空→400「盘点任务ID不能为空」;任务不存在→400「盘点任务不存在」;状态非 approved/checking→400「当前状态(xx)不允许删除作业记录」;ids 为空→400「请至少选择一条作业记录」;超 200→400「单次最多删除 200 条作业记录」;查不到计入 skipped_ids;清理 FileReference 图片引用、_recalcCheckSummary 重算、写 STOCK_CHECK_DELETE_RECORD 日志)。",
|
||||
"代码依据:app/service/systemMethods/stock/check.js#recheckClearLocation(location_id 兼容 locationId 驼峰,warehouse_id 由 ctx.user.store_id 注入)+ app/service/systems/stock_check.js#recheckClearLocation(校验顺序:任务ID 为空/库位ID 为空/任务不存在/状态非 approved/checking→「当前状态(xx)不允许清除库位盘点信息」/任务范围非库位 type≠location/all→「仅库位盘点任务支持重盘清除库位」/库位不在任务范围→「该库位不在盘点任务范围内」;删除该库位范围明细全部作业记录含空库位标记、清理图片引用、重算汇总、主表状态不回退、写 STOCK_CHECK_CLEAR_LOCATION 日志)。",
|
||||
"影响面:recordDelete 前端需改传 record_ids 数组并按新响应字段(deleted_count/deleted_ids/skipped_ids)解析;recheckClearLocation 为库位盘点重盘场景新接口,非库位任务调用报 400。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.recordDelete(params/response/errors/description/notes 按新批量口径重写,description 注明「由旧版单值删除升级为批量删除」)并新增 stock.check.recheckClearLocation(位于 recordDelete 之后);分组内「21 个 method」「21 个方法共用统一包装」等字样全部更新为 22 个(workData 权限口径 ALL_METHOD_NAMES 清单加入 recheckClearLocation);根版本 0.3.235 → 0.3.236、updatedAt 2026-10-02;methods/changes/system.json 插入本条(数组首位);stock.check 分组由 21 条增至 22 条。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production + --env production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,库与文件一致;stock.check 分组共 22 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-markEmpty",
|
||||
"date": "2026-10-02",
|
||||
"type": "added",
|
||||
"summary": "盘点模块新增 stock.check.markEmpty 方法(标记库位为空,库位盘点模式专属):仅库位范围任务(type=location/all)与库位明细行(scope_type=location)支持;内部转调 report(is_empty=true) 口径——写/更新空标记记录(stock_id/barcode/item_name=null、quantity=0、is_empty=1)、清除该明细商品记录、主表 approved→checking、重算 checked_items/diff_items/detail_status;按校验顺序返回 400(任务ID/明细ID 为空、任务不存在、状态不允许、非库位任务、明细不存在、明细非库位行);ALL_METHOD_NAMES 由 20 个增至 21 个(加入 markEmpty)——免 API 权限、免仓库有效期鉴权、必须登录,写操作记录操作日志(STOCK_CHECK_REPORT)。",
|
||||
"methods": [
|
||||
"stock.check.markEmpty"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/stock/check.js#markEmpty(warehouse_id 由服务端从 ctx.user.store_id 自动注入)+ app/service/systems/stock_check.js#markEmpty(校验后转调 this.report({ is_empty: true }));ALL_METHOD_NAMES 更新为 create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,report,markEmpty,recordList,recordDelete,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate(21 个)。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.markEmpty 一条(位于 stock.check.report 之后);分组内各 method notes 的「20 个方法共用统一包装」与 workData 权限口径 note 的 ALL_METHOD_NAMES 列表同步更新为 21 个;根版本 0.3.234 → 0.3.235、updatedAt 2026-10-02;methods/changes/system.json 插入本条(数组首位);stock.check 分组由 20 条增至 21 条。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;先经 script/method-doc-create.cjs 在维护源新建(--bump 升版本),再按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入本变更记录;同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,库与文件一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-empty-location-mark",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "盘点模块新增「空库位标记」能力:stock.check.report 新增 is_empty 入参(仅库位盘点明细支持,确认该库位为空——不要求商品/条码、quantity 恒 0,写特殊作业记录 stock_id/barcode/item_name=null、quantity=0、is_empty=1,与商品记录互斥:标记空删除该明细商品记录、上报商品删除空标记记录,商品明细行传 is_empty 报 400「仅库位盘点明细支持空库位标记」);stock.check.workData location 视图行新增 is_empty 字段(空标记记录不计入 goods 子列表,空标记后 status=checked 视为已盘点);stock.check.result 库位行新增 is_empty 字段(空标记时 stocks=[]、unknown_items=[]、checked_quantity=0、status=checked,账面有库存时 diff_quantity 为负数(盘亏)、is_diff=1);主表汇总(_recalcCheckSummary)空标记记录计入已盘明细、空标记明细库位账面有库存即计盘亏差异(diff_items);stock.check.recordList/export 记录行输出 is_empty(export Sheet2 空库位记录商品编码列输出「(空库位)」、数量 0);数据库 wms_stock_check_record 新增 is_empty 字段(TINYINT(1) NOT NULL DEFAULT 0,迁移 20261002160000 已在开发/生产执行)。代码已改并测试通过 201/201、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.report",
|
||||
"stock.check.workData",
|
||||
"stock.check.result",
|
||||
"stock.check.recordList",
|
||||
"stock.check.export"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:report 空库位标记(is_empty 归一化 true/'true'/1,仅 scope_type=location 支持、商品明细行报 400『仅库位盘点明细支持空库位标记』;标记空时 quantity 恒 0、写 stock_id/barcode/item_name=null、quantity=0、is_empty=1 的特殊作业记录;覆盖式查重按 detail_id+is_empty=1+location_code;互斥:标记空删除该明细 is_empty=false 记录、上报商品删除该明细 is_empty=true 记录)app/service/systems/stock_check.js#report;workData location 视图行 is_empty(空标记记录不进 goods 子列表、行 status=checked)app/service/systems/stock_check.js#_buildLocationWorkRows;result 库位行 is_empty 与盘亏口径(stocks=[]、unknown_items=[]、checked_quantity=0、status=checked;按 wms_storage SUM(quantity) 账面>0 时 diff_quantity=-账面总量、is_diff=1)app/service/systems/stock_check.js#_formatDetailAggregationRow;主表汇总(空标记计入已盘明细、账面有库存计盘亏差异)app/service/systems/stock_check.js#_recalcCheckSummary;recordList 记录全字段带 is_empty;export Sheet2 空库位行商品编码列输出『(空库位)』、数量 0 app/service/systems/stock_check.js#_generateAndUploadStockCheckExcel。本次代码已改并测试通过 201/201、ESLint 0 错误。",
|
||||
"数据库变更:database/migrations/20261002160000-add-is-empty-to-stock-check-record.js(wms_stock_check_record 新增 is_empty TINYINT(1) NOT NULL DEFAULT 0 COMMENT 是否空库位标记,位于 item_name 之后),开发库(127.0.0.1:3307/wms)与生产库(112.124.21.102:3306/wms)均已执行。",
|
||||
"影响面:前端库位盘点(明细 scope_type=location)可传 is_empty=true 快速确认空库位(无需扫描商品/条码);workData/result 库位行新增 is_empty 字段用于展示空标记状态(空标记行按已盘点处理、账面有库存显示盘亏差异);recordList/export 自动带出 is_empty(export 空库位行商品编码列显示「(空库位)」);商品明细行传 is_empty 会被 400 拒绝。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 20 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-work-data-location-unknown-merge",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData location 视图行结构调整:删除 unknown 未知商品子列表——未知商品记录(stock_id 为空)不再单独输出,与已知商品统一并入 goods 子列表、输出字段对齐已知商品(record_id/stock_id=null/item_code 用条码兜底/item_name 用名称快照兜底条码/barcode/images/store_id=null/store_name=null/quantity/checked_at/checker_name);行级 has_unknown 标记保留(该库位是否含未知商品记录)。代码已改并测试通过 197/197、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/stock_check.js#_buildLocationWorkRows——records 按 detail_id 聚合后,已知商品(stock_id 正整数)与未知商品(stock_id 为空/非正整数)均 push 进 goods:已知商品取 stockDetailMap(stockWarehouse.getStockDetails 带缓存)补 item_code/item_name/barcode(barcodes[0].barcode)/images(image_url)/store_id/store_name(_resolveStoreNameMap 解析);未知商品 stock_id=null、item_code=条码兜底、item_name=名称快照兜底条码、barcode=记录条码、images=_attachRecordImages 挂载(FileReference business_type=stock_check_record)、store_id/store_name=null;quantity/checked_at/checker_name 与已知商品一致;行级 has_unknown=true 标记保留。本次代码已改并测试通过 197/197、ESLint 0 错误。",
|
||||
"影响面:前端无需再处理 unknown 数组——直接遍历 goods 子列表,按 stock_id 是否为 null 区分未知商品(未知商品 item_code 即扫描条码、item_name 即上报名称快照);has_unknown 仍可用于快速判断该库位是否含未知商品;其余视图(goods/space)与分页等结构不变。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步 location 视图行结构——删除 unknown 子列表字段说明、goods 改为「已知商品与未知商品记录均入内,未知商品 stock_id=null、item_code 用条码兜底、store_id/store_name 为 null」、has_unknown 保留说明;headers/params/errors/isNeedAuth/isNeedLogin 与 goods/space 视图及分页描述不变);根版本 0.3.232 → 0.3.233、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-data-envelope",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "stock.check 分组全部 20 个方法响应统一增加 data 层封装:成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp };业务数据结构本身不变(如 create 返回盘点任务字段、list 返回 { rows,total,page,pageSize }、workData 返回 { check,rows,total,page,pageSize }),只是整体包进 data。代码已改并测试通过 197/197、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.create",
|
||||
"stock.check.list",
|
||||
"stock.check.addDetail",
|
||||
"stock.check.detailDelete",
|
||||
"stock.check.detail",
|
||||
"stock.check.result",
|
||||
"stock.check.workData",
|
||||
"stock.check.report",
|
||||
"stock.check.recordList",
|
||||
"stock.check.recordDelete",
|
||||
"stock.check.finish",
|
||||
"stock.check.submit",
|
||||
"stock.check.cancel",
|
||||
"stock.check.audit",
|
||||
"stock.check.batchDelete",
|
||||
"stock.check.export",
|
||||
"stock.check.exportTaskProgress",
|
||||
"stock.check.patternList",
|
||||
"stock.check.patternCreate",
|
||||
"stock.check.addLocationDetail"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/stock/check.js#_call(20 个方法共用的统一调用包装)——成功返回 { flag:\"success\", code:1, message:\"ok\", data:result };业务错误(code 为 400-599 整数)返回 { flag:\"failure\", code, message, data:null };其余异常记录日志并返回 { flag:\"failure\", code:500, message:\"服务器内部错误\", data:null };app/lib/api_response.js#toSuccess 识别标准载荷后顶层补充 timestamp。",
|
||||
"旧口径(改造前):成功 { flag:\"success\", code:1, message:\"ok\", ...业务字段平铺 }(MainService.success 展开 data 的平铺结构);失败响应 { flag:\"failure\", code, message }(无 data);本次统一为 data 层封装,与项目 toSuccess/toFailure 常规口径一致。",
|
||||
"失败语义变化:业务错误(400/500 等)不再由控制器 catch 后转 HTTP 4xx/5xx + toFailure,而是由 _call 捕获后在 body 内以 flag=failure + data=null 返回(HTTP 200);未登录/鉴权失败(checkAuth 401)仍走控制器 toFailure(HTTP 401)。前端失败判定建议以 flag 为准。",
|
||||
"影响面:前端解析响应需从 data 取业务数据(原顶层业务字段全部移入 data);业务数据结构本身不变。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组全部 20 条 method 的 response 统一调整——顶层固定为 flag/code/message/data/timestamp,原业务字段整体移入 data.children(字段与说明不变),每条 notes 追加统一 data 层封装口径;headers/params/errors/isNeedAuth/isNeedLogin/description 不变;根版本 0.3.231 → 0.3.232、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production + --env production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-work-data-view-driven",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData 视图驱动规则改造:view 入参废弃(不再校验、不再使用,传任何值都被忽略、不报错);新增 is_goods 入参(boolean,body,可选,兼容 isGoods 驼峰写法)——任务范围为库位(type=location/all)一律按库位视图(location)返回、无视 view/is_goods;任务范围为商品(type=goods/store)默认聚合库位视图(space),仅 is_goods=true 时按商品视图(goods)返回,is_goods 其他值(false/0/缺省等)一律按默认 space;分页能力不变(pagination.{page,pageSize},与 stock.check.list 口径一致,默认 20 上限 200);errors 移除「视图类型非法(仅支持 location/goods/space)」条目,保留任务ID不能为空/状态限制/任务不存在/500。代码已改并测试通过 197/197、ESLint 0 错误。",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/stock/check.js#workData(warehouse_id 由 ctx.user.store_id 注入;const { id, is_goods: isGoodsSnake, isGoods: isGoodsCamel, pagination } = data || {},isGoods=is_goods 未定义时回退 isGoods 兼容驼峰写法;不再读取/校验 view)+ app/service/systems/stock_check.js#workData(视图解析:normalizedType=String(check.type||'').trim(),type=location/all 一律 location 无视 view/is_goods;否则 isGoods===true||'true'||1 → goods、其余默认 space;错误口径不变:ID 不能为空/任务不存在/状态限制/500)。本次代码已改并测试通过 197/197、ESLint 0 错误。",
|
||||
"影响面:前端如需商品视图须改传 is_goods=true(或 isGoods=true);view 传值不再生效、不会被校验;库位任务前端无需传 is_goods。响应结构 { check, rows, total, page, pageSize } 与分页口径不变。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 删除 view、新增 is_goods;description 视图规则改为「库位任务一律 location、商品任务默认 space、is_goods=true 才 goods;view 入参已废弃忽略」;errors 删除视图非法条目;response 结构不变;notes 同步代码依据与视图驱动规则);根版本 0.3.230 → 0.3.231、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-work-data-pagination-conventional",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData 分页口径修正:改为与 stock.check.list 一致的常规口径——仅入参 pagination.{page,pageSize}(不再兼容 page_size 蛇形写法、不再支持顶层 page/pageSize/page_size),默认 page=1、pageSize=20、上限 200,响应 page/pageSize 结构不变",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/stock/check.js#workData(const { id, view, pagination } = data || {},pagination 直接透传,不再解析顶层 page/pageSize/page_size、不做 page_size 兼容)+ app/service/systems/stock_check.js#workData(pagination 默认 {};page=Math.max(1, Number(pagination.page)||1) 默认 1、pageSize=Math.min(200, Math.max(1, Number(pagination.pageSize)||20)) 默认 20 上限 200、非法回退默认;先构建全量行再 slice(offset, offset+pageSize);返回 { check, rows, total, page, pageSize })。分页口径与 stock.check.list 完全一致。本次代码已改并测试通过 197/197、ESLint 0 错误。",
|
||||
"口径修正说明:上一轮变更记录(2026.10.02-stock-check-work-data-pagination)曾描述「入参支持 pagination 对象与顶层 page/pageSize/page_size(顶层优先)、兼容 page_size 蛇形写法」,代码按用户要求改为常规分页方式后上述描述不再成立;本条为口径修正记录,替换上一轮记录中的入参兼容口径(历史记录保留不回改),以本条为准。",
|
||||
"影响面:仅文档口径修正(methods/system.json 的 workData params.pagination 描述、description、response.page/pageSize 描述、notes),代码接口行为与响应结构(check/rows/total/page/pageSize)不变;涉及文件:methods/system.json、methods/changes/system.json、库表 wms_api_method_doc/wms_method_doc_meta。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params.pagination 描述、description、response.page/pageSize 描述、notes 同步常规分页口径并注明与 stock.check.list 一致;response.rows/total、headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.229 → 0.3.230、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-work-data-pagination",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "stock.check.workData 新增分页能力:入参支持 pagination 对象与顶层 page/pageSize/page_size(顶层优先),响应新增 page/pageSize,rows 为当前页行、total 为全部行数(默认 page=1、pageSize=20 上限 200,向后兼容)",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/stock/check.js#workData(入参归一化:data.pagination.{page,pageSize} 兼容 page_size 蛇形写法;顶层 data.page / data.pageSize / data.page_size 顶层值优先,口径与 stock/report.js 一致)+ app/service/systems/stock_check.js#workData(三视图先构建全量行再按页切片 slice(offset, offset+pageSize);page=Math.max(1, Number(page)||1) 默认 1、pageSize=Math.min(200, Math.max(1, Number(pageSize)||20)) 默认 20 上限 200、非法回退默认;返回 { check, rows, total, page, pageSize },total=allRows.length 未分页口径)。本次代码已改并测试通过 197/197、ESLint 0 错误。",
|
||||
"影响面:仅新增可选入参(pagination/page/pageSize/page_size)与两个响应字段(page/pageSize);旧调用方不传分页时 page=1、pageSize=20、rows 行为不变、total 不变,向后兼容;涉及文件:app/service/systemMethods/stock/check.js、app/service/systems/stock_check.js、methods/system.json、methods/changes/system.json、库表 wms_api_method_doc/wms_method_doc_meta。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 pagination、response 新增 page/pageSize 并同步 rows/total 口径、description/notes 补充分页口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.228 → 0.3.229、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production + --env production)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-stock-check-work-data-space-fields",
|
||||
"date": "2026-10-02",
|
||||
"type": "updated",
|
||||
"summary": "workData space 视图两处调整:库位聚合来源扩展为当前库存库位∪作业记录库位(盘点前库存已出空但已有作业记录的库位也能展示);行字段对齐库位查询惯例 index.searchSpace(id/space_code/custom_barcode/custom_name,custom_name 空输出 null 不兜底编码)",
|
||||
"methods": [
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows——库位集合由原「仅 wms_storage(warehouse_id + 任务 stock_id 集合 + is_enabled=1)DISTINCT space_id」扩展为「当前库存库位 ∪ 作业记录库位」:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查(attributes 含 id/space_code/custom_barcode/custom_name/pick_sequence/pick_priority);仅记录库位(当前库存无该商品)按库位归集补行(totalQuantity 按 0),明盘该系统 quantity 按 0、checked_quantity 按该库位实盘合计;本次仅同步文档,未改动任何代码(代码已改并测试通过 196/196、ESLint 0 错误)。",
|
||||
"行字段口径:space 视图行输出 id(wms_location_space.id)/space_code/custom_barcode(空为 null)/custom_name(空为 null,不再兜底 space_code),与库位查询惯例 index.searchSpace 一致;goods 子列表字段不变(detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/status,明盘另含 system_quantity/checked_quantity);location/goods 视图行字段不变。",
|
||||
"影响面:仅 space 视图行字段与库位集合口径变化(涉及文件:app/service/systems/stock_check.js、methods/system.json、methods/changes/system.json、库表 wms_api_method_doc/wms_method_doc_meta);check/total 结构、location/goods 视图行、明盘/盲盘数量控制、排序口径(pick_sequence 升序/pick_priority 降序/库位 id 升序兜底)、状态限制均不变。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步新口径);根版本 0.3.227 → 0.3.228、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。",
|
||||
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production + --env production)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.02-system-platform-header-miniprogram",
|
||||
"date": "2026-10-02",
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"module": "qimen",
|
||||
"description": "奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)",
|
||||
"version": "0.3.10",
|
||||
"updatedAt": "2026-09-12",
|
||||
"version": "0.3.11",
|
||||
"updatedAt": "2026-10-08",
|
||||
"headers": [],
|
||||
"methods": {
|
||||
"groups": [
|
||||
@ -1375,7 +1375,12 @@
|
||||
"description": "出库单号"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
"errors": [],
|
||||
"notes": [
|
||||
"明细行商品匹配二级策略:itemId 主键直查(货主一致)> itemCode 精确匹配(warehouse_id + store_id + app_key 维度)",
|
||||
"item_id 统一写入实际匹配到的 StockStore 数字主键 id(wms_stock_store.id),避免非数字值(如「编码+名称」拼接串)写入 BIGINT 列触发 MySQL 严格模式报错(Incorrect integer value for column item_id)",
|
||||
"item_code / item_name / plan_qty / inventory_type 落报文原值,stock_id 落系统解析值"
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "stockout.query",
|
||||
|
||||
2872
methods/system.json
2872
methods/system.json
File diff suppressed because one or more lines are too long
@ -88,4 +88,126 @@ describe('test/app/lib/printer_data_builder.test.js', () => {
|
||||
CRLF: '\r\n',
|
||||
});
|
||||
});
|
||||
|
||||
describe('kuaishou senderInfo fallback', () => {
|
||||
const buildKuaishouInput = (policyConfig, subjectConfig) => ({
|
||||
platform: 'KS',
|
||||
order_express: {
|
||||
waybill_code: 'WB-KS-001',
|
||||
},
|
||||
order_delivery: {
|
||||
name: '收件人',
|
||||
mobile: '13800000000',
|
||||
detail_address: '收货地址',
|
||||
},
|
||||
policy_config: policyConfig,
|
||||
subject_config: subjectConfig,
|
||||
template_sample: {
|
||||
cmd: 'print',
|
||||
version: '1.0',
|
||||
task: {
|
||||
taskID: 'task-ks-001',
|
||||
documents: [
|
||||
{
|
||||
documentID: 'doc-ks-001',
|
||||
contents: [
|
||||
{
|
||||
addData: {},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const getSenderInfo = result => {
|
||||
return result.request_skeleton.task.documents[0].contents[0].addData.senderInfo;
|
||||
};
|
||||
|
||||
it('should fall back to subject_config when policy_config has no sender fields', () => {
|
||||
const result = PrinterDataBuilder.buildPlatformRequestSkeleton(buildKuaishouInput(
|
||||
{ waybill_custom_display_type: '2' },
|
||||
{
|
||||
sender_name: '仓库发件人',
|
||||
sender_tel: '13800138000',
|
||||
province_name: '广东省',
|
||||
city_name: '广州市',
|
||||
district_name: '白云区',
|
||||
town_name: '钟落潭镇',
|
||||
address: '某路1号',
|
||||
}
|
||||
));
|
||||
const senderInfo = getSenderInfo(result);
|
||||
|
||||
assert.equal(senderInfo.contact.name, '仓库发件人');
|
||||
assert.equal(senderInfo.contact.mobile, '13800138000');
|
||||
assert.equal(senderInfo.address.provinceName, '广东省');
|
||||
assert.equal(senderInfo.address.cityName, '广州市');
|
||||
assert.equal(senderInfo.address.districtName, '白云区');
|
||||
assert.equal(senderInfo.address.detailAddress, '某路1号');
|
||||
assert.equal(senderInfo.address.countryCode, 'CHN');
|
||||
});
|
||||
|
||||
it('should prefer policy_config sender fields over subject_config', () => {
|
||||
const result = PrinterDataBuilder.buildPlatformRequestSkeleton(buildKuaishouInput(
|
||||
{
|
||||
sender_name: '货主发件人',
|
||||
sender_tel: '13700137000',
|
||||
province_name: '浙江省',
|
||||
city_name: '杭州市',
|
||||
district_name: '余杭区',
|
||||
address: '货主地址',
|
||||
},
|
||||
{
|
||||
sender_name: '仓库发件人',
|
||||
sender_tel: '13800138000',
|
||||
province_name: '广东省',
|
||||
city_name: '广州市',
|
||||
district_name: '白云区',
|
||||
address: '某路1号',
|
||||
}
|
||||
));
|
||||
const senderInfo = getSenderInfo(result);
|
||||
|
||||
assert.equal(senderInfo.contact.name, '货主发件人');
|
||||
assert.equal(senderInfo.contact.mobile, '13700137000');
|
||||
assert.equal(senderInfo.address.provinceName, '浙江省');
|
||||
assert.equal(senderInfo.address.cityName, '杭州市');
|
||||
assert.equal(senderInfo.address.districtName, '余杭区');
|
||||
assert.equal(senderInfo.address.detailAddress, '货主地址');
|
||||
});
|
||||
|
||||
it('should fall back to subject_config when policy_config sender fields are empty strings', () => {
|
||||
// 生产场景:getContractConfig 会合并策略默认值,发件人字段以空串存在
|
||||
const result = PrinterDataBuilder.buildPlatformRequestSkeleton(buildKuaishouInput(
|
||||
{
|
||||
sender_name: '',
|
||||
sender_tel: '',
|
||||
province_name: '',
|
||||
city_name: '',
|
||||
district_name: '',
|
||||
town_name: '',
|
||||
address: '',
|
||||
},
|
||||
{
|
||||
sender_name: '仓库发件人',
|
||||
sender_tel: '13800138000',
|
||||
province_name: '广东省',
|
||||
city_name: '广州市',
|
||||
district_name: '白云区',
|
||||
town_name: '钟落潭镇',
|
||||
address: '某路1号',
|
||||
}
|
||||
));
|
||||
const senderInfo = getSenderInfo(result);
|
||||
|
||||
assert.equal(senderInfo.contact.name, '仓库发件人');
|
||||
assert.equal(senderInfo.contact.mobile, '13800138000');
|
||||
assert.equal(senderInfo.address.provinceName, '广东省');
|
||||
assert.equal(senderInfo.address.cityName, '广州市');
|
||||
assert.equal(senderInfo.address.districtName, '白云区');
|
||||
assert.equal(senderInfo.address.detailAddress, '某路1号');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
276
test/app/service/systems/storage_report_export.test.js
Normal file
276
test/app/service/systems/storage_report_export.test.js
Normal file
@ -0,0 +1,276 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const ExcelJS = require('exceljs');
|
||||
const StorageReportService = require('../../../../app/service/systems/storage/report');
|
||||
|
||||
/**
|
||||
* 库存报表导出(storage.report.export)流式改造测试。
|
||||
*
|
||||
* 覆盖:
|
||||
* - 明细按主键 id 游标分批拉取(batchSize=5000),12000 行 = 3 批;
|
||||
* - 进度回调序列:5(命中总量)→ 分批推进 → 95 → 100(含 result 上传结果);
|
||||
* - Excel 流式生成:汇总/变更记录两个 sheet、表头、行数与抽样单元格;
|
||||
* - 汇总无数据时(明细 0 行)仍生成含表头的空文件。
|
||||
*/
|
||||
|
||||
function createDetailRows(total) {
|
||||
return Array.from({ length: total }, (_, index) => {
|
||||
const id = index + 1;
|
||||
return {
|
||||
id,
|
||||
created_at: new Date(Date.UTC(2026, 8, 1) + id * 1000).toISOString().replace('T', ' ')
|
||||
.slice(0, 19),
|
||||
transaction_type: index % 3 === 0 ? 'OUTBOUND' : 'INBOUND',
|
||||
store_id: 1000305,
|
||||
warehouse_id: 1000028,
|
||||
stock_id: id % 2 === 0 ? 101 : 102,
|
||||
space_id: 0,
|
||||
quantity: 2,
|
||||
before_quantity: 100 + id,
|
||||
after_quantity: 102 + id,
|
||||
before_locked_quantity: 0,
|
||||
after_locked_quantity: 0,
|
||||
batch_no: `B-${id}`,
|
||||
inventory_type: '',
|
||||
order_type: index % 3 === 0 ? 'OUTBOUND' : 'INBOUND',
|
||||
order_no: `NO-${id}`,
|
||||
order_id: 0,
|
||||
receiving_id: 0,
|
||||
entry_order_id: 0,
|
||||
operator_name: '测试操作员',
|
||||
remark: `备注${id}`,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function createSummaryList() {
|
||||
return [
|
||||
{
|
||||
start_time: '',
|
||||
end_time: '',
|
||||
store_id: 1000305,
|
||||
store_name: '测试货主',
|
||||
warehouse_id: 1000028,
|
||||
warehouse_name: '测试仓',
|
||||
stock_id: 101,
|
||||
item_code: 'SKU-A',
|
||||
item_name: '商品A',
|
||||
barcode: 'B1',
|
||||
begin_total: 100,
|
||||
inbound_total: 10,
|
||||
outbound_total: 5,
|
||||
end_total: 105,
|
||||
},
|
||||
{
|
||||
start_time: '',
|
||||
end_time: '',
|
||||
store_id: 1000305,
|
||||
store_name: '测试货主',
|
||||
warehouse_id: 1000028,
|
||||
warehouse_name: '测试仓',
|
||||
stock_id: 102,
|
||||
item_code: 'SKU-B',
|
||||
item_name: '商品B',
|
||||
barcode: 'B2',
|
||||
begin_total: 50,
|
||||
inbound_total: 8,
|
||||
outbound_total: 3,
|
||||
end_total: 55,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function createHarness({ detailRows = [], summaryList = [] } = {}) {
|
||||
const captured = {
|
||||
queries: [],
|
||||
upload: null,
|
||||
uploadedBuffer: null,
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
Sequelize: {
|
||||
QueryTypes: { SELECT: 'SELECT' },
|
||||
},
|
||||
logger: {
|
||||
warn() {},
|
||||
info() {},
|
||||
error() {},
|
||||
},
|
||||
},
|
||||
user: {
|
||||
store_id: 1000305,
|
||||
},
|
||||
logger: {
|
||||
warn() {},
|
||||
info() {},
|
||||
error() {},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
stockWarehouse: {
|
||||
async getStockDetails() {
|
||||
return [
|
||||
{ id: 101, item_code: 'SKU-A', item_name: '商品A', barcodes: [{ barcode: 'B1' }] },
|
||||
{ id: 102, item_code: 'SKU-B', item_name: '商品B', barcodes: [{ barcode: 'B2' }] },
|
||||
];
|
||||
},
|
||||
},
|
||||
excel: {
|
||||
async uploadExistingFile({ filePath, filename }) {
|
||||
captured.upload = { filePath, filename };
|
||||
captured.uploadedBuffer = fs.readFileSync(filePath);
|
||||
return {
|
||||
filename,
|
||||
fileKey: `exports/storage/report/1000305/20261008/${filename}`,
|
||||
size: captured.uploadedBuffer.length,
|
||||
url: `https://cdn.example.com/${filename}`,
|
||||
cdnUrl: `https://cdn.example.com/${filename}`,
|
||||
cosUrl: `https://cdn.example.com/${filename}`,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
model: {
|
||||
async query(sql, options = {}) {
|
||||
captured.queries.push({ sql, replacements: options.replacements });
|
||||
if (sql.includes('COUNT(*) AS cnt')) {
|
||||
return [{ cnt: detailRows.length }];
|
||||
}
|
||||
if (sql.includes('wms_stock_transaction')) {
|
||||
const cursorId = Number(options.replacements && options.replacements.cursorId) || 0;
|
||||
return detailRows
|
||||
.filter(row => row.id > cursorId)
|
||||
.slice(0, 5000)
|
||||
.map(row => ({ ...row }));
|
||||
}
|
||||
if (sql.includes('wms_entry_order') || sql.includes('wms_order_delivery') || sql.includes('wms_order_express')) {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
Store: {
|
||||
async findAll() {
|
||||
return [{ id: 1000305, company_name: '测试货主' }];
|
||||
},
|
||||
},
|
||||
LocationSpace: {
|
||||
async findAll() {
|
||||
return [];
|
||||
},
|
||||
},
|
||||
StoreWarehouse: {
|
||||
async findAll() {
|
||||
return [];
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new StorageReportService(ctx);
|
||||
service.search = async () => ({
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: summaryList },
|
||||
});
|
||||
|
||||
return { service, captured };
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/storage_report_export.test.js', () => {
|
||||
it('明细 12000 行按游标 3 批流式导出,进度回调与 Excel 内容正确', async () => {
|
||||
const detailRows = createDetailRows(12000);
|
||||
const { service, captured } = createHarness({
|
||||
detailRows,
|
||||
summaryList: createSummaryList(),
|
||||
});
|
||||
const progressEvents = [];
|
||||
|
||||
const result = await service.export(
|
||||
null, null, false, [], null, '', 'store', null, '',
|
||||
async progress => {
|
||||
progressEvents.push({ ...progress });
|
||||
}
|
||||
);
|
||||
|
||||
// 上传结果
|
||||
assert.ok(result && result.filename, '应返回文件名');
|
||||
assert.ok(String(result.filename).startsWith('库存报表_'), '文件名应以 库存报表_ 开头');
|
||||
assert.ok(captured.upload, '应调用 uploadExistingFile');
|
||||
|
||||
// 进度回调序列
|
||||
assert.ok(progressEvents.length >= 4, `进度事件应不少于 4 次,实际 ${progressEvents.length}`);
|
||||
assert.equal(progressEvents[0].progress, 5);
|
||||
assert.equal(progressEvents[0].totalCount, 12000);
|
||||
assert.equal(progressEvents[0].currentCount, 0);
|
||||
const lastEvent = progressEvents[progressEvents.length - 1];
|
||||
assert.equal(lastEvent.progress, 100);
|
||||
assert.equal(lastEvent.totalCount, 12000);
|
||||
assert.ok(lastEvent.result && lastEvent.result.fileKey, '末次进度应携带上传结果');
|
||||
assert.ok(progressEvents.some(event => event.progress === 95 && event.currentCount === 12000), '应有 95 进度事件');
|
||||
|
||||
// 游标批次数:COUNT 1 次 + 明细 3 批
|
||||
const detailQueries = captured.queries.filter(query => query.sql.includes('wms_stock_transaction') && !query.sql.includes('COUNT(*)'));
|
||||
assert.equal(detailQueries.length, 3, '明细应分 3 批拉取');
|
||||
assert.equal(detailQueries[0].replacements.cursorId, 0, '第一批游标应为 0');
|
||||
|
||||
// 回读生成的 Excel
|
||||
const buffer = captured.uploadedBuffer;
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
await workbook.xlsx.load(buffer);
|
||||
|
||||
assert.deepEqual(
|
||||
workbook.worksheets.map(sheet => sheet.name),
|
||||
[ '汇总', '变更记录' ]
|
||||
);
|
||||
|
||||
const summarySheet = workbook.getWorksheet('汇总');
|
||||
assert.equal(summarySheet.rowCount, 3, '汇总 sheet 应为表头+2 行');
|
||||
assert.equal(summarySheet.getCell('A1').value, '开始时间');
|
||||
|
||||
const detailSheet = workbook.getWorksheet('变更记录');
|
||||
assert.equal(detailSheet.rowCount, 12001, '变更记录 sheet 应为表头+12000 行');
|
||||
assert.equal(detailSheet.getCell('A1').value, '时间');
|
||||
assert.equal(detailSheet.getCell('A2').value, detailRows[0].created_at);
|
||||
assert.equal(detailSheet.getCell('I2').value, 2, '变动数量应为数值 2');
|
||||
assert.equal(detailSheet.getCell('B2').value, '出库', '第一条为 OUTBOUND 应显示 出库');
|
||||
assert.equal(detailSheet.getCell('F2').value, 'SKU-B', '商品编码来自富化映射');
|
||||
assert.equal(detailSheet.getCell('N2').value, 'B-1', '批次号');
|
||||
});
|
||||
|
||||
it('汇总无数据时明细为 0 行,仍生成含表头的文件并正常完成', async () => {
|
||||
const { service, captured } = createHarness({
|
||||
detailRows: [],
|
||||
summaryList: [],
|
||||
});
|
||||
const progressEvents = [];
|
||||
|
||||
const result = await service.export(
|
||||
null, null, false, [], null, '', 'store', null, '',
|
||||
async progress => {
|
||||
progressEvents.push({ ...progress });
|
||||
}
|
||||
);
|
||||
|
||||
assert.ok(result && result.filename, '应返回文件名');
|
||||
assert.ok(captured.upload, '应调用 uploadExistingFile');
|
||||
|
||||
const firstEvent = progressEvents[0];
|
||||
assert.equal(firstEvent.totalCount, 0, '明细总数应为 0');
|
||||
assert.equal(progressEvents[progressEvents.length - 1].progress, 100, '末次进度应为 100');
|
||||
|
||||
const buffer = captured.uploadedBuffer;
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
await workbook.xlsx.load(buffer);
|
||||
assert.deepEqual(
|
||||
workbook.worksheets.map(sheet => sheet.name),
|
||||
[ '汇总', '变更记录' ]
|
||||
);
|
||||
const detailSheet = workbook.getWorksheet('变更记录');
|
||||
assert.equal(detailSheet.rowCount, 1, '空明细 sheet 应只有表头行');
|
||||
assert.equal(detailSheet.getCell('A1').value, '时间');
|
||||
});
|
||||
});
|
||||
399
test/app/service/systems/wave_batch_closure.test.js
Normal file
399
test/app/service/systems/wave_batch_closure.test.js
Normal file
@ -0,0 +1,399 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const WaveBatchClosureService = require('../../../../app/service/systems/wave_batch_closure');
|
||||
|
||||
const CACHE_KEY = 'schedule:sync_finished_wave_batch:empty_confirm';
|
||||
|
||||
/**
|
||||
* 构造波次自动终结测试上下文。
|
||||
*
|
||||
* @param {Object} [options={}] 测试选项。
|
||||
* @param {Array<Object>} [options.candidateRows] 候选波次行。
|
||||
* @param {Array<number>} [options.wavesWithOrders] 待处理表里仍有订单的波次ID。
|
||||
* @param {boolean} [options.queryShouldFail] 待处理表查询是否抛错。
|
||||
* @param {boolean} [options.cacheUnavailable] 是否禁用缓存(模拟 Redis 不可用)。
|
||||
* @param {Array<number>} [options.wavesWithIndex] 波次索引表里有行的波次ID(默认全部候选,
|
||||
* 模拟"订单离表但索引残留"的正常清理目标形态)。
|
||||
* @param {boolean} [options.indexQueryShouldFail] 波次索引表查询是否抛错。
|
||||
* @param {number} [options.probeCount] 索引抽样核对返回的订单表命中数(默认 0)。
|
||||
* @param {boolean} [options.probeShouldFail] 索引抽样核对查询是否抛错。
|
||||
* @return {{ service: Object, captures: Object, cacheStore: Map }} 测试对象。
|
||||
*/
|
||||
function createHarness(options = {}) {
|
||||
const {
|
||||
candidateRows = [],
|
||||
wavesWithOrders = [],
|
||||
queryShouldFail = false,
|
||||
cacheUnavailable = false,
|
||||
wavesWithIndex = candidateRows.map(row => Number(row && row.wave_id || 0)).filter(waveId => waveId > 0),
|
||||
indexQueryShouldFail = false,
|
||||
probeCount = 0,
|
||||
probeShouldFail = false,
|
||||
} = options;
|
||||
|
||||
const captures = {
|
||||
sqlList: [],
|
||||
updateWaveIdList: [],
|
||||
updateReplacementList: [],
|
||||
infoLogList: [],
|
||||
warnLogList: [],
|
||||
};
|
||||
const cacheStore = new Map();
|
||||
const wavesWithOrdersSet = new Set(wavesWithOrders);
|
||||
const wavesWithIndexSet = new Set(wavesWithIndex);
|
||||
|
||||
const app = { config: {} };
|
||||
if (!cacheUnavailable) {
|
||||
app.getCacheAsync = async cacheKey => (cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null);
|
||||
app.setCacheAsync = async (cacheKey, data) => {
|
||||
cacheStore.set(cacheKey, data);
|
||||
};
|
||||
}
|
||||
|
||||
const ctx = {
|
||||
app,
|
||||
model: {
|
||||
QueryTypes: { SELECT: 'SELECT', UPDATE: 'UPDATE' },
|
||||
OrderDeliveryFactory: {
|
||||
generateTableName(warehouseId) {
|
||||
return `wms_order_delivery_${warehouseId}`;
|
||||
},
|
||||
},
|
||||
async query(sql, queryOptions = {}) {
|
||||
const normalizedSql = String(sql || '').replace(/\s+/g, ' ').trim();
|
||||
const replacements = queryOptions.replacements || {};
|
||||
captures.sqlList.push(normalizedSql);
|
||||
|
||||
if (/^UPDATE\s+wms_wave_batch/i.test(normalizedSql)) {
|
||||
const waveIds = Array.isArray(replacements.waveIds) ? replacements.waveIds : [];
|
||||
captures.updateWaveIdList.push(...waveIds);
|
||||
captures.updateReplacementList.push(replacements);
|
||||
// 真实 SQL 带 wave_status IN (0,1) 守卫:这里按"全部命中"模拟最理想情况
|
||||
return [ undefined, { affectedRows: waveIds.length }];
|
||||
}
|
||||
|
||||
if (/SELECT DISTINCT wave_id[\s\S]*FROM\s+wms_order_wave_index/i.test(normalizedSql)) {
|
||||
if (indexQueryShouldFail) {
|
||||
throw new Error('mock wave index query failed');
|
||||
}
|
||||
const waveIds = Array.isArray(replacements.waveIds) ? replacements.waveIds : [];
|
||||
return waveIds
|
||||
.filter(waveId => wavesWithIndexSet.has(waveId))
|
||||
.map(waveId => ({ wave_id: waveId }));
|
||||
}
|
||||
|
||||
if (/SELECT DISTINCT wave_id/i.test(normalizedSql)) {
|
||||
if (queryShouldFail) {
|
||||
throw new Error('mock order table query failed');
|
||||
}
|
||||
const waveIds = Array.isArray(replacements.waveIds) ? replacements.waveIds : [];
|
||||
return waveIds
|
||||
.filter(waveId => wavesWithOrdersSet.has(waveId))
|
||||
.map(waveId => ({ wave_id: waveId }));
|
||||
}
|
||||
|
||||
if (/SELECT COUNT\(\*\) AS probe_count/i.test(normalizedSql)) {
|
||||
if (probeShouldFail) {
|
||||
throw new Error('mock probe query failed');
|
||||
}
|
||||
return [{ probe_count: probeCount }];
|
||||
}
|
||||
|
||||
if (/FROM\s+wms_wave_batch/i.test(normalizedSql)) {
|
||||
return candidateRows;
|
||||
}
|
||||
|
||||
return [];
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info(message) {
|
||||
captures.infoLogList.push(String(message));
|
||||
},
|
||||
warn(message) {
|
||||
captures.warnLogList.push(String(message));
|
||||
},
|
||||
error() {},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
service: new WaveBatchClosureService(ctx),
|
||||
captures,
|
||||
cacheStore,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成候选波次行。
|
||||
*
|
||||
* @param {number} waveId 波次ID。
|
||||
* @param {number} [warehouseId=1000028] 仓库ID。
|
||||
* @return {Object} 候选行。
|
||||
*/
|
||||
function buildCandidate(waveId, warehouseId = 1000028) {
|
||||
return {
|
||||
wave_id: waveId,
|
||||
wave_no: `B${waveId}`,
|
||||
warehouse_id: warehouseId,
|
||||
wave_status: 1,
|
||||
total_orders: 20,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/wave_batch_closure.test.js', () => {
|
||||
it('首轮判空不终结,只登记待确认(避免瞬时空表误关)', async () => {
|
||||
const { service, captures, cacheStore } = createHarness({
|
||||
candidateRows: [ buildCandidate(1777888535813505) ],
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves();
|
||||
|
||||
assert.equal(result.empty_count, 1);
|
||||
assert.equal(result.confirmed_count, 0);
|
||||
assert.equal(result.closed_count, 0);
|
||||
assert.equal(result.pending_confirm_count, 1);
|
||||
assert.deepEqual(result.pending_confirm_wave_ids, [ 1777888535813505 ]);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
assert.deepEqual(cacheStore.get(CACHE_KEY).waveIds, [ 1777888535813505 ]);
|
||||
});
|
||||
|
||||
it('连续两轮判空且间隔达标后才终结(受 wave_status/total_orders 守卫)', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures, cacheStore } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
});
|
||||
// 预置上一轮判空结果(轮次时间早于确认间隔)
|
||||
cacheStore.set(CACHE_KEY, { roundAt: Date.now() - 60000, waveIds: [ waveId ] });
|
||||
|
||||
const result = await service.closeFinishedWaves();
|
||||
|
||||
assert.equal(result.confirmed_count, 1);
|
||||
assert.equal(result.closed_count, 1);
|
||||
assert.equal(result.pending_confirm_count, 0);
|
||||
assert.deepEqual(captures.updateWaveIdList, [ waveId ]);
|
||||
assert.deepEqual(result.closed_waves, [{
|
||||
waveId,
|
||||
waveNo: `B${waveId}`,
|
||||
warehouseId: 1000028,
|
||||
}]);
|
||||
|
||||
const updateSql = captures.sqlList.find(sql => /^UPDATE\s+wms_wave_batch/i.test(sql));
|
||||
assert.ok(updateSql, '应执行终结 UPDATE');
|
||||
assert.ok(/wave_status IN \(:waveStatuses\)/i.test(updateSql), '终结 UPDATE 需带 wave_status 守卫');
|
||||
assert.ok(/total_orders > 0/i.test(updateSql), '终结 UPDATE 需带 total_orders > 0 守卫');
|
||||
assert.deepEqual(captures.updateReplacementList[0].waveStatuses, [ 0, 1 ]);
|
||||
assert.equal(captures.updateReplacementList[0].closedStatus, 5);
|
||||
});
|
||||
|
||||
it('上一轮判空但本轮订单已回来时不终结', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures, cacheStore } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
wavesWithOrders: [ waveId ],
|
||||
});
|
||||
cacheStore.set(CACHE_KEY, { roundAt: Date.now() - 60000, waveIds: [ waveId ] });
|
||||
|
||||
const result = await service.closeFinishedWaves();
|
||||
|
||||
assert.equal(result.empty_count, 0);
|
||||
assert.equal(result.confirmed_count, 0);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
});
|
||||
|
||||
it('两次判空间隔不足时不终结,且不刷新首轮时间(避免调度过密饿死确认)', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const staleRoundAt = Date.now() - 5000;
|
||||
const { service, captures, cacheStore } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
});
|
||||
cacheStore.set(CACHE_KEY, { roundAt: staleRoundAt, waveIds: [ waveId ] });
|
||||
|
||||
const result = await service.closeFinishedWaves();
|
||||
|
||||
assert.equal(result.confirmed_count, 0);
|
||||
assert.equal(result.pending_confirm_count, 1);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
assert.equal(cacheStore.get(CACHE_KEY).roundAt, staleRoundAt);
|
||||
});
|
||||
|
||||
it('confirmMinIntervalMs=0 时跳过二次确认、首轮即终结(兼容/手动强制口径)', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 });
|
||||
|
||||
assert.equal(result.confirmed_count, 1);
|
||||
assert.equal(result.closed_count, 1);
|
||||
assert.deepEqual(captures.updateWaveIdList, [ waveId ]);
|
||||
});
|
||||
|
||||
it('dryRun 只盘点不写库、不读写确认状态', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures, cacheStore } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves({ dryRun: true });
|
||||
|
||||
assert.equal(result.dryRun, true);
|
||||
assert.equal(result.empty_count, 1);
|
||||
assert.equal(result.confirmed_count, 1);
|
||||
assert.equal(result.closed_count, 0);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
assert.equal(cacheStore.size, 0);
|
||||
});
|
||||
|
||||
it('待处理表查询失败时跳过该仓库,不产生误关', async () => {
|
||||
const { service, captures } = createHarness({
|
||||
candidateRows: [ buildCandidate(1777888535813505) ],
|
||||
queryShouldFail: true,
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 });
|
||||
|
||||
assert.equal(result.empty_count, 0);
|
||||
assert.equal(result.confirmed_count, 0);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
assert.ok(captures.warnLogList.some(message => /查询仓库 1000028 待处理表失败/.test(message)));
|
||||
});
|
||||
|
||||
it('缓存不可用时本轮不终结任何波次(宁可漏关,不可误关)', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
cacheUnavailable: true,
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves();
|
||||
|
||||
assert.equal(result.empty_count, 1);
|
||||
assert.equal(result.confirmed_count, 0);
|
||||
assert.equal(result.pending_confirm_count, 1);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
assert.ok(captures.warnLogList.some(message => /二次确认状态缓存不可用/.test(message)));
|
||||
});
|
||||
|
||||
it('多仓库分别按各自待处理表判定,只终结确认过的仓库波次', async () => {
|
||||
const waveIdA = 1777888535813505;
|
||||
const waveIdB = 1777888535764266;
|
||||
const { service, captures, cacheStore } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveIdA, 1000028), buildCandidate(waveIdB, 100000) ],
|
||||
// 仓库 100000 的波次仍有订单
|
||||
wavesWithOrders: [ waveIdB ],
|
||||
});
|
||||
cacheStore.set(CACHE_KEY, { roundAt: Date.now() - 60000, waveIds: [ waveIdA, waveIdB ] });
|
||||
|
||||
const result = await service.closeFinishedWaves();
|
||||
|
||||
assert.deepEqual(result.warehouse_ids.sort(), [ 100000, 1000028 ]);
|
||||
assert.equal(result.empty_count, 1);
|
||||
assert.deepEqual(captures.updateWaveIdList, [ waveIdA ]);
|
||||
});
|
||||
|
||||
it('订单表与索引表双空(建波未完成中间态)时不终结', async () => {
|
||||
const waveId = 1777888535853195;
|
||||
const { service, captures } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
wavesWithIndex: [],
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 });
|
||||
|
||||
assert.equal(result.empty_count, 0);
|
||||
assert.equal(result.unbound_count, 1);
|
||||
assert.deepEqual(result.unbound_wave_ids, [ waveId ]);
|
||||
assert.equal(result.confirmed_count, 0);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
// 双空形态不做抽样核对
|
||||
assert.equal(captures.sqlList.some(sql => /probe_count/i.test(sql)), false);
|
||||
assert.ok(captures.warnLogList.some(message => /双空/.test(message)));
|
||||
});
|
||||
|
||||
it('索引有行但抽样核对命中订单(读偏)时不终结', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
wavesWithIndex: [ waveId ],
|
||||
probeCount: 3,
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 });
|
||||
|
||||
assert.equal(result.empty_count, 0);
|
||||
assert.equal(result.misread_count, 1);
|
||||
assert.deepEqual(result.misread_wave_ids, [ waveId ]);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
assert.ok(captures.warnLogList.some(message => /读偏/.test(message)));
|
||||
});
|
||||
|
||||
it('索引有行且抽样为 0(订单真离表)按正常清理口径终结', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
wavesWithIndex: [ waveId ],
|
||||
probeCount: 0,
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 });
|
||||
|
||||
assert.equal(result.empty_count, 1);
|
||||
assert.equal(result.unbound_count, 0);
|
||||
assert.equal(result.misread_count, 0);
|
||||
assert.equal(result.confirmed_count, 1);
|
||||
assert.deepEqual(captures.updateWaveIdList, [ waveId ]);
|
||||
});
|
||||
|
||||
it('波次索引表查询失败时跳过该仓库,不产生误关', async () => {
|
||||
const { service, captures } = createHarness({
|
||||
candidateRows: [ buildCandidate(1777888535813505) ],
|
||||
indexQueryShouldFail: true,
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 });
|
||||
|
||||
assert.equal(result.empty_count, 0);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
assert.ok(captures.warnLogList.some(message => /波次索引表失败/.test(message)));
|
||||
});
|
||||
|
||||
it('索引抽样核对失败时本轮不终结该波次(宁可漏关)', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
wavesWithIndex: [ waveId ],
|
||||
probeShouldFail: true,
|
||||
});
|
||||
|
||||
const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 });
|
||||
|
||||
assert.equal(result.empty_count, 0);
|
||||
assert.equal(result.probe_failed_count, 1);
|
||||
assert.deepEqual(result.probe_failed_wave_ids, [ waveId ]);
|
||||
assert.equal(captures.updateWaveIdList.length, 0);
|
||||
});
|
||||
|
||||
it('候选查询与终结 UPDATE 使用 UTC_TIMESTAMP 口径(与 create_time UTC 存储一致)', async () => {
|
||||
const waveId = 1777888535813505;
|
||||
const { service, captures, cacheStore } = createHarness({
|
||||
candidateRows: [ buildCandidate(waveId) ],
|
||||
wavesWithIndex: [ waveId ],
|
||||
});
|
||||
cacheStore.set(CACHE_KEY, { roundAt: Date.now() - 60000, waveIds: [ waveId ] });
|
||||
|
||||
await service.closeFinishedWaves();
|
||||
|
||||
const candidateSql = captures.sqlList.find(sql => /FROM\s+wms_wave_batch/i.test(sql));
|
||||
assert.ok(candidateSql, '应执行候选查询');
|
||||
assert.ok(/UTC_TIMESTAMP\(\)/i.test(candidateSql), '候选查询需使用 UTC_TIMESTAMP');
|
||||
assert.ok(!/NOW\(\)/i.test(candidateSql), '候选查询不应再使用 NOW()');
|
||||
|
||||
const updateSql = captures.sqlList.find(sql => /^UPDATE\s+wms_wave_batch/i.test(sql));
|
||||
assert.ok(updateSql, '应执行终结 UPDATE');
|
||||
assert.ok(/UTC_TIMESTAMP\(\)/i.test(updateSql), '终结 UPDATE 需使用 UTC_TIMESTAMP');
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,341 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const Sequelize = require('sequelize');
|
||||
const { Op } = Sequelize;
|
||||
const WaybillService = require('../../../../app/service/systems/waybill');
|
||||
const { matchesWhere } = require('../../../support/where_matcher');
|
||||
|
||||
const TEST_WAREHOUSE_ID = 100000;
|
||||
const TEST_STORE_ID = 1000000;
|
||||
|
||||
/**
|
||||
* 运单 fixture(主单号数组查询场景):
|
||||
* - order 101:主单 SF9001-MAIN + 子单 SF9001-1 / SF9001-2
|
||||
* - order 102:主单 SF9002-MAIN + 子单 SF9002-1
|
||||
* - order 103:主单 SF9003-MAIN(无子单)
|
||||
* - id 7 为其他仓库同主单号运单(验证仓库隔离)
|
||||
* @return {Array<Object>} 运单行。
|
||||
*/
|
||||
function buildExpressRows() {
|
||||
const base = [
|
||||
{ id: 1, order_id: 101, waybill_code: 'SF9001-MAIN', business_key: 1, warehouse_id: TEST_WAREHOUSE_ID },
|
||||
{ id: 2, order_id: 101, waybill_code: 'SF9001-1', business_key: 2, warehouse_id: TEST_WAREHOUSE_ID },
|
||||
{ id: 3, order_id: 101, waybill_code: 'SF9001-2', business_key: 3, warehouse_id: TEST_WAREHOUSE_ID },
|
||||
{ id: 4, order_id: 102, waybill_code: 'SF9002-MAIN', business_key: 1, warehouse_id: TEST_WAREHOUSE_ID },
|
||||
{ id: 5, order_id: 102, waybill_code: 'SF9002-1', business_key: 2, warehouse_id: TEST_WAREHOUSE_ID },
|
||||
{ id: 6, order_id: 103, waybill_code: 'SF9003-MAIN', business_key: 1, warehouse_id: TEST_WAREHOUSE_ID },
|
||||
{ id: 7, order_id: 104, waybill_code: 'SF9001-MAIN', business_key: 1, warehouse_id: 999999 },
|
||||
];
|
||||
|
||||
return base.map((item, index) => ({
|
||||
...item,
|
||||
store_id: TEST_STORE_ID,
|
||||
status: 1,
|
||||
delivery_order_code: `DO-${item.order_id}`,
|
||||
source_order_codes: `SO-${item.order_id}`,
|
||||
logistics_code: 'SF',
|
||||
logistics_name: '顺丰',
|
||||
logistics_interface_id: 1,
|
||||
logistics_interface_name: 'SF-IF',
|
||||
platform_code: 'PDD',
|
||||
is_back: 'N',
|
||||
is_intercept: 'N',
|
||||
is_galaxy_receive: 'N',
|
||||
weighing_weight: 0,
|
||||
package_material_id: 0,
|
||||
package_material_name_snapshot: '',
|
||||
create_at: `2026-08-0${(index % 9) + 1} 03:20:00`,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 waybill list/export 服务测试环境(mock 模型按真实 where 语义过滤 fixture 行)。
|
||||
* @return {{service: WaybillService, calls: Object, captured: Object}} 测试上下文。
|
||||
*/
|
||||
function createWaybillHarness() {
|
||||
const expressRows = buildExpressRows();
|
||||
|
||||
const calls = {
|
||||
listFindAndCountAllWhere: null,
|
||||
listFindAllWheres: [],
|
||||
exportCountWhere: null,
|
||||
exportFindAllWheres: [],
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
Sequelize,
|
||||
config: {},
|
||||
formatDate(value) {
|
||||
return value === null || value === undefined ? null : String(value);
|
||||
},
|
||||
},
|
||||
user: { store_id: TEST_WAREHOUSE_ID },
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
service: {},
|
||||
model: {
|
||||
OrderExpress: {
|
||||
async findAndCountAll(query = {}) {
|
||||
calls.listFindAndCountAllWhere = query.where || null;
|
||||
const filtered = expressRows.filter(item => matchesWhere(item, query.where || {}));
|
||||
const offset = Number(query.offset) || 0;
|
||||
const limit = Number(query.limit) || filtered.length;
|
||||
return { count: filtered.length, rows: filtered.slice(offset, offset + limit) };
|
||||
},
|
||||
async findAll(query = {}) {
|
||||
const where = query.where || {};
|
||||
if (where.waybill_code && where.waybill_code[Op.in]) {
|
||||
calls.listFindAllWheres.push(where);
|
||||
} else if (where.order_id && where.order_id[Op.in]) {
|
||||
calls.exportFindAllWheres.push(where);
|
||||
calls.listFindAllWheres.push(where);
|
||||
} else {
|
||||
calls.listFindAllWheres.push(where);
|
||||
}
|
||||
return expressRows.filter(item => matchesWhere(item, where));
|
||||
},
|
||||
async count(query = {}) {
|
||||
calls.exportCountWhere = query.where || null;
|
||||
return expressRows.filter(item => matchesWhere(item, query.where || {})).length;
|
||||
},
|
||||
},
|
||||
ExpressPrintRecord: {
|
||||
async findAll() {
|
||||
return [];
|
||||
},
|
||||
},
|
||||
StoreWarehouse: {
|
||||
async findAll() {
|
||||
return [];
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new WaybillService(ctx);
|
||||
|
||||
// export 的建表/上传副作用与筛选逻辑无关,打桩到文件生成边界,
|
||||
// 通过 captured.filePayload 断言筛选后的行集,确保测的是真实 where 构建链路。
|
||||
const captured = { filePayload: null };
|
||||
service.buildWaybillExportFile = async payload => {
|
||||
captured.filePayload = payload;
|
||||
return {
|
||||
current_count: payload.totalCount,
|
||||
total_count: payload.totalCount,
|
||||
url: 'mock-url',
|
||||
};
|
||||
};
|
||||
|
||||
return { service, calls, captured };
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取 list 结果中的运单号集合(排序后)。
|
||||
* @param {Object} result list 返回结果。
|
||||
* @return {Array<string>} 排序后的运单号列表。
|
||||
*/
|
||||
function resultWaybillCodes(result) {
|
||||
return (result && result.list ? result.list : []).map(item => String(item.waybill_code)).sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* 取主单号查询发出的 where(含 waybill_code Op.in 的那次)。
|
||||
* @param {Array<Object>} wheres 捕获的 where 列表。
|
||||
* @return {Object|null} 主单号查询 where。
|
||||
*/
|
||||
function mainCodeLookupWhere(wheres) {
|
||||
return wheres.find(where => where.waybill_code && where.waybill_code[Op.in]) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 where 中提取 order_id 条件(标量或 Op.in 数组)。
|
||||
* @param {Object|null} where Sequelize where 条件。
|
||||
* @return {number|Array<number>|null} order_id 条件。
|
||||
*/
|
||||
function orderIdCondition(where) {
|
||||
if (!where) return null;
|
||||
const value = where.order_id;
|
||||
if (value === undefined || value === null) return null;
|
||||
if (typeof value === 'object' && value[Op.in]) return value[Op.in];
|
||||
return value;
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/waybill.warehouse.mainWaybillCode.in.test.js', () => {
|
||||
describe('waybill.warehouse.list where.mainWaybillCode 数组支持', () => {
|
||||
it('数组两个主单号:返回两个订单下全部运单(主+子),order_id 使用 Op.in', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: { mainWaybillCode: [ 'SF9001-MAIN', 'SF9002-MAIN' ] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.deepEqual(orderIdCondition(calls.listFindAndCountAllWhere), [ 101, 102 ]);
|
||||
assert.equal(result.pagination.total, 5);
|
||||
assert.deepEqual(resultWaybillCodes(result), [ 'SF9001-1', 'SF9001-2', 'SF9001-MAIN', 'SF9002-1', 'SF9002-MAIN' ]);
|
||||
});
|
||||
|
||||
it('数组内元素自动 trim 并过滤空值', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: { mainWaybillCode: [ ' SF9001-MAIN ', '', null, undefined ] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.equal(orderIdCondition(calls.listFindAndCountAllWhere), 101);
|
||||
assert.deepEqual(resultWaybillCodes(result), [ 'SF9001-1', 'SF9001-2', 'SF9001-MAIN' ]);
|
||||
});
|
||||
|
||||
it('存在+不存在混合:仅返回存在主单号对应运单,不抛错', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: { mainWaybillCode: [ 'SF9001-MAIN', 'SF-NOT-EXIST' ] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.equal(orderIdCondition(calls.listFindAndCountAllWhere), 101);
|
||||
assert.equal(result.pagination.total, 3);
|
||||
assert.deepEqual(resultWaybillCodes(result), [ 'SF9001-1', 'SF9001-2', 'SF9001-MAIN' ]);
|
||||
});
|
||||
|
||||
it('全部不存在:直接返回空结果,不发起主查询', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: { mainWaybillCode: [ 'SF-NOT-EXIST-A', 'SF-NOT-EXIST-B' ] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.equal(calls.listFindAndCountAllWhere, null, '主单号均不存在时不应发起主查询');
|
||||
assert.deepEqual(result.list, []);
|
||||
assert.equal(result.pagination.total, 0);
|
||||
});
|
||||
|
||||
it('重复主单号自动去重,不产生重复 order_id', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: { mainWaybillCode: [ 'SF9001-MAIN', 'SF9001-MAIN', 'SF9002-MAIN' ] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.deepEqual(orderIdCondition(calls.listFindAndCountAllWhere), [ 101, 102 ]);
|
||||
assert.equal(result.pagination.total, 5);
|
||||
});
|
||||
|
||||
it('单元素数组:与单值等价,order_id 保持标量(向后兼容)', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
await service.list({
|
||||
where: { mainWaybillCode: [ 'SF9001-MAIN' ] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.equal(orderIdCondition(calls.listFindAndCountAllWhere), 101);
|
||||
});
|
||||
|
||||
it('字符串单值:行为不变(order_id 标量)', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: { mainWaybillCode: 'SF9002-MAIN' },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.equal(orderIdCondition(calls.listFindAndCountAllWhere), 102);
|
||||
assert.deepEqual(resultWaybillCodes(result), [ 'SF9002-1', 'SF9002-MAIN' ]);
|
||||
});
|
||||
|
||||
it('标准 where 格式 {operator:"in", value:[...]}:经 normalizeWhereParams 后同样支持', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: { mainWaybillCode: { operator: 'in', value: [ 'SF9001-MAIN', 'SF9003-MAIN' ] } },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.deepEqual(orderIdCondition(calls.listFindAndCountAllWhere), [ 101, 103 ]);
|
||||
assert.equal(result.pagination.total, 4);
|
||||
});
|
||||
|
||||
it('空数组 / 全空值数组:不加主单号筛选,返回本仓全部运单', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const emptyResult = await service.list({
|
||||
where: { mainWaybillCode: [] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
assert.equal(orderIdCondition(calls.listFindAndCountAllWhere), null, '空数组不应添加 order_id 条件');
|
||||
assert.equal(emptyResult.pagination.total, 6, '仓库内全部 6 条');
|
||||
|
||||
const blankResult = await service.list({
|
||||
where: { mainWaybillCode: [ ' ', null ] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
assert.equal(blankResult.pagination.total, 6);
|
||||
});
|
||||
|
||||
it('仓库隔离:其他仓库同主单号运单不会被带出', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: { mainWaybillCode: [ 'SF9001-MAIN' ] },
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
const lookup = mainCodeLookupWhere(calls.listFindAllWheres);
|
||||
assert.equal(lookup.warehouse_id, TEST_WAREHOUSE_ID);
|
||||
assert.equal(lookup.business_key, 1);
|
||||
assert.equal(orderIdCondition(calls.listFindAndCountAllWhere), 101, '不含其他仓库 order 104');
|
||||
assert.equal(result.pagination.total, 3);
|
||||
});
|
||||
|
||||
it('与 waybillCode 数组共存:AND 叠加', async () => {
|
||||
const { service, calls } = createWaybillHarness();
|
||||
|
||||
const result = await service.list({
|
||||
where: {
|
||||
mainWaybillCode: [ 'SF9001-MAIN', 'SF9002-MAIN' ],
|
||||
waybillCode: [ 'SF9002-1' ],
|
||||
},
|
||||
pagination: { page: 1, pageSize: 20 },
|
||||
});
|
||||
|
||||
assert.deepEqual(orderIdCondition(calls.listFindAndCountAllWhere), [ 101, 102 ]);
|
||||
assert.deepEqual(calls.listFindAndCountAllWhere.waybill_code[Op.in], [ 'SF9002-1' ]);
|
||||
assert.deepEqual(resultWaybillCodes(result), [ 'SF9002-1' ]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('waybill.warehouse.export where.mainWaybillCode 数组支持(与 list 保持一致)', () => {
|
||||
it('数组两个主单号:导出两个订单下全部运单', async () => {
|
||||
const { service, calls, captured } = createWaybillHarness();
|
||||
|
||||
await service.export({
|
||||
where: { mainWaybillCode: [ 'SF9001-MAIN', 'SF9002-MAIN' ] },
|
||||
});
|
||||
|
||||
assert.deepEqual(orderIdCondition(calls.exportCountWhere), [ 101, 102 ]);
|
||||
assert.equal(captured.filePayload.totalCount, 5);
|
||||
assert.deepEqual(
|
||||
captured.filePayload.list.map(item => item.waybill_code).sort(),
|
||||
[ 'SF9001-1', 'SF9001-2', 'SF9001-MAIN', 'SF9002-1', 'SF9002-MAIN' ]
|
||||
);
|
||||
});
|
||||
|
||||
it('全部不存在:导出空结果,不发起统计查询', async () => {
|
||||
const { service, calls, captured } = createWaybillHarness();
|
||||
|
||||
const result = await service.export({
|
||||
where: { mainWaybillCode: [ 'SF-NOT-EXIST' ] },
|
||||
});
|
||||
|
||||
assert.equal(calls.exportCountWhere, null, '主单号不存在时不应发起统计查询');
|
||||
assert.equal(result.total_count, 0);
|
||||
assert.equal(captured.filePayload, null);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user