1
This commit is contained in:
parent
736ad34351
commit
9845a239e2
241
app/lib/express_print_payload_builder.js
Normal file
241
app/lib/express_print_payload_builder.js
Normal file
@ -0,0 +1,241 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const PrinterDataBuilder = require('./printer_data_builder');
|
||||
|
||||
const TEMPLATE_CACHE = new Map();
|
||||
|
||||
/**
|
||||
* 判断是否为普通对象。
|
||||
* @param {any} value 待判断值。
|
||||
* @return {boolean} 判断结果。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以 JSON 方式做深拷贝,避免污染模板缓存对象。
|
||||
* @param {Object} source 原对象。
|
||||
* @return {Object} 深拷贝结果。
|
||||
*/
|
||||
function deepClone(source) {
|
||||
return JSON.parse(JSON.stringify(source));
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求内 ID 生成器。
|
||||
*/
|
||||
class RequestScopedPrintIdGenerator {
|
||||
/**
|
||||
* @param {string} requestCode 前端请求参数码。
|
||||
*/
|
||||
constructor(requestCode) {
|
||||
this.requestCode = String(requestCode || '').trim();
|
||||
this.sequence = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成请求 ID。
|
||||
* @return {string} 唯一请求 ID。
|
||||
*/
|
||||
nextRequestId() {
|
||||
return this.next('request');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成任务 ID。
|
||||
* @return {string} 唯一任务 ID。
|
||||
*/
|
||||
nextTaskId() {
|
||||
return this.next('task');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成文档 ID。
|
||||
* @return {string} 唯一文档 ID。
|
||||
*/
|
||||
nextDocumentId() {
|
||||
return this.next('document');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带前缀的递增 ID。
|
||||
* @param {string} prefix ID 前缀。
|
||||
* @return {string} 生成结果。
|
||||
*/
|
||||
next(prefix) {
|
||||
this.sequence += 1;
|
||||
return `${this.requestCode}_${prefix}_${this.sequence}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 快递打印请求组装器。
|
||||
*/
|
||||
class ExpressPrintPayloadBuilder {
|
||||
/**
|
||||
* @param {Object} options 初始化参数。
|
||||
* @param {string} options.baseDir 项目根目录。
|
||||
*/
|
||||
constructor(options = {}) {
|
||||
const requestOptions = isPlainObject(options) ? options : {};
|
||||
this.baseDir = String(requestOptions.baseDir || process.cwd());
|
||||
this.templateDir = path.join(this.baseDir, 'printer_data_template');
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装平台快递打印 payload。
|
||||
* @param {Object} options 组装参数。
|
||||
* @param {string} options.platform 平台编码。
|
||||
* @param {string} options.printerName 打印机名称。
|
||||
* @param {Array<Object>} options.orders 外部传入的订单打印数据数组。
|
||||
* @param {RequestScopedPrintIdGenerator} options.idGenerator 请求内 ID 生成器。
|
||||
* @return {Object} 可直接发送给打印服务的 payload。
|
||||
*/
|
||||
buildPayload(options = {}) {
|
||||
const requestOptions = isPlainObject(options) ? options : {};
|
||||
const platform = String(requestOptions.platform || '').trim();
|
||||
if (!platform) {
|
||||
throw new Error('快递打印缺少平台标识');
|
||||
}
|
||||
|
||||
const idGenerator = requestOptions.idGenerator;
|
||||
if (!idGenerator || typeof idGenerator.nextRequestId !== 'function') {
|
||||
throw new Error('快递打印缺少请求 ID 生成器');
|
||||
}
|
||||
|
||||
const printerName = String(requestOptions.printerName || '').trim();
|
||||
if (!printerName) {
|
||||
throw new Error('快递打印缺少打印机名称');
|
||||
}
|
||||
|
||||
const orders = Array.isArray(requestOptions.orders) ? requestOptions.orders : [];
|
||||
if (orders.length === 0) {
|
||||
throw new Error('快递打印缺少订单数据');
|
||||
}
|
||||
|
||||
const payload = this.loadTemplate(platform);
|
||||
if (!isPlainObject(payload.task)) {
|
||||
payload.task = {};
|
||||
}
|
||||
|
||||
const requestId = idGenerator.nextRequestId();
|
||||
this.applyRequestId(payload, requestId);
|
||||
payload.task.taskID = idGenerator.nextTaskId();
|
||||
payload.task.printer = printerName;
|
||||
payload.task.documents = this.buildDocumentsFromOrders(orders, idGenerator);
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 orders 映射为 documents。
|
||||
* @param {Array<Object>} orders 订单数组。
|
||||
* @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。
|
||||
* @return {Array<Object>} documents 数组。
|
||||
*/
|
||||
buildDocumentsFromOrders(orders, idGenerator) {
|
||||
return orders.map((order, index) => {
|
||||
const sourceDocument = this.resolveOrderDocument(order, index);
|
||||
const document = deepClone(sourceDocument);
|
||||
if (!Array.isArray(document.contents)) {
|
||||
document.contents = [];
|
||||
}
|
||||
document.documentID = idGenerator.nextDocumentId();
|
||||
return document;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析单个订单对应的 document。
|
||||
* @param {Object} order 订单对象。
|
||||
* @param {number} index 订单索引。
|
||||
* @return {Object} document 对象。
|
||||
*/
|
||||
resolveOrderDocument(order, index) {
|
||||
if (!isPlainObject(order)) {
|
||||
throw new Error(`orders[${index}] 必须是对象`);
|
||||
}
|
||||
|
||||
const printData = isPlainObject(order.print_data) ? order.print_data : order;
|
||||
if (!isPlainObject(printData)) {
|
||||
throw new Error(`orders[${index}] 缺少 print_data`);
|
||||
}
|
||||
|
||||
const hasDocumentShape = Object.prototype.hasOwnProperty.call(printData, 'documentID')
|
||||
|| Array.isArray(printData.contents);
|
||||
if (!hasDocumentShape) {
|
||||
throw new Error(`orders[${index}] 的 print_data 不是有效 document 结构`);
|
||||
}
|
||||
|
||||
return printData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入请求 ID,兼容 requestID / requetID 两种字段。
|
||||
* @param {Object} payload 请求 payload。
|
||||
* @param {string} requestId 请求 ID。
|
||||
*/
|
||||
applyRequestId(payload, requestId) {
|
||||
const hasRequestId = Object.prototype.hasOwnProperty.call(payload, 'requestID');
|
||||
const hasRequetId = Object.prototype.hasOwnProperty.call(payload, 'requetID');
|
||||
|
||||
if (hasRequestId) {
|
||||
payload.requestID = requestId;
|
||||
}
|
||||
if (hasRequetId) {
|
||||
payload.requetID = requestId;
|
||||
}
|
||||
if (!hasRequestId && !hasRequetId) {
|
||||
payload.requestID = requestId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载并缓存平台模板,然后返回深拷贝对象。
|
||||
* @param {string} platform 平台编码。
|
||||
* @return {Object} 模板拷贝。
|
||||
*/
|
||||
loadTemplate(platform) {
|
||||
const normalizedPlatform = this.normalizePlatform(platform);
|
||||
const templatePath = path.join(this.templateDir, `${normalizedPlatform}.json`);
|
||||
if (!TEMPLATE_CACHE.has(templatePath)) {
|
||||
let templateContent = '';
|
||||
try {
|
||||
templateContent = fs.readFileSync(templatePath, 'utf8');
|
||||
} catch (error) {
|
||||
throw new Error(`未找到平台模板: ${normalizedPlatform}.json`);
|
||||
}
|
||||
|
||||
let templateData;
|
||||
try {
|
||||
templateData = JSON.parse(templateContent);
|
||||
} catch (error) {
|
||||
throw new Error(`平台模板 JSON 解析失败: ${normalizedPlatform}.json`);
|
||||
}
|
||||
TEMPLATE_CACHE.set(templatePath, templateData);
|
||||
}
|
||||
|
||||
return deepClone(TEMPLATE_CACHE.get(templatePath));
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化平台编码。
|
||||
* @param {string} platform 平台编码或别名。
|
||||
* @return {string} 规范化平台编码。
|
||||
*/
|
||||
normalizePlatform(platform) {
|
||||
const normalized = PrinterDataBuilder.normalizePlatformAlias(platform);
|
||||
if (normalized && normalized.platform) {
|
||||
return normalized.platform;
|
||||
}
|
||||
return String(platform || '').trim().toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ExpressPrintPayloadBuilder,
|
||||
RequestScopedPrintIdGenerator,
|
||||
};
|
||||
@ -454,6 +454,7 @@ function resolveItemQuantity(item) {
|
||||
* @param {Array<Object>} items 商品列表。
|
||||
* @param {Object} policyConfig 策略配置。
|
||||
* @param {string} lineBreak 换行符。
|
||||
* @param options
|
||||
* @return {string} 自定义区文本。
|
||||
*/
|
||||
function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) {
|
||||
@ -751,6 +752,7 @@ function buildBaseData(input, platform, platformMeta) {
|
||||
* 清洗模板样例,保留结构并裁切样例噪声。
|
||||
* @param {any} value 原始对象。
|
||||
* @param {string[]} warnings 警告列表。
|
||||
* @param currentKey
|
||||
* @return {any} 清洗后的对象。
|
||||
*/
|
||||
function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') {
|
||||
@ -819,6 +821,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') {
|
||||
* @param {string} platform 归一化平台编码。
|
||||
* @param {Object} skeleton 打印请求骨架。
|
||||
* @param {Object} orderExpress 快递单对象。
|
||||
* @param orderDelivery
|
||||
* @param {string[]} warnings 风险提示列表。
|
||||
* @param {Object} policyConfig 策略配置对象。
|
||||
* @param {string} customDataTemplateURL 自定义区模板地址默认值。
|
||||
@ -960,6 +963,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
|
||||
* @param {string} platform 归一化平台编码。
|
||||
* @param {Object} skeleton 打印请求骨架。
|
||||
* @param {Object} orderExpress 快递单对象。
|
||||
* @param orderDelivery
|
||||
* @param {Object} policyConfig 策略配置对象。
|
||||
*/
|
||||
function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) {
|
||||
@ -1033,13 +1037,13 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli
|
||||
templateURL: toTrimmedString(templateURL || DEFAULT_PDD_CUSTOM_TEMPLATE_URL),
|
||||
data: {
|
||||
height: 240,
|
||||
list: [ {
|
||||
list: [{
|
||||
fontSize: 28,
|
||||
left: 2.08,
|
||||
text: customProductInfo,
|
||||
top: 2.08,
|
||||
width: 550,
|
||||
} ],
|
||||
}],
|
||||
waterdata: {
|
||||
text: '',
|
||||
},
|
||||
|
||||
@ -108,10 +108,10 @@ module.exports = app => {
|
||||
comment: '更新时间',
|
||||
},
|
||||
type: {
|
||||
type: ENUM('web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block'),
|
||||
type: ENUM('web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block', 'workerstation_pages'),
|
||||
allowNull: false,
|
||||
defaultValue: 'web_pages',
|
||||
comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块)',
|
||||
comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块,workerstation_pages:工作台菜单)',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_permission',
|
||||
@ -163,6 +163,7 @@ module.exports = app => {
|
||||
api: '接口权限',
|
||||
miniprogram_pages: '小程序页面',
|
||||
block: '功能模块',
|
||||
workerstation_pages: '工作台菜单',
|
||||
};
|
||||
return typeMap[this.type] || this.type;
|
||||
};
|
||||
|
||||
@ -1,5 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 平台表模型定义。
|
||||
* @param {import('egg').Application} app Egg 应用实例
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 平台模型
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER } = app.Sequelize;
|
||||
|
||||
@ -60,6 +65,11 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '订单来源',
|
||||
},
|
||||
component: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '打印组件标识',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_platform',
|
||||
freezeTableName: true,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize;
|
||||
const { STRING, INTEGER, BIGINT, ENUM, DATE, TEXT } = app.Sequelize;
|
||||
|
||||
const StockTransaction = app.model.define('stock_transaction', {
|
||||
id: {
|
||||
@ -11,7 +11,7 @@ module.exports = app => {
|
||||
comment: '主键ID',
|
||||
},
|
||||
transaction_type: {
|
||||
type: ENUM('INBOUND', 'OUTBOUND'),
|
||||
type: ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'),
|
||||
allowNull: false,
|
||||
comment: '出入库类型',
|
||||
},
|
||||
@ -81,7 +81,7 @@ module.exports = app => {
|
||||
comment: '关联单据类型(如 SCRK=收货入库, MATCH=匹配入库, CGTH=采购退货等)',
|
||||
},
|
||||
order_no: {
|
||||
type: STRING(100),
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '关联单据号',
|
||||
},
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other' ]);
|
||||
const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other', 'workerstation', 'workstation' ]);
|
||||
// project: all=全部, warehouse=仓库, store=货主, tms=物流
|
||||
const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 'scm', 'other' ]);
|
||||
|
||||
|
||||
@ -770,6 +770,245 @@ class WaveService extends OrderBaseService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按订单ID清理波次索引记录。
|
||||
*
|
||||
* @param {Object} params 清理参数。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @param {Array<number|string>|number|string} params.orderIds 订单ID集合。
|
||||
* @param {Object} params.transaction Sequelize 事务。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async deleteOrderWaveIndexByOrderIds({ warehouseId, orderIds, transaction } = {}) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const normalizedOrderIds = this.normalizeIdsInput(orderIds);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedOrderIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const deleteSql = `
|
||||
DELETE FROM wms_order_wave_index
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND order_id IN (:orderIds)
|
||||
`;
|
||||
|
||||
await this.ctx.model.query(deleteSql, {
|
||||
replacements: {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderIds: normalizedOrderIds,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按波次ID清理波次索引记录(用于兜底)。
|
||||
*
|
||||
* @param {Object} params 清理参数。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @param {Array<number|string>|number|string} params.waveIds 波次ID集合。
|
||||
* @param {Object} params.transaction Sequelize 事务。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds, transaction } = {}) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const normalizedWaveIds = this.normalizeIdsInput(waveIds);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const deleteSql = `
|
||||
DELETE FROM wms_order_wave_index
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id IN (:waveIds)
|
||||
`;
|
||||
|
||||
await this.ctx.model.query(deleteSql, {
|
||||
replacements: {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
waveIds: normalizedWaveIds,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 重建订单波次索引。
|
||||
*
|
||||
* 兼容历史入参校验后,统一委托按波次整批覆盖索引,
|
||||
* 避免与重排流程存在两套排序规则。
|
||||
*
|
||||
* @param {Object} params 重建参数。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @param {number|string} params.waveId 波次ID。
|
||||
* @param {Array<number|string>|number|string} params.orderIds 订单ID集合。
|
||||
* @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。
|
||||
* @param {Object} params.transaction Sequelize 事务。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async rebuildOrderWaveIndex({ warehouseId, waveId, orderIds, orderModel, transaction } = {}) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const normalizedWaveId = Number(waveId || 0);
|
||||
const normalizedOrderIds = this.normalizeIdsInput(orderIds);
|
||||
if (
|
||||
!Number.isInteger(normalizedWarehouseId)
|
||||
|| normalizedWarehouseId <= 0
|
||||
|| !Number.isInteger(normalizedWaveId)
|
||||
|| normalizedWaveId <= 0
|
||||
|| normalizedOrderIds.length === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await this.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId: normalizedWarehouseId,
|
||||
waveIds: [ normalizedWaveId ],
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按波次整批覆盖订单索引并返回各波次当前订单数。
|
||||
*
|
||||
* 处理流程:
|
||||
* 1. 查询目标波次下当前订单(按 wave_id ASC, id ASC)。
|
||||
* 2. 先按波次批量删除 wms_order_wave_index。
|
||||
* 3. 按每个波次内订单顺序重建 wave_index;platforms_index 按平台内顺序重建(同平台按 id ASC,从 1 开始)。
|
||||
*
|
||||
* @param {Object} params 覆盖参数。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @param {Array<number|string>|number|string} params.waveIds 波次ID集合。
|
||||
* @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。
|
||||
* @param {Object} params.transaction Sequelize 事务。
|
||||
* @return {Promise<Map<number, number>>} 波次当前订单数映射。
|
||||
*/
|
||||
async replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds, orderModel, transaction } = {}) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const normalizedWaveIds = this.normalizeIdsInput(waveIds);
|
||||
const currentOrderModel = orderModel || await this.getOrderModel('pendingOrder', normalizedWarehouseId);
|
||||
|
||||
if (
|
||||
!Number.isInteger(normalizedWarehouseId)
|
||||
|| normalizedWarehouseId <= 0
|
||||
|| normalizedWaveIds.length === 0
|
||||
|| !currentOrderModel
|
||||
|| typeof currentOrderModel.findAll !== 'function'
|
||||
) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const orderRows = await currentOrderModel.findAll({
|
||||
attributes: [ 'id', 'wave_id', 'sys_platform_code', 'source_platform_code' ],
|
||||
where: {
|
||||
wave_id: {
|
||||
[Op.in]: normalizedWaveIds,
|
||||
[Op.gt]: 0,
|
||||
},
|
||||
},
|
||||
order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const orderRowsList = Array.isArray(orderRows) ? orderRows : [];
|
||||
const waveOrderRowsMap = new Map(normalizedWaveIds.map(waveId => [ waveId, []]));
|
||||
for (const row of orderRowsList) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
const orderId = Number(row && row.id || 0);
|
||||
if (!Number.isInteger(waveId) || waveId <= 0 || !waveOrderRowsMap.has(waveId)) {
|
||||
continue;
|
||||
}
|
||||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
waveOrderRowsMap.get(waveId).push({
|
||||
id: orderId,
|
||||
sys_platform_code: String(row && row.sys_platform_code || ''),
|
||||
source_platform_code: String(row && row.source_platform_code || ''),
|
||||
});
|
||||
}
|
||||
|
||||
await this.deleteOrderWaveIndexByWaveIds({
|
||||
warehouseId: normalizedWarehouseId,
|
||||
waveIds: normalizedWaveIds,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const valueSqlList = [];
|
||||
const replacements = {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
};
|
||||
|
||||
let rowIndex = 0;
|
||||
for (const waveId of normalizedWaveIds) {
|
||||
const orderRowsByWave = waveOrderRowsMap.get(waveId) || [];
|
||||
const platformsIndexMap = new Map();
|
||||
const platformSequenceMap = new Map();
|
||||
for (const orderRow of orderRowsByWave) {
|
||||
const currentOrderId = Number(orderRow && orderRow.id || 0);
|
||||
if (!Number.isInteger(currentOrderId) || currentOrderId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const platformKey = String(
|
||||
(orderRow && orderRow.sys_platform_code)
|
||||
|| (orderRow && orderRow.source_platform_code)
|
||||
|| ''
|
||||
).trim().toLowerCase();
|
||||
const nextPlatformSequence = Number(platformSequenceMap.get(platformKey) || 0) + 1;
|
||||
platformSequenceMap.set(platformKey, nextPlatformSequence);
|
||||
platformsIndexMap.set(currentOrderId, nextPlatformSequence);
|
||||
}
|
||||
|
||||
for (const [ orderIndex, orderRow ] of orderRowsByWave.entries()) {
|
||||
const orderId = Number(orderRow && orderRow.id || 0);
|
||||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||||
continue;
|
||||
}
|
||||
const waveSequence = orderIndex + 1;
|
||||
const platformsSequence = Number(platformsIndexMap.get(orderId) || waveSequence);
|
||||
valueSqlList.push(
|
||||
`(:warehouseId, :orderId_${rowIndex}, :waveId_${rowIndex}, :waveIndex_${rowIndex}, :platformsIndex_${rowIndex}, NOW())`
|
||||
);
|
||||
replacements[`orderId_${rowIndex}`] = orderId;
|
||||
replacements[`waveId_${rowIndex}`] = waveId;
|
||||
replacements[`waveIndex_${rowIndex}`] = waveSequence;
|
||||
replacements[`platformsIndex_${rowIndex}`] = platformsSequence;
|
||||
rowIndex += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (valueSqlList.length > 0) {
|
||||
const insertSql = `
|
||||
INSERT INTO wms_order_wave_index
|
||||
(
|
||||
warehouse_id,
|
||||
order_id,
|
||||
wave_id,
|
||||
wave_index,
|
||||
platforms_index,
|
||||
create_at
|
||||
)
|
||||
VALUES
|
||||
${valueSqlList.join(',\n ')}
|
||||
`;
|
||||
|
||||
await this.ctx.model.query(insertSql, {
|
||||
replacements,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
const totalOrdersMap = new Map();
|
||||
for (const waveId of normalizedWaveIds) {
|
||||
const orderRowsByWave = waveOrderRowsMap.get(waveId) || [];
|
||||
totalOrdersMap.set(waveId, orderRowsByWave.length);
|
||||
}
|
||||
|
||||
return totalOrdersMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建抓取候选订单筛选条件。
|
||||
*
|
||||
@ -951,6 +1190,14 @@ class WaveService extends OrderBaseService {
|
||||
});
|
||||
}
|
||||
|
||||
await this.rebuildOrderWaveIndex({
|
||||
warehouseId,
|
||||
waveId,
|
||||
orderIds: grabbedOrderIds,
|
||||
orderModel: model,
|
||||
transaction,
|
||||
});
|
||||
|
||||
allWaveIds.push(waveId);
|
||||
allOrderIds.push(...grabbedOrderIds);
|
||||
fetchedOrderLogItems.push(...grabbedOrderIds.map(orderId => ({
|
||||
@ -1753,7 +2000,6 @@ class WaveService extends OrderBaseService {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 归一化拣货任务列表请求参数。
|
||||
*
|
||||
@ -1942,7 +2188,7 @@ class WaveService extends OrderBaseService {
|
||||
replacements,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
buildItemSnapshotKey(itemDetails = []) {
|
||||
if (!Array.isArray(itemDetails) || itemDetails.length === 0) {
|
||||
return '';
|
||||
@ -5321,6 +5567,14 @@ class WaveService extends OrderBaseService {
|
||||
});
|
||||
}
|
||||
|
||||
await this.rebuildOrderWaveIndex({
|
||||
warehouseId,
|
||||
waveId,
|
||||
orderIds: grabbedOrderIds,
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
await this.batchCreateOrderOperationLogs(grabbedOrderIds.map(orderId => ({
|
||||
@ -5446,33 +5700,13 @@ class WaveService extends OrderBaseService {
|
||||
|
||||
const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0);
|
||||
|
||||
const remainingRows = await orderModel.findAll({
|
||||
attributes: [
|
||||
'wave_id',
|
||||
[ this.ctx.model.fn('COUNT', this.ctx.model.col('id')), 'remaining_count' ],
|
||||
],
|
||||
where: {
|
||||
wave_id: {
|
||||
[Op.in]: affectedWaveIds,
|
||||
[Op.gt]: 0,
|
||||
},
|
||||
},
|
||||
group: [ 'wave_id' ],
|
||||
raw: true,
|
||||
const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: affectedWaveIds,
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const remainingCountMap = new Map();
|
||||
for (const row of (Array.isArray(remainingRows) ? remainingRows : [])) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
const remainingCount = Number(row && row.remaining_count || 0);
|
||||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
remainingCountMap.set(waveId, Number.isInteger(remainingCount) && remainingCount > 0 ? remainingCount : 0);
|
||||
}
|
||||
|
||||
const updatedWaveIds = [];
|
||||
const emptiedWaveIds = [];
|
||||
|
||||
@ -6312,6 +6546,9 @@ class WaveService extends OrderBaseService {
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
const affectedOrderIds = [ ...new Set((Array.isArray(affectedOrderRows) ? affectedOrderRows : [])
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)) ];
|
||||
|
||||
const orderUpdateResult = await orderModel.update({
|
||||
wave_id: 0,
|
||||
@ -6322,6 +6559,21 @@ class WaveService extends OrderBaseService {
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (affectedOrderIds.length > 0) {
|
||||
await this.deleteOrderWaveIndexByOrderIds({
|
||||
warehouseId,
|
||||
orderIds: affectedOrderIds,
|
||||
transaction,
|
||||
});
|
||||
} else {
|
||||
await this.deleteOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: [ waveId ],
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
const currentAffectedOrderCount = Number(
|
||||
Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0
|
||||
);
|
||||
@ -7464,6 +7716,14 @@ class WaveService extends OrderBaseService {
|
||||
transaction,
|
||||
});
|
||||
|
||||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||||
await this.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: updatableWaveIds,
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null;
|
||||
const updatedWaveCount = Number(
|
||||
updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount)
|
||||
@ -7573,6 +7833,14 @@ class WaveService extends OrderBaseService {
|
||||
transaction,
|
||||
});
|
||||
|
||||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||||
await this.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: updatedWaveIds,
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null;
|
||||
const updatedWaveCount = Number(
|
||||
updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount)
|
||||
|
||||
@ -2,6 +2,10 @@
|
||||
|
||||
// 打印相关 Service
|
||||
const MainService = require('../main');
|
||||
const {
|
||||
ExpressPrintPayloadBuilder,
|
||||
RequestScopedPrintIdGenerator,
|
||||
} = require('../../lib/express_print_payload_builder');
|
||||
|
||||
/**
|
||||
* 打印 Service
|
||||
@ -29,50 +33,210 @@ class PrintService extends MainService {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建 print.send 入参摘要,避免打印超大对象。
|
||||
* @param {Object} payload 原始入参。
|
||||
* @return {Object} 安全摘要信息。
|
||||
*/
|
||||
buildPrintSendInputSummary(payload = {}) {
|
||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
||||
const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {};
|
||||
const waveGroups = Array.isArray(data.waveGroups) ? data.waveGroups : [];
|
||||
const firstWavePlatforms = Array.isArray(waveGroups[0] && waveGroups[0].platforms) ? waveGroups[0].platforms : [];
|
||||
const firstPlatformOrders = Array.isArray(firstWavePlatforms[0] && firstWavePlatforms[0].orders)
|
||||
? firstWavePlatforms[0].orders
|
||||
: [];
|
||||
return {
|
||||
type: normalizedPayload.type || '',
|
||||
printer: normalizedPayload.printer || '',
|
||||
computerId: normalizedPayload.computerId || '',
|
||||
printStationId: normalizedPayload.printStationId || '',
|
||||
hasTemplate: Boolean(normalizedPayload.template),
|
||||
requestCode: normalizedPayload.requestCode ? String(normalizedPayload.requestCode) : '',
|
||||
waveGroupsCount: waveGroups.length,
|
||||
firstWavePlatformsCount: firstWavePlatforms.length,
|
||||
firstGroupOrdersCount: firstPlatformOrders.length,
|
||||
dataKeys: Object.keys(data).slice(0, 20),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计快递 payload 摘要,避免输出完整文档对象。
|
||||
* @param {Object} payload 快递发送 payload。
|
||||
* @return {{documentCount:number}} 文档数量摘要。
|
||||
*/
|
||||
summarizeExpressPayload(payload = {}) {
|
||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
||||
let documentCount = 0;
|
||||
if (normalizedPayload.task && Array.isArray(normalizedPayload.task.documents)) {
|
||||
documentCount = normalizedPayload.task.documents.length;
|
||||
} else if (Array.isArray(normalizedPayload.documents)) {
|
||||
documentCount = normalizedPayload.documents.length;
|
||||
} else if (Array.isArray(normalizedPayload.document_list)) {
|
||||
documentCount = normalizedPayload.document_list.length;
|
||||
} else if (Array.isArray(normalizedPayload.data)) {
|
||||
documentCount = normalizedPayload.data.length;
|
||||
} else if (normalizedPayload.document || normalizedPayload.print_data) {
|
||||
documentCount = 1;
|
||||
}
|
||||
return { documentCount };
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送打印任务到打印电脑。
|
||||
* 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。
|
||||
* 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。
|
||||
* @param {Object} _data 打印请求参数
|
||||
* @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 可不传)
|
||||
* @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 忽略)
|
||||
* @param {string} _data.type 打印类型,支持 customize/express
|
||||
* @param {Object} [_data.template] 打印模板对象(customize 必填)
|
||||
* @param {Object} _data.data 打印业务数据
|
||||
* @param {string} _data.computerId 打印电脑 ID
|
||||
* @param {string} [_data.timestamp] 业务时间戳
|
||||
* @param {number} [_data.count] 打印份数
|
||||
* @returns {Promise<Object>} 统一返回结构
|
||||
* @param {Object} _data.data 打印业务数据(express 场景要求 data.waveGroups)
|
||||
* @param {string|number} [_data.printStationId] 打印台 ID(express 必填)
|
||||
* @param {string} [_data.requestCode] 请求参数码(express 必填,用于本次请求内 ID 唯一化)
|
||||
* @param {string} [_data.computerId] 打印电脑 ID(customize 必填,express 忽略)
|
||||
* @param {string} [_data.timestamp] 业务时间戳(express 忽略)
|
||||
* @param {number} [_data.count] 打印份数(express 忽略)
|
||||
* @return {Promise<Object>} 统一返回结构
|
||||
*/
|
||||
async send(_data) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
const { printer, type, template, data, computerId, timestamp, count } = _data;
|
||||
// 生成打印编号并记录到数据库
|
||||
const printRecord = await ctx.model.PrintRecord.create({
|
||||
warehouse_id: warehouseId,
|
||||
computer_id: computerId,
|
||||
const {
|
||||
printer,
|
||||
type,
|
||||
data: { template, data },
|
||||
status: 'pending',
|
||||
template,
|
||||
data,
|
||||
computerId,
|
||||
timestamp,
|
||||
count,
|
||||
printStationId,
|
||||
requestCode,
|
||||
} = _data;
|
||||
this.ctx.logger.info('[print.send] 入参接收', {
|
||||
warehouseId,
|
||||
inputSummary: this.buildPrintSendInputSummary(_data),
|
||||
});
|
||||
this.ctx.logger.info('[print.send] 分支判定', {
|
||||
warehouseId,
|
||||
type,
|
||||
isExpress: type === 'express',
|
||||
isCustomize: type === 'customize',
|
||||
});
|
||||
if (type === 'express') {
|
||||
const expressValidationResult = this.validateExpressSendInput({ data, printStationId, requestCode });
|
||||
if (expressValidationResult) {
|
||||
this.ctx.logger.warn('[print.send] express 参数校验失败', {
|
||||
warehouseId,
|
||||
printStationId,
|
||||
requestCode: requestCode ? String(requestCode) : '',
|
||||
waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: 'express 参数校验失败',
|
||||
});
|
||||
return expressValidationResult;
|
||||
}
|
||||
this.ctx.logger.info('[print.send] express 参数校验通过', {
|
||||
warehouseId,
|
||||
printStationId,
|
||||
waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0,
|
||||
});
|
||||
}
|
||||
let printRecord = null;
|
||||
if (type !== 'express') {
|
||||
// 生成打印编号并记录到数据库
|
||||
try {
|
||||
printRecord = await ctx.model.PrintRecord.create({
|
||||
warehouse_id: warehouseId,
|
||||
computer_id: computerId,
|
||||
printer,
|
||||
type,
|
||||
data: { template, data },
|
||||
status: 'pending',
|
||||
});
|
||||
this.ctx.logger.info('[print.send] PrintRecord 创建成功', {
|
||||
warehouseId,
|
||||
type,
|
||||
printId: printRecord.id,
|
||||
computerId,
|
||||
printer,
|
||||
});
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[print.send] PrintRecord 创建失败', {
|
||||
warehouseId,
|
||||
type,
|
||||
computerId,
|
||||
printer,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
stack: error && error.stack ? error.stack : '',
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
// 处理后的数据
|
||||
let processedData = {};
|
||||
switch (type) {
|
||||
case 'customize': {
|
||||
if (printer === undefined || printer === null || printer === '') {
|
||||
this.ctx.logger.warn('[print.send] customize 参数校验失败-printer 为空', {
|
||||
warehouseId,
|
||||
type,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: 'printer 参数不能为空',
|
||||
});
|
||||
return this.fail('type=customize 时 printer 参数不能为空', { code: 400 });
|
||||
}
|
||||
if (!template || typeof template !== 'object' || Array.isArray(template)) {
|
||||
this.ctx.logger.warn('[print.send] customize 参数校验失败-template 非对象', {
|
||||
warehouseId,
|
||||
type,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: 'template 参数不合法',
|
||||
});
|
||||
return this.fail('type=customize 时 template 参数不能为空', { code: 400 });
|
||||
}
|
||||
const { page_width, page_height, template_content } = template;
|
||||
if (page_width === undefined || page_width === null || page_width === '') {
|
||||
this.ctx.logger.warn('[print.send] customize 参数校验失败-page_width 为空', {
|
||||
warehouseId,
|
||||
type,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: 'page_width 参数不能为空',
|
||||
});
|
||||
return this.fail('type=customize 时 page_width 参数不能为空', { code: 400 });
|
||||
}
|
||||
if (page_height === undefined || page_height === null || page_height === '') {
|
||||
this.ctx.logger.warn('[print.send] customize 参数校验失败-page_height 为空', {
|
||||
warehouseId,
|
||||
type,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: 'page_height 参数不能为空',
|
||||
});
|
||||
return this.fail('type=customize 时 page_height 参数不能为空', { code: 400 });
|
||||
}
|
||||
if (!Array.isArray(template_content)) {
|
||||
this.ctx.logger.warn('[print.send] customize 参数校验失败-template_content 非数组', {
|
||||
warehouseId,
|
||||
type,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: 'template_content 参数不合法',
|
||||
});
|
||||
return this.fail('type=customize 时 template_content 必须是数组', { code: 400 });
|
||||
}
|
||||
let htm = `<body style="position:relative; width:${page_width}mm; height:${page_height}mm;margin:0; padding:0;overflow:hidden;">`;
|
||||
@ -176,12 +340,119 @@ class PrintService extends MainService {
|
||||
htm,
|
||||
lodopkey: [ '', '13528A153BAEE3A0254B9507DCDE2839', 'EDE92F75B6A3D917F65910', 'D60BC84D7CF2DE18156A6F88987304CB6D8' ],
|
||||
};
|
||||
this.ctx.logger.info('[print.send] customize payload 组装完成', {
|
||||
warehouseId,
|
||||
type,
|
||||
pageWidth: page_width,
|
||||
pageHeight: page_height,
|
||||
templateItemCount: template_content.length,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'express':
|
||||
|
||||
break;
|
||||
case 'express': {
|
||||
const expressPrintStation = await this.loadExpressPrintStation({ printStationId, warehouseId });
|
||||
if (!expressPrintStation.success) {
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: expressPrintStation.error,
|
||||
});
|
||||
return this.fail(expressPrintStation.error, { code: 400 });
|
||||
}
|
||||
const expressRecordFields = this.buildExpressPrintRecordFields(expressPrintStation.data);
|
||||
if (!expressRecordFields.success) {
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: expressRecordFields.error,
|
||||
});
|
||||
return this.fail(expressRecordFields.error, { code: 400 });
|
||||
}
|
||||
|
||||
const platformCodes = this.collectExpressPlatformCodes(data.waveGroups);
|
||||
const platformComponentsResult = await this.loadExpressPlatformComponents({ platformCodes });
|
||||
if (!platformComponentsResult.success) {
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: platformComponentsResult.error,
|
||||
});
|
||||
return this.fail(platformComponentsResult.error, { code: 400 });
|
||||
}
|
||||
const componentOnlineResult = await this.validateExpressComponentsOnline({
|
||||
computerId: expressRecordFields.data.computer_id,
|
||||
platformComponents: platformComponentsResult.data,
|
||||
});
|
||||
if (!componentOnlineResult.success) {
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: componentOnlineResult.error,
|
||||
});
|
||||
return this.fail(componentOnlineResult.error, { code: 400 });
|
||||
}
|
||||
try {
|
||||
printRecord = await ctx.model.PrintRecord.create({
|
||||
warehouse_id: warehouseId,
|
||||
computer_id: expressRecordFields.data.computer_id,
|
||||
printer: expressRecordFields.data.printer,
|
||||
type,
|
||||
data: { template, data },
|
||||
status: 'pending',
|
||||
});
|
||||
this.ctx.logger.info('[print.send] PrintRecord 创建成功', {
|
||||
warehouseId,
|
||||
type,
|
||||
printId: printRecord.id,
|
||||
computerId: expressRecordFields.data.computer_id,
|
||||
printer: expressRecordFields.data.printer,
|
||||
});
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[print.send] PrintRecord 创建失败', {
|
||||
warehouseId,
|
||||
type,
|
||||
computerId: expressRecordFields.data.computer_id,
|
||||
printer: expressRecordFields.data.printer,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
stack: error && error.stack ? error.stack : '',
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
const payloadBuilder = new ExpressPrintPayloadBuilder({ baseDir: this.app.baseDir });
|
||||
const idGenerator = new RequestScopedPrintIdGenerator(requestCode);
|
||||
const expressSendResult = await this.sendExpressWaveGroups({
|
||||
warehouseId,
|
||||
waveGroups: data.waveGroups,
|
||||
printStation: expressPrintStation.data,
|
||||
payloadBuilder,
|
||||
idGenerator,
|
||||
printRecordId: printRecord.id,
|
||||
platformComponents: platformComponentsResult.data,
|
||||
});
|
||||
if (!expressSendResult.success) {
|
||||
await printRecord.update({ status: 'failed', error_message: expressSendResult.error });
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
printId: printRecord.id,
|
||||
reason: expressSendResult.error,
|
||||
});
|
||||
return this.fail(expressSendResult.error, { code: 504, printId: printRecord.id });
|
||||
}
|
||||
await printRecord.update({ status: 'sent' });
|
||||
this.ctx.logger.info('[print.send] 最终返回 success', {
|
||||
warehouseId,
|
||||
type,
|
||||
printId: printRecord.id,
|
||||
});
|
||||
return this.success('发送打印任务成功', { code: 200, printId: printRecord.id });
|
||||
}
|
||||
default:
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
reason: '不支持的打印类型',
|
||||
});
|
||||
return this.fail('不支持的打印类型', 1001);
|
||||
}
|
||||
|
||||
@ -194,15 +465,531 @@ class PrintService extends MainService {
|
||||
count,
|
||||
printId: printRecord.id,
|
||||
};
|
||||
const sendStartAt = Date.now();
|
||||
const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData });
|
||||
const sendDurationMs = Date.now() - sendStartAt;
|
||||
if (res.status === 'success') {
|
||||
this.ctx.logger.info('[print.send] sendToComputer 调用成功', {
|
||||
warehouseId,
|
||||
type,
|
||||
printId: printRecord.id,
|
||||
computerId,
|
||||
durationMs: sendDurationMs,
|
||||
});
|
||||
} else {
|
||||
this.ctx.logger.error('[print.send] sendToComputer 调用失败', {
|
||||
warehouseId,
|
||||
type,
|
||||
printId: printRecord.id,
|
||||
computerId,
|
||||
durationMs: sendDurationMs,
|
||||
error: res && res.error ? res.error : '打印服务返回失败',
|
||||
});
|
||||
}
|
||||
// 发送成功后更新打印记录状态
|
||||
if (res.status === 'success') {
|
||||
await printRecord.update({ status: 'sent' });
|
||||
this.ctx.logger.info('[print.send] 最终返回 success', {
|
||||
warehouseId,
|
||||
type,
|
||||
printId: printRecord.id,
|
||||
});
|
||||
return this.success('发送打印任务成功', { code: 200, printId: printRecord.id });
|
||||
}
|
||||
await printRecord.update({ status: 'failed', error_message: res.error });
|
||||
this.ctx.logger.error('[print.send] 最终返回 failure', {
|
||||
warehouseId,
|
||||
type,
|
||||
printId: printRecord.id,
|
||||
reason: res.error || '打印服务返回失败',
|
||||
});
|
||||
return this.fail(res.error, { code: 504, printId: printRecord.id });
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验快递打印请求的必要参数。
|
||||
* @param {Object} payload 校验参数。
|
||||
* @param {Object} payload.data 请求 data。
|
||||
* @param {number|string} payload.printStationId 打印台 ID。
|
||||
* @param {string} payload.requestCode 请求参数码。
|
||||
* @return {Object|null} 失败时返回 fail 响应,成功返回 null。
|
||||
*/
|
||||
validateExpressSendInput(payload = {}) {
|
||||
const requestData = payload && typeof payload === 'object' ? payload : {};
|
||||
const waveGroups = Array.isArray(requestData.data && requestData.data.waveGroups)
|
||||
? requestData.data.waveGroups
|
||||
: [];
|
||||
if (waveGroups.length === 0) {
|
||||
this.ctx.logger.warn('[print.send] express 参数校验失败-data.waveGroups 为空', {
|
||||
printStationId: requestData.printStationId || '',
|
||||
requestCode: requestData.requestCode ? String(requestData.requestCode) : '',
|
||||
});
|
||||
return this.fail('type=express 时 data.waveGroups 必须是非空数组', { code: 400 });
|
||||
}
|
||||
|
||||
const normalizedPrintStationId = String(requestData.printStationId || '').trim();
|
||||
if (!normalizedPrintStationId) {
|
||||
this.ctx.logger.warn('[print.send] express 参数校验失败-printStationId 为空', {
|
||||
requestCode: requestData.requestCode ? String(requestData.requestCode) : '',
|
||||
waveGroupsCount: waveGroups.length,
|
||||
});
|
||||
return this.fail('type=express 时 printStationId 参数不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
const normalizedRequestCode = String(requestData.requestCode || '').trim();
|
||||
if (!normalizedRequestCode) {
|
||||
this.ctx.logger.warn('[print.send] express 参数校验失败-requestCode 为空', {
|
||||
printStationId: normalizedPrintStationId,
|
||||
waveGroupsCount: waveGroups.length,
|
||||
});
|
||||
return this.fail('type=express 时 requestCode 参数不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询并校验快递打印台。
|
||||
* @param {Object} payload 查询参数。
|
||||
* @param {number|string} payload.printStationId 打印台 ID。
|
||||
* @param {number|string} payload.warehouseId 仓库 ID。
|
||||
* @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询结果。
|
||||
*/
|
||||
async loadExpressPrintStation(payload = {}) {
|
||||
const { ctx } = this;
|
||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
||||
const printStation = await ctx.model.PrintStations.findOne({
|
||||
where: {
|
||||
id: normalizedPayload.printStationId,
|
||||
warehouse_id: normalizedPayload.warehouseId,
|
||||
deleted: 0,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
if (!printStation) {
|
||||
this.ctx.logger.warn('[print.send] 打印台查询失败', {
|
||||
printStationId: normalizedPayload.printStationId,
|
||||
warehouseId: normalizedPayload.warehouseId,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error: '打印台不存在',
|
||||
};
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[print.send] 打印台查询成功', {
|
||||
printStationId: printStation.id,
|
||||
warehouseId: normalizedPayload.warehouseId,
|
||||
computerId: printStation.computer_id || '',
|
||||
defaultPrinterName: printStation.default_printer_name || '',
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: printStation,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装快递打印记录的必填字段,避免写入 null。
|
||||
* @param {Object} printStation 打印台配置。
|
||||
* @return {{success:boolean,data?:{computer_id:string,printer:string},error?:string}} 组装结果。
|
||||
*/
|
||||
buildExpressPrintRecordFields(printStation = {}) {
|
||||
const normalizedStation = printStation && typeof printStation === 'object' ? printStation : {};
|
||||
const computerId = String(normalizedStation.computer_id || '').trim();
|
||||
if (!computerId) {
|
||||
return {
|
||||
success: false,
|
||||
error: '打印台未配置打印电脑',
|
||||
};
|
||||
}
|
||||
|
||||
const defaultPrinterName = String(normalizedStation.default_printer_name || '').trim();
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
computer_id: computerId,
|
||||
printer: defaultPrinterName || 'EXPRESS_DYNAMIC_PRINTER',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集 express 请求中涉及的平台编码列表。
|
||||
* @param {Array<Object>} waveGroups 波次分组数据。
|
||||
* @return {Array<string>} 去重后的平台编码列表。
|
||||
*/
|
||||
collectExpressPlatformCodes(waveGroups = []) {
|
||||
const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : [];
|
||||
const platformCodeSet = new Set();
|
||||
for (const waveGroup of normalizedWaveGroups) {
|
||||
const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : [];
|
||||
for (const platformGroup of platforms) {
|
||||
const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : [];
|
||||
if (orders.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim();
|
||||
if (platformCode) {
|
||||
platformCodeSet.add(platformCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.from(platformCodeSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载并校验 express 请求涉及平台的打印组件配置。
|
||||
* @param {Object} payload 查询参数。
|
||||
* @param {Array<string>} payload.platformCodes 平台编码列表。
|
||||
* @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询与校验结果。
|
||||
*/
|
||||
async loadExpressPlatformComponents(payload = {}) {
|
||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
||||
const platformCodes = Array.isArray(normalizedPayload.platformCodes)
|
||||
? normalizedPayload.platformCodes.filter(item => String(item || '').trim())
|
||||
: [];
|
||||
if (platformCodes.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'type=express 时未识别到有效平台编码',
|
||||
};
|
||||
}
|
||||
|
||||
const platformRows = await this.ctx.model.Platform.findAll({
|
||||
attributes: [ 'code', 'component' ],
|
||||
where: {
|
||||
code: platformCodes,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
const platformComponentMap = {};
|
||||
for (const row of platformRows) {
|
||||
const platformCode = String(row && row.code ? row.code : '').trim();
|
||||
if (!platformCode) {
|
||||
continue;
|
||||
}
|
||||
platformComponentMap[platformCode] = String(row && row.component ? row.component : '').trim();
|
||||
}
|
||||
|
||||
for (const platformCode of platformCodes) {
|
||||
const component = String(platformComponentMap[platformCode] || '').trim();
|
||||
if (!component) {
|
||||
return {
|
||||
success: false,
|
||||
error: `平台 ${platformCode} 未配置打印组件`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: platformComponentMap,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 express 请求涉及组件是否全部在线。
|
||||
* @param {Object} payload 校验参数。
|
||||
* @param {string} payload.computerId 打印电脑 ID。
|
||||
* @param {Object} payload.platformComponents 平台到组件映射。
|
||||
* @return {Promise<{success:boolean,error?:string}>} 校验结果。
|
||||
*/
|
||||
async validateExpressComponentsOnline(payload = {}) {
|
||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
||||
const computerId = String(normalizedPayload.computerId || '').trim();
|
||||
const platformComponents = normalizedPayload.platformComponents && typeof normalizedPayload.platformComponents === 'object'
|
||||
? normalizedPayload.platformComponents
|
||||
: {};
|
||||
if (!computerId) {
|
||||
return {
|
||||
success: false,
|
||||
error: '打印台未配置打印电脑',
|
||||
};
|
||||
}
|
||||
|
||||
const redisPrinter = this.app.redis.get('printer');
|
||||
const entries = Object.entries(platformComponents);
|
||||
for (const entry of entries) {
|
||||
const platformCode = String(entry[0] || '').trim();
|
||||
const component = String(entry[1] || '').trim();
|
||||
const statusKey = `printer:${computerId}:name:${component}:status`;
|
||||
const componentStatus = await redisPrinter.get(statusKey);
|
||||
if (componentStatus !== 'connected') {
|
||||
return {
|
||||
success: false,
|
||||
error: `平台 ${platformCode} 打印组件 ${component} 未在线`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据平台快递编码解析打印机名称。
|
||||
* @param {Object} payload 解析参数。
|
||||
* @param {Object} payload.printStation 打印台配置。
|
||||
* @param {string} payload.sysLogisticsCode 系统快递编码。
|
||||
* @return {{success:boolean,data?:string,error?:string}} 解析结果。
|
||||
*/
|
||||
resolveExpressPrinterName(payload = {}) {
|
||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
||||
const printStation = normalizedPayload.printStation && typeof normalizedPayload.printStation === 'object'
|
||||
? normalizedPayload.printStation
|
||||
: {};
|
||||
let subjectConfig = printStation.subject_config;
|
||||
if (typeof subjectConfig === 'string') {
|
||||
try {
|
||||
subjectConfig = JSON.parse(subjectConfig);
|
||||
} catch (error) {
|
||||
subjectConfig = {};
|
||||
}
|
||||
}
|
||||
if (!subjectConfig || typeof subjectConfig !== 'object' || Array.isArray(subjectConfig)) {
|
||||
subjectConfig = {};
|
||||
}
|
||||
|
||||
const expressBindPrinter = Array.isArray(subjectConfig.express_bind_printer)
|
||||
? subjectConfig.express_bind_printer
|
||||
: [];
|
||||
const sysLogisticsCode = String(normalizedPayload.sysLogisticsCode || '').trim();
|
||||
const matchedPrinter = expressBindPrinter.find(item => {
|
||||
const sourceItem = item && typeof item === 'object' ? item : {};
|
||||
return String(sourceItem.express_code || '').trim() === sysLogisticsCode;
|
||||
});
|
||||
const printerName = String(
|
||||
matchedPrinter && matchedPrinter.printer_name
|
||||
? matchedPrinter.printer_name
|
||||
: (printStation.default_printer_name || '')
|
||||
).trim();
|
||||
if (!printerName) {
|
||||
return {
|
||||
success: false,
|
||||
error: '打印台未配置默认打印机',
|
||||
};
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[print.send] resolveExpressPrinterName 成功', {
|
||||
sysLogisticsCode,
|
||||
printerName,
|
||||
matched: Boolean(matchedPrinter),
|
||||
matchSource: matchedPrinter ? '命中快递绑定' : '回退默认打印机',
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: printerName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 串行发送快递打印任务(波次 -> 平台快递组)。
|
||||
* @param {Object} payload 发送参数。
|
||||
* @param {number|string} payload.warehouseId 仓库 ID。
|
||||
* @param {Array<Object>} payload.waveGroups 波次分组。
|
||||
* @param {Object} payload.printStation 打印台配置。
|
||||
* @param {Object} payload.payloadBuilder 快递模板组装器。
|
||||
* @param {Object} payload.idGenerator 本次请求 ID 生成器。
|
||||
* @param {number|string} payload.printRecordId 打印记录 ID。
|
||||
* @param {Object} payload.platformComponents 平台到打印组件映射。
|
||||
* @return {Promise<{success:boolean,error?:string}>} 发送结果。
|
||||
*/
|
||||
async sendExpressWaveGroups(payload = {}) {
|
||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
||||
const waveGroups = Array.isArray(normalizedPayload.waveGroups)
|
||||
? normalizedPayload.waveGroups
|
||||
: [];
|
||||
for (const waveGroup of waveGroups) {
|
||||
const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : [];
|
||||
for (const platformGroup of platforms) {
|
||||
const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : [];
|
||||
if (orders.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const groupSummary = {
|
||||
waveNo: waveGroup && waveGroup.wave_no ? waveGroup.wave_no : '',
|
||||
platform: platformGroup && platformGroup.platform ? platformGroup.platform : '',
|
||||
sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '',
|
||||
ordersCount: orders.length,
|
||||
printRecordId: normalizedPayload.printRecordId,
|
||||
};
|
||||
this.ctx.logger.info('[print.send] 平台快递组发送开始', groupSummary);
|
||||
|
||||
const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim();
|
||||
const component = String(
|
||||
normalizedPayload.platformComponents
|
||||
&& normalizedPayload.platformComponents[platformCode]
|
||||
? normalizedPayload.platformComponents[platformCode]
|
||||
: ''
|
||||
).trim();
|
||||
if (!component) {
|
||||
this.ctx.logger.error('[print.send] 平台快递组发送失败-打印组件缺失', {
|
||||
...groupSummary,
|
||||
reason: `平台 ${platformCode} 未配置打印组件`,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
|
||||
...groupSummary,
|
||||
status: 'failure',
|
||||
reason: `平台 ${platformCode} 未配置打印组件`,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error: `平台 ${platformCode} 未配置打印组件`,
|
||||
};
|
||||
}
|
||||
|
||||
const printerNameResult = this.resolveExpressPrinterName({
|
||||
printStation: normalizedPayload.printStation,
|
||||
sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code,
|
||||
});
|
||||
if (!printerNameResult.success) {
|
||||
this.ctx.logger.error('[print.send] 平台快递组发送失败-打印机解析失败', {
|
||||
...groupSummary,
|
||||
reason: printerNameResult.error,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
|
||||
...groupSummary,
|
||||
status: 'failure',
|
||||
reason: printerNameResult.error,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error: printerNameResult.error,
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedPlatformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim().toLowerCase();
|
||||
const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou' || normalizedPlatformCode === 'ks';
|
||||
const orderBatches = [];
|
||||
if (isKuaishouPlatform) {
|
||||
for (let index = 0; index < orders.length; index += 10) {
|
||||
orderBatches.push(orders.slice(index, index + 10));
|
||||
}
|
||||
} else {
|
||||
orderBatches.push(orders);
|
||||
}
|
||||
const totalDocumentCount = orders.length;
|
||||
|
||||
for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) {
|
||||
const batchOrders = orderBatches[batchIndex];
|
||||
const batchSummary = {
|
||||
...groupSummary,
|
||||
batchIndex: batchIndex + 1,
|
||||
batchCount: orderBatches.length,
|
||||
batchOrdersCount: batchOrders.length,
|
||||
};
|
||||
let requestPayload;
|
||||
try {
|
||||
requestPayload = normalizedPayload.payloadBuilder.buildPayload({
|
||||
platform: platformGroup && platformGroup.platform,
|
||||
printerName: printerNameResult.data,
|
||||
orders: batchOrders,
|
||||
idGenerator: normalizedPayload.idGenerator,
|
||||
});
|
||||
if (isKuaishouPlatform && requestPayload && requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) {
|
||||
requestPayload.task.firstDocumentNumber = batchIndex * 10 + 1;
|
||||
requestPayload.task.totalDocumentCount = totalDocumentCount;
|
||||
}
|
||||
const payloadSummary = this.summarizeExpressPayload(requestPayload);
|
||||
this.ctx.logger.info('[print.send] 组装 payload 成功', {
|
||||
...batchSummary,
|
||||
platform: platformGroup && platformGroup.platform ? platformGroup.platform : '',
|
||||
ordersCount: batchOrders.length,
|
||||
documentCount: payloadSummary.documentCount,
|
||||
});
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[print.send] 组装 payload 失败', {
|
||||
...batchSummary,
|
||||
platform: platformGroup && platformGroup.platform ? platformGroup.platform : '',
|
||||
ordersCount: batchOrders.length,
|
||||
reason: error && error.message ? error.message : '快递打印任务组装失败',
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
|
||||
...batchSummary,
|
||||
status: 'failure',
|
||||
reason: error && error.message ? error.message : '快递打印任务组装失败',
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error: error && error.message ? error.message : '快递打印任务组装失败',
|
||||
};
|
||||
}
|
||||
|
||||
const printData = {
|
||||
printer: printerNameResult.data,
|
||||
component,
|
||||
type: 'express',
|
||||
data: requestPayload,
|
||||
printId: normalizedPayload.printRecordId,
|
||||
};
|
||||
const sendStartAt = Date.now();
|
||||
let sendResult;
|
||||
try {
|
||||
sendResult = await this.service.systems.print.index.sendToComputer({
|
||||
warehouse: normalizedPayload.warehouseId,
|
||||
computerId: normalizedPayload.printStation.computer_id,
|
||||
data: printData,
|
||||
});
|
||||
} catch (error) {
|
||||
const sendDurationMs = Date.now() - sendStartAt;
|
||||
this.ctx.logger.error('[print.send] sendToComputer 调用失败', {
|
||||
...batchSummary,
|
||||
computerId: normalizedPayload.printStation.computer_id,
|
||||
durationMs: sendDurationMs,
|
||||
reason: error && error.message ? error.message : `${error}`,
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
|
||||
...batchSummary,
|
||||
computerId: normalizedPayload.printStation.computer_id,
|
||||
status: 'failure',
|
||||
reason: error && error.message ? error.message : `${error}`,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error: error && error.message ? error.message : '打印服务调用失败',
|
||||
};
|
||||
}
|
||||
const sendDurationMs = Date.now() - sendStartAt;
|
||||
if (sendResult.status !== 'success') {
|
||||
this.ctx.logger.error('[print.send] sendToComputer 调用失败', {
|
||||
...batchSummary,
|
||||
computerId: normalizedPayload.printStation.computer_id,
|
||||
durationMs: sendDurationMs,
|
||||
reason: sendResult.error || '打印服务返回失败',
|
||||
});
|
||||
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
|
||||
...batchSummary,
|
||||
computerId: normalizedPayload.printStation.computer_id,
|
||||
status: 'failure',
|
||||
reason: sendResult.error || '打印服务返回失败',
|
||||
});
|
||||
} else {
|
||||
this.ctx.logger.info('[print.send] sendToComputer 调用成功', {
|
||||
...batchSummary,
|
||||
computerId: normalizedPayload.printStation.computer_id,
|
||||
durationMs: sendDurationMs,
|
||||
});
|
||||
}
|
||||
if (sendResult.status !== 'success') {
|
||||
return {
|
||||
success: false,
|
||||
error: sendResult.error || '打印服务返回失败',
|
||||
};
|
||||
}
|
||||
this.ctx.logger.info('[print.send] 平台快递组发送结束', {
|
||||
...batchSummary,
|
||||
computerId: normalizedPayload.printStation.computer_id,
|
||||
status: 'success',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async getPrintResult(data) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
@ -317,6 +1104,7 @@ class PrintService extends MainService {
|
||||
/**
|
||||
* 2. 获取单个打印台
|
||||
* @param {Object} data { id }
|
||||
* @return {Promise<Object>} 返回打印台详情(不包含 warehouse_id)
|
||||
*/
|
||||
async getItem(data) {
|
||||
const { ctx } = this;
|
||||
@ -324,12 +1112,14 @@ class PrintService extends MainService {
|
||||
if (!id) return this.fail('参数错误', 1001);
|
||||
const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true });
|
||||
if (!item) return this.fail('打印台不存在', 1002);
|
||||
return this.success('success', { ...item, code: 0 });
|
||||
const rest = { ...item };
|
||||
delete rest.warehouse_id;
|
||||
return this.success('success', { ...rest, code: 0 });
|
||||
}
|
||||
/**
|
||||
* 3. 添加打印台
|
||||
* @param {Object} data { id, name, computer_id, custom_barcode }
|
||||
* @returns {Promise<Object>} 返回新增结果。
|
||||
* @return {Promise<Object>} 返回新增结果。
|
||||
*/
|
||||
async add(data) {
|
||||
const { ctx } = this;
|
||||
@ -371,7 +1161,7 @@ class PrintService extends MainService {
|
||||
/**
|
||||
* 3. 修改打印台
|
||||
* @param {Object} data { id, name, computer_id, custom_barcode }
|
||||
* @returns {Promise<Object>} 返回更新结果。
|
||||
* @return {Promise<Object>} 返回更新结果。
|
||||
*/
|
||||
async updateItem(data) {
|
||||
const { ctx } = this;
|
||||
@ -444,7 +1234,7 @@ class PrintService extends MainService {
|
||||
* @param {string} data.defaultPrinter 默认打印机名称,必填。
|
||||
* @param {Array<Object>} data.express 快递绑定数组,必填。
|
||||
* @param {number|string} data.print_station_id 打印台 ID,必填。
|
||||
* @returns {Promise<Object>} 保存结果。
|
||||
* @return {Promise<Object>} 保存结果。
|
||||
*/
|
||||
async savePrinters(data) {
|
||||
const { ctx } = this;
|
||||
|
||||
298
app/service/systemMethods/storage/report.js
Normal file
298
app/service/systemMethods/storage/report.js
Normal file
@ -0,0 +1,298 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
const STORAGE_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_report_export_task_';
|
||||
const STORAGE_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
|
||||
/**
|
||||
* 系统方法层:storage.report(库存流水报表接口包装层)。
|
||||
*/
|
||||
class StorageReportMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'search,export,exportTaskProgress';
|
||||
const _noNeedLog = 'search,export,exportTaskProgress';
|
||||
const _noNeedAuth = 'search,export,exportTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询库存流水统计报表。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field)
|
||||
* @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order)
|
||||
* @param {string|Date} [data.where.start_time] 开始时间
|
||||
* @param {string|Date} [data.where.end_time] 结束时间
|
||||
* @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回
|
||||
* @param {Array<number|string>} [data.where.store_ids] 货主ID列表
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async search(data = {}) {
|
||||
const { service } = this;
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
const {
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
by_space: bySpace,
|
||||
store_ids: storeIds,
|
||||
sort_field: whereSortField,
|
||||
sortField: whereSortFieldCamel,
|
||||
sort_order: whereSortOrder,
|
||||
sortOrder: whereSortOrderCamel,
|
||||
} = whereValue;
|
||||
|
||||
const { sort = {} } = data;
|
||||
const {
|
||||
sort_field: sortFieldSnake,
|
||||
sortField: sortFieldCamel,
|
||||
sort_order: sortOrderSnake,
|
||||
sortOrder: sortOrderCamel,
|
||||
} = sort || {};
|
||||
|
||||
const result = await service.systems.storage.report.search(startTime, endTime, bySpace, storeIds, {
|
||||
sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField,
|
||||
sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder,
|
||||
});
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交库存流水统计报表导出任务。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field)
|
||||
* @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order)
|
||||
* @param {string|Date} [data.where.start_time] 开始时间
|
||||
* @param {string|Date} [data.where.end_time] 结束时间
|
||||
* @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回
|
||||
* @param {Array<number|string>} [data.where.store_ids] 货主ID列表
|
||||
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
|
||||
*/
|
||||
async export(data = {}) {
|
||||
const { service } = this;
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
const {
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
by_space: bySpace,
|
||||
store_ids: storeIds,
|
||||
sort_field: whereSortField,
|
||||
sortField: whereSortFieldCamel,
|
||||
sort_order: whereSortOrder,
|
||||
sortOrder: whereSortOrderCamel,
|
||||
} = whereValue;
|
||||
|
||||
const { sort = {} } = data;
|
||||
const {
|
||||
sort_field: sortFieldSnake,
|
||||
sortField: sortFieldCamel,
|
||||
sort_order: sortOrderSnake,
|
||||
sortOrder: sortOrderCamel,
|
||||
} = sort || {};
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
const sortOption = {
|
||||
sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField,
|
||||
sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder,
|
||||
};
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption);
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询库存流水统计报表导出任务进度。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async exportTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cndUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成导出任务ID。
|
||||
* @return {string} 导出任务ID
|
||||
*/
|
||||
generateExportTaskId() {
|
||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `storage_report_export_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范导出任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {string} 归一化后的任务ID
|
||||
*/
|
||||
normalizeExportTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取导出任务缓存键。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${STORAGE_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @param {Object} payload 任务状态载荷
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
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,
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[storage.report.export] 写入导出任务缓存失败: %s', error && error.message ? error.message : error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {Promise<Object|null>} 任务缓存
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[storage.report.export] 读取导出任务缓存失败: %s', error && error.message ? error.message : error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StorageReportMethodService;
|
||||
@ -3,6 +3,27 @@
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class RolePermissionService extends Service {
|
||||
/**
|
||||
* 规范化权限类型过滤参数
|
||||
* @param {string|string[]|undefined|null} type 权限类型过滤值
|
||||
* @return {null|string|string[]} 可用于 where.type 的过滤值;null 表示不加过滤
|
||||
*/
|
||||
normalizeTypeFilter(type) {
|
||||
if (Array.isArray(type)) {
|
||||
const normalizedTypes = Array.from(new Set(type
|
||||
.map(item => (typeof item === 'string' ? item.trim() : ''))
|
||||
.filter(Boolean)));
|
||||
return normalizedTypes.length > 0 ? normalizedTypes : null;
|
||||
}
|
||||
|
||||
if (typeof type === 'string') {
|
||||
const normalizedType = type.trim();
|
||||
return normalizedType || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
normalizePermissionSet(rawValue) {
|
||||
if (rawValue === undefined || rawValue === null) {
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
@ -113,8 +134,13 @@ class RolePermissionService extends Service {
|
||||
status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1,
|
||||
};
|
||||
|
||||
if (options.type) {
|
||||
permissionWhere.type = options.type;
|
||||
const typeFilter = this.normalizeTypeFilter(options.type);
|
||||
if (Array.isArray(typeFilter) && typeFilter.length > 0) {
|
||||
permissionWhere.type = {
|
||||
[Op.in]: typeFilter,
|
||||
};
|
||||
} else if (typeFilter) {
|
||||
permissionWhere.type = typeFilter;
|
||||
}
|
||||
|
||||
if (allAccess) {
|
||||
|
||||
@ -16,6 +16,67 @@ const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:';
|
||||
const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60;
|
||||
|
||||
class UserService extends Service {
|
||||
/**
|
||||
* 根据平台解析菜单权限类型过滤条件
|
||||
* @param {string} platform 平台标识
|
||||
* @return {{ type: object }} 菜单权限类型过滤条件
|
||||
*/
|
||||
getMenuTypeWhereByPlatform(platform) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const normalizedPlatform = String(platform || '').trim().toLowerCase();
|
||||
const platformTypeStrategy = {
|
||||
web: {
|
||||
mode: 'prefix',
|
||||
values: [ 'web_' ],
|
||||
},
|
||||
pda: {
|
||||
mode: 'prefix',
|
||||
values: [ 'pda_' ],
|
||||
},
|
||||
miniprogram: {
|
||||
mode: 'prefix',
|
||||
values: [ 'miniprogram_' ],
|
||||
},
|
||||
workerstation: {
|
||||
mode: 'type',
|
||||
values: [ 'workerstation_pages' ],
|
||||
},
|
||||
workstation: {
|
||||
mode: 'type',
|
||||
values: [ 'workerstation_pages' ],
|
||||
},
|
||||
};
|
||||
|
||||
const strategy = platformTypeStrategy[normalizedPlatform];
|
||||
if (!strategy) {
|
||||
return {
|
||||
type: {
|
||||
[Op.like]: `${normalizedPlatform}_%`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (strategy.mode === 'prefix') {
|
||||
const likeConditions = strategy.values.map(prefix => ({ [Op.like]: `${prefix}%` }));
|
||||
if (likeConditions.length === 1) {
|
||||
return {
|
||||
type: likeConditions[0],
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: {
|
||||
[Op.or]: likeConditions,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: strategy.values.length === 1 ? strategy.values[0] : {
|
||||
[Op.in]: strategy.values,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
getCurrentAccountId() {
|
||||
const { ctx } = this;
|
||||
const rawUserId = ctx.userId || (ctx.user && ctx.user.id);
|
||||
@ -1987,7 +2048,7 @@ class UserService extends Service {
|
||||
[Op.in]: permissionIds,
|
||||
},
|
||||
status: 1,
|
||||
// 修正 like 查询
|
||||
// 页面权限(`*_pages`)仅用于菜单路由,不应出现在接口权限集合中,包含 workerstation_pages。
|
||||
type: {
|
||||
[ctx.app.Sequelize.Op.notLike]: '%_pages',
|
||||
},
|
||||
@ -2008,6 +2069,11 @@ class UserService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前员工菜单
|
||||
* @param {number} activeEmployeeId 员工ID
|
||||
* @return {Promise<Array>} 菜单路由列表
|
||||
*/
|
||||
async getMenus(activeEmployeeId) {
|
||||
const { ctx, app } = this;
|
||||
const { Sequelize } = app;
|
||||
@ -2053,17 +2119,15 @@ class UserService extends Service {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 3. 获取权限对应的菜单(根据设备筛选)
|
||||
// 3. 获取权限对应的菜单(根据平台权限类型策略筛选)
|
||||
const menuTypeWhere = this.getMenuTypeWhereByPlatform(ctx.header.platform);
|
||||
const permissions = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: permissionIds,
|
||||
},
|
||||
status: 1,
|
||||
// 修正 like 查询
|
||||
type: {
|
||||
[Op.like]: `${ctx.header.platform}_%`,
|
||||
},
|
||||
...menuTypeWhere,
|
||||
},
|
||||
order: [
|
||||
[ 'sort', 'ASC' ],
|
||||
|
||||
@ -453,7 +453,7 @@ async function markPendingExceptionInternal(service, orderModel, orderId, wareho
|
||||
};
|
||||
}
|
||||
|
||||
async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId) {
|
||||
async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow = null) {
|
||||
const stockStoreService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.stockStore;
|
||||
|
||||
if (!service.ctx.model || typeof service.ctx.model.transaction !== 'function') {
|
||||
@ -465,6 +465,21 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte
|
||||
}
|
||||
|
||||
await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulQimenSync', async transaction => {
|
||||
let resolvedOrderRow = orderRow;
|
||||
if (!resolvedOrderRow && orderModel && typeof orderModel.findOne === 'function') {
|
||||
resolvedOrderRow = await orderModel.findOne({
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'delivery_order_code', 'order_type' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
const outboundMetaOrderId = Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null;
|
||||
const outboundMetaOrderNo = String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null;
|
||||
const freshOrderItems = await orderItemsModel.findAll({
|
||||
where: {
|
||||
order_id: orderId,
|
||||
@ -481,7 +496,12 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte
|
||||
continue;
|
||||
}
|
||||
|
||||
const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction);
|
||||
const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null;
|
||||
const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, {
|
||||
orderId: outboundMetaOrderId,
|
||||
orderNo: outboundMetaOrderNo,
|
||||
orderItemId: outboundOrderItemId,
|
||||
});
|
||||
if (!outboundResult || outboundResult.success !== true) {
|
||||
throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim());
|
||||
}
|
||||
@ -530,7 +550,12 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod
|
||||
continue;
|
||||
}
|
||||
|
||||
const outboundResult = await service.ctx.service.systems.stockStore.outbound(itemId, quantity, transaction);
|
||||
const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null;
|
||||
const outboundResult = await service.ctx.service.systems.stockStore.outbound(itemId, quantity, transaction, {
|
||||
orderId: Number(orderRow && orderRow.id) || Number(orderId) || null,
|
||||
orderNo: String(orderRow && orderRow.delivery_order_code || '').trim() || null,
|
||||
orderItemId: outboundOrderItemId,
|
||||
});
|
||||
if (!outboundResult || outboundResult.success !== true) {
|
||||
throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim());
|
||||
}
|
||||
@ -895,7 +920,7 @@ async function processQmOrderInternal(service, orderModel, orderItemsModel, qime
|
||||
|
||||
if (isSuccess) {
|
||||
try {
|
||||
await finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId);
|
||||
await finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow);
|
||||
} catch (error) {
|
||||
await orderModel.update({
|
||||
sync_status: 'error',
|
||||
@ -1080,8 +1105,8 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) {
|
||||
* 订单异步同步路由服务。
|
||||
*/
|
||||
class OrderAsyncService extends MainService {
|
||||
async finalizeSuccessfulQimenSync(orderModel, orderItemsModel, orderId, warehouseId) {
|
||||
return await finalizeSuccessfulQimenSyncInternal(this, orderModel, orderItemsModel, orderId, warehouseId);
|
||||
async finalizeSuccessfulQimenSync(orderModel, orderItemsModel, orderId, warehouseId, orderRow = null) {
|
||||
return await finalizeSuccessfulQimenSyncInternal(this, orderModel, orderItemsModel, orderId, warehouseId, orderRow);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -6,25 +6,6 @@ const { Op } = require('sequelize');
|
||||
const OrderBaseService = require('../systemMethods/order/base');
|
||||
const PrinterDataBuilder = require('../../lib/printer_data_builder');
|
||||
|
||||
const SYS_PLATFORM_TO_PRINT_PLATFORM_MAP = Object.freeze({
|
||||
tb: 'cainiao',
|
||||
taobao: 'cainiao',
|
||||
cainiao: 'cainiao',
|
||||
cn: 'cainiao',
|
||||
jd: 'jd',
|
||||
jingdong: 'jd',
|
||||
dy: 'douyin',
|
||||
douyin: 'douyin',
|
||||
ks: 'kuaishou',
|
||||
kuaishou: 'kuaishou',
|
||||
pdd: 'pdd',
|
||||
pinduoduo: 'pdd',
|
||||
sph: 'sph',
|
||||
shipinhao: 'sph',
|
||||
xhs: 'xhs',
|
||||
xiaohongshu: 'xhs',
|
||||
});
|
||||
|
||||
class OrderPrintSystemService extends OrderBaseService {
|
||||
/**
|
||||
* 判断当前配置是否需要补查拣货明细。
|
||||
@ -388,6 +369,9 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
} = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows);
|
||||
const validWaveIdSet = new Set(validWaveIds);
|
||||
const validOrderRows = orderRows.filter(order => validWaveIdSet.has(Number(order && order.wave_id || 0)));
|
||||
const validOrderWaveIds = Array.from(new Set(validOrderRows
|
||||
.map(row => Number(row && row.wave_id || 0))
|
||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
|
||||
|
||||
if (validOrderRows.length === 0) {
|
||||
const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({
|
||||
@ -424,10 +408,12 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
return this.shouldLoadPickingDetails(policyConfig);
|
||||
});
|
||||
const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId);
|
||||
const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(orderIds, normalizedWarehouseId);
|
||||
const waveIdsForCount = Array.from(new Set(Array.from(waveOrderIndexMap.values())
|
||||
.map(item => Number(item && item.wave_id || 0))
|
||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
|
||||
const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(
|
||||
orderIds,
|
||||
normalizedWarehouseId,
|
||||
validOrderWaveIds
|
||||
);
|
||||
const waveIdsForCount = validOrderWaveIds;
|
||||
const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId);
|
||||
const templateSampleCache = new Map();
|
||||
const orderPrintList = [];
|
||||
@ -441,7 +427,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
const orderExpress = orderExpressMap.get(orderId) || {};
|
||||
const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow;
|
||||
const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {};
|
||||
const waveIdForCount = Number(waveOrderIndexInfo.wave_id || effectiveOrderRow.wave_id || 0);
|
||||
const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0);
|
||||
const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0);
|
||||
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
|
||||
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
|
||||
@ -604,6 +590,8 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
'sys_platform_name',
|
||||
'logistics_code',
|
||||
'logistics_name',
|
||||
'sys_logistics_code',
|
||||
'sys_logistics_name',
|
||||
'post_status',
|
||||
'status',
|
||||
'outbound_status',
|
||||
@ -681,13 +669,17 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
*
|
||||
* @param {Array<number>} orderIds 订单ID数组。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Array<number>} [waveIds] 可选波次ID数组,用于限制查询范围。
|
||||
* @return {Promise<Map<number, {wave_id:number, wave_index:number, platforms_index:number}>>} 订单顺序映射。
|
||||
*/
|
||||
async queryWaveOrderIndexMapByOrderIds(orderIds = [], warehouseId) {
|
||||
async queryWaveOrderIndexMapByOrderIds(orderIds = [], warehouseId, waveIds = []) {
|
||||
const resultMap = new Map();
|
||||
const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : [])
|
||||
.map(id => Number(id))
|
||||
.filter(id => Number.isInteger(id) && id > 0)));
|
||||
const normalizedWaveIds = Array.from(new Set((Array.isArray(waveIds) ? waveIds : [])
|
||||
.map(id => Number(id))
|
||||
.filter(id => Number.isInteger(id) && id > 0)));
|
||||
|
||||
if (normalizedOrderIds.length === 0) {
|
||||
return resultMap;
|
||||
@ -698,11 +690,15 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
const waveFilterSql = normalizedWaveIds.length > 0
|
||||
? ' AND wave_id IN (:waveIds)\n'
|
||||
: '';
|
||||
const querySql = `
|
||||
SELECT order_id, wave_id, wave_index, platforms_index
|
||||
FROM wms_order_wave_index
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND order_id IN (:orderIds)
|
||||
${waveFilterSql}
|
||||
`;
|
||||
|
||||
try {
|
||||
@ -710,6 +706,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
replacements: {
|
||||
warehouseId,
|
||||
orderIds: normalizedOrderIds,
|
||||
...(normalizedWaveIds.length > 0 ? { waveIds: normalizedWaveIds } : {}),
|
||||
},
|
||||
type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT,
|
||||
});
|
||||
@ -903,7 +900,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析订单平台编码并转换为打印平台别名。
|
||||
* 解析订单平台编码,保留原始平台值(仅去首尾空白)。
|
||||
*
|
||||
* @param {Object} orderRow 订单行。
|
||||
* @param {Object} orderExpress 快递行。
|
||||
@ -917,16 +914,12 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const normalizedCandidate = String(candidate || '').trim().toLowerCase();
|
||||
if (!normalizedCandidate) {
|
||||
const rawCandidate = String(candidate || '').trim();
|
||||
if (!rawCandidate) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const mappedPlatform = SYS_PLATFORM_TO_PRINT_PLATFORM_MAP[normalizedCandidate] || normalizedCandidate;
|
||||
const normalizedPlatform = PrinterDataBuilder.normalizePlatformAlias(mappedPlatform);
|
||||
if (normalizedPlatform.platform) {
|
||||
return normalizedPlatform.platform;
|
||||
}
|
||||
return rawCandidate;
|
||||
}
|
||||
|
||||
return '';
|
||||
@ -990,6 +983,10 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
const waveId = Number(orderRow.wave_id || 0);
|
||||
const requestId = `wave_${waveId}_order_${orderId}`;
|
||||
const waybillCode = String(orderExpress.waybill_code || '').trim();
|
||||
const orderSysLogisticsCode = String(orderRow.sys_logistics_code || '').trim();
|
||||
const orderSysLogisticsName = String(orderRow.sys_logistics_name || '').trim();
|
||||
const expressSysLogisticsCode = String(orderExpress.sys_logistics_code || '').trim();
|
||||
const expressSysLogisticsName = String(orderExpress.sys_logistics_name || '').trim();
|
||||
const documentId = waybillCode || `doc_${orderId}`;
|
||||
const printPayload = PrinterDataBuilder.buildPlatformRequestSkeleton({
|
||||
platform: platformCode,
|
||||
@ -1015,10 +1012,12 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(),
|
||||
store_id: Number(orderRow.store_id || 0),
|
||||
warehouse_id: Number(orderRow.warehouse_id || 0),
|
||||
platform: String(printPayload.platform || '').trim(),
|
||||
platform: platformCode,
|
||||
platform_name: printPayload.platform_meta && printPayload.platform_meta.name
|
||||
? String(printPayload.platform_meta.name).trim()
|
||||
: '',
|
||||
sys_logistics_code: orderSysLogisticsCode || expressSysLogisticsCode,
|
||||
sys_logistics_name: orderSysLogisticsName || expressSysLogisticsName,
|
||||
waybill_code: String(orderExpress.waybill_code || '').trim(),
|
||||
print_data: printData,
|
||||
};
|
||||
@ -1088,13 +1087,13 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将逐单打印中间态按波次分组,并在波次内按平台分组。
|
||||
* 将逐单打印中间态按波次分组,并在波次内按平台+系统快递分组。
|
||||
*
|
||||
* @param {Object} payload 聚合输入。
|
||||
* @param {Array<Object>} payload.waveRows 波次元数据列表。
|
||||
* @param {Array<number>} payload.hitWaveIds 命中的波次ID数组(已过滤)。
|
||||
* @param {Array<Object>} payload.orderPrintList 逐单打印中间态列表。
|
||||
* @return {Array<Object>} 波次平台分组结果。
|
||||
* @return {Array<Object>} 波次平台分组结果(platforms 为扁平平台+系统快递项)。
|
||||
*/
|
||||
groupOrderPrintItemsByWaveAndPlatform(payload = {}) {
|
||||
const {
|
||||
@ -1145,17 +1144,24 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
}
|
||||
|
||||
const platform = String(item && item.platform || '').trim() || 'unknown';
|
||||
const normalizedSysLogisticsCode = String(item && item.sys_logistics_code || '').trim();
|
||||
const normalizedSysLogisticsName = String(item && item.sys_logistics_name || '').trim();
|
||||
const normalizedSysLogisticsIdentity = normalizedSysLogisticsCode || normalizedSysLogisticsName || 'unknown';
|
||||
const platformSysKey = `${platform}@@${normalizedSysLogisticsIdentity}`;
|
||||
const platformMap = wavePlatformMap.get(waveId) || new Map();
|
||||
const platformGroup = platformMap.get(platform) || {
|
||||
const platformGroup = platformMap.get(platformSysKey) || {
|
||||
platform,
|
||||
platform_name: String(item && item.platform_name || '').trim(),
|
||||
sys_logistics_code: normalizedSysLogisticsCode || 'unknown',
|
||||
sys_logistics_name: normalizedSysLogisticsName || 'unknown',
|
||||
order_count: 0,
|
||||
orders: [],
|
||||
};
|
||||
|
||||
platformGroup.orders.push(this.isPlainObject(item && item.print_data) ? item.print_data : {});
|
||||
platformGroup.order_count = platformGroup.orders.length;
|
||||
platformMap.set(platform, platformGroup);
|
||||
|
||||
platformMap.set(platformSysKey, platformGroup);
|
||||
wavePlatformMap.set(waveId, platformMap);
|
||||
}
|
||||
|
||||
@ -1163,7 +1169,19 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
for (const waveGroup of waveGroups) {
|
||||
const platformMap = wavePlatformMap.get(Number(waveGroup.wave_id)) || new Map();
|
||||
const platforms = Array.from(platformMap.values());
|
||||
platforms.sort((a, b) => String(a.platform || '').localeCompare(String(b.platform || '')));
|
||||
platforms.sort((a, b) => {
|
||||
const platformCompare = String(a.platform || '').localeCompare(String(b.platform || ''));
|
||||
if (platformCompare !== 0) {
|
||||
return platformCompare;
|
||||
}
|
||||
|
||||
const sysCodeCompare = String(a.sys_logistics_code || '').localeCompare(String(b.sys_logistics_code || ''));
|
||||
if (sysCodeCompare !== 0) {
|
||||
return sysCodeCompare;
|
||||
}
|
||||
|
||||
return String(a.sys_logistics_name || '').localeCompare(String(b.sys_logistics_name || ''));
|
||||
});
|
||||
waveGroup.platforms = platforms;
|
||||
waveGroup.order_count = platforms.reduce((sum, platformGroup) => {
|
||||
return sum + Number(platformGroup && platformGroup.order_count || 0);
|
||||
|
||||
@ -71,13 +71,18 @@ class SettingPermissionService extends Service {
|
||||
return permission;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化并校验权限类型
|
||||
* @param {string} type 权限类型
|
||||
* @return {string} 规范化后的权限类型
|
||||
*/
|
||||
normalizePermissionType(type) {
|
||||
const normalized = typeof type === 'string' ? type.trim() : '';
|
||||
if (!normalized) {
|
||||
throw this.createError('type 参数不能为空', 400);
|
||||
}
|
||||
|
||||
const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block' ]);
|
||||
const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'workerstation_pages', 'block' ]);
|
||||
if (!allowedTypes.has(normalized)) {
|
||||
throw this.createError('type 参数不合法', 400);
|
||||
}
|
||||
|
||||
@ -827,17 +827,143 @@ class stockStoreService extends Service {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化出库元信息,兼容驼峰与下划线字段。
|
||||
*
|
||||
* @param {Object} meta 出库元信息。
|
||||
* @return {Object} 规范化后的订单上下文。
|
||||
*/
|
||||
normalizeOutboundMeta(meta = {}) {
|
||||
const normalized = meta && typeof meta === 'object' ? meta : {};
|
||||
const orderIdRaw = normalized.orderId
|
||||
?? normalized.order_id
|
||||
?? normalized.deliveryOrderId
|
||||
?? normalized.delivery_order_id
|
||||
?? normalized.id;
|
||||
const orderItemIdRaw = normalized.orderItemId ?? normalized.order_item_id;
|
||||
const sourceOrderCodesRaw = normalized.sourceOrderCodes ?? normalized.source_order_codes;
|
||||
const orderNoRaw = normalized.orderNo
|
||||
?? sourceOrderCodesRaw
|
||||
?? normalized.order_no
|
||||
?? normalized.deliveryOrderCode
|
||||
?? normalized.delivery_order_code;
|
||||
const orderId = Number(orderIdRaw);
|
||||
const orderItemId = Number(orderItemIdRaw);
|
||||
const orderNo = String(orderNoRaw || '').trim();
|
||||
const sourceOrderCodes = String(sourceOrderCodesRaw || '').trim();
|
||||
|
||||
return {
|
||||
orderId: Number.isFinite(orderId) && orderId > 0 ? orderId : null,
|
||||
orderItemId: Number.isFinite(orderItemId) && orderItemId > 0 ? orderItemId : null,
|
||||
orderNo: orderNo || null,
|
||||
sourceOrderCodes: sourceOrderCodes || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单明细对应的拣货分配记录。
|
||||
*
|
||||
* @param {number|null} orderId 订单 ID。
|
||||
* @param {number|null} orderItemId 订单明细 ID。
|
||||
* @param {Object|null} transaction 事务对象。
|
||||
* @return {Promise<Array<Object>>} 拣货分配列表。
|
||||
*/
|
||||
async getPickingRowsForOutbound(orderId, orderItemId, transaction) {
|
||||
const { ctx } = this;
|
||||
const pickingModel = ctx.model && ctx.model.Picking;
|
||||
|
||||
if (!pickingModel || typeof pickingModel.findAll !== 'function') {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!orderId || !orderItemId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await pickingModel.findAll({
|
||||
where: {
|
||||
order_id: orderId,
|
||||
order_item_id: orderItemId,
|
||||
},
|
||||
attributes: [ 'storage_id', 'space_id', 'quantity' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成出库流水写入明细,优先按拣货分配逐条记录。
|
||||
*
|
||||
* @param {Object} options 参数集合。
|
||||
* @param {number} options.outboundQty 本次出库总数量。
|
||||
* @param {Array<Object>} options.pickingRows 拣货分配记录。
|
||||
* @param {Object} options.basePayload 流水公共字段。
|
||||
* @return {Array<Object>} 待写入的出库流水列表。
|
||||
*/
|
||||
buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload }) {
|
||||
const payloads = [];
|
||||
const normalizedRows = Array.isArray(pickingRows) ? pickingRows : [];
|
||||
let consumedQty = 0;
|
||||
|
||||
for (const pickingRow of normalizedRows) {
|
||||
const remainingQty = outboundQty - consumedQty;
|
||||
if (remainingQty <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
const pickingQty = Number(pickingRow && pickingRow.quantity) || 0;
|
||||
if (pickingQty <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const transactionQty = Math.min(pickingQty, remainingQty);
|
||||
payloads.push({
|
||||
...basePayload,
|
||||
storage_id: pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null,
|
||||
space_id: pickingRow && pickingRow.space_id ? Number(pickingRow.space_id) : null,
|
||||
quantity: transactionQty,
|
||||
});
|
||||
consumedQty += transactionQty;
|
||||
}
|
||||
|
||||
if (payloads.length === 0) {
|
||||
return [{
|
||||
...basePayload,
|
||||
storage_id: null,
|
||||
space_id: null,
|
||||
quantity: outboundQty,
|
||||
}];
|
||||
}
|
||||
|
||||
if (consumedQty < outboundQty) {
|
||||
payloads.push({
|
||||
...basePayload,
|
||||
storage_id: null,
|
||||
space_id: null,
|
||||
quantity: outboundQty - consumedQty,
|
||||
});
|
||||
}
|
||||
|
||||
return payloads;
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品出库服务
|
||||
* @param {number} itemId 商品ID (StockStore.id)
|
||||
* @param {number} quantity 出库数量(正数)
|
||||
* @param {Object} transaction 数据库事务
|
||||
* @param {Object} meta 出库元信息(订单、明细等)
|
||||
*/
|
||||
async outbound(itemId, quantity, transaction) {
|
||||
async outbound(itemId, quantity, transaction, meta = {}) {
|
||||
const {
|
||||
ctx,
|
||||
app,
|
||||
} = this;
|
||||
const outboundMeta = this.normalizeOutboundMeta(meta);
|
||||
|
||||
// 1. 参数验证
|
||||
const outboundQty = parseInt(quantity);
|
||||
@ -946,33 +1072,50 @@ class stockStoreService extends Service {
|
||||
const afterQuantity = Number(updatedRecord.quantity) || 0;
|
||||
const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0;
|
||||
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
let pickingRows = [];
|
||||
if (outboundMeta.orderId && outboundMeta.orderItemId) {
|
||||
try {
|
||||
pickingRows = await this.getPickingRowsForOutbound(outboundMeta.orderId, outboundMeta.orderItemId, currentTransaction);
|
||||
} catch (error) {
|
||||
app.logger.warn(`[outbound] 读取拣货分配失败,降级为单条出库流水: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const baseTransactionPayload = {
|
||||
transaction_type: 'OUTBOUND',
|
||||
warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id,
|
||||
store_id: ctx.user.store_id,
|
||||
store_id: storage.storeId || updatedRecord.store_id || ctx.user.store_id,
|
||||
stock_id: storage.id,
|
||||
storage_id: null,
|
||||
space_id: null,
|
||||
quantity: outboundQty,
|
||||
batch_no: null,
|
||||
inventory_type: 'ZP',
|
||||
order_type: 'STOCK_STORE_OUTBOUND',
|
||||
order_no: null,
|
||||
order_id: null,
|
||||
order_no: outboundMeta.orderNo,
|
||||
order_id: outboundMeta.orderId,
|
||||
source_order_codes: outboundMeta.sourceOrderCodes,
|
||||
receiving_id: null,
|
||||
entry_order_id: null,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
operator_name: ctx.user?.employees_name || '',
|
||||
remark: '商品出库',
|
||||
remark: '订单出库',
|
||||
before_quantity: beforeQuantity,
|
||||
after_quantity: afterQuantity,
|
||||
before_locked_quantity: beforeLockedQuantity,
|
||||
after_locked_quantity: afterLockedQuantity,
|
||||
created_at: new Date(),
|
||||
}, {
|
||||
transaction: currentTransaction,
|
||||
};
|
||||
|
||||
const transactionPayloads = this.buildOutboundTransactionPayloads({
|
||||
outboundQty,
|
||||
pickingRows,
|
||||
basePayload: baseTransactionPayload,
|
||||
});
|
||||
|
||||
for (const payload of transactionPayloads) {
|
||||
await ctx.service.systems.stockTransaction.create(payload, {
|
||||
transaction: currentTransaction,
|
||||
});
|
||||
}
|
||||
|
||||
app.logger.info('[出库] 成功', {
|
||||
itemId,
|
||||
stockId: storage.id,
|
||||
|
||||
@ -4,6 +4,115 @@ const Service = require('egg').Service;
|
||||
|
||||
class StockTransactionService extends Service {
|
||||
|
||||
/**
|
||||
* 规范化入库流水的单据字段。
|
||||
*
|
||||
* 约束:
|
||||
* 1) transaction_type=INBOUND 时,order_id 必须写 null;
|
||||
* 2) 其他类型保持上游值不变。
|
||||
*
|
||||
* @param {Object} data 流水数据。
|
||||
* @param {number|null|undefined} orderId 候选单据ID。
|
||||
* @return {number|null} 规范化后的单据ID。
|
||||
*/
|
||||
normalizeInboundOrderId(data = {}, orderId) {
|
||||
if (data.transaction_type === 'INBOUND') {
|
||||
return null;
|
||||
}
|
||||
return orderId ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前流水是否属于订单出库链路。
|
||||
*
|
||||
* 说明:
|
||||
* 1) 仅 OUTBOUND 才可能是订单出库;
|
||||
* 2) 允许上游传入多种 order_type,只要具备订单出库特征均视为订单出库;
|
||||
* 3) 订单ID合法性由 resolveOutboundOrderReference 统一校验。
|
||||
*
|
||||
* @param {Object} data 流水数据。
|
||||
* @return {boolean} 是否为订单出库流水。
|
||||
*/
|
||||
isOrderOutboundTransaction(data = {}) {
|
||||
if (data.transaction_type !== 'OUTBOUND') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalizedOrderType = String(data.order_type || '').trim();
|
||||
const sourceOrderCodes = String(data.source_order_codes || '').trim();
|
||||
const remark = String(data.remark || '').trim();
|
||||
|
||||
return Boolean(
|
||||
sourceOrderCodes
|
||||
|| normalizedOrderType === 'STOCK_STORE_OUTBOUND'
|
||||
|| normalizedOrderType === 'ORDER'
|
||||
|| remark === '订单出库'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化订单出库流水的单据字段。
|
||||
*
|
||||
* 约束:
|
||||
* 1) order_id 必须是订单主键 ID;
|
||||
* 2) order_no 必须写订单 source_order_codes。
|
||||
* 3) batch_no 必须以订单 wave_no 为准(无 wave_no 时写 null)。
|
||||
*
|
||||
* @param {Object} data 流水数据。
|
||||
* @param {Object} options 写入选项。
|
||||
* @return {Promise<{orderId: number|null, orderNo: string|null, batchNo: string|null}>} 规范化后的单据字段。
|
||||
*/
|
||||
async resolveOutboundOrderReference(data = {}, options = {}) {
|
||||
const { ctx } = this;
|
||||
const isOrderOutbound = this.isOrderOutboundTransaction(data);
|
||||
|
||||
if (!isOrderOutbound) {
|
||||
return {
|
||||
orderId: data.order_id ?? null,
|
||||
orderNo: data.order_no ?? null,
|
||||
batchNo: data.batch_no ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
const orderId = Number(data.order_id);
|
||||
if (!Number.isFinite(orderId) || orderId <= 0) {
|
||||
throw new Error('订单出库流水 order_id 必须为订单主键 id');
|
||||
}
|
||||
|
||||
let sourceOrderCodes = String(data.source_order_codes || '').trim();
|
||||
let waveNo = null;
|
||||
|
||||
const orderDeliveryModel = ctx.model && ctx.model.OrderDelivery;
|
||||
if (orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') {
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: {
|
||||
id: orderId,
|
||||
},
|
||||
attributes: [ 'id', 'source_order_codes', 'wave_no' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
if (orderRow) {
|
||||
if (!sourceOrderCodes) {
|
||||
sourceOrderCodes = String(orderRow.source_order_codes || '').trim();
|
||||
}
|
||||
const normalizedWaveNo = String(orderRow.wave_no || '').trim();
|
||||
waveNo = normalizedWaveNo || null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!sourceOrderCodes) {
|
||||
throw new Error(`订单出库流水 order_no 必须使用 source_order_codes,订单ID: ${orderId}`);
|
||||
}
|
||||
|
||||
return {
|
||||
orderId,
|
||||
orderNo: sourceOrderCodes,
|
||||
batchNo: waveNo,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一写入库存流水记录。
|
||||
*
|
||||
@ -37,6 +146,10 @@ class StockTransactionService extends Service {
|
||||
async create(data = {}, options = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
if (!options.transaction) {
|
||||
throw new Error('stockTransaction.create 缺少 transaction,库存流水写入必须在事务中执行');
|
||||
}
|
||||
|
||||
const quantity = Number(data.quantity);
|
||||
if (!data.transaction_type) {
|
||||
throw new Error('transaction_type 必填');
|
||||
@ -54,6 +167,13 @@ class StockTransactionService extends Service {
|
||||
throw new Error('quantity 必须为正数');
|
||||
}
|
||||
|
||||
const isOrderOutbound = this.isOrderOutboundTransaction(data);
|
||||
const normalizedOrderReference = await this.resolveOutboundOrderReference(data, options);
|
||||
const normalizedOrderType = isOrderOutbound ? 'ORDER' : (data.order_type ?? null);
|
||||
const normalizedBatchNo = isOrderOutbound ? normalizedOrderReference.batchNo : (data.batch_no ?? null);
|
||||
|
||||
const normalizedOrderId = this.normalizeInboundOrderId(data, normalizedOrderReference.orderId);
|
||||
|
||||
const payload = {
|
||||
transaction_type: data.transaction_type,
|
||||
warehouse_id: data.warehouse_id,
|
||||
@ -62,11 +182,11 @@ class StockTransactionService extends Service {
|
||||
storage_id: data.storage_id ?? null,
|
||||
space_id: data.space_id ?? null,
|
||||
quantity,
|
||||
batch_no: data.batch_no ?? null,
|
||||
batch_no: normalizedBatchNo,
|
||||
inventory_type: data.inventory_type || 'ZP',
|
||||
order_type: data.order_type ?? null,
|
||||
order_no: data.order_no ?? null,
|
||||
order_id: data.order_id ?? null,
|
||||
order_type: normalizedOrderType,
|
||||
order_no: normalizedOrderReference.orderNo,
|
||||
order_id: normalizedOrderId,
|
||||
receiving_id: data.receiving_id ?? null,
|
||||
entry_order_id: data.entry_order_id ?? null,
|
||||
operator_id: data.operator_id ?? null,
|
||||
|
||||
@ -563,7 +563,7 @@ class InventoryService extends Service {
|
||||
inventory_type: inventoryType,
|
||||
order_type: 'SCRK',
|
||||
order_no: entryOrderCode,
|
||||
order_id: entryOrder.id,
|
||||
order_id: null,
|
||||
receiving_id: receivingId,
|
||||
entry_order_id: entryOrder.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
@ -946,7 +946,7 @@ class InventoryService extends Service {
|
||||
inventory_type: inventoryType,
|
||||
order_type: 'MATCH',
|
||||
order_no: firstEntryOrder.entry_order_code,
|
||||
order_id: firstEntryOrder.id,
|
||||
order_id: null,
|
||||
receiving_id: firstRcv.id,
|
||||
entry_order_id: firstEntryOrder.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
@ -1185,6 +1185,82 @@ class InventoryService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入移库双向库存流水(移库出/移库入)。
|
||||
*
|
||||
* 说明:
|
||||
* 1) before/after 与锁定字段均写同值快照,避免被识别为普通出入库数量变化;
|
||||
* 2) 仅记录移库行为本身,不绑定订单字段。
|
||||
*
|
||||
* @param {Object} data 入参
|
||||
* @param {Object} data.transaction 数据库事务
|
||||
* @param {Object} data.srcRecord 源库存记录
|
||||
* @param {number} data.transferQuantity 移库数量
|
||||
* @param {number} data.sourceSpaceId 源库位ID
|
||||
* @param {number} data.targetSpaceId 目标库位ID
|
||||
* @param {number|null} data.targetStorageId 目标库存记录ID
|
||||
* @param {number} data.totalSnapshotQuantity stock_id 总库存快照数量
|
||||
* @param {number} data.totalSnapshotLockedQuantity stock_id 总锁定快照数量
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async createTransferStockTransactions(data = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
const operatorId = ctx.user?.employees_id || ctx.user?.id || null;
|
||||
const operatorName = ctx.user?.employees_name || '';
|
||||
|
||||
const totalSnapshotQuantity = Number(data.totalSnapshotQuantity) || 0;
|
||||
const totalSnapshotLockedQuantity = Number(data.totalSnapshotLockedQuantity) || 0;
|
||||
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
transaction_type: 'TRANSFER_OUT',
|
||||
warehouse_id: data.srcRecord.warehouse_id,
|
||||
store_id: data.srcRecord.store_id,
|
||||
stock_id: data.srcRecord.stock_id,
|
||||
storage_id: data.srcRecord.id,
|
||||
space_id: data.sourceSpaceId,
|
||||
quantity: data.transferQuantity,
|
||||
batch_no: data.srcRecord.batch_no,
|
||||
inventory_type: data.srcRecord.inventory_type,
|
||||
order_type: null,
|
||||
order_no: null,
|
||||
order_id: null,
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorName,
|
||||
remark: '移库出',
|
||||
before_quantity: totalSnapshotQuantity,
|
||||
after_quantity: totalSnapshotQuantity,
|
||||
before_locked_quantity: totalSnapshotLockedQuantity,
|
||||
after_locked_quantity: totalSnapshotLockedQuantity,
|
||||
}, {
|
||||
transaction: data.transaction,
|
||||
});
|
||||
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
transaction_type: 'TRANSFER_IN',
|
||||
warehouse_id: data.srcRecord.warehouse_id,
|
||||
store_id: data.srcRecord.store_id,
|
||||
stock_id: data.srcRecord.stock_id,
|
||||
storage_id: data.targetStorageId,
|
||||
space_id: data.targetSpaceId,
|
||||
quantity: data.transferQuantity,
|
||||
batch_no: data.srcRecord.batch_no,
|
||||
inventory_type: data.srcRecord.inventory_type,
|
||||
order_type: null,
|
||||
order_no: null,
|
||||
order_id: null,
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorName,
|
||||
remark: '移库入',
|
||||
before_quantity: totalSnapshotQuantity,
|
||||
after_quantity: totalSnapshotQuantity,
|
||||
before_locked_quantity: totalSnapshotLockedQuantity,
|
||||
after_locked_quantity: totalSnapshotLockedQuantity,
|
||||
}, {
|
||||
transaction: data.transaction,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 移库(库位转移):将单条库存从一个库位移动到另一个库位。
|
||||
* 支持部分/全量移库、目标库位合并。
|
||||
@ -1239,6 +1315,17 @@ class InventoryService extends Service {
|
||||
|
||||
const warehouseId = srcRecord.warehouse_id;
|
||||
|
||||
const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({
|
||||
where: { id: srcRecord.stock_id },
|
||||
attributes: [ 'id', 'quantity', 'locked_quantity' ],
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
if (!stockWarehouseSnapshot) {
|
||||
await transaction.rollback();
|
||||
return { code: 404, message: `商品SKU不存在: stock_id=${srcRecord.stock_id}`, data: null };
|
||||
}
|
||||
|
||||
// ────────── 4. 校验目标库位 ──────────
|
||||
const targetSpace = await ctx.model.LocationSpace.findOne({
|
||||
where: {
|
||||
@ -1322,6 +1409,7 @@ class InventoryService extends Service {
|
||||
});
|
||||
|
||||
let afterSnapshot;
|
||||
let targetStorageId = null;
|
||||
// 原库位统计变化
|
||||
const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 };
|
||||
// 目标库位统计变化
|
||||
@ -1380,6 +1468,7 @@ class InventoryService extends Service {
|
||||
tgtSpaceDelta.qtyDelta += transferQty;
|
||||
// 目标库位该 SKU 之前已有记录,skuDelta 不变
|
||||
|
||||
targetStorageId = existingTarget.id;
|
||||
afterSnapshot = {
|
||||
merged_into: existingTarget.id,
|
||||
target_space_id: targetSpaceId,
|
||||
@ -1428,6 +1517,7 @@ class InventoryService extends Service {
|
||||
}
|
||||
tgtSpaceDelta.qtyDelta += srcRecord.quantity;
|
||||
|
||||
targetStorageId = storageId;
|
||||
afterSnapshot = {
|
||||
storage_id: storageId,
|
||||
target_space_id: targetSpaceId,
|
||||
@ -1487,6 +1577,7 @@ class InventoryService extends Service {
|
||||
}
|
||||
tgtSpaceDelta.qtyDelta += transferQty;
|
||||
|
||||
targetStorageId = newRecord.id;
|
||||
afterSnapshot = {
|
||||
new_storage_id: newRecord.id,
|
||||
target_space_id: targetSpaceId,
|
||||
@ -1495,6 +1586,17 @@ class InventoryService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
await this.createTransferStockTransactions({
|
||||
transaction,
|
||||
srcRecord,
|
||||
transferQuantity: transferQty,
|
||||
sourceSpaceId: srcRecord.space_id,
|
||||
targetSpaceId,
|
||||
targetStorageId,
|
||||
totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0,
|
||||
totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0,
|
||||
});
|
||||
|
||||
// ────────── 记录操作日志(事务内) ──────────
|
||||
try {
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
@ -1697,6 +1799,17 @@ class InventoryService extends Service {
|
||||
|
||||
const warehouseId = srcRecords[0].warehouse_id;
|
||||
|
||||
const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({
|
||||
where: { id: stockId },
|
||||
attributes: [ 'id', 'quantity', 'locked_quantity' ],
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
if (!stockWarehouseSnapshot) {
|
||||
await transaction.rollback();
|
||||
return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null };
|
||||
}
|
||||
|
||||
// ────────── 6. 校验目标库位 ──────────
|
||||
const targetSpace = await ctx.model.LocationSpace.findOne({
|
||||
where: {
|
||||
@ -1750,6 +1863,7 @@ class InventoryService extends Service {
|
||||
|
||||
affectedCount++;
|
||||
const isFullTransfer = (toTransfer === srcRecord.quantity);
|
||||
let targetStorageId = null;
|
||||
|
||||
// ── 在目标库位查找同 stock_id + batch_no + inventory_type 的记录 ──
|
||||
const existingTarget = await ctx.model.Storage.findOne({
|
||||
@ -1798,6 +1912,8 @@ class InventoryService extends Service {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
targetStorageId = existingTarget.id;
|
||||
} else if (isFullTransfer) {
|
||||
// 全量移库 & 目标无同规格记录:直接改 space_id
|
||||
await ctx.model.Storage.update({
|
||||
@ -1807,6 +1923,8 @@ class InventoryService extends Service {
|
||||
where: { id: srcRecord.id },
|
||||
transaction,
|
||||
});
|
||||
|
||||
targetStorageId = srcRecord.id;
|
||||
} else {
|
||||
// 部分移库 & 目标无同规格记录:减少原记录,新建目标记录
|
||||
await ctx.model.Storage.update({
|
||||
@ -1818,7 +1936,7 @@ class InventoryService extends Service {
|
||||
transaction,
|
||||
});
|
||||
|
||||
await ctx.model.Storage.create({
|
||||
const newRecord = await ctx.model.Storage.create({
|
||||
warehouse_id: srcRecord.warehouse_id,
|
||||
store_id: srcRecord.store_id,
|
||||
space_id: targetSpaceId,
|
||||
@ -1840,8 +1958,21 @@ class InventoryService extends Service {
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}, { transaction });
|
||||
|
||||
targetStorageId = newRecord.id;
|
||||
}
|
||||
|
||||
await this.createTransferStockTransactions({
|
||||
transaction,
|
||||
srcRecord,
|
||||
transferQuantity: toTransfer,
|
||||
sourceSpaceId: srcRecord.space_id,
|
||||
targetSpaceId,
|
||||
targetStorageId,
|
||||
totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0,
|
||||
totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0,
|
||||
});
|
||||
|
||||
srcSpaceDelta.qtyDelta -= toTransfer;
|
||||
tgtSpaceDelta.qtyDelta += toTransfer;
|
||||
remainingQty -= toTransfer;
|
||||
|
||||
1232
app/service/systems/storage/report.js
Normal file
1232
app/service/systems/storage/report.js
Normal file
File diff suppressed because it is too large
Load Diff
@ -5,7 +5,7 @@ module.exports = {
|
||||
* 为打印台电脑表新增上次登录时间字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @returns {Promise<void>} 无返回值
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_print_computer', 'last_login_time', {
|
||||
@ -19,7 +19,7 @@ module.exports = {
|
||||
* 回滚删除打印台电脑表的上次登录时间字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @returns {Promise<void>} 无返回值
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('wms_print_computer', 'last_login_time');
|
||||
|
||||
@ -5,7 +5,7 @@ module.exports = {
|
||||
* 创建订单波次顺序副表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @returns {Promise<void>} 无返回值
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable('wms_order_wave_index', {
|
||||
@ -78,7 +78,7 @@ module.exports = {
|
||||
* 回滚删除订单波次顺序副表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @returns {Promise<void>} 无返回值
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable('wms_order_wave_index');
|
||||
|
||||
@ -5,7 +5,7 @@ module.exports = {
|
||||
* 为打印台表新增主体配置字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @returns {Promise<void>} 无返回值
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tableDefinition = await queryInterface.describeTable('wms_print_stations');
|
||||
@ -24,7 +24,7 @@ module.exports = {
|
||||
* 回滚删除打印台表主体配置字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @returns {Promise<void>} 无返回值
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tableDefinition = await queryInterface.describeTable('wms_print_stations');
|
||||
|
||||
@ -5,7 +5,7 @@ module.exports = {
|
||||
* 删除已弃用的打印台快递关联表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @returns {Promise<void>} 无返回值
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
@ -17,7 +17,7 @@ module.exports = {
|
||||
* 回滚重建打印台快递关联表(核心字段与唯一索引)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @returns {Promise<void>} 无返回值
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable('wms_print_station_express', {
|
||||
|
||||
@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 扩展权限类型枚举,新增 workerstation_pages。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.changeColumn('wms_permission', 'type', {
|
||||
type: Sequelize.ENUM(
|
||||
'web_pages',
|
||||
'pda_pages',
|
||||
'btns',
|
||||
'api',
|
||||
'miniprogram_pages',
|
||||
'block',
|
||||
'workerstation_pages'
|
||||
),
|
||||
allowNull: false,
|
||||
defaultValue: 'web_pages',
|
||||
comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块,workerstation_pages:工作台菜单)',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚权限类型枚举,先将 workerstation_pages 转换为 web_pages。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
"UPDATE `wms_permission` SET `type` = 'web_pages' WHERE `type` = 'workerstation_pages'"
|
||||
);
|
||||
|
||||
await queryInterface.changeColumn('wms_permission', 'type', {
|
||||
type: Sequelize.ENUM(
|
||||
'web_pages',
|
||||
'pda_pages',
|
||||
'btns',
|
||||
'api',
|
||||
'miniprogram_pages',
|
||||
'block'
|
||||
),
|
||||
allowNull: false,
|
||||
defaultValue: 'web_pages',
|
||||
comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块)',
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为 wms_platform 新增 component 字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 component 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tableName = 'wms_platform';
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
|
||||
if (columns.component) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(tableName, 'component', {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '打印组件标识',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:删除 component 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tableName = 'wms_platform';
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
|
||||
if (!columns.component) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, 'component');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 调整 wms_stock_transaction 的单据号字段类型并扩展出入库类型枚举。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:
|
||||
* 1. order_no 由 STRING(100) 调整为 TEXT;
|
||||
* 2. transaction_type 增加 TRANSFER_OUT、TRANSFER_IN 枚举值。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.changeColumn('wms_stock_transaction', 'order_no', {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '关联单据号',
|
||||
});
|
||||
|
||||
await queryInterface.changeColumn('wms_stock_transaction', 'transaction_type', {
|
||||
type: Sequelize.ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'),
|
||||
allowNull: false,
|
||||
comment: '出入库类型(含移库)',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:
|
||||
* 1. 先将移库枚举值映射回原有枚举,避免收缩 ENUM 失败;
|
||||
* 2. transaction_type 回退为仅 INBOUND、OUTBOUND;
|
||||
* 3. order_no 回退为 STRING(100)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
"UPDATE wms_stock_transaction SET transaction_type = 'OUTBOUND' WHERE transaction_type = 'TRANSFER_OUT'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"UPDATE wms_stock_transaction SET transaction_type = 'INBOUND' WHERE transaction_type = 'TRANSFER_IN'"
|
||||
);
|
||||
|
||||
await queryInterface.changeColumn('wms_stock_transaction', 'transaction_type', {
|
||||
type: Sequelize.ENUM('INBOUND', 'OUTBOUND'),
|
||||
allowNull: false,
|
||||
comment: '出入库类型',
|
||||
});
|
||||
|
||||
await queryInterface.changeColumn('wms_stock_transaction', 'order_no', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '关联单据号',
|
||||
});
|
||||
},
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
1324
methods/system.json
1324
methods/system.json
File diff suppressed because it is too large
Load Diff
@ -7,8 +7,9 @@
|
||||
|
||||
"taskID": "001778509772549",
|
||||
"printer": "打印机",
|
||||
"preview": {},
|
||||
|
||||
"preview": false,
|
||||
"firstDocumentNumber": 1,
|
||||
"totalDocumentCount": 1,
|
||||
"documents": [
|
||||
|
||||
|
||||
|
||||
@ -1,141 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
getAuthToken,
|
||||
invokeSystemMethod,
|
||||
} = require('../../support/system_method_client');
|
||||
|
||||
const EXTRA_HEADERS = {
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
};
|
||||
|
||||
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
|
||||
|
||||
async function switchToWarehouseRole(token) {
|
||||
let currentToken = token;
|
||||
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(infoRes.status, 200);
|
||||
assert.equal(infoRes.body.flag, 'success');
|
||||
assert.equal(infoRes.body.code, 200);
|
||||
|
||||
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
|
||||
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
|
||||
const candidateRoleIds = [ ...new Set([
|
||||
...warehouseRoles.map(item => Number(item.id)),
|
||||
...FALLBACK_ROLE_IDS,
|
||||
].filter(Boolean)) ];
|
||||
|
||||
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
|
||||
|
||||
for (const roleId of candidateRoleIds) {
|
||||
const changeRes = await invokeSystemMethod('user.changeRole', {
|
||||
roleId,
|
||||
}, currentToken, EXTRA_HEADERS);
|
||||
|
||||
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
|
||||
continue;
|
||||
}
|
||||
|
||||
currentToken = changeRes.body?.data?.token || currentToken;
|
||||
|
||||
const listRes = await invokeSystemMethod('storage.inventory.list', {
|
||||
pagination: { page: 1, pageSize: 1 },
|
||||
where: {},
|
||||
}, currentToken, EXTRA_HEADERS);
|
||||
|
||||
if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) {
|
||||
return {
|
||||
token: currentToken,
|
||||
roleId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('未找到可访问库存列表的仓库角色');
|
||||
}
|
||||
|
||||
describe('test/app/controller/system.storage.inventory.list.test.js', () => {
|
||||
let warehouseToken;
|
||||
|
||||
before(async function() {
|
||||
const { token } = await getAuthToken();
|
||||
|
||||
try {
|
||||
const switched = await switchToWarehouseRole(token);
|
||||
warehouseToken = switched.token;
|
||||
} catch (error) {
|
||||
this.skip();
|
||||
}
|
||||
});
|
||||
|
||||
it('should return merged inventory list by default', async () => {
|
||||
const res = await invokeSystemMethod('storage.inventory.list', {
|
||||
pagination: { page: 1, pageSize: 200 },
|
||||
where: {},
|
||||
}, warehouseToken, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
|
||||
const data = res.body.data;
|
||||
assert.ok(data, '响应缺少 data');
|
||||
assert.ok(Array.isArray(data.list), 'list 应为数组');
|
||||
assert.ok(data.pagination, '缺少 pagination');
|
||||
|
||||
const hasMergedRow = data.list.some(row => row && row.batch_count !== undefined);
|
||||
assert.ok(hasMergedRow, '默认模式应返回聚合后的库存记录');
|
||||
|
||||
const firstRow = data.list[0];
|
||||
assert.ok(firstRow?.stock, '默认模式应包含 stock 子对象');
|
||||
assert.ok(Array.isArray(firstRow.stock.barcodes), 'stock.barcodes 应为数组');
|
||||
assert.ok(Array.isArray(firstRow.stock.images), 'stock.images 应为数组');
|
||||
});
|
||||
|
||||
it('should return batch-level inventory records when group_by_batch=true', async () => {
|
||||
const mergedRes = await invokeSystemMethod('storage.inventory.list', {
|
||||
pagination: { page: 1, pageSize: 200 },
|
||||
where: {},
|
||||
}, warehouseToken, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(mergedRes.status, 200);
|
||||
assert.equal(mergedRes.body.flag, 'success');
|
||||
assert.equal(mergedRes.body.code, 200);
|
||||
|
||||
const mergedList = mergedRes.body.data.list;
|
||||
|
||||
const detailRes = await invokeSystemMethod('storage.inventory.list', {
|
||||
pagination: { page: 1, pageSize: 200 },
|
||||
group_by_batch: true,
|
||||
where: {},
|
||||
}, warehouseToken, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(detailRes.status, 200);
|
||||
assert.equal(detailRes.body.flag, 'success');
|
||||
assert.equal(detailRes.body.code, 200);
|
||||
|
||||
const detailList = detailRes.body.data.list;
|
||||
assert.ok(Array.isArray(detailList), 'group_by_batch=true 时 list 应为数组');
|
||||
assert.ok(detailList.length >= mergedList.length, 'group_by_batch=true 时记录数不应少于合并模式');
|
||||
|
||||
for (const row of detailList) {
|
||||
assert.ok('id' in row, '明细模式应包含 id');
|
||||
assert.ok('batch_no' in row, '明细模式应包含 batch_no');
|
||||
assert.ok('production_date' in row, '明细模式应包含 production_date');
|
||||
assert.ok('expiry_date' in row, '明细模式应包含 expiry_date');
|
||||
assert.ok('expiry_remaining_days' in row, '明细模式应包含 expiry_remaining_days');
|
||||
assert.ok('inventory_warning_level' in row, '明细模式应包含 inventory_warning_level');
|
||||
assert.ok('inventory_warning_color' in row, '明细模式应包含 inventory_warning_color');
|
||||
assert.ok('inventory_warning_range' in row, '明细模式应包含 inventory_warning_range');
|
||||
assert.ok('inventory_warning_tip_text' in row, '明细模式应包含 inventory_warning_tip_text');
|
||||
assert.ok('inbound_time' in row, '明细模式应包含 inbound_time');
|
||||
assert.ok('inbound_order_no' in row, '明细模式应包含 inbound_order_no');
|
||||
assert.ok('supplier_batch_no' in row, '明细模式应包含 supplier_batch_no');
|
||||
assert.ok(Array.isArray(row.stock?.barcodes), 'stock.barcodes 应为数组');
|
||||
assert.ok(Array.isArray(row.stock?.images), 'stock.images 应为数组');
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -4,7 +4,7 @@ const assert = require('node:assert/strict');
|
||||
|
||||
/**
|
||||
* 构造 print_stations 模型测试所需的最小 Sequelize 类型集合。
|
||||
* @returns {Object} Sequelize 类型集合。
|
||||
* @return {Object} Sequelize 类型集合。
|
||||
*/
|
||||
function createSequelizeTypes() {
|
||||
const makeType = sql => ({
|
||||
@ -30,7 +30,7 @@ function createSequelizeTypes() {
|
||||
|
||||
/**
|
||||
* 构造加载 print_stations 模型所需的最小应用对象。
|
||||
* @returns {Object} 应用对象。
|
||||
* @return {Object} 应用对象。
|
||||
*/
|
||||
function createApp() {
|
||||
return {
|
||||
|
||||
@ -0,0 +1,242 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const { Op } = require('sequelize');
|
||||
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
|
||||
|
||||
/**
|
||||
* 创建自动加团相关测试上下文。
|
||||
*
|
||||
* @param {Object} options 初始化选项。
|
||||
* @param {Array<Object>} options.orders 订单初始数据。
|
||||
* @param {Array<Object>} options.waves 波次初始数据。
|
||||
* @param {number} [options.storeId=100000] 仓库ID。
|
||||
* @param {number} [options.maxWaveQuantity=500] 最大波次订单数。
|
||||
* @return {{ service: WaveService, txState: Object, waves: Array<Object> }} 测试上下文。
|
||||
*/
|
||||
function createHarness({ orders = [], waves = [], storeId = 100000, maxWaveQuantity = 500 } = {}) {
|
||||
const orderStore = orders.map(row => ({ ...row }));
|
||||
const waveStore = waves.map(row => ({ ...row }));
|
||||
const txState = {
|
||||
committed: false,
|
||||
rolledBack: false,
|
||||
sqlCalls: [],
|
||||
};
|
||||
|
||||
const transaction = {
|
||||
async commit() {
|
||||
txState.committed = true;
|
||||
},
|
||||
async rollback() {
|
||||
txState.rolledBack = true;
|
||||
},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
config: {},
|
||||
},
|
||||
user: {
|
||||
store_id: storeId,
|
||||
},
|
||||
model: {
|
||||
QueryTypes: {
|
||||
SELECT: 'SELECT',
|
||||
},
|
||||
async transaction() {
|
||||
return transaction;
|
||||
},
|
||||
async query(sql, options = {}) {
|
||||
txState.sqlCalls.push({ sql, options });
|
||||
|
||||
if (sql.includes('SELECT wave_id, wave_status, total_orders')) {
|
||||
const targetIds = Array.isArray(options.replacements && options.replacements.ids)
|
||||
? options.replacements.ids
|
||||
: [];
|
||||
return waveStore
|
||||
.filter(item => Number(item.warehouse_id) === Number(options.replacements.warehouseId))
|
||||
.filter(item => targetIds.includes(item.wave_id))
|
||||
.map(item => ({
|
||||
wave_id: item.wave_id,
|
||||
wave_status: item.wave_status,
|
||||
total_orders: item.total_orders,
|
||||
}));
|
||||
}
|
||||
|
||||
if (sql.includes('SELECT wave_id, wave_status') && !sql.includes('total_orders')) {
|
||||
const targetIds = Array.isArray(options.replacements && options.replacements.ids)
|
||||
? options.replacements.ids
|
||||
: [];
|
||||
return waveStore
|
||||
.filter(item => Number(item.warehouse_id) === Number(options.replacements.warehouseId))
|
||||
.filter(item => targetIds.includes(item.wave_id))
|
||||
.map(item => ({
|
||||
wave_id: item.wave_id,
|
||||
wave_status: item.wave_status,
|
||||
}));
|
||||
}
|
||||
|
||||
if (sql.includes('SET wave_status = 0')) {
|
||||
const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds)
|
||||
? options.replacements.waveIds
|
||||
: [];
|
||||
let affectedRows = 0;
|
||||
for (const wave of waveStore) {
|
||||
if (targetWaveIds.includes(wave.wave_id) && Number(wave.warehouse_id) === Number(options.replacements.warehouseId)) {
|
||||
wave.wave_status = 0;
|
||||
affectedRows += 1;
|
||||
}
|
||||
}
|
||||
return [[], { affectedRows }];
|
||||
}
|
||||
|
||||
if (sql.includes('SET wave_status = 1')) {
|
||||
const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds)
|
||||
? options.replacements.waveIds
|
||||
: [];
|
||||
let affectedRows = 0;
|
||||
for (const wave of waveStore) {
|
||||
if (
|
||||
targetWaveIds.includes(wave.wave_id)
|
||||
&& Number(wave.warehouse_id) === Number(options.replacements.warehouseId)
|
||||
&& Number(wave.wave_status) === 0
|
||||
) {
|
||||
wave.wave_status = 1;
|
||||
affectedRows += 1;
|
||||
}
|
||||
}
|
||||
return [[], { affectedRows }];
|
||||
}
|
||||
|
||||
if (sql.includes('DELETE FROM wms_order_wave_index')) {
|
||||
const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds)
|
||||
? options.replacements.waveIds
|
||||
: [];
|
||||
return [[], { affectedRows: targetWaveIds.length }];
|
||||
}
|
||||
|
||||
if (sql.includes('INSERT INTO wms_order_wave_index')) {
|
||||
const replacements = options.replacements || {};
|
||||
let affectedRows = 0;
|
||||
for (const key of Object.keys(replacements)) {
|
||||
if (key.startsWith('orderId_')) {
|
||||
affectedRows += 1;
|
||||
}
|
||||
}
|
||||
return [[], { affectedRows }];
|
||||
}
|
||||
|
||||
return [[], { affectedRows: 0 }];
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new WaveService(ctx);
|
||||
service.getDefaultWaveQuantity = async () => maxWaveQuantity;
|
||||
service.getOrderModel = async () => ({
|
||||
async findAll(options = {}) {
|
||||
const where = options.where || {};
|
||||
const waveIn = (where.wave_id && where.wave_id[Op.in]) || [];
|
||||
const waveGt = Number((where.wave_id && where.wave_id[Op.gt]) || 0);
|
||||
|
||||
const rows = orderStore
|
||||
.filter(item => waveIn.includes(item.wave_id))
|
||||
.filter(item => Number(item.wave_id) > waveGt)
|
||||
.sort((a, b) => {
|
||||
if (Number(a.wave_id) !== Number(b.wave_id)) {
|
||||
return Number(a.wave_id) - Number(b.wave_id);
|
||||
}
|
||||
return Number(a.id) - Number(b.id);
|
||||
});
|
||||
|
||||
return rows.map(item => ({
|
||||
id: item.id,
|
||||
wave_id: item.wave_id,
|
||||
sys_platform_code: item.sys_platform_code,
|
||||
}));
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
service,
|
||||
txState,
|
||||
waves: waveStore,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systemMethods/order/wave.batchAutoGrouping.test.js', () => {
|
||||
it('batchAutoGrouping should rebuild wave indexes for updatable waves', async () => {
|
||||
const { service, txState, waves } = createHarness({
|
||||
maxWaveQuantity: 3,
|
||||
orders: [
|
||||
{ id: 1001, wave_id: 501, sys_platform_code: 'pdd' },
|
||||
{ id: 1002, wave_id: 501, sys_platform_code: 'cainiao' },
|
||||
{ id: 1003, wave_id: 502, sys_platform_code: 'pdd' },
|
||||
],
|
||||
waves: [
|
||||
{ warehouse_id: 100000, wave_id: 501, wave_status: 1, total_orders: 2 },
|
||||
{ warehouse_id: 100000, wave_id: 502, wave_status: 2, total_orders: 1 },
|
||||
{ warehouse_id: 100000, wave_id: 503, wave_status: 1, total_orders: 3 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.batchAutoGrouping({ ids: [ 501, 502, 503 ] });
|
||||
|
||||
assert.equal(txState.committed, true);
|
||||
assert.equal(txState.rolledBack, false);
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.deepEqual(result.affected_wave_ids, [ 501, 502, 503 ]);
|
||||
assert.equal(result.updated_wave_count, 1);
|
||||
|
||||
const targetWave = waves.find(item => item.wave_id === 501);
|
||||
assert.equal(targetWave.wave_status, 0);
|
||||
|
||||
const deleteIndexCall = txState.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index'));
|
||||
assert.ok(deleteIndexCall, '应按可更新波次整批删除索引');
|
||||
assert.deepEqual(deleteIndexCall.options.replacements.waveIds, [ 501 ]);
|
||||
|
||||
const insertIndexCall = txState.sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index'));
|
||||
assert.ok(insertIndexCall, '应按可更新波次整批重建索引');
|
||||
assert.equal(insertIndexCall.options.replacements.waveId_0, 501);
|
||||
assert.equal(insertIndexCall.options.replacements.orderId_0, 1001);
|
||||
assert.equal(insertIndexCall.options.replacements.orderId_1, 1002);
|
||||
assert.equal(insertIndexCall.options.replacements.platformsIndex_0, 2);
|
||||
assert.equal(insertIndexCall.options.replacements.platformsIndex_1, 1);
|
||||
});
|
||||
|
||||
it('batchFinishAutoGrouping should rebuild wave indexes for updated waves', async () => {
|
||||
const { service, txState, waves } = createHarness({
|
||||
orders: [
|
||||
{ id: 2001, wave_id: 601 },
|
||||
{ id: 2002, wave_id: 601 },
|
||||
{ id: 2003, wave_id: 602 },
|
||||
],
|
||||
waves: [
|
||||
{ warehouse_id: 100000, wave_id: 601, wave_status: 0, total_orders: 2 },
|
||||
{ warehouse_id: 100000, wave_id: 602, wave_status: 1, total_orders: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.batchFinishAutoGrouping({ ids: [ 601, 602 ] });
|
||||
|
||||
assert.equal(txState.committed, true);
|
||||
assert.equal(txState.rolledBack, false);
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.deepEqual(result.updated_wave_ids, [ 601 ]);
|
||||
assert.equal(result.updated_wave_count, 1);
|
||||
|
||||
const updatedWave = waves.find(item => item.wave_id === 601);
|
||||
assert.equal(updatedWave.wave_status, 1);
|
||||
|
||||
const deleteIndexCall = txState.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index'));
|
||||
assert.ok(deleteIndexCall, '应按完成加团波次整批删除索引');
|
||||
assert.deepEqual(deleteIndexCall.options.replacements.waveIds, [ 601 ]);
|
||||
|
||||
const insertIndexCall = txState.sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index'));
|
||||
assert.ok(insertIndexCall, '应按完成加团波次整批重建索引');
|
||||
assert.equal(insertIndexCall.options.replacements.waveId_0, 601);
|
||||
assert.equal(insertIndexCall.options.replacements.orderId_0, 2001);
|
||||
assert.equal(insertIndexCall.options.replacements.orderId_1, 2002);
|
||||
});
|
||||
});
|
||||
126
test/app/service/systemMethods/order/wave.batchCancel.test.js
Normal file
126
test/app/service/systemMethods/order/wave.batchCancel.test.js
Normal file
@ -0,0 +1,126 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
|
||||
|
||||
/**
|
||||
* 创建 batchCancel 轻量测试上下文。
|
||||
*
|
||||
* @return {{ service: WaveService, state: Object }} 服务实例与状态记录。
|
||||
*/
|
||||
function createHarness() {
|
||||
const cacheStore = new Map();
|
||||
const state = {
|
||||
sqlCalls: [],
|
||||
orders: [
|
||||
{ id: 101, wave_id: 11, wave_no: 'W11' },
|
||||
{ id: 102, wave_id: 11, wave_no: 'W11' },
|
||||
],
|
||||
};
|
||||
|
||||
const transaction = {
|
||||
async commit() {},
|
||||
async rollback() {},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
config: {},
|
||||
async setCacheAsync(key, value) {
|
||||
cacheStore.set(key, value);
|
||||
},
|
||||
async getCacheAsync(key) {
|
||||
return cacheStore.get(key) || null;
|
||||
},
|
||||
},
|
||||
user: {
|
||||
store_id: 100000,
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
model: {
|
||||
QueryTypes: {
|
||||
SELECT: 'SELECT',
|
||||
},
|
||||
async transaction() {
|
||||
return transaction;
|
||||
},
|
||||
async query(sql, options = {}) {
|
||||
state.sqlCalls.push({ sql, options });
|
||||
|
||||
if (sql.includes('SELECT wave_id, wave_no') && options.type === 'SELECT') {
|
||||
return [
|
||||
{ wave_id: 11, wave_no: 'W11' },
|
||||
];
|
||||
}
|
||||
|
||||
if (sql.includes('DELETE FROM wms_order_wave_index')) {
|
||||
return [[], { affectedRows: 2 }];
|
||||
}
|
||||
|
||||
if (sql.includes('UPDATE wms_wave_batch') && sql.includes('SET wave_status = -1')) {
|
||||
return [[], { affectedRows: 1 }];
|
||||
}
|
||||
|
||||
return [[], { affectedRows: 0 }];
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new WaveService(ctx);
|
||||
service.batchCreateOrderOperationLogs = async () => 0;
|
||||
service.getOrderModel = async () => ({
|
||||
async findAll() {
|
||||
return state.orders.map(item => ({ ...item }));
|
||||
},
|
||||
async update(values = {}, options = {}) {
|
||||
const waveId = Number(options.where && options.where.wave_id || 0);
|
||||
let affected = 0;
|
||||
for (const row of state.orders) {
|
||||
if (Number(row.wave_id || 0) !== waveId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
row.wave_id = Number(values.wave_id || 0);
|
||||
row.wave_no = String(values.wave_no || '');
|
||||
affected += 1;
|
||||
}
|
||||
return [ affected ];
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
service,
|
||||
state,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systemMethods/order/wave.batchCancel.test.js', () => {
|
||||
it('runBatchCancelTask 应在取消波次时清理 wms_order_wave_index', async () => {
|
||||
const { service, state } = createHarness();
|
||||
|
||||
await service.setBatchCancelTaskProgress('task_cancel_1', 'submitted', {
|
||||
warehouse_id: 100000,
|
||||
wave_ids: '11',
|
||||
wave_id_list: [ 11 ],
|
||||
});
|
||||
|
||||
await service.runBatchCancelTask({
|
||||
taskId: 'task_cancel_1',
|
||||
warehouseId: 100000,
|
||||
waveIds: [ 11 ],
|
||||
});
|
||||
|
||||
const deleteCall = state.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index'));
|
||||
assert.ok(deleteCall, '应删除波次索引');
|
||||
assert.deepEqual(deleteCall.options.replacements.orderIds.sort((a, b) => a - b), [ 101, 102 ]);
|
||||
|
||||
const progress = await service.getBatchCancelTaskProgress('task_cancel_1');
|
||||
assert.equal(progress.state, 'success');
|
||||
assert.equal(progress.result.canceled_wave_count, 1);
|
||||
});
|
||||
});
|
||||
@ -20,6 +20,7 @@ function createHarness({ orders = [], waves = [], storeId = 100000 } = {}) {
|
||||
const txState = {
|
||||
committed: false,
|
||||
rolledBack: false,
|
||||
sqlCalls: [],
|
||||
};
|
||||
|
||||
const transaction = {
|
||||
@ -52,6 +53,26 @@ function createHarness({ orders = [], waves = [], storeId = 100000 } = {}) {
|
||||
return transaction;
|
||||
},
|
||||
async query(sql, options = {}) {
|
||||
txState.sqlCalls.push({ sql, options });
|
||||
|
||||
if (sql.includes('DELETE FROM wms_order_wave_index')) {
|
||||
const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds)
|
||||
? options.replacements.waveIds
|
||||
: [];
|
||||
return [[], { affectedRows: targetWaveIds.length }];
|
||||
}
|
||||
|
||||
if (sql.includes('INSERT INTO wms_order_wave_index')) {
|
||||
let affectedRows = 0;
|
||||
const replacements = options.replacements || {};
|
||||
for (const key of Object.keys(replacements)) {
|
||||
if (key.startsWith('orderId_')) {
|
||||
affectedRows += 1;
|
||||
}
|
||||
}
|
||||
return [[], { affectedRows }];
|
||||
}
|
||||
|
||||
if (sql.includes('SET total_orders = :remainingCount')) {
|
||||
const waveId = Number(options.replacements && options.replacements.waveId || 0);
|
||||
const remainingCount = Number(options.replacements && options.replacements.remainingCount || 0);
|
||||
@ -87,32 +108,38 @@ function createHarness({ orders = [], waves = [], storeId = 100000 } = {}) {
|
||||
async findAll(options = {}) {
|
||||
const where = options.where || {};
|
||||
const idIn = (where.id && where.id[Op.in]) || [];
|
||||
const stepIn = (where.step && where.step[Op.in]) || [];
|
||||
const hasStepFilter = !!(where.step && where.step[Op.in]);
|
||||
const stepIn = hasStepFilter ? where.step[Op.in] : [];
|
||||
const waveIn = (where.wave_id && where.wave_id[Op.in]) || [];
|
||||
const waveGt = Number((where.wave_id && where.wave_id[Op.gt]) || 0);
|
||||
|
||||
if (Array.isArray(options.group) && options.group.includes('wave_id')) {
|
||||
const result = [];
|
||||
for (const waveId of waveIn) {
|
||||
const count = orderStore.filter(item => Number(item.wave_id) === Number(waveId) && Number(item.wave_id) > waveGt).length;
|
||||
if (count > 0) {
|
||||
result.push({
|
||||
wave_id: Number(waveId),
|
||||
remaining_count: count,
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
let rows = orderStore.slice();
|
||||
if (idIn.length > 0) {
|
||||
rows = rows.filter(item => idIn.includes(item.id));
|
||||
}
|
||||
if (hasStepFilter) {
|
||||
rows = rows.filter(item => stepIn.includes(item.step));
|
||||
}
|
||||
if (waveIn.length > 0) {
|
||||
rows = rows.filter(item => waveIn.includes(item.wave_id));
|
||||
}
|
||||
if (waveGt > 0) {
|
||||
rows = rows.filter(item => Number(item.wave_id) > waveGt);
|
||||
}
|
||||
|
||||
return orderStore
|
||||
.filter(item => idIn.includes(item.id))
|
||||
.filter(item => stepIn.includes(item.step))
|
||||
.filter(item => Number(item.wave_id) > waveGt)
|
||||
.map(item => ({
|
||||
id: item.id,
|
||||
wave_id: item.wave_id,
|
||||
}));
|
||||
rows.sort((a, b) => {
|
||||
if (Number(a.wave_id) !== Number(b.wave_id)) {
|
||||
return Number(a.wave_id) - Number(b.wave_id);
|
||||
}
|
||||
return Number(a.id) - Number(b.id);
|
||||
});
|
||||
|
||||
return rows.map(item => ({
|
||||
id: item.id,
|
||||
wave_id: item.wave_id,
|
||||
sys_platform_code: item.sys_platform_code,
|
||||
source_platform_code: item.source_platform_code,
|
||||
}));
|
||||
},
|
||||
|
||||
async update(values = {}, options = {}) {
|
||||
@ -202,6 +229,63 @@ describe('test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js',
|
||||
assert.equal(emptiedWave.total_orders, 0);
|
||||
assert.equal(emptiedWave.processed_orders, 0);
|
||||
assert.equal(emptiedWave.wave_status, -1);
|
||||
|
||||
const deleteIndexCall = txState.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index'));
|
||||
assert.ok(deleteIndexCall, '应按波次整批删除波次索引');
|
||||
assert.deepEqual(deleteIndexCall.options.replacements.waveIds.sort((a, b) => a - b), [ 21, 22 ]);
|
||||
|
||||
const insertIndexCall = txState.sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index'));
|
||||
assert.ok(insertIndexCall, '应按当前波次订单重建波次索引');
|
||||
assert.equal(insertIndexCall.options.replacements.orderId_0, 12);
|
||||
assert.equal(insertIndexCall.options.replacements.waveId_0, 21);
|
||||
assert.equal(insertIndexCall.options.replacements.waveIndex_0, 1);
|
||||
assert.equal(insertIndexCall.options.replacements.platformsIndex_0, 1);
|
||||
});
|
||||
|
||||
it('should rebuild platforms_index by normalized sys/source platform key after batch remove', async () => {
|
||||
const { service, txState } = createHarness({
|
||||
orders: [
|
||||
{ id: 50, step: 1, wave_id: 61, wave_no: 'W61', sys_platform_code: 'PDD', source_platform_code: '' },
|
||||
{ id: 51, step: 2, wave_id: 61, wave_no: 'W61', sys_platform_code: ' JD ', source_platform_code: '' },
|
||||
{ id: 52, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: '', source_platform_code: 'tmall' },
|
||||
{ id: 53, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: ' pdd ', source_platform_code: '' },
|
||||
{ id: 54, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: '', source_platform_code: ' JD' },
|
||||
{ id: 55, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: 'jd', source_platform_code: '' },
|
||||
{ id: 56, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: '', source_platform_code: ' pdd ' },
|
||||
],
|
||||
waves: [
|
||||
{ wave_id: 61, total_orders: 7, processed_orders: 0, wave_status: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.batchRemoveOrders({ ids: [ 50, 51 ] });
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.deepEqual(result.updated_wave_ids, [ 61 ]);
|
||||
|
||||
const insertIndexCall = txState.sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index'));
|
||||
assert.ok(insertIndexCall, '应在移除后重建剩余订单索引');
|
||||
|
||||
const { replacements } = insertIndexCall.options;
|
||||
assert.equal(replacements.orderId_0, 52);
|
||||
assert.equal(replacements.waveIndex_0, 1);
|
||||
assert.equal(replacements.platformsIndex_0, 1);
|
||||
|
||||
assert.equal(replacements.orderId_1, 53);
|
||||
assert.equal(replacements.waveIndex_1, 2);
|
||||
assert.equal(replacements.platformsIndex_1, 1);
|
||||
|
||||
assert.equal(replacements.orderId_2, 54);
|
||||
assert.equal(replacements.waveIndex_2, 3);
|
||||
assert.equal(replacements.platformsIndex_2, 1);
|
||||
|
||||
assert.equal(replacements.orderId_3, 55);
|
||||
assert.equal(replacements.waveIndex_3, 4);
|
||||
assert.equal(replacements.platformsIndex_3, 2);
|
||||
|
||||
assert.equal(replacements.orderId_4, 56);
|
||||
assert.equal(replacements.waveIndex_4, 5);
|
||||
assert.equal(replacements.platformsIndex_4, 2);
|
||||
});
|
||||
|
||||
it('should accept order_ids alias and normalize ids in response', async () => {
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
'use strict';
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { Op } = require('sequelize');
|
||||
@ -224,7 +224,7 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => {
|
||||
return transaction;
|
||||
},
|
||||
async query(sql, options = {}) {
|
||||
sqlCalls.push({ sql, options });
|
||||
sqlCalls.push({ sql, options }); console.log('SQL:', sql); console.log('Replacements:', JSON.stringify(options.replacements));
|
||||
if (sql.includes('INSERT INTO wms_wave_batch')) {
|
||||
return [{ insertId: 900001 }, { insertId: 900001 }];
|
||||
}
|
||||
@ -350,7 +350,7 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => {
|
||||
return transaction;
|
||||
},
|
||||
async query(sql, options = {}) {
|
||||
sqlCalls.push({ sql, options });
|
||||
sqlCalls.push({ sql, options }); console.log('SQL:', sql); console.log('Replacements:', JSON.stringify(options.replacements));
|
||||
if (sql.includes('INSERT INTO wms_wave_batch')) {
|
||||
return [{}, {}];
|
||||
}
|
||||
@ -480,7 +480,7 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => {
|
||||
return transaction;
|
||||
},
|
||||
async query(sql, options = {}) {
|
||||
sqlCalls.push({ sql, options });
|
||||
sqlCalls.push({ sql, options }); console.log('SQL:', sql); console.log('Replacements:', JSON.stringify(options.replacements));
|
||||
if (sql.includes('INSERT INTO wms_wave_batch')) {
|
||||
return [{ insertId: 900003 }, { insertId: 900003 }];
|
||||
}
|
||||
@ -522,10 +522,14 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => {
|
||||
.filter(item => item.wave_id === 0)
|
||||
.map(item => ({ id: item.id }));
|
||||
}
|
||||
if (where.wave_id === 900003) {
|
||||
const waveIdInList = where.wave_id && where.wave_id[Op.in];
|
||||
const normalizedWaveIdInList = Array.isArray(waveIdInList)
|
||||
? waveIdInList.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
if (where.wave_id === 900003 || normalizedWaveIdInList.includes(900003)) {
|
||||
return orders
|
||||
.filter(item => item.wave_id === 900003)
|
||||
.map(item => ({ id: item.id }));
|
||||
.map(item => ({ id: item.id, wave_id: item.wave_id }));
|
||||
}
|
||||
return [];
|
||||
},
|
||||
@ -564,5 +568,10 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => {
|
||||
|
||||
const insertCall = sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index'));
|
||||
assert.ok(insertCall, '应触发 INSERT INTO wms_order_wave_index');
|
||||
|
||||
const deleteIndex = sqlCalls.findIndex(call => call.sql.includes('DELETE FROM wms_order_wave_index'));
|
||||
const insertIndex = sqlCalls.findIndex(call => call.sql.includes('INSERT INTO wms_order_wave_index'));
|
||||
assert.ok(deleteIndex >= 0 && insertIndex >= 0 && deleteIndex < insertIndex, '应先删除旧索引再写入新索引');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@ -7,7 +7,7 @@ const PrintService = require('../../../../app/service/systemMethods/print');
|
||||
* 构造 savePrinters 测试上下文。
|
||||
* @param {Object} [options] 测试选项。
|
||||
* @param {Object|null} [options.stationItem] 打印台模型实例。
|
||||
* @returns {{ctx: Object, calls: Object, stationItem: Object|null}} 测试上下文与调用记录。
|
||||
* @return {{ctx: Object, calls: Object, stationItem: Object|null}} 测试上下文与调用记录。
|
||||
*/
|
||||
function createContext(options = {}) {
|
||||
const calls = {
|
||||
|
||||
@ -5,21 +5,96 @@ const PrintService = require('../../../../app/service/systemMethods/print');
|
||||
|
||||
/**
|
||||
* 构建 print.send 测试上下文。
|
||||
* @returns {{ctx: Object, calls: Object}}
|
||||
* @param {Object} [options] 可选项。
|
||||
* @param {Object} [options.printStation] 打印台数据。
|
||||
* @param {Function} [options.sendToComputer] 发送函数桩。
|
||||
* @return {{ctx: Object, calls: Object}} 包含模拟上下文与调用记录。
|
||||
*/
|
||||
function createContext() {
|
||||
function createContext(options = {}) {
|
||||
const requestOptions = options && typeof options === 'object' ? options : {};
|
||||
const calls = {
|
||||
printRecordCreatePayloads: [],
|
||||
printRecordUpdatePayloads: [],
|
||||
sendToComputerPayloads: [],
|
||||
sendOrderMarks: [],
|
||||
redisGetKeys: [],
|
||||
platformFindAllWheres: [],
|
||||
};
|
||||
|
||||
const platformComponents = requestOptions.platformComponents || {
|
||||
cainiao: '菜鸟',
|
||||
pdd: '拼多多',
|
||||
douyin: '抖音',
|
||||
};
|
||||
|
||||
const printStation = requestOptions.printStation || {
|
||||
id: 101,
|
||||
warehouse_id: 100000,
|
||||
deleted: 0,
|
||||
computer_id: 'PC-STATION-001',
|
||||
default_printer_name: 'PRN-DEFAULT',
|
||||
subject_config: {
|
||||
express_bind_printer: [
|
||||
{
|
||||
express_code: 'STO',
|
||||
printer_name: 'PRN-STO',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const sendToComputer = requestOptions.sendToComputer || (async payload => {
|
||||
calls.sendToComputerPayloads.push(payload);
|
||||
const marker = payload
|
||||
&& payload.data
|
||||
&& payload.data.data
|
||||
&& payload.data.data.task
|
||||
&& Array.isArray(payload.data.data.task.documents)
|
||||
&& payload.data.data.task.documents[0]
|
||||
&& Array.isArray(payload.data.data.task.documents[0].contents)
|
||||
&& payload.data.data.task.documents[0].contents[0]
|
||||
? payload.data.data.task.documents[0].contents[0].marker
|
||||
: '';
|
||||
calls.sendOrderMarks.push(marker);
|
||||
return {
|
||||
status: 'success',
|
||||
};
|
||||
});
|
||||
|
||||
const defaultComponentStatusMap = {
|
||||
'printer:PC-STATION-001:name:菜鸟:status': 'connected',
|
||||
'printer:PC-STATION-001:name:拼多多:status': 'connected',
|
||||
'printer:PC-STATION-001:name:抖音:status': 'connected',
|
||||
};
|
||||
const componentStatusMap = {
|
||||
...defaultComponentStatusMap,
|
||||
...(requestOptions.componentStatuses || {}),
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
baseDir: process.cwd(),
|
||||
config: {
|
||||
jwt: {},
|
||||
},
|
||||
Sequelize: {},
|
||||
redis: {
|
||||
get() {
|
||||
return {
|
||||
async get(key) {
|
||||
calls.redisGetKeys.push(key);
|
||||
return Object.prototype.hasOwnProperty.call(componentStatusMap, key)
|
||||
? componentStatusMap[key]
|
||||
: null;
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
user: {
|
||||
store_id: 100000,
|
||||
@ -36,17 +111,31 @@ function createContext() {
|
||||
};
|
||||
},
|
||||
},
|
||||
PrintStations: {
|
||||
async findOne() {
|
||||
return printStation;
|
||||
},
|
||||
},
|
||||
Platform: {
|
||||
async findAll(query) {
|
||||
calls.platformFindAllWheres.push(query && query.where ? query.where : {});
|
||||
const codeList = query && query.where && Array.isArray(query.where.code)
|
||||
? query.where.code
|
||||
: [];
|
||||
return codeList.map(code => ({
|
||||
code,
|
||||
component: Object.prototype.hasOwnProperty.call(platformComponents, code)
|
||||
? platformComponents[code]
|
||||
: '',
|
||||
}));
|
||||
},
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
print: {
|
||||
index: {
|
||||
async sendToComputer(payload) {
|
||||
calls.sendToComputerPayloads.push(payload);
|
||||
return {
|
||||
status: 'success',
|
||||
};
|
||||
},
|
||||
sendToComputer,
|
||||
},
|
||||
},
|
||||
},
|
||||
@ -56,48 +145,409 @@ function createContext() {
|
||||
return { ctx, calls };
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建 express 场景的 waveGroups。
|
||||
* @return {Array<Object>} waveGroups。
|
||||
*/
|
||||
function createExpressWaveGroups() {
|
||||
return [
|
||||
{
|
||||
wave_id: 1,
|
||||
wave_no: 'WAVE-1',
|
||||
platforms: [
|
||||
{
|
||||
platform: 'cainiao',
|
||||
sys_logistics_code: 'STO',
|
||||
orders: [
|
||||
{
|
||||
print_data: {
|
||||
documentID: 'DOC-OLD-1',
|
||||
contents: [
|
||||
{
|
||||
marker: 'W1-P1',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
print_data: {
|
||||
documentID: 'DOC-OLD-2',
|
||||
contents: [
|
||||
{
|
||||
marker: 'W1-P1-2',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
platform: 'pdd',
|
||||
sys_logistics_code: 'YTO',
|
||||
orders: [
|
||||
{
|
||||
print_data: {
|
||||
documentID: 'DOC-OLD-3',
|
||||
contents: [
|
||||
{
|
||||
marker: 'W1-P2',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
wave_id: 2,
|
||||
wave_no: 'WAVE-2',
|
||||
platforms: [
|
||||
{
|
||||
platform: 'douyin',
|
||||
sys_logistics_code: 'STO',
|
||||
orders: [
|
||||
{
|
||||
print_data: {
|
||||
documentID: 'DOC-OLD-4',
|
||||
contents: [
|
||||
{
|
||||
marker: 'W2-P1',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建快手平台的 express 场景波次数据。
|
||||
* @param {number} orderCount 订单数量。
|
||||
* @return {Array<Object>} waveGroups。
|
||||
*/
|
||||
function createKuaishouWaveGroups(orderCount) {
|
||||
const normalizedOrderCount = Number(orderCount) || 0;
|
||||
const orders = [];
|
||||
for (let index = 0; index < normalizedOrderCount; index++) {
|
||||
const current = index + 1;
|
||||
orders.push({
|
||||
print_data: {
|
||||
documentID: `DOC-KS-${current}`,
|
||||
contents: [
|
||||
{
|
||||
marker: `KS-${current}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
return [
|
||||
{
|
||||
wave_id: 1,
|
||||
wave_no: 'WAVE-KS-1',
|
||||
platforms: [
|
||||
{
|
||||
platform: 'kuaishou',
|
||||
sys_logistics_code: 'STO',
|
||||
orders,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
describe('test/app/service/systemMethods/print.send.test.js', () => {
|
||||
it('type=express 不传 printer 时应发送成功并调用 sendToComputer', async () => {
|
||||
it('type=express 缺失 printStationId 时应返回失败', async () => {
|
||||
const { ctx, calls } = createContext();
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
computerId: 'PC-00',
|
||||
type: 'express',
|
||||
requestCode: 'REQ-MISSING-STATION',
|
||||
data: {
|
||||
order_no: 'SO10000',
|
||||
waveGroups: createExpressWaveGroups(),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'failure');
|
||||
assert.equal(result.code, 400);
|
||||
assert.match(result.message, /printStationId/);
|
||||
assert.equal(calls.sendToComputerPayloads.length, 0);
|
||||
});
|
||||
|
||||
it('type=express 使用 waveGroups 串行发送并保持 success 返回风格', async () => {
|
||||
const { ctx, calls } = createContext();
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-SEQ-001',
|
||||
data: {
|
||||
waveGroups: createExpressWaveGroups(),
|
||||
},
|
||||
timestamp: '1709999999',
|
||||
count: 1,
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(calls.sendToComputerPayloads.length, 1);
|
||||
assert.equal(calls.printRecordCreatePayloads.length, 1);
|
||||
assert.equal(calls.printRecordCreatePayloads[0].computer_id, 'PC-STATION-001');
|
||||
assert.equal(calls.printRecordCreatePayloads[0].printer, 'PRN-DEFAULT');
|
||||
assert.equal(calls.sendToComputerPayloads.length, 3);
|
||||
assert.deepEqual(calls.sendOrderMarks, [ 'W1-P1', 'W1-P2', 'W2-P1' ]);
|
||||
assert.equal(calls.printRecordUpdatePayloads.length, 1);
|
||||
assert.equal(calls.printRecordUpdatePayloads[0].status, 'sent');
|
||||
});
|
||||
|
||||
it('type=express 不传 template 时应发送成功并调用 sendToComputer', async () => {
|
||||
it('type=express 默认打印机为空时创建记录应写入稳定占位值', async () => {
|
||||
const { ctx, calls } = createContext({
|
||||
printStation: {
|
||||
id: 101,
|
||||
warehouse_id: 100000,
|
||||
deleted: 0,
|
||||
computer_id: 'PC-STATION-001',
|
||||
default_printer_name: '',
|
||||
subject_config: {
|
||||
express_bind_printer: [
|
||||
{
|
||||
express_code: 'STO',
|
||||
printer_name: 'PRN-STO',
|
||||
},
|
||||
{
|
||||
express_code: 'YTO',
|
||||
printer_name: 'PRN-YTO',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-RECORD-PLACEHOLDER-001',
|
||||
data: {
|
||||
waveGroups: createExpressWaveGroups(),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(calls.printRecordCreatePayloads.length, 1);
|
||||
assert.equal(calls.printRecordCreatePayloads[0].computer_id, 'PC-STATION-001');
|
||||
assert.equal(calls.printRecordCreatePayloads[0].printer, 'EXPRESS_DYNAMIC_PRINTER');
|
||||
});
|
||||
|
||||
it('type=express 应按快递匹配打印机并在未命中时回退默认打印机', async () => {
|
||||
const { ctx, calls } = createContext();
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
computerId: 'PC-01',
|
||||
printer: 'Printer-A',
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-PRINTER-001',
|
||||
data: {
|
||||
order_no: 'SO10001',
|
||||
waveGroups: createExpressWaveGroups(),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(calls.sendToComputerPayloads.length, 3);
|
||||
const printerNames = calls.sendToComputerPayloads.map(item => item.data.printer);
|
||||
assert.deepEqual(printerNames, [ 'PRN-STO', 'PRN-DEFAULT', 'PRN-STO' ]);
|
||||
});
|
||||
|
||||
it('type=express 发送成功时 payload 应带 component 字段', async () => {
|
||||
const { ctx, calls } = createContext();
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-COMPONENT-OK-001',
|
||||
data: {
|
||||
waveGroups: createExpressWaveGroups(),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
const components = calls.sendToComputerPayloads.map(item => item.data.component);
|
||||
assert.deepEqual(components, [ '菜鸟', '拼多多', '抖音' ]);
|
||||
});
|
||||
|
||||
it('type=express 任意组件离线时应整批失败且不发送任务', async () => {
|
||||
const { ctx, calls } = createContext({
|
||||
componentStatuses: {
|
||||
'printer:PC-STATION-001:name:拼多多:status': 'disconnected',
|
||||
},
|
||||
});
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-COMPONENT-OFFLINE-001',
|
||||
data: {
|
||||
waveGroups: createExpressWaveGroups(),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'failure');
|
||||
assert.equal(result.code, 400);
|
||||
assert.match(result.message, /未在线/);
|
||||
assert.equal(calls.printRecordCreatePayloads.length, 0);
|
||||
assert.equal(calls.sendToComputerPayloads.length, 0);
|
||||
});
|
||||
|
||||
it('type=express 某平台 orders 为空且组件离线时不应影响整批发送', async () => {
|
||||
const { ctx, calls } = createContext({
|
||||
componentStatuses: {
|
||||
'printer:PC-STATION-001:name:拼多多:status': 'disconnected',
|
||||
},
|
||||
});
|
||||
const service = new PrintService(ctx);
|
||||
const waveGroups = [
|
||||
{
|
||||
wave_id: 1,
|
||||
wave_no: 'WAVE-EMPTY-PLATFORM-1',
|
||||
platforms: [
|
||||
{
|
||||
platform: 'cainiao',
|
||||
sys_logistics_code: 'STO',
|
||||
orders: [
|
||||
{
|
||||
print_data: {
|
||||
documentID: 'DOC-ONLY-1',
|
||||
contents: [
|
||||
{
|
||||
marker: 'ONLY-CAINIAO',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
platform: 'pdd',
|
||||
sys_logistics_code: 'YTO',
|
||||
orders: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const result = await service.send({
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-EMPTY-PLATFORM-OFFLINE-001',
|
||||
data: {
|
||||
waveGroups,
|
||||
},
|
||||
timestamp: '1710000000',
|
||||
count: 1,
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(calls.sendToComputerPayloads.length, 1);
|
||||
assert.equal(calls.printRecordUpdatePayloads.length, 1);
|
||||
assert.equal(calls.printRecordUpdatePayloads[0].status, 'sent');
|
||||
assert.deepEqual(calls.sendOrderMarks, [ 'ONLY-CAINIAO' ]);
|
||||
assert.equal(calls.platformFindAllWheres.length, 1);
|
||||
assert.deepEqual(calls.platformFindAllWheres[0].code, [ 'cainiao' ]);
|
||||
assert.deepEqual(calls.redisGetKeys, [ 'printer:PC-STATION-001:name:菜鸟:status' ]);
|
||||
});
|
||||
|
||||
it('type=express 平台 component 为空时应失败且不发送任务', async () => {
|
||||
const { ctx, calls } = createContext({
|
||||
platformComponents: {
|
||||
cainiao: '菜鸟',
|
||||
pdd: '',
|
||||
douyin: '抖音',
|
||||
},
|
||||
});
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-COMPONENT-EMPTY-001',
|
||||
data: {
|
||||
waveGroups: createExpressWaveGroups(),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'failure');
|
||||
assert.equal(result.code, 400);
|
||||
assert.match(result.message, /未配置打印组件/);
|
||||
assert.equal(calls.printRecordCreatePayloads.length, 0);
|
||||
assert.equal(calls.sendToComputerPayloads.length, 0);
|
||||
});
|
||||
|
||||
it('type=express 快手平台应按10单分批发送并注入文档位置信息', async () => {
|
||||
const { ctx, calls } = createContext({
|
||||
platformComponents: {
|
||||
kuaishou: '快手',
|
||||
},
|
||||
componentStatuses: {
|
||||
'printer:PC-STATION-001:name:快手:status': 'connected',
|
||||
},
|
||||
});
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-KS-BATCH-001',
|
||||
data: {
|
||||
waveGroups: createKuaishouWaveGroups(21),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(calls.sendToComputerPayloads.length, 3);
|
||||
|
||||
const requestPayloads = calls.sendToComputerPayloads.map(item => item.data.data);
|
||||
const firstDocumentNumbers = requestPayloads.map(item => item.task.firstDocumentNumber);
|
||||
const totalDocumentCounts = requestPayloads.map(item => item.task.totalDocumentCount);
|
||||
const documentCounts = requestPayloads.map(item => item.task.documents.length);
|
||||
|
||||
assert.deepEqual(firstDocumentNumbers, [ 1, 11, 21 ]);
|
||||
assert.deepEqual(totalDocumentCounts, [ 21, 21, 21 ]);
|
||||
assert.deepEqual(documentCounts, [ 10, 10, 1 ]);
|
||||
});
|
||||
|
||||
it('type=express 同一次请求内 requestId/taskID/documentID 应唯一', async () => {
|
||||
const { ctx, calls } = createContext();
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.send({
|
||||
type: 'express',
|
||||
printStationId: 101,
|
||||
requestCode: 'REQ-UNIQ-001',
|
||||
data: {
|
||||
waveGroups: createExpressWaveGroups(),
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
const requestIdSet = new Set();
|
||||
const taskIdSet = new Set();
|
||||
const documentIdSet = new Set();
|
||||
|
||||
for (const callPayload of calls.sendToComputerPayloads) {
|
||||
const requestPayload = callPayload.data.data;
|
||||
const requestId = requestPayload.requestID || requestPayload.requetID;
|
||||
requestIdSet.add(requestId);
|
||||
taskIdSet.add(requestPayload.task.taskID);
|
||||
const documents = Array.isArray(requestPayload.task.documents) ? requestPayload.task.documents : [];
|
||||
for (const document of documents) {
|
||||
documentIdSet.add(document.documentID);
|
||||
}
|
||||
}
|
||||
|
||||
assert.equal(requestIdSet.size, calls.sendToComputerPayloads.length);
|
||||
assert.equal(taskIdSet.size, calls.sendToComputerPayloads.length);
|
||||
assert.equal(documentIdSet.size, 4);
|
||||
});
|
||||
|
||||
it('type=customize 不传 printer 时应返回失败且提示 printer', async () => {
|
||||
|
||||
@ -30,6 +30,7 @@ function createHarness(options = {}) {
|
||||
? options.orderItems.map(item => ({ ...item }))
|
||||
: [
|
||||
{
|
||||
id: 101,
|
||||
order_id: 1,
|
||||
order_line_no: '1',
|
||||
source_order_code: 'SRC-1',
|
||||
@ -107,6 +108,12 @@ function createHarness(options = {}) {
|
||||
const normalizedIds = targetIds.map(item => Number(item));
|
||||
return orderRows.filter(row => normalizedIds.includes(Number(row.id)));
|
||||
},
|
||||
async findOne(query = {}) {
|
||||
const where = query.where || {};
|
||||
const targetId = Number(where.id);
|
||||
const targetWarehouseId = Number(where.warehouse_id);
|
||||
return orderRows.find(row => Number(row.id) === targetId && Number(row.warehouse_id) === targetWarehouseId) || null;
|
||||
},
|
||||
async update(values, options) {
|
||||
updates.push({ values, options });
|
||||
return [ 1 ];
|
||||
@ -180,10 +187,10 @@ function createHarness(options = {}) {
|
||||
},
|
||||
}),
|
||||
stockStore: {
|
||||
async outbound(itemId, quantity, transaction) {
|
||||
outboundCalls.push({ itemId, quantity, transaction });
|
||||
async outbound(itemId, quantity, transaction, meta) {
|
||||
outboundCalls.push({ itemId, quantity, transaction, meta });
|
||||
if (typeof options.onOutbound === 'function') {
|
||||
return await options.onOutbound({ itemId, quantity, transaction });
|
||||
return await options.onOutbound({ itemId, quantity, transaction, meta });
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
@ -251,6 +258,11 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => {
|
||||
assert.equal(outboundCalls[0].itemId, 1001);
|
||||
assert.equal(outboundCalls[0].quantity, 2);
|
||||
assert.equal(outboundCalls[0].transaction, transactionCalls[0].transaction);
|
||||
assert.deepEqual(outboundCalls[0].meta, {
|
||||
orderId: 1,
|
||||
orderNo: 'DO-1001',
|
||||
orderItemId: 101,
|
||||
});
|
||||
assert.equal(updates.length, 1);
|
||||
assert.equal(updates[0].values.sync_status, 'fin');
|
||||
assert.equal(updates[0].values.inspection_status, 'padding');
|
||||
@ -368,6 +380,11 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => {
|
||||
assert.equal(noticeCalls[0].event, 'order_sync_completed');
|
||||
assert.equal(noticeCalls[0].businessName, 'order');
|
||||
assert.equal(outboundCalls.length, 1);
|
||||
assert.deepEqual(outboundCalls[0].meta, {
|
||||
orderId: 1,
|
||||
orderNo: 'DO-1001',
|
||||
orderItemId: 101,
|
||||
});
|
||||
});
|
||||
|
||||
it('should include waybill code in manual notice payload', async () => {
|
||||
@ -616,6 +633,11 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => {
|
||||
assert.equal(result.sync_results.length, 1);
|
||||
assert.equal(result.sync_results[0].status, 'success');
|
||||
assert.equal(outboundCalls.length, 1);
|
||||
assert.deepEqual(outboundCalls[0].meta, {
|
||||
orderId: 1,
|
||||
orderNo: 'DO-1001',
|
||||
orderItemId: 101,
|
||||
});
|
||||
});
|
||||
|
||||
it('should process QM orders concurrently per order', async () => {
|
||||
|
||||
@ -700,6 +700,45 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
assert.equal(capturedWhere.business_key, 1);
|
||||
});
|
||||
|
||||
it('should keep original platform value in resolvePrintPlatformCode without alias mapping', () => {
|
||||
const service = createOrderPrintServiceHarness();
|
||||
|
||||
const platformCode = service.resolvePrintPlatformCode(
|
||||
{
|
||||
sys_platform_code: ' Taobao ',
|
||||
source_platform_code: ' tb ',
|
||||
},
|
||||
{
|
||||
platform_code: ' cainiao ',
|
||||
}
|
||||
);
|
||||
|
||||
assert.equal(platformCode, 'Taobao');
|
||||
});
|
||||
|
||||
it('should keep original platform field in buildOrderPlatformPrintItem result', () => {
|
||||
const service = createOrderPrintServiceHarness();
|
||||
|
||||
const result = service.buildOrderPlatformPrintItem({
|
||||
orderRow: {
|
||||
id: 301,
|
||||
wave_id: 31,
|
||||
wave_no: 'W031',
|
||||
delivery_order_code: 'DO301',
|
||||
store_id: 1,
|
||||
warehouse_id: 100000,
|
||||
},
|
||||
orderExpress: {
|
||||
waybill_code: 'WB301',
|
||||
},
|
||||
policyConfig: {},
|
||||
platformCode: ' Taobao ',
|
||||
templateSample: {},
|
||||
});
|
||||
|
||||
assert.equal(result.platform, 'Taobao');
|
||||
});
|
||||
|
||||
it('should throw when business_key=1 waybill data is missing', async () => {
|
||||
const service = createOrderPrintServiceHarness();
|
||||
|
||||
@ -758,7 +797,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
);
|
||||
});
|
||||
|
||||
it('should return waveGroups grouped by wave then platform and keep summary counters correct', async () => {
|
||||
it('should return waveGroups grouped by wave then platform+sys_logistics and keep summary counters correct', async () => {
|
||||
const service = createOrderPrintServiceHarness();
|
||||
|
||||
service.queryWavesByIds = async () => ([
|
||||
@ -863,6 +902,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
{
|
||||
platform: 'cainiao',
|
||||
platform_name: '菜鸟',
|
||||
sys_logistics_code: 'unknown',
|
||||
sys_logistics_name: 'unknown',
|
||||
order_count: 1,
|
||||
orders: [
|
||||
{
|
||||
@ -874,6 +915,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
{
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: 'unknown',
|
||||
sys_logistics_name: 'unknown',
|
||||
order_count: 1,
|
||||
orders: [
|
||||
{
|
||||
@ -893,6 +936,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
{
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: 'unknown',
|
||||
sys_logistics_name: 'unknown',
|
||||
order_count: 1,
|
||||
orders: [
|
||||
{
|
||||
@ -910,6 +955,95 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
});
|
||||
});
|
||||
|
||||
it('should group platform orders by platform+sys_logistics as flattened platform items', () => {
|
||||
const service = createOrderPrintServiceHarness();
|
||||
|
||||
const waveGroups = service.groupOrderPrintItemsByWaveAndPlatform({
|
||||
waveRows: [
|
||||
{ wave_id: 1, wave_no: 'W001' },
|
||||
],
|
||||
hitWaveIds: [ 1 ],
|
||||
orderPrintList: [
|
||||
{
|
||||
wave_id: 1,
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: 'ZTO',
|
||||
sys_logistics_name: '中通快递',
|
||||
print_data: { order_id: 11 },
|
||||
},
|
||||
{
|
||||
wave_id: 1,
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: 'YTO',
|
||||
sys_logistics_name: '圆通速递',
|
||||
print_data: { order_id: 12 },
|
||||
},
|
||||
{
|
||||
wave_id: 1,
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: 'ZTO',
|
||||
sys_logistics_name: '中通快递',
|
||||
print_data: { order_id: 13 },
|
||||
},
|
||||
{
|
||||
wave_id: 1,
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: '',
|
||||
sys_logistics_name: '',
|
||||
print_data: { order_id: 14 },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(waveGroups.length, 1);
|
||||
assert.equal(waveGroups[0].platforms.length, 3);
|
||||
assert.equal(waveGroups[0].order_count, 4);
|
||||
|
||||
const ztoGroup = waveGroups[0].platforms.find(item => item && item.sys_logistics_code === 'ZTO');
|
||||
assert.ok(ztoGroup);
|
||||
assert.deepEqual(ztoGroup, {
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: 'ZTO',
|
||||
sys_logistics_name: '中通快递',
|
||||
order_count: 2,
|
||||
orders: [
|
||||
{ order_id: 11 },
|
||||
{ order_id: 13 },
|
||||
],
|
||||
});
|
||||
|
||||
const ytoGroup = waveGroups[0].platforms.find(item => item && item.sys_logistics_code === 'YTO');
|
||||
assert.ok(ytoGroup);
|
||||
assert.deepEqual(ytoGroup, {
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: 'YTO',
|
||||
sys_logistics_name: '圆通速递',
|
||||
order_count: 1,
|
||||
orders: [
|
||||
{ order_id: 12 },
|
||||
],
|
||||
});
|
||||
|
||||
const unknownGroup = waveGroups[0].platforms.find(item => item && item.sys_logistics_code === 'unknown');
|
||||
assert.ok(unknownGroup);
|
||||
assert.deepEqual(unknownGroup, {
|
||||
platform: 'jd',
|
||||
platform_name: '京东',
|
||||
sys_logistics_code: 'unknown',
|
||||
sys_logistics_name: 'unknown',
|
||||
order_count: 1,
|
||||
orders: [
|
||||
{ order_id: 14 },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('should batch load picking locations from wms_picking for print items', async () => {
|
||||
const service = createOrderPrintServiceHarness();
|
||||
const currentOrderItemsModel = {
|
||||
@ -988,7 +1122,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
wave_id: 30,
|
||||
wave_index: 12,
|
||||
platforms_index: 3,
|
||||
} ],
|
||||
}],
|
||||
]);
|
||||
service.queryWaveTotalOrderCountMap = async () => new Map([
|
||||
[ 30, 66 ],
|
||||
@ -996,7 +1130,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
service.getPolicyConfigMapByStore = async () => new Map([
|
||||
[ 1, {
|
||||
waybill_custom_display_type: '4',
|
||||
} ],
|
||||
}],
|
||||
]);
|
||||
service.loadTemplateSampleByPlatform = () => ({
|
||||
cmd: 'print',
|
||||
@ -1054,6 +1188,82 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
assert.ok(printText.includes('E2区08-05-02 55443 【1】'));
|
||||
});
|
||||
|
||||
it('should use real order wave_id for wave total count when wave index has dirty wave_id', async () => {
|
||||
const service = createOrderPrintServiceHarness();
|
||||
let capturedWaveIdsForIndexQuery = [];
|
||||
let capturedWaveIdsForCountQuery = [];
|
||||
|
||||
service.queryWavesByIds = async () => ([
|
||||
{ wave_id: 40, wave_no: 'W040' },
|
||||
]);
|
||||
service.queryOrdersByWaveIds = async () => ([
|
||||
{
|
||||
id: 401,
|
||||
wave_id: 40,
|
||||
wave_no: 'W040',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1,
|
||||
delivery_order_code: 'O401',
|
||||
post_status: 'fin',
|
||||
sys_platform_code: 'pdd',
|
||||
},
|
||||
]);
|
||||
service.filterFullyAssignedExpressWaves = () => ({
|
||||
validWaveIds: [ 40 ],
|
||||
filteredWaveIds: [],
|
||||
});
|
||||
service.queryOrderExpressByOrderIds = async () => ([
|
||||
{
|
||||
order_id: 401,
|
||||
business_key: 1,
|
||||
waybill_code: 'WB401',
|
||||
},
|
||||
]);
|
||||
service.getPolicyConfigMapByStore = async () => new Map([
|
||||
[ 1, {}],
|
||||
]);
|
||||
service.queryWaveOrderIndexMapByOrderIds = async (orderIds, warehouseId, waveIds) => {
|
||||
capturedWaveIdsForIndexQuery = Array.isArray(waveIds) ? waveIds : [];
|
||||
assert.deepEqual(orderIds, [ 401 ]);
|
||||
assert.equal(warehouseId, 100000);
|
||||
|
||||
return new Map([
|
||||
[ 401, {
|
||||
wave_id: 999,
|
||||
wave_index: 7,
|
||||
platforms_index: 2,
|
||||
}],
|
||||
]);
|
||||
};
|
||||
service.queryWaveTotalOrderCountMap = async waveIds => {
|
||||
capturedWaveIdsForCountQuery = Array.isArray(waveIds) ? waveIds : [];
|
||||
return new Map([
|
||||
[ 40, 66 ],
|
||||
[ 999, 1 ],
|
||||
]);
|
||||
};
|
||||
service.loadTemplateSampleByPlatform = () => ({});
|
||||
service.buildOrderPlatformPrintItem = ({ orderRow, platformCode }) => ({
|
||||
wave_id: Number(orderRow.wave_id || 0),
|
||||
platform: String(platformCode || ''),
|
||||
platform_name: '拼多多',
|
||||
print_data: {
|
||||
order_id: Number(orderRow.id || 0),
|
||||
wave_total_orders: Number(orderRow.wave_total_orders || 0),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.getWavePlatformPrintData({
|
||||
waveIds: [ 40 ],
|
||||
warehouseId: 100000,
|
||||
});
|
||||
|
||||
assert.deepEqual(capturedWaveIdsForIndexQuery, [ 40 ]);
|
||||
assert.deepEqual(capturedWaveIdsForCountQuery, [ 40 ]);
|
||||
assert.ok(!capturedWaveIdsForCountQuery.includes(999));
|
||||
assert.equal(result.waveGroups[0].platforms[0].orders[0].wave_total_orders, 66);
|
||||
});
|
||||
|
||||
it('should prefer snapshot item_name for display type 2 in getWavePlatformPrintData', async () => {
|
||||
const service = createOrderPrintServiceHarness();
|
||||
const currentOrderItemsModel = {
|
||||
@ -1132,7 +1342,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
wave_id: 31,
|
||||
wave_index: 1,
|
||||
platforms_index: 1,
|
||||
} ],
|
||||
}],
|
||||
]);
|
||||
service.queryWaveTotalOrderCountMap = async () => new Map([
|
||||
[ 31, 10 ],
|
||||
@ -1140,7 +1350,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
|
||||
service.getPolicyConfigMapByStore = async () => new Map([
|
||||
[ 1, {
|
||||
waybill_custom_display_type: '2',
|
||||
} ],
|
||||
}],
|
||||
]);
|
||||
service.loadTemplateSampleByPlatform = () => ({
|
||||
cmd: 'print',
|
||||
|
||||
145
test/app/service/systems/stock_store.outbound.picking.test.js
Normal file
145
test/app/service/systems/stock_store.outbound.picking.test.js
Normal file
@ -0,0 +1,145 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const StockStoreService = require('../../../../app/service/systems/stock_store');
|
||||
|
||||
function createHarness() {
|
||||
const stockTransactionCalls = [];
|
||||
const ctx = {
|
||||
user: {
|
||||
store_id: 100000,
|
||||
employees_id: 9001,
|
||||
employees_name: '测试用户',
|
||||
},
|
||||
model: {
|
||||
Picking: {
|
||||
async findAll() {
|
||||
return [
|
||||
{
|
||||
storage_id: 501,
|
||||
space_id: 601,
|
||||
quantity: 2,
|
||||
},
|
||||
{
|
||||
storage_id: 502,
|
||||
space_id: 602,
|
||||
quantity: 1,
|
||||
},
|
||||
];
|
||||
},
|
||||
},
|
||||
StockWarehouse: {
|
||||
async update() {
|
||||
return [ 1 ];
|
||||
},
|
||||
async findByPk() {
|
||||
return {
|
||||
id: 77,
|
||||
warehouse_id: 100000,
|
||||
quantity: 5,
|
||||
locked_quantity: 1,
|
||||
update_at: new Date('2026-05-15T08:00:00.000Z'),
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
stockTransaction: {
|
||||
async create(payload) {
|
||||
stockTransactionCalls.push(payload);
|
||||
return {
|
||||
id: stockTransactionCalls.length,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const app = {
|
||||
Sequelize: {
|
||||
Op: {
|
||||
gte: Symbol('gte'),
|
||||
},
|
||||
literal(sql) {
|
||||
return sql;
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
};
|
||||
|
||||
ctx.app = app;
|
||||
ctx.logger = app.logger;
|
||||
|
||||
const service = new StockStoreService(ctx);
|
||||
service.getItemStorages = async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
storage: {
|
||||
exists: true,
|
||||
id: 77,
|
||||
storeId: 200001,
|
||||
quantity: 10,
|
||||
lockedQuantity: 6,
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
service.getStoreWarehousePolicyConfigByStockId = async () => {
|
||||
return {
|
||||
allowOversell: false,
|
||||
};
|
||||
};
|
||||
service.clearItemStorageCache = async () => {};
|
||||
|
||||
return {
|
||||
service,
|
||||
stockTransactionCalls,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/stock_store.outbound.picking.test.js', () => {
|
||||
it('should write outbound transactions by picking rows with order and location fields', async () => {
|
||||
const { service, stockTransactionCalls } = createHarness();
|
||||
|
||||
const result = await service.outbound(1001, 5, {
|
||||
id: 'tx-1',
|
||||
}, {
|
||||
orderId: 2001,
|
||||
orderNo: 'DO-2001',
|
||||
orderItemId: 3001,
|
||||
});
|
||||
|
||||
assert.equal(result.success, true);
|
||||
assert.equal(stockTransactionCalls.length, 3);
|
||||
|
||||
assert.equal(stockTransactionCalls[0].storage_id, 501);
|
||||
assert.equal(stockTransactionCalls[0].space_id, 601);
|
||||
assert.equal(stockTransactionCalls[0].quantity, 2);
|
||||
assert.equal(stockTransactionCalls[0].order_id, 2001);
|
||||
assert.equal(stockTransactionCalls[0].order_no, 'DO-2001');
|
||||
|
||||
assert.equal(stockTransactionCalls[1].storage_id, 502);
|
||||
assert.equal(stockTransactionCalls[1].space_id, 602);
|
||||
assert.equal(stockTransactionCalls[1].quantity, 1);
|
||||
assert.equal(stockTransactionCalls[1].order_id, 2001);
|
||||
assert.equal(stockTransactionCalls[1].order_no, 'DO-2001');
|
||||
|
||||
assert.equal(stockTransactionCalls[2].storage_id, null);
|
||||
assert.equal(stockTransactionCalls[2].space_id, null);
|
||||
assert.equal(stockTransactionCalls[2].quantity, 2);
|
||||
assert.equal(stockTransactionCalls[2].order_id, 2001);
|
||||
assert.equal(stockTransactionCalls[2].order_no, 'DO-2001');
|
||||
|
||||
stockTransactionCalls.forEach(payload => {
|
||||
assert.equal(payload.store_id, 200001);
|
||||
assert.equal(payload.remark, '订单出库');
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -6,6 +6,15 @@ const StockTransactionService = require('../../../../app/service/systems/stock_t
|
||||
function createServiceHarness() {
|
||||
const calls = {
|
||||
createArgs: null,
|
||||
orderFindOneArgs: null,
|
||||
};
|
||||
|
||||
const state = {
|
||||
orderRow: {
|
||||
id: 500001,
|
||||
source_order_codes: 'SRC-ORDER-001,SRC-ORDER-002',
|
||||
wave_no: 'WAVE-001',
|
||||
},
|
||||
};
|
||||
|
||||
const model = {
|
||||
@ -21,6 +30,12 @@ function createServiceHarness() {
|
||||
};
|
||||
},
|
||||
},
|
||||
OrderDelivery: {
|
||||
async findOne(query) {
|
||||
calls.orderFindOneArgs = query;
|
||||
return state.orderRow;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
@ -35,10 +50,25 @@ function createServiceHarness() {
|
||||
return {
|
||||
service,
|
||||
calls,
|
||||
state,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/stock_transaction.create.test.js', () => {
|
||||
it('should throw error when transaction is missing', async () => {
|
||||
const { service } = createServiceHarness();
|
||||
|
||||
await assert.rejects(async () => {
|
||||
await service.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1000000,
|
||||
stock_id: 200001,
|
||||
quantity: 12,
|
||||
});
|
||||
}, /stockTransaction\.create.*transaction/);
|
||||
});
|
||||
|
||||
it('should create stock transaction with snapshot fields', async () => {
|
||||
const { service, calls } = createServiceHarness();
|
||||
const transaction = {
|
||||
@ -82,4 +112,195 @@ describe('test/app/service/systems/stock_transaction.create.test.js', () => {
|
||||
assert.equal(calls.createArgs.payload.quantity, 12);
|
||||
assert.equal(calls.createArgs.payload.transaction_type, 'INBOUND');
|
||||
});
|
||||
|
||||
it('should force inbound order_id to null when upstream passes order_id', async () => {
|
||||
const { service, calls } = createServiceHarness();
|
||||
const transaction = {
|
||||
id: 'tx-inbound-null-order-id',
|
||||
};
|
||||
|
||||
await service.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1000000,
|
||||
stock_id: 200001,
|
||||
quantity: 5,
|
||||
order_type: 'SCRK',
|
||||
order_no: 'EO-999999',
|
||||
order_id: 999999,
|
||||
remark: '入库测试',
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
assert.equal(calls.createArgs.payload.order_id, null);
|
||||
assert.equal(calls.createArgs.payload.order_no, 'EO-999999');
|
||||
assert.equal(calls.createArgs.payload.order_type, 'SCRK');
|
||||
});
|
||||
|
||||
it('should normalize outbound order fields by order id and source_order_codes', async () => {
|
||||
const { service, calls } = createServiceHarness();
|
||||
const transaction = {
|
||||
id: 'tx-2',
|
||||
};
|
||||
|
||||
await service.create({
|
||||
transaction_type: 'OUTBOUND',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1000000,
|
||||
stock_id: 200001,
|
||||
quantity: 3,
|
||||
order_type: 'STOCK_STORE_OUTBOUND',
|
||||
order_id: 500001,
|
||||
order_no: 'DO-500001',
|
||||
remark: '订单出库',
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
assert.ok(calls.orderFindOneArgs, '应查询订单来源单号用于出库流水兜底');
|
||||
assert.equal(calls.orderFindOneArgs.where.id, 500001);
|
||||
assert.equal(calls.orderFindOneArgs.transaction, transaction);
|
||||
assert.equal(calls.createArgs.payload.order_id, 500001);
|
||||
assert.equal(calls.createArgs.payload.order_no, 'SRC-ORDER-001,SRC-ORDER-002');
|
||||
assert.equal(calls.createArgs.payload.order_type, 'ORDER');
|
||||
assert.equal(calls.createArgs.payload.batch_no, 'WAVE-001');
|
||||
});
|
||||
|
||||
it('should keep non-inbound order_id unchanged for outbound transaction', async () => {
|
||||
const { service, calls } = createServiceHarness();
|
||||
const transaction = {
|
||||
id: 'tx-outbound-keep-order-id',
|
||||
};
|
||||
|
||||
await service.create({
|
||||
transaction_type: 'OUTBOUND',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1000000,
|
||||
stock_id: 200001,
|
||||
quantity: 3,
|
||||
order_type: 'STOCK_STORE_OUTBOUND',
|
||||
order_id: 500001,
|
||||
source_order_codes: 'SRC-ORDER-001,SRC-ORDER-002',
|
||||
remark: '订单出库',
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
assert.equal(calls.createArgs.payload.order_id, 500001);
|
||||
assert.equal(calls.createArgs.payload.order_type, 'ORDER');
|
||||
});
|
||||
|
||||
it('should overwrite outbound batch_no with wave_no when order has wave_no', async () => {
|
||||
const { service, calls, state } = createServiceHarness();
|
||||
const transaction = {
|
||||
id: 'tx-2-1',
|
||||
};
|
||||
|
||||
state.orderRow = {
|
||||
id: 500001,
|
||||
source_order_codes: 'SRC-ORDER-009',
|
||||
wave_no: 'WAVE-009',
|
||||
};
|
||||
|
||||
await service.create({
|
||||
transaction_type: 'OUTBOUND',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1000000,
|
||||
stock_id: 200001,
|
||||
quantity: 3,
|
||||
order_type: 'ANY_UPSTREAM_TYPE',
|
||||
order_id: 500001,
|
||||
source_order_codes: 'SRC-ORDER-009',
|
||||
batch_no: 'UPSTREAM-BATCH-009',
|
||||
remark: '订单出库',
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
assert.equal(calls.createArgs.payload.order_type, 'ORDER');
|
||||
assert.equal(calls.createArgs.payload.order_id, 500001);
|
||||
assert.equal(calls.createArgs.payload.order_no, 'SRC-ORDER-009');
|
||||
assert.equal(calls.createArgs.payload.batch_no, 'WAVE-009');
|
||||
});
|
||||
|
||||
it('should set outbound batch_no to null when order wave_no is empty', async () => {
|
||||
const { service, calls, state } = createServiceHarness();
|
||||
const transaction = {
|
||||
id: 'tx-2-1-null',
|
||||
};
|
||||
|
||||
state.orderRow = {
|
||||
id: 500001,
|
||||
source_order_codes: 'SRC-ORDER-010',
|
||||
wave_no: '',
|
||||
};
|
||||
|
||||
await service.create({
|
||||
transaction_type: 'OUTBOUND',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1000000,
|
||||
stock_id: 200001,
|
||||
quantity: 3,
|
||||
order_type: 'ORDER',
|
||||
order_id: 500001,
|
||||
source_order_codes: 'SRC-ORDER-010',
|
||||
batch_no: 'UPSTREAM-BATCH-010',
|
||||
remark: '订单出库',
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
assert.equal(calls.createArgs.payload.order_type, 'ORDER');
|
||||
assert.equal(calls.createArgs.payload.batch_no, null);
|
||||
});
|
||||
|
||||
it('should keep non-order outbound order_type unchanged', async () => {
|
||||
const { service, calls } = createServiceHarness();
|
||||
const transaction = {
|
||||
id: 'tx-2-2',
|
||||
};
|
||||
|
||||
await service.create({
|
||||
transaction_type: 'OUTBOUND',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1000000,
|
||||
stock_id: 200001,
|
||||
quantity: 2,
|
||||
order_type: 'STOCK_MOVE',
|
||||
batch_no: 'MOVE-BATCH-001',
|
||||
order_id: null,
|
||||
order_no: 'MOVE-001',
|
||||
remark: '移库出库',
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
assert.equal(calls.createArgs.payload.order_type, 'STOCK_MOVE');
|
||||
assert.equal(calls.createArgs.payload.order_no, 'MOVE-001');
|
||||
assert.equal(calls.createArgs.payload.batch_no, 'MOVE-BATCH-001');
|
||||
assert.equal(calls.orderFindOneArgs, null);
|
||||
});
|
||||
|
||||
it('should reject outbound transaction when order_id is invalid', async () => {
|
||||
const { service } = createServiceHarness();
|
||||
const transaction = {
|
||||
id: 'tx-3',
|
||||
};
|
||||
|
||||
await assert.rejects(async () => {
|
||||
await service.create({
|
||||
transaction_type: 'OUTBOUND',
|
||||
warehouse_id: 100000,
|
||||
store_id: 1000000,
|
||||
stock_id: 200001,
|
||||
quantity: 1,
|
||||
order_type: 'STOCK_STORE_OUTBOUND',
|
||||
order_id: null,
|
||||
remark: '订单出库',
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
}, /order_id 必须为订单主键 id/);
|
||||
});
|
||||
});
|
||||
|
||||
374
test/app/service/systems/storage.inventory.transfer.test.js
Normal file
374
test/app/service/systems/storage.inventory.transfer.test.js
Normal file
@ -0,0 +1,374 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const StorageInventoryService = require('../../../../app/service/systems/storage/inventory');
|
||||
|
||||
/**
|
||||
* 创建移库测试支架。
|
||||
* @return {{service: StorageInventoryService, calls: Object}} 测试支架
|
||||
*/
|
||||
function createTransferHarness() {
|
||||
const calls = {
|
||||
stockTransactions: [],
|
||||
storageUpdates: [],
|
||||
locationSpaceUpdates: [],
|
||||
commitCount: 0,
|
||||
rollbackCount: 0,
|
||||
};
|
||||
|
||||
const transaction = {
|
||||
LOCK: {
|
||||
UPDATE: 'UPDATE',
|
||||
},
|
||||
async commit() {
|
||||
calls.commitCount += 1;
|
||||
},
|
||||
async rollback() {
|
||||
calls.rollbackCount += 1;
|
||||
},
|
||||
};
|
||||
|
||||
const srcRecord = {
|
||||
id: 11,
|
||||
warehouse_id: 100000,
|
||||
store_id: 100001,
|
||||
space_id: 21,
|
||||
stock_id: 301,
|
||||
batch_no: 'BATCH-TRANSFER-001',
|
||||
inventory_type: 'ZP',
|
||||
quantity: 10,
|
||||
locked_quantity: 0,
|
||||
available_quantity: 10,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
};
|
||||
|
||||
const model = {
|
||||
async transaction() {
|
||||
return transaction;
|
||||
},
|
||||
StockWarehouse: {
|
||||
async findOne() {
|
||||
return {
|
||||
id: 301,
|
||||
quantity: 100,
|
||||
locked_quantity: 12,
|
||||
};
|
||||
},
|
||||
},
|
||||
Storage: {
|
||||
async findOne(args) {
|
||||
if (typeof args.where.id === 'number') {
|
||||
return srcRecord;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
async update(values, options) {
|
||||
calls.storageUpdates.push({ values, options });
|
||||
},
|
||||
async count() {
|
||||
return 0;
|
||||
},
|
||||
},
|
||||
LocationSpace: {
|
||||
async findOne() {
|
||||
return {
|
||||
id: 22,
|
||||
warehouse_id: 100000,
|
||||
is_enabled: true,
|
||||
space_status: 'AVAILABLE',
|
||||
space_code: 'A-22',
|
||||
};
|
||||
},
|
||||
async update(values, options) {
|
||||
calls.locationSpaceUpdates.push({ values, options });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
model,
|
||||
app: {
|
||||
Sequelize: {
|
||||
Op: {
|
||||
ne: '$ne',
|
||||
},
|
||||
literal(value) {
|
||||
return { literal: value };
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
user: {
|
||||
employees_id: 'EMP-001',
|
||||
employees_name: '测试操作员',
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
stockTransaction: {
|
||||
async create(payload, options) {
|
||||
calls.stockTransactions.push({ payload, options });
|
||||
return { id: calls.stockTransactions.length, ...payload };
|
||||
},
|
||||
},
|
||||
operationLog: {
|
||||
async createOperationLog() {},
|
||||
},
|
||||
notice: {
|
||||
async send() {},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
service: new StorageInventoryService(ctx),
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建按商品移库测试支架。
|
||||
* @return {{service: StorageInventoryService, calls: Object}} 测试支架
|
||||
*/
|
||||
function createTransferByProductHarness() {
|
||||
const calls = {
|
||||
stockTransactions: [],
|
||||
storageUpdates: [],
|
||||
storageCreates: [],
|
||||
locationSpaceUpdates: [],
|
||||
commitCount: 0,
|
||||
rollbackCount: 0,
|
||||
};
|
||||
|
||||
const transaction = {
|
||||
LOCK: {
|
||||
UPDATE: 'UPDATE',
|
||||
},
|
||||
async commit() {
|
||||
calls.commitCount += 1;
|
||||
},
|
||||
async rollback() {
|
||||
calls.rollbackCount += 1;
|
||||
},
|
||||
};
|
||||
|
||||
const srcRecords = [
|
||||
{
|
||||
id: 101,
|
||||
warehouse_id: 100000,
|
||||
store_id: 100001,
|
||||
space_id: 21,
|
||||
stock_id: 301,
|
||||
batch_no: null,
|
||||
inventory_type: 'ZP',
|
||||
quantity: 2,
|
||||
locked_quantity: 0,
|
||||
available_quantity: 2,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
},
|
||||
{
|
||||
id: 102,
|
||||
warehouse_id: 100000,
|
||||
store_id: 100001,
|
||||
space_id: 21,
|
||||
stock_id: 301,
|
||||
batch_no: null,
|
||||
inventory_type: 'ZP',
|
||||
quantity: 4,
|
||||
locked_quantity: 0,
|
||||
available_quantity: 4,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
},
|
||||
];
|
||||
|
||||
const model = {
|
||||
async transaction() {
|
||||
return transaction;
|
||||
},
|
||||
StockWarehouse: {
|
||||
async findOne() {
|
||||
return {
|
||||
id: 301,
|
||||
is_batch_mgmt: 'N',
|
||||
quantity: 50,
|
||||
locked_quantity: 7,
|
||||
};
|
||||
},
|
||||
},
|
||||
Storage: {
|
||||
async findAll() {
|
||||
return srcRecords;
|
||||
},
|
||||
async findOne() {
|
||||
return null;
|
||||
},
|
||||
async update(values, options) {
|
||||
calls.storageUpdates.push({ values, options });
|
||||
},
|
||||
async create(payload) {
|
||||
const created = {
|
||||
id: 900 + calls.storageCreates.length + 1,
|
||||
...payload,
|
||||
};
|
||||
calls.storageCreates.push(created);
|
||||
return created;
|
||||
},
|
||||
async count(options) {
|
||||
if (options.where.space_id === 22) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
},
|
||||
},
|
||||
LocationSpace: {
|
||||
async findOne() {
|
||||
return {
|
||||
id: 22,
|
||||
warehouse_id: 100000,
|
||||
is_enabled: true,
|
||||
space_status: 'AVAILABLE',
|
||||
space_code: 'A-22',
|
||||
};
|
||||
},
|
||||
async update(values, options) {
|
||||
calls.locationSpaceUpdates.push({ values, options });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
model,
|
||||
app: {
|
||||
Sequelize: {
|
||||
Op: {
|
||||
ne: '$ne',
|
||||
},
|
||||
literal(value) {
|
||||
return { literal: value };
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
user: {
|
||||
employees_id: 'EMP-001',
|
||||
employees_name: '测试操作员',
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
stockTransaction: {
|
||||
async create(payload, options) {
|
||||
calls.stockTransactions.push({ payload, options });
|
||||
return { id: calls.stockTransactions.length, ...payload };
|
||||
},
|
||||
},
|
||||
operationLog: {
|
||||
async createOperationLog() {},
|
||||
},
|
||||
notice: {
|
||||
async send() {},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
service: new StorageInventoryService(ctx),
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/storage.inventory.transfer.test.js', () => {
|
||||
it('should create TRANSFER_OUT and TRANSFER_IN transactions in transferLocation', async () => {
|
||||
const { service, calls } = createTransferHarness();
|
||||
|
||||
const result = await service.transferLocation({
|
||||
storage_id: 11,
|
||||
target_space_id: 22,
|
||||
quantity: 10,
|
||||
});
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(calls.commitCount, 1);
|
||||
assert.equal(calls.rollbackCount, 0);
|
||||
assert.equal(calls.stockTransactions.length, 2);
|
||||
|
||||
const transferOut = calls.stockTransactions[0];
|
||||
const transferIn = calls.stockTransactions[1];
|
||||
|
||||
assert.equal(transferOut.payload.transaction_type, 'TRANSFER_OUT');
|
||||
assert.equal(transferOut.payload.storage_id, 11);
|
||||
assert.equal(transferOut.payload.space_id, 21);
|
||||
assert.equal(transferOut.payload.quantity, 10);
|
||||
assert.equal(transferOut.payload.before_quantity, 100);
|
||||
assert.equal(transferOut.payload.after_quantity, 100);
|
||||
assert.equal(transferOut.payload.before_locked_quantity, 12);
|
||||
assert.equal(transferOut.payload.after_locked_quantity, 12);
|
||||
assert.equal(transferOut.payload.order_id, null);
|
||||
assert.equal(transferOut.payload.order_no, null);
|
||||
assert.equal(transferOut.payload.order_type, null);
|
||||
assert.equal(transferOut.payload.remark, '移库出');
|
||||
|
||||
assert.equal(transferIn.payload.transaction_type, 'TRANSFER_IN');
|
||||
assert.equal(transferIn.payload.storage_id, 11);
|
||||
assert.equal(transferIn.payload.space_id, 22);
|
||||
assert.equal(transferIn.payload.quantity, 10);
|
||||
assert.equal(transferIn.payload.before_quantity, 100);
|
||||
assert.equal(transferIn.payload.after_quantity, 100);
|
||||
assert.equal(transferIn.payload.before_locked_quantity, 12);
|
||||
assert.equal(transferIn.payload.after_locked_quantity, 12);
|
||||
assert.equal(transferIn.payload.order_id, null);
|
||||
assert.equal(transferIn.payload.order_no, null);
|
||||
assert.equal(transferIn.payload.order_type, null);
|
||||
assert.equal(transferIn.payload.remark, '移库入');
|
||||
});
|
||||
|
||||
it('should create TRANSFER_OUT and TRANSFER_IN transactions in transferByProduct for each toTransfer', async () => {
|
||||
const { service, calls } = createTransferByProductHarness();
|
||||
|
||||
const result = await service.transferByProduct({
|
||||
space_id: 21,
|
||||
stock_id: 301,
|
||||
target_space_id: 22,
|
||||
quantity: 5,
|
||||
});
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(calls.commitCount, 1);
|
||||
assert.equal(calls.rollbackCount, 0);
|
||||
assert.equal(calls.stockTransactions.length, 4);
|
||||
|
||||
const transferOutTransactions = calls.stockTransactions.filter((item) => item.payload.transaction_type === 'TRANSFER_OUT');
|
||||
const transferInTransactions = calls.stockTransactions.filter((item) => item.payload.transaction_type === 'TRANSFER_IN');
|
||||
|
||||
assert.equal(transferOutTransactions.length, 2);
|
||||
assert.equal(transferInTransactions.length, 2);
|
||||
|
||||
const outTotalQuantity = transferOutTransactions.reduce((sum, item) => sum + Number(item.payload.quantity || 0), 0);
|
||||
const inTotalQuantity = transferInTransactions.reduce((sum, item) => sum + Number(item.payload.quantity || 0), 0);
|
||||
assert.equal(outTotalQuantity, 5);
|
||||
assert.equal(inTotalQuantity, 5);
|
||||
|
||||
for (const tx of calls.stockTransactions) {
|
||||
assert.equal(tx.payload.before_quantity, tx.payload.after_quantity);
|
||||
assert.equal(tx.payload.before_locked_quantity, tx.payload.after_locked_quantity);
|
||||
assert.equal(tx.payload.before_quantity, 50);
|
||||
assert.equal(tx.payload.after_quantity, 50);
|
||||
assert.equal(tx.payload.before_locked_quantity, 7);
|
||||
assert.equal(tx.payload.after_locked_quantity, 7);
|
||||
assert.equal(tx.payload.order_id, null);
|
||||
assert.equal(tx.payload.order_no, null);
|
||||
assert.equal(tx.payload.order_type, null);
|
||||
}
|
||||
});
|
||||
});
|
||||
764
test/app/service/systems/storage.report.test.js
Normal file
764
test/app/service/systems/storage.report.test.js
Normal file
@ -0,0 +1,764 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const StorageReportService = require('../../../../app/service/systems/storage/report');
|
||||
const StorageReportMethodService = require('../../../../app/service/systemMethods/storage/report');
|
||||
|
||||
/**
|
||||
* 构建 storage.report service 测试桩。
|
||||
* @param {Object} options 自定义参数
|
||||
* @return {{service: StorageReportService, calls: Object}} service 与调用记录
|
||||
*/
|
||||
function createReportServiceHarness(options = {}) {
|
||||
const calls = {
|
||||
queries: [],
|
||||
exports: [],
|
||||
};
|
||||
let queryIndex = 0;
|
||||
const queryResults = Array.isArray(options.queryResults) ? options.queryResults : [];
|
||||
|
||||
const model = {
|
||||
async query(sql, queryOptions = {}) {
|
||||
calls.queries.push({
|
||||
sql,
|
||||
options: queryOptions,
|
||||
});
|
||||
const result = queryResults[queryIndex] || [];
|
||||
queryIndex += 1;
|
||||
return result;
|
||||
},
|
||||
StockWarehouse: {
|
||||
async findAll() {
|
||||
return options.stockRows || [];
|
||||
},
|
||||
},
|
||||
StockBarcode: {
|
||||
async findAll() {
|
||||
return options.barcodeRows || [];
|
||||
},
|
||||
},
|
||||
Store: {
|
||||
async findAll() {
|
||||
return options.storeRows || [];
|
||||
},
|
||||
},
|
||||
LocationSpace: {
|
||||
async findAll() {
|
||||
return options.spaceRows || [];
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
store_id: options.warehouseId || 100000,
|
||||
},
|
||||
model,
|
||||
app: {
|
||||
Sequelize: {
|
||||
QueryTypes: {
|
||||
SELECT: 'SELECT',
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
excel: {
|
||||
async generateAndUpload(exportOptions) {
|
||||
calls.exports.push(exportOptions);
|
||||
return {
|
||||
filename: exportOptions.filename,
|
||||
fileKey: `exports/mock/${exportOptions.filename}`,
|
||||
url: `https://cdn.example.com/${exportOptions.filename}`,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
service: new StorageReportService(ctx),
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建 storage.report method 测试桩。
|
||||
* @param {Object} options 自定义参数
|
||||
* @return {{methodService: StorageReportMethodService, captured: Object, cacheStore: Map<string, Object>}} method 与调用记录
|
||||
*/
|
||||
function createReportMethodHarness(options = {}) {
|
||||
const captured = {
|
||||
exportCalls: [],
|
||||
};
|
||||
const cacheStore = new Map();
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
Sequelize: {
|
||||
Op: {},
|
||||
},
|
||||
async setCacheAsync(cacheKey, value) {
|
||||
cacheStore.set(cacheKey, value);
|
||||
},
|
||||
async getCacheAsync(cacheKey) {
|
||||
return cacheStore.get(cacheKey);
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
storage: {
|
||||
report: {
|
||||
async export(startTime, endTime, bySpace, storeIds, sort) {
|
||||
captured.exportCalls.push({
|
||||
startTime,
|
||||
endTime,
|
||||
bySpace,
|
||||
storeIds,
|
||||
sort,
|
||||
});
|
||||
return options.exportResult || {
|
||||
filename: '库存报表_20260501_20260502.xlsx',
|
||||
fileKey: 'exports/mock/库存报表_20260501_20260502.xlsx',
|
||||
url: 'https://cdn.example.com/库存报表_20260501_20260502.xlsx',
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
user: {
|
||||
store_id: options.warehouseId || 100000,
|
||||
},
|
||||
};
|
||||
|
||||
const methodService = new StorageReportMethodService(ctx);
|
||||
methodService.prepareWhereContext = function prepareWhereContext() {
|
||||
return {
|
||||
whereValue: {
|
||||
start_time: '2026-05-01 00:00:00',
|
||||
end_time: '2026-05-02 23:59:59',
|
||||
by_space: false,
|
||||
store_ids: [ 33, 44 ],
|
||||
sort_field: 'inbound_total',
|
||||
sort_order: 'ASC',
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
methodService,
|
||||
captured,
|
||||
cacheStore,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/storage.report.test.js', () => {
|
||||
it('should use last pre-start after and last in-range after by stock+store when by_space is false', async () => {
|
||||
const { service, calls } = createReportServiceHarness({
|
||||
queryResults: [
|
||||
[
|
||||
{ stock_id: 101, store_id: 201, quantity: 99 },
|
||||
{ stock_id: 102, store_id: 202, quantity: 88 },
|
||||
],
|
||||
[
|
||||
{ stock_id: 101, space_id: 11, store_id: 201, inbound_total: 5, outbound_total: 2 },
|
||||
{ stock_id: 101, space_id: 12, store_id: 201, inbound_total: 3, outbound_total: 1 },
|
||||
{ stock_id: 102, space_id: 13, store_id: 202, inbound_total: 4, outbound_total: 0 },
|
||||
],
|
||||
[
|
||||
{ id: 1, stock_id: 101, space_id: 11, storage_id: 9001, store_id: 201, before_quantity: 50, after_quantity: 55, created_at: '2026-05-01 09:00:00' },
|
||||
{ id: 2, stock_id: 101, space_id: 12, storage_id: 9009, store_id: 201, before_quantity: 55, after_quantity: 60, created_at: '2026-05-01 10:00:00' },
|
||||
{ id: 3, stock_id: 101, space_id: 11, storage_id: 9010, store_id: 201, before_quantity: 60, after_quantity: 66, created_at: '2026-05-02 12:00:00' },
|
||||
{ id: 4, stock_id: 102, space_id: 13, storage_id: 9003, store_id: 202, before_quantity: 3, after_quantity: 4, created_at: '2026-05-02 14:00:00' },
|
||||
],
|
||||
[
|
||||
{ id: 10, stock_id: 101, space_id: 11, store_id: 201, after_quantity: 47, created_at: '2026-04-30 09:00:00' },
|
||||
{ id: 11, stock_id: 101, space_id: 12, store_id: 201, after_quantity: 48, created_at: '2026-04-30 23:00:00' },
|
||||
{ id: 12, stock_id: 102, space_id: 13, store_id: 202, after_quantity: 2, created_at: '2026-04-30 20:00:00' },
|
||||
],
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 101, item_name: '商品A', item_code: 'SKU-A' },
|
||||
{ id: 102, item_name: '商品B', item_code: 'SKU-B' },
|
||||
],
|
||||
barcodeRows: [
|
||||
{ stock_id: 101, barcode: 'BC-A-1' },
|
||||
{ stock_id: 101, barcode: 'BC-A-2' },
|
||||
{ stock_id: 102, barcode: 'BC-B-1' },
|
||||
],
|
||||
storeRows: [
|
||||
{ id: 201, company_name: '货主甲' },
|
||||
{ id: 202, company_name: '货主乙' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.search('2026-05-01 00:00:00', '2026-05-02 23:59:59', false, [ 201, 202 ]);
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(result.data.list.length, 2);
|
||||
|
||||
const stockA = result.data.list.find(item => item.stock_id === 101 && item.store_id === 201);
|
||||
assert.ok(stockA);
|
||||
assert.equal(stockA.begin_total, 48);
|
||||
assert.equal(stockA.end_total, 66);
|
||||
assert.equal(stockA.inbound_total, 8);
|
||||
assert.equal(stockA.outbound_total, 3);
|
||||
assert.notEqual(stockA.begin_total, 50);
|
||||
assert.equal(stockA.space_id, undefined);
|
||||
assert.match(stockA.barcode, /BC-A-1/);
|
||||
assert.match(stockA.barcode, /BC-A-2/);
|
||||
|
||||
const stockB = result.data.list.find(item => item.stock_id === 102 && item.store_id === 202);
|
||||
assert.ok(stockB);
|
||||
assert.equal(stockB.begin_total, 2);
|
||||
assert.equal(stockB.end_total, 4);
|
||||
assert.equal(stockB.inbound_total, 4);
|
||||
assert.equal(stockB.outbound_total, 0);
|
||||
assert.match(calls.queries[2].sql, /before_quantity/);
|
||||
assert.doesNotMatch(calls.queries[2].sql, /storage_id/);
|
||||
assert.match(calls.queries[3].sql, /created_at < :startTime/);
|
||||
assert.match(calls.queries[3].sql, /after_quantity/);
|
||||
});
|
||||
|
||||
it('should keep space dimension with pre-start-last-after for begin and in-range-last-after for end', async () => {
|
||||
const { service } = createReportServiceHarness({
|
||||
queryResults: [
|
||||
[
|
||||
{ stock_id: 301, space_id: 501, store_id: 401, quantity: 7 },
|
||||
{ stock_id: 301, space_id: 502, store_id: 401, quantity: 11 },
|
||||
],
|
||||
[
|
||||
{ stock_id: 301, space_id: 501, store_id: 401, inbound_total: 2, outbound_total: 1 },
|
||||
{ stock_id: 301, space_id: 502, store_id: 401, inbound_total: 3, outbound_total: 0 },
|
||||
],
|
||||
[
|
||||
{ id: 1, stock_id: 301, space_id: 501, storage_id: 8801, store_id: 401, before_quantity: 7, after_quantity: 8, created_at: '2026-05-01 09:00:00' },
|
||||
{ id: 2, stock_id: 301, space_id: 501, storage_id: 8802, store_id: 401, before_quantity: 8, after_quantity: 10, created_at: '2026-05-01 12:00:00' },
|
||||
{ id: 3, stock_id: 301, space_id: 502, storage_id: 8803, store_id: 401, before_quantity: 11, after_quantity: 12, created_at: '2026-05-01 10:00:00' },
|
||||
],
|
||||
[
|
||||
{ id: 10, stock_id: 301, space_id: 501, store_id: 401, after_quantity: 6, created_at: '2026-04-30 23:00:00' },
|
||||
{ id: 11, stock_id: 301, space_id: 502, store_id: 401, after_quantity: 10, created_at: '2026-04-30 22:00:00' },
|
||||
],
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 301, item_name: '商品C', item_code: 'SKU-C' },
|
||||
],
|
||||
barcodeRows: [
|
||||
{ stock_id: 301, barcode: 'BC-C-1' },
|
||||
],
|
||||
storeRows: [
|
||||
{ id: 401, company_name: '货主丙' },
|
||||
],
|
||||
spaceRows: [
|
||||
{ id: 501, custom_name: '高位货架', space_code: 'A-01' },
|
||||
{ id: 502, custom_name: '', space_code: 'B-02' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.search('2026-05-01 00:00:00', '2026-05-01 23:59:59', true, [ 401 ]);
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(result.data.list.length, 2);
|
||||
|
||||
const spaceA = result.data.list.find(item => item.space_id === 501);
|
||||
const spaceB = result.data.list.find(item => item.space_id === 502);
|
||||
assert.ok(spaceA);
|
||||
assert.ok(spaceB);
|
||||
assert.equal(spaceA.space_name, '高位货架');
|
||||
assert.equal(spaceB.space_name, 'B-02');
|
||||
assert.equal(spaceA.begin_total, 6);
|
||||
assert.equal(spaceA.end_total, 10);
|
||||
assert.equal(spaceB.begin_total, 10);
|
||||
assert.equal(spaceB.end_total, 12);
|
||||
});
|
||||
|
||||
it('should return base space keys with zero fallback when by_space is true and interval has no transactions', async () => {
|
||||
const { service } = createReportServiceHarness({
|
||||
queryResults: [
|
||||
[
|
||||
{ stock_id: 901, space_id: 301, store_id: 701, quantity: 15 },
|
||||
{ stock_id: 902, space_id: 302, store_id: 701, quantity: 9 },
|
||||
],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 901, item_name: '商品M', item_code: 'SKU-M' },
|
||||
{ id: 902, item_name: '商品N', item_code: 'SKU-N' },
|
||||
],
|
||||
storeRows: [
|
||||
{ id: 701, company_name: '货主M' },
|
||||
],
|
||||
spaceRows: [
|
||||
{ id: 301, custom_name: '一号位', space_code: 'A-01' },
|
||||
{ id: 302, custom_name: '', space_code: 'A-02' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.search(
|
||||
'2026-05-10 00:00:00',
|
||||
'2026-05-10 23:59:59',
|
||||
true,
|
||||
[],
|
||||
{
|
||||
sortField: 'begin_total',
|
||||
sortOrder: 'DESC',
|
||||
}
|
||||
);
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(result.data.list.length, 2);
|
||||
|
||||
assert.deepEqual(result.data.list[0], {
|
||||
start_time: '2026-05-10 00:00:00',
|
||||
end_time: '2026-05-10 23:59:59',
|
||||
stock_id: 901,
|
||||
store_id: 701,
|
||||
space_id: 301,
|
||||
begin_total: 0,
|
||||
end_total: 0,
|
||||
inbound_total: 0,
|
||||
outbound_total: 0,
|
||||
store_name: '货主M',
|
||||
item_name: '商品M',
|
||||
barcode: '',
|
||||
item_code: 'SKU-M',
|
||||
space_name: '一号位',
|
||||
});
|
||||
|
||||
assert.deepEqual(result.data.list[1], {
|
||||
start_time: '2026-05-10 00:00:00',
|
||||
end_time: '2026-05-10 23:59:59',
|
||||
stock_id: 902,
|
||||
store_id: 701,
|
||||
space_id: 302,
|
||||
begin_total: 0,
|
||||
end_total: 0,
|
||||
inbound_total: 0,
|
||||
outbound_total: 0,
|
||||
store_name: '货主M',
|
||||
item_name: '商品N',
|
||||
barcode: '',
|
||||
item_code: 'SKU-N',
|
||||
space_name: 'A-02',
|
||||
});
|
||||
});
|
||||
|
||||
it('should return base stocks with zero fallback when by_space is false and interval has no transactions', async () => {
|
||||
const { service, calls } = createReportServiceHarness({
|
||||
queryResults: [
|
||||
[
|
||||
{ stock_id: 701, store_id: 901, quantity: 37 },
|
||||
],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 701, item_name: '商品X', item_code: 'SKU-X' },
|
||||
],
|
||||
storeRows: [
|
||||
{ id: 901, company_name: '货主X' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.search('2026-05-10 00:00:00', '2026-05-10 23:59:59', false, [ 901 ]);
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(result.data.list.length, 1);
|
||||
assert.deepEqual(result.data.list[0], {
|
||||
start_time: '2026-05-10 00:00:00',
|
||||
end_time: '2026-05-10 23:59:59',
|
||||
stock_id: 701,
|
||||
store_id: 901,
|
||||
begin_total: 0,
|
||||
end_total: 0,
|
||||
inbound_total: 0,
|
||||
outbound_total: 0,
|
||||
store_name: '货主X',
|
||||
item_name: '商品X',
|
||||
barcode: '',
|
||||
item_code: 'SKU-X',
|
||||
});
|
||||
assert.equal(calls.queries.length, 4);
|
||||
assert.match(calls.queries[1].sql, /created_at >= :startTime/);
|
||||
assert.match(calls.queries[1].sql, /created_at <= :endTime/);
|
||||
assert.deepEqual(calls.queries[1].options.replacements.storeIds, [ 901 ]);
|
||||
assert.match(calls.queries[3].sql, /created_at < :startTime/);
|
||||
});
|
||||
|
||||
it('should sort by end_total in DESC order when sort params are valid', async () => {
|
||||
const { service } = createReportServiceHarness({
|
||||
queryResults: [
|
||||
[
|
||||
{ stock_id: 801, store_id: 901, quantity: 10 },
|
||||
{ stock_id: 802, store_id: 901, quantity: 20 },
|
||||
],
|
||||
[
|
||||
{ stock_id: 801, space_id: 0, store_id: 901, inbound_total: 1, outbound_total: 0 },
|
||||
{ stock_id: 802, space_id: 0, store_id: 901, inbound_total: 2, outbound_total: 0 },
|
||||
],
|
||||
[
|
||||
{ id: 1, stock_id: 801, space_id: 0, storage_id: 9101, store_id: 901, before_quantity: 10, after_quantity: 11, created_at: '2026-05-01 12:00:00' },
|
||||
{ id: 2, stock_id: 802, space_id: 0, storage_id: 9102, store_id: 901, before_quantity: 20, after_quantity: 22, created_at: '2026-05-01 12:00:00' },
|
||||
],
|
||||
[],
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 801, item_name: '商品Y', item_code: 'SKU-Y' },
|
||||
{ id: 802, item_name: '商品Z', item_code: 'SKU-Z' },
|
||||
],
|
||||
storeRows: [
|
||||
{ id: 901, company_name: '货主Y' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.search(
|
||||
'2026-05-01 00:00:00',
|
||||
'2026-05-01 23:59:59',
|
||||
false,
|
||||
[ 901 ],
|
||||
{
|
||||
sortField: 'end_total',
|
||||
sortOrder: 'DESC',
|
||||
}
|
||||
);
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(result.data.list.length, 2);
|
||||
assert.equal(result.data.list[0].stock_id, 802);
|
||||
assert.equal(result.data.list[0].end_total, 22);
|
||||
assert.equal(result.data.list[1].stock_id, 801);
|
||||
assert.equal(result.data.list[1].end_total, 11);
|
||||
});
|
||||
|
||||
it('should pass destructured where params from method layer to systems layer', async () => {
|
||||
const captured = {
|
||||
startTime: null,
|
||||
endTime: null,
|
||||
bySpace: null,
|
||||
storeIds: null,
|
||||
sort: null,
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
Sequelize: {
|
||||
Op: {},
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
storage: {
|
||||
report: {
|
||||
async search(startTime, endTime, bySpace, storeIds, sort) {
|
||||
captured.startTime = startTime;
|
||||
captured.endTime = endTime;
|
||||
captured.bySpace = bySpace;
|
||||
captured.storeIds = storeIds;
|
||||
captured.sort = sort;
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: [] },
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
user: {
|
||||
store_id: 100000,
|
||||
},
|
||||
};
|
||||
|
||||
const methodService = new StorageReportMethodService(ctx);
|
||||
methodService.prepareWhereContext = function prepareWhereContext() {
|
||||
return {
|
||||
whereValue: {
|
||||
start_time: '2026-05-01 00:00:00',
|
||||
end_time: '2026-05-02 23:59:59',
|
||||
by_space: true,
|
||||
store_ids: [ 11, 22 ],
|
||||
sort_field: 'begin_total',
|
||||
sort_order: 'asc',
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const result = await methodService.search({
|
||||
sort: {
|
||||
sort_field: 'end_total',
|
||||
sort_order: 'desc',
|
||||
},
|
||||
where: {
|
||||
start_time: 'ignored',
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(captured.startTime, '2026-05-01 00:00:00');
|
||||
assert.equal(captured.endTime, '2026-05-02 23:59:59');
|
||||
assert.equal(captured.bySpace, true);
|
||||
assert.deepEqual(captured.storeIds, [ 11, 22 ]);
|
||||
assert.deepEqual(captured.sort, {
|
||||
sortField: 'end_total',
|
||||
sortOrder: 'desc',
|
||||
});
|
||||
});
|
||||
|
||||
it('should submit export task and return task_id with submitted status', async () => {
|
||||
const { methodService } = createReportMethodHarness();
|
||||
|
||||
const result = await methodService.export({
|
||||
sort: {
|
||||
sort_field: 'end_total',
|
||||
sort_order: 'desc',
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.code, 1);
|
||||
assert.ok(result.task_id);
|
||||
assert.equal(result.status, 'submitted');
|
||||
assert.equal(result.progress, 0);
|
||||
});
|
||||
|
||||
it('should return success progress and download_url after setImmediate task execution', async () => {
|
||||
const { methodService, captured } = createReportMethodHarness();
|
||||
|
||||
const submitResult = await methodService.export({
|
||||
sort: {
|
||||
sort_field: 'end_total',
|
||||
sort_order: 'desc',
|
||||
},
|
||||
});
|
||||
const taskId = submitResult.task_id;
|
||||
assert.ok(taskId);
|
||||
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
const progressResult = await methodService.exportTaskProgress({
|
||||
task_id: taskId,
|
||||
});
|
||||
|
||||
assert.equal(progressResult.flag, 'success');
|
||||
assert.equal(progressResult.code, 1);
|
||||
assert.equal(progressResult.task_id, taskId);
|
||||
assert.equal(progressResult.status, 'success');
|
||||
assert.equal(progressResult.progress, 100);
|
||||
assert.equal(progressResult.download_url, 'https://cdn.example.com/库存报表_20260501_20260502.xlsx');
|
||||
assert.equal(captured.exportCalls.length, 1);
|
||||
assert.equal(captured.exportCalls[0].startTime, '2026-05-01 00:00:00');
|
||||
assert.equal(captured.exportCalls[0].endTime, '2026-05-02 23:59:59');
|
||||
assert.equal(captured.exportCalls[0].bySpace, false);
|
||||
assert.deepEqual(captured.exportCalls[0].storeIds, [ 33, 44 ]);
|
||||
assert.deepEqual(captured.exportCalls[0].sort, {
|
||||
sortField: 'end_total',
|
||||
sortOrder: 'desc',
|
||||
});
|
||||
});
|
||||
|
||||
it('should return not_found when task_id does not exist', async () => {
|
||||
const { methodService } = createReportMethodHarness();
|
||||
|
||||
const result = await methodService.exportTaskProgress({
|
||||
task_id: 'not_exists_task_id',
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.code, 1);
|
||||
assert.equal(result.task_id, 'not_exists_task_id');
|
||||
assert.equal(result.status, 'not_found');
|
||||
assert.equal(result.progress, 0);
|
||||
assert.equal(result.download_url, '');
|
||||
});
|
||||
|
||||
it('should export summary and transaction sheets with readable detail fields', async () => {
|
||||
const { service, calls } = createReportServiceHarness({
|
||||
queryResults: [
|
||||
[
|
||||
{ stock_id: 701, store_id: 901, quantity: 37 },
|
||||
],
|
||||
[
|
||||
{ stock_id: 701, space_id: 0, store_id: 901, inbound_total: 2, outbound_total: 1 },
|
||||
],
|
||||
[
|
||||
{ id: 1, stock_id: 701, space_id: 0, storage_id: 5001, store_id: 901, before_quantity: 10, after_quantity: 11, created_at: '2026-05-01 12:00:00' },
|
||||
],
|
||||
[
|
||||
{ id: 10, stock_id: 701, space_id: 0, store_id: 901, after_quantity: 9, created_at: '2026-04-30 23:00:00' },
|
||||
],
|
||||
[
|
||||
{
|
||||
id: 1001,
|
||||
created_at: '2026-05-01 12:00:00',
|
||||
transaction_type: ' inbound ',
|
||||
store_id: 901,
|
||||
stock_id: 701,
|
||||
space_id: 301,
|
||||
quantity: 2,
|
||||
before_quantity: 10,
|
||||
after_quantity: 12,
|
||||
before_locked_quantity: 1,
|
||||
after_locked_quantity: 1,
|
||||
batch_no: 'BATCH-001',
|
||||
inventory_type: 'ZP',
|
||||
order_type: 'SCRK',
|
||||
order_no: 'RK20260501001',
|
||||
order_id: 6001,
|
||||
receiving_id: 7001,
|
||||
entry_order_id: 8001,
|
||||
operator_name: '张三',
|
||||
remark: '测试备注',
|
||||
},
|
||||
{
|
||||
id: 1002,
|
||||
created_at: '2026-05-01 12:30:00',
|
||||
transaction_type: ' transfer_out ',
|
||||
store_id: 901,
|
||||
stock_id: 701,
|
||||
space_id: 301,
|
||||
quantity: 1,
|
||||
before_quantity: 12,
|
||||
after_quantity: 12,
|
||||
before_locked_quantity: 0,
|
||||
after_locked_quantity: 0,
|
||||
batch_no: 'BATCH-001',
|
||||
inventory_type: 'ZP',
|
||||
order_type: null,
|
||||
order_no: null,
|
||||
order_id: null,
|
||||
receiving_id: null,
|
||||
entry_order_id: null,
|
||||
operator_name: '张三',
|
||||
remark: '移库出',
|
||||
},
|
||||
{
|
||||
id: 1003,
|
||||
created_at: '2026-05-01 12:31:00',
|
||||
transaction_type: 'transfer_in',
|
||||
store_id: 901,
|
||||
stock_id: 701,
|
||||
space_id: 301,
|
||||
quantity: 1,
|
||||
before_quantity: 15,
|
||||
after_quantity: 15,
|
||||
before_locked_quantity: 0,
|
||||
after_locked_quantity: 0,
|
||||
batch_no: 'BATCH-001',
|
||||
inventory_type: 'ZP',
|
||||
order_type: null,
|
||||
order_no: null,
|
||||
order_id: null,
|
||||
receiving_id: null,
|
||||
entry_order_id: null,
|
||||
operator_name: '张三',
|
||||
remark: '移库入',
|
||||
},
|
||||
{
|
||||
id: 1004,
|
||||
created_at: '2026-05-01 12:32:00',
|
||||
transaction_type: ' custom_type ',
|
||||
store_id: 901,
|
||||
stock_id: 701,
|
||||
space_id: 301,
|
||||
quantity: 1,
|
||||
before_quantity: 15,
|
||||
after_quantity: 16,
|
||||
before_locked_quantity: 0,
|
||||
after_locked_quantity: 0,
|
||||
batch_no: 'BATCH-001',
|
||||
inventory_type: 'ZP',
|
||||
order_type: null,
|
||||
order_no: null,
|
||||
order_id: null,
|
||||
receiving_id: null,
|
||||
entry_order_id: null,
|
||||
operator_name: '张三',
|
||||
remark: '未知类型',
|
||||
},
|
||||
],
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 701, item_name: '商品X', item_code: 'SKU-X' },
|
||||
],
|
||||
barcodeRows: [
|
||||
{ stock_id: 701, barcode: 'BC-X-1' },
|
||||
],
|
||||
storeRows: [
|
||||
{ id: 901, company_name: '货主X' },
|
||||
],
|
||||
spaceRows: [
|
||||
{ id: 301, custom_name: 'A01位', space_code: 'A-01' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.export(
|
||||
'2026-05-01 00:00:00',
|
||||
'2026-05-01 23:59:59',
|
||||
false,
|
||||
[ 901 ],
|
||||
{
|
||||
sortField: 'end_total',
|
||||
sortOrder: 'DESC',
|
||||
}
|
||||
);
|
||||
|
||||
assert.ok(result.filename.endsWith('.xlsx'));
|
||||
assert.ok(result.fileKey);
|
||||
assert.ok(result.url);
|
||||
assert.equal(calls.exports.length, 1);
|
||||
|
||||
const exportPayload = calls.exports[0];
|
||||
assert.equal(exportPayload.sheets.length, 2);
|
||||
assert.equal(exportPayload.sheets[0].name, '汇总');
|
||||
assert.equal(exportPayload.sheets[1].name, '变更记录');
|
||||
|
||||
assert.equal(exportPayload.sheets[0].rows.length, 1);
|
||||
assert.equal(exportPayload.sheets[0].rows[0].stock_id, 701);
|
||||
assert.equal(exportPayload.sheets[0].rows[0].store_name, '货主X');
|
||||
|
||||
assert.equal(exportPayload.sheets[1].rows.length, 4);
|
||||
const detailRow = exportPayload.sheets[1].rows[0];
|
||||
assert.equal(detailRow.transaction_type, '入库');
|
||||
assert.equal(detailRow.store_name, '货主X');
|
||||
assert.equal(detailRow.item_code, 'SKU-X');
|
||||
assert.equal(detailRow.item_name, '商品X');
|
||||
assert.equal(detailRow.barcode, 'BC-X-1');
|
||||
assert.equal(detailRow.space_name, 'A01位');
|
||||
assert.equal(detailRow.quantity, 2);
|
||||
assert.equal(detailRow.before_locked_quantity, 1);
|
||||
assert.equal(detailRow.after_locked_quantity, 1);
|
||||
assert.equal(detailRow.order_no, 'RK20260501001');
|
||||
assert.equal(detailRow.operator_name, '张三');
|
||||
|
||||
const transferOutRow = exportPayload.sheets[1].rows[1];
|
||||
const transferInRow = exportPayload.sheets[1].rows[2];
|
||||
const unknownTypeRow = exportPayload.sheets[1].rows[3];
|
||||
assert.equal(transferOutRow.transaction_type, '移库出');
|
||||
assert.equal(transferInRow.transaction_type, '移库入');
|
||||
assert.equal(unknownTypeRow.transaction_type, 'custom_type');
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user