This commit is contained in:
liufumingren 2026-05-20 16:31:29 +08:00
parent b629b59d4b
commit 8cf2c5befa
38 changed files with 4128 additions and 89 deletions

View File

@ -148,6 +148,21 @@ function buildSequelizeCondition(fieldKey, condition, app) {
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}%` } } };
case 'notlike':
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {
ok: true,
condition: {
[Sequelize.Op.and]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.notLike]: `%${val}%`,
},
})),
},
};
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notLike]: `%${processedValue}%` } } };
case 'startswith':
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {

View File

@ -137,6 +137,12 @@ module.exports = app => {
allowNull: true,
comment: 'ERP备注',
},
expense_record: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '费用是否记录',
},
store_name: {
type: STRING(200),
allowNull: true,

View File

@ -15,6 +15,7 @@ module.exports = app => {
SENDED_STATUS: [ 'none', 'padding', 'fin', 'error' ],
INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ],
PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ],
PRINT_LOCK_STATUS: [ 'none', 'warehouse' ],
CLAIM_STATUS: [ 'none', 'padding', 'fin', 'error' ],
OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
LOCK_STATUS: [ 'none', 'warehouse', 'store' ],
@ -448,6 +449,17 @@ module.exports = app => {
defaultValue: 'none',
comment: '检验状态机',
},
recheck_status: {
type: STRING(20),
allowNull: true,
defaultValue: 'none',
comment: '复核状态',
},
recheck_time: {
type: DATE,
allowNull: true,
comment: '复核时间',
},
step: {
type: INTEGER(10),
allowNull: false,
@ -478,6 +490,12 @@ module.exports = app => {
defaultValue: 'none',
comment: '锁定状态机',
},
print_lock_status: {
type: ENUM(...StatusEnum.PRINT_LOCK_STATUS),
allowNull: true,
defaultValue: 'none',
comment: '打印锁定状态机',
},
intercept_status: {
type: ENUM(...StatusEnum.INTERCEPT_STATUS),
allowNull: true,

View File

@ -799,6 +799,7 @@ module.exports = app => {
inspection_status: [ 'none', 'padding', 'running', 'fin', 'error' ],
step: [ 0, 1 ],
print_status: [ 'none', 'padding', 'fin', 'error' ],
print_lock_status: [ 'none', 'warehouse' ],
claim_status: [ 'none', 'padding', 'fin', 'error' ],
outbound_status: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
lock_status: [ 'none', 'warehouse', 'store' ],

View File

@ -1,7 +1,7 @@
'use strict';
module.exports = app => {
const { BIGINT, STRING, JSON, ENUM, TEXT, DATE } = app.Sequelize;
const { BIGINT, STRING, JSON, ENUM, TEXT, DATE, INTEGER } = app.Sequelize;
const PrintRecord = app.model.define('PrintRecord', {
id: {
type: BIGINT.UNSIGNED,
@ -40,11 +40,95 @@ module.exports = app => {
defaultValue: 'pending',
comment: '打印状态:pending-待发送,sent-已发送,success-打印成功,failed-打印失败',
},
send_status: {
type: STRING(32),
allowNull: false,
defaultValue: 'pending',
comment: '发送状态',
},
print_status: {
type: STRING(32),
allowNull: false,
defaultValue: 'unknown',
comment: '打印状态',
},
retry_count: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: '已重试次数',
},
max_retry_count: {
type: INTEGER,
allowNull: false,
defaultValue: 3,
comment: '最大重试次数',
},
next_retry_at: {
type: DATE,
allowNull: true,
comment: '下次重试时间',
},
last_retry_at: {
type: DATE,
allowNull: true,
comment: '最后重试时间',
},
fail_code: {
type: STRING(64),
allowNull: true,
comment: '失败编码',
},
retry_of_print_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '补偿来源打印记录ID',
},
error_message: {
type: TEXT,
allowNull: true,
comment: '错误信息',
},
print_task_code: {
type: TEXT,
allowNull: true,
comment: '自定义打印任务编码,多个编码以逗号分隔',
},
request_code: {
type: STRING(128),
allowNull: true,
comment: '请求参数码',
},
wave_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '波次ID',
},
wave_no: {
type: STRING(64),
allowNull: true,
comment: '波次号',
},
platform_code: {
type: STRING(32),
allowNull: true,
comment: '平台编码',
},
platform_name: {
type: STRING(64),
allowNull: true,
comment: '平台名称',
},
sys_logistics_code: {
type: STRING(32),
allowNull: true,
comment: '系统快递编码',
},
sys_logistics_name: {
type: STRING(64),
allowNull: true,
comment: '系统快递名称',
},
sent_time: {
type: DATE,
allowNull: true,
@ -78,6 +162,16 @@ module.exports = app => {
{ name: 'idx_status', fields: [ 'status' ] },
{ name: 'idx_created_at', fields: [ 'created_at' ] },
{ name: 'idx_sent_time', fields: [ 'sent_time' ] },
{ name: 'idx_send_status', fields: [ 'send_status' ] },
{ name: 'idx_print_status', fields: [ 'print_status' ] },
{ name: 'idx_next_retry_at', fields: [ 'next_retry_at' ] },
{ name: 'idx_retry_of_print_id', fields: [ 'retry_of_print_id' ] },
{ name: 'idx_print_status_next_retry', fields: [ 'print_status', 'next_retry_at' ] },
{ name: 'idx_request_code', fields: [ 'request_code' ] },
{ name: 'idx_wave_id', fields: [ 'wave_id' ] },
{ name: 'idx_platform_code', fields: [ 'platform_code' ] },
{ name: 'idx_sys_logistics_code', fields: [ 'sys_logistics_code' ] },
{ name: 'idx_wave_platform_status', fields: [ 'wave_id', 'platform_code', 'status' ] },
],
comment: '打印记录表',
});

View File

@ -0,0 +1,59 @@
'use strict';
module.exports = app => {
const { BIGINT, STRING, DATE } = app.Sequelize;
const PrintTaskMap = app.model.define('PrintTaskMap', {
id: {
type: BIGINT.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
task_code: {
type: STRING(128),
allowNull: false,
comment: '打印任务编码',
},
print_record_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '关联打印记录ID',
},
provider: {
type: STRING(64),
allowNull: true,
comment: 'provider返回任务ID或标识',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
}, {
tableName: 'wms_print_task_map',
freezeTableName: true,
underscored: false,
timestamps: false,
comment: '打印任务唯一映射表',
indexes: [
{
name: 'uix_task_code',
unique: true,
fields: [ 'task_code' ],
},
{
name: 'idx_print_record_id',
fields: [ 'print_record_id' ],
},
{
name: 'idx_created_at',
fields: [ 'created_at' ],
},
],
});
return PrintTaskMap;
};

View File

@ -0,0 +1,187 @@
'use strict';
const DEFAULT_INTERVAL_MS = 60 * 1000;
const DEFAULT_BATCH_SIZE = 50;
/**
* 归一化打印补偿调度配置。
* @param {Object} app Egg 应用实例。
* @return {{enable:boolean,intervalMs:number,batchSize:number,force:boolean}} 标准化配置。
*/
function getCompensationConfig(app) {
const rawConfig = app && app.config && app.config.printRetryCompensation
? app.config.printRetryCompensation
: {};
const intervalMs = Number.parseInt(rawConfig.intervalMs, 10);
const batchSize = Number.parseInt(rawConfig.batchSize, 10);
return {
enable: Boolean(rawConfig.enable),
intervalMs: Number.isInteger(intervalMs) && intervalMs > 0 ? intervalMs : DEFAULT_INTERVAL_MS,
batchSize: Number.isInteger(batchSize) && batchSize > 0 ? batchSize : DEFAULT_BATCH_SIZE,
force: Boolean(rawConfig.force),
};
}
/**
* 按仓库维度分组打印记录。
* @param {Array<Object>} printRecords 打印记录列表。
* @return {Map<number, Array<number>>} 仓库到打印记录 ID 的映射。
*/
function groupPrintIdsByWarehouse(printRecords = []) {
const groupedMap = new Map();
if (!Array.isArray(printRecords)) {
return groupedMap;
}
for (const printRecord of printRecords) {
const warehouseId = Number(printRecord && printRecord.warehouse_id);
const printId = Number(printRecord && printRecord.id);
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(printId) || printId <= 0) {
continue;
}
const currentPrintIds = groupedMap.get(warehouseId) || [];
currentPrintIds.push(printId);
groupedMap.set(warehouseId, currentPrintIds);
}
return groupedMap;
}
/**
* 自动扫描并触发失败打印补偿任务。
*/
module.exports = {
schedule: {
interval: '30s',
type: 'worker',
immediate: false,
disable: false,
},
/**
* 执行打印失败自动补偿任务。
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
const taskName = 'print-retry-compensation';
const compensationConfig = getCompensationConfig(ctx.app);
if (!compensationConfig.enable) {
return;
}
if (ctx.app._printRetryCompensationRunning) {
ctx.logger.info(`[${taskName}] 任务仍在运行中,跳过本轮调度`);
return;
}
const nowMs = Date.now();
const lastRunAt = Number(ctx.app._printRetryCompensationLastRunAt || 0);
if (lastRunAt > 0 && (nowMs - lastRunAt) < compensationConfig.intervalMs) {
return;
}
ctx.app._printRetryCompensationRunning = true;
ctx.app._printRetryCompensationLastRunAt = nowMs;
let scannedCount = 0;
let invokeCount = 0;
let retriedSuccessCount = 0;
let retriedFailedCount = 0;
let skippedCount = 0;
try {
const { Op } = ctx.app.Sequelize;
const printRecords = await ctx.model.PrintRecord.findAll({
attributes: [ 'id', 'warehouse_id', 'retry_count', 'max_retry_count', 'next_retry_at', 'send_status', 'print_status' ],
where: {
[Op.and]: [
{
[Op.or]: [
{ send_status: 'send_failed' },
{
print_status: {
[Op.in]: [ 'print_failed', 'timeout' ],
},
},
],
},
{
next_retry_at: {
[Op.lte]: new Date(),
},
},
{
retry_count: {
[Op.lt]: ctx.app.Sequelize.col('max_retry_count'),
},
},
],
},
order: [
[ 'next_retry_at', 'ASC' ],
[ 'id', 'ASC' ],
],
limit: compensationConfig.batchSize,
raw: true,
});
scannedCount = Array.isArray(printRecords) ? printRecords.length : 0;
if (scannedCount === 0) {
return;
}
const groupedPrintIds = groupPrintIdsByWarehouse(printRecords);
for (const [ warehouseId, printIds ] of groupedPrintIds.entries()) {
if (!Array.isArray(printIds) || printIds.length === 0) {
continue;
}
invokeCount += 1;
try {
const retryResult = await ctx.service.systemMethods.print.retryFailed({
print_ids: printIds,
warehouse_id: warehouseId,
force: compensationConfig.force,
});
if (!retryResult || retryResult.flag !== 'success') {
ctx.logger.warn(`[${taskName}] 触发补打失败`, {
warehouseId,
printIdsCount: printIds.length,
message: retryResult && retryResult.message ? retryResult.message : '未知错误',
});
continue;
}
retriedSuccessCount += Number(retryResult.success_count || 0);
retriedFailedCount += Number(retryResult.failed_count || 0);
skippedCount += Number(retryResult.skipped_count || 0);
} catch (error) {
ctx.logger.error(`[${taskName}] 触发补打异常`, {
warehouseId,
printIdsCount: printIds.length,
error: error && error.message ? error.message : `${error}`,
});
}
}
ctx.logger.info(`[${taskName}] 任务执行完成`, {
scannedCount,
warehouseGroupCount: groupedPrintIds.size,
invokeCount,
retriedSuccessCount,
retriedFailedCount,
skippedCount,
});
} catch (error) {
ctx.logger.error(`[${taskName}] 执行失败`, {
error: error && error.message ? error.message : `${error}`,
});
} finally {
ctx.app._printRetryCompensationRunning = false;
}
},
};

View File

@ -0,0 +1,257 @@
'use strict';
const OrderBaseService = require('./base');
class RecheckOrderService extends OrderBaseService {
/**
* 初始化复核订单系统方法免登录、免权限、免日志与免鉴权配置。
* @param {Egg.Context} ctx 请求上下文。
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'scanWaybill,confirmRecheck';
const _noNeedLog = 'scanWaybill,confirmRecheck';
const _noNeedAuth = 'scanWaybill,confirmRecheck';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 扫描运单号并返回订单头与商品明细。
* @param {Object} data 请求体。
* @param {string} [data.waybill_no] 运单号。
* @param {string} [data.waybillCode] 运单号别名。
* @param {string} [data.waybill_code] 运单号别名。
* @return {Promise<Object>} 扫描结果。
*/
async scanWaybill(data = {}) {
const warehouseId = this.getWarehouseId();
const waybillNo = this.resolveWaybillNo(data);
const orderId = await this.pickOrderIdByWaybill(waybillNo);
const orderModel = await this.getOrderModelByTableType('current', warehouseId);
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
const order = await orderModel.findOne({
where: orderWhere,
raw: true,
});
if (!order) {
throw new Error('未找到对应订单');
}
if (String(order.print_status || '') !== 'fin') {
throw new Error('运单状态必须已打印');
}
const detailResult = await this.detail({
id: orderId,
});
return {
order_id: orderId,
waybill_no: waybillNo,
order: detailResult.detail || {},
items: Array.isArray(detailResult.items) ? detailResult.items : [],
expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [],
logs: Array.isArray(detailResult.logs) ? detailResult.logs : [],
};
}
/**
* 确认订单已复核,并写入复核任务记录。
* @param {Object} data 请求体。
* @param {number|string} [data.order_id] 订单ID。
* @param {number|string} [data.id] 订单ID别名。
* @param {number|string} [data.orderId] 订单ID别名。
* @return {Promise<Object>} 复核确认结果。
*/
async confirmRecheck(data = {}) {
const { ctx } = this;
const warehouseId = this.getWarehouseId();
const orderId = this.resolveOrderId(data);
const orderModel = await this.getOrderModelByTableType('current', warehouseId);
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
const order = await orderModel.findOne({
where: orderWhere,
raw: true,
});
if (!order) {
throw new Error('未找到对应订单');
}
if (String(order.print_status || '') !== 'fin') {
throw new Error('运单状态必须已打印');
}
const expresses = await this.getOrderExpressesByOrderId(orderId);
const waybillNo = String(expresses?.[0]?.waybill_code || '').trim();
const now = new Date();
const updateValues = {
recheck_status: 'fin',
recheck_time: now,
updated_at: now,
};
const updateResult = await orderModel.update(updateValues, {
where: orderWhere,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('未找到对应订单');
}
const operator = this.getOrderLogOperator();
const reviewNo = this.buildRecheckReviewNo(orderId, now);
const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim();
const operatorNo = String(operator.id || '').trim();
const operatorName = String(operator.name || '').trim();
await ctx.model.query(
`
INSERT INTO wms_recheck_task (
review_no,
warehouse_id,
order_id,
order_no,
waybill_no,
task_status,
scan_status,
review_emp_no,
review_emp_name,
scan_emp_no,
scan_emp_name,
scan_time,
finish_time,
remark
)
VALUES (
:reviewNo,
:warehouseId,
:orderId,
:orderNo,
:waybillNo,
:taskStatus,
:scanStatus,
:reviewEmpNo,
:reviewEmpName,
:scanEmpNo,
:scanEmpName,
:scanTime,
:finishTime,
:remark
)
`,
{
replacements: {
reviewNo,
warehouseId,
orderId,
orderNo,
waybillNo,
taskStatus: 2,
scanStatus: 1,
reviewEmpNo: operatorNo,
reviewEmpName: operatorName,
scanEmpNo: operatorNo,
scanEmpName: operatorName,
scanTime: now,
finishTime: now,
remark: '系统复核完成',
},
type: ctx.model.QueryTypes.INSERT,
}
);
return {
order_id: orderId,
waybill_no: waybillNo,
recheck_status: 'fin',
recheck_time: now,
review_no: reviewNo,
};
}
/**
* 从多种兼容字段中解析订单ID。
* @param {Object} data 请求体。
* @return {number} 规范化后的订单ID。
*/
resolveOrderId(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const {
order_id: orderId,
id,
orderId: orderIdAlias,
} = requestData;
const normalizedOrderId = Number(orderId || id || orderIdAlias || 0);
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
throw new Error('订单ID不能为空');
}
return normalizedOrderId;
}
/**
* 从多种兼容字段中解析运单号。
* @param {Object} data 请求体。
* @return {string} 规范化后的运单号。
*/
resolveWaybillNo(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const {
waybill_no: waybillNo,
waybillCode,
waybill_code: waybillCodeAlias,
} = requestData;
const normalizedWaybillNo = String(waybillNo || waybillCode || waybillCodeAlias || '').trim();
if (!normalizedWaybillNo) {
throw new Error('运单号不能为空');
}
return normalizedWaybillNo;
}
/**
* 根据运单号解析唯一订单ID。
* @param {string} waybillNo 运单号。
* @return {Promise<number>} 订单ID。
*/
async pickOrderIdByWaybill(waybillNo) {
const warehouseId = this.getWarehouseId();
const orderIds = await this.findOrderIdsByExpressNumbers([ waybillNo ], warehouseId);
if (!Array.isArray(orderIds) || orderIds.length === 0) {
throw new Error('未找到对应订单');
}
const normalizedOrderIds = orderIds
.map(item => Number(item))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
.sort((a, b) => a - b);
if (normalizedOrderIds.length === 0) {
throw new Error('未找到对应订单');
}
return normalizedOrderIds[0];
}
/**
* 生成复核单号。
* @param {number} orderId 订单ID。
* @param {Date} now 当前时间。
* @return {string} 复核单号。
*/
buildRecheckReviewNo(orderId, now = new Date()) {
const timestamp = Number(now.getTime());
const paddedOrderId = String(orderId).padStart(6, '0');
return `RC${timestamp}${paddedOrderId}`;
}
}
module.exports = RecheckOrderService;

View File

@ -138,8 +138,9 @@ class PrintService extends MainService {
return {
status: 'sent',
send_status: 'sent',
print_status: 'unknown',
print_status: 'printed',
sent_time: sentTime,
print_time: sentTime,
fail_code: null,
error_message: null,
};
@ -570,7 +571,7 @@ class PrintService extends MainService {
const normalizedPrintStatus = String(printRecord.print_status || '').trim();
const needUpdateStatus = normalizedStatus !== 'sent'
|| normalizedSendStatus !== 'sent'
|| normalizedPrintStatus !== 'unknown'
|| normalizedPrintStatus !== 'printed'
|| !printRecord.sent_time;
if (!needWriteTaskCode && !needUpdateStatus) {
return;
@ -1616,7 +1617,6 @@ class PrintService extends MainService {
const waveGroups = Array.isArray(normalizedPayload.waveGroups)
? normalizedPayload.waveGroups
: [];
const expressOrderIds = this.collectOrderIdsFromWaveGroups(waveGroups);
const generatedTaskCodes = [];
const createdPrintRecordIds = [];
for (const waveGroup of waveGroups) {
@ -1913,6 +1913,34 @@ class PrintService extends MainService {
printIds: createdPrintRecordIds,
};
}
const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({
warehouseId: normalizedPayload.warehouseId,
orderIds: batchOrderIds,
});
if (!lockResult.success) {
this.ctx.logger.error('[print.send] 批次发送成功后锁定订单失败', {
...batchSummary,
warehouseId: normalizedPayload.warehouseId,
orderIdsCount: batchOrderIds.length,
reason: lockResult.errorMessage,
});
}
const orderPrintStatusUpdateResult = await this.updateOrderPrintStatusByCallback({
warehouseId: normalizedPayload.warehouseId,
orderIds: batchOrderIds,
result: 'success',
});
if (!orderPrintStatusUpdateResult.success) {
this.ctx.logger.error('[print.send] 批次发送成功后同步订单主表 print_status 失败', {
...batchSummary,
warehouseId: normalizedPayload.warehouseId,
orderIdsCount: batchOrderIds.length,
reason: orderPrintStatusUpdateResult.errorMessage,
});
}
this.ctx.logger.info('[print.send] 平台快递组发送结束', {
...batchSummary,
printId: currentPrintRecord.id,
@ -1923,18 +1951,6 @@ class PrintService extends MainService {
}
}
const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({
warehouseId: normalizedPayload.warehouseId,
orderIds: expressOrderIds,
});
if (!lockResult.success) {
this.ctx.logger.error('[print.send] 打印成功后锁定订单失败', {
warehouseId: normalizedPayload.warehouseId,
orderIdsCount: expressOrderIds.length,
reason: lockResult.errorMessage,
});
}
return {
success: true,
taskCodes: generatedTaskCodes,

View File

@ -15,6 +15,37 @@ class WarehouseService extends MainService {
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 归一化回收站筛选条件,兼容历史 is_deleted 字段。
* @param {Object} where 原始 where 条件
* @return {Object} 归一化后的 where 条件
*/
normalizeWarehouseRecycleWhere(where = {}) {
if (!this.isPlainObject(where)) {
return {};
}
const normalizedWhere = { ...where };
const recycleCondition = normalizedWhere.is_deleted;
if (!this.isPlainObject(recycleCondition)) {
return normalizedWhere;
}
const recycleValue = recycleCondition.value;
const isDeleted = recycleValue === true
|| recycleValue === 1
|| String(recycleValue || '').trim().toLowerCase() === 'true'
|| String(recycleValue || '').trim() === '1';
normalizedWhere.deleted_at = {
operator: isDeleted ? 'isnotnull' : 'isnull',
value: isDeleted ? 1 : 0,
};
delete normalizedWhere.is_deleted;
return normalizedWhere;
}
/**
* 仓库商品列表查询。
* @param {Object} data 请求体
@ -25,6 +56,10 @@ class WarehouseService extends MainService {
async list(data = {}) {
const { service } = this;
const { pagination } = data;
if (this.isPlainObject(data)) {
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
}
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
barcode: {
@ -51,6 +86,10 @@ class WarehouseService extends MainService {
*/
async export(data = {}) {
const { service } = this;
if (this.isPlainObject(data)) {
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
}
const { where, whereValue = {} } = this.prepareWhereContext(data, {
specialFieldMap: {
barcode: {
@ -295,8 +334,89 @@ class WarehouseService extends MainService {
*/
async saveWarehouseStock(data) {
const { service } = this;
const {
id,
item_code,
item_name,
goods_code,
sku_property,
stock_unit,
packing_requirements,
length,
width,
height,
volume,
volume_cm3,
volumeCm3,
gross_weight,
net_weight,
tag_price,
retail_price,
is_sn_mgmt,
is_shelf_life_mgmt,
is_batch_mgmt,
prohibited_id,
brand_name,
managementFlags,
enable_box_spec,
box_unit,
quantity_per_box,
box_gross_weight,
box_net_weight,
box_length,
box_width,
box_height,
box_volume,
box_volume_m3,
boxVolumeM3,
box_remark,
shelf_life_days,
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
} = data || {};
try {
const result = await service.systems.stockStore.saveWarehouseStock(data);
const result = await service.systems.stockStore.saveWarehouseStock({
id,
item_code,
item_name,
goods_code,
sku_property,
stock_unit,
packing_requirements,
length,
width,
height,
volume,
volume_cm3,
volumeCm3,
gross_weight,
net_weight,
tag_price,
retail_price,
is_sn_mgmt,
is_shelf_life_mgmt,
is_batch_mgmt,
prohibited_id,
brand_name,
managementFlags,
enable_box_spec,
box_unit,
quantity_per_box,
box_gross_weight,
box_net_weight,
box_length,
box_width,
box_height,
box_volume,
box_volume_m3,
boxVolumeM3,
box_remark,
shelf_life_days,
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
});
return this.success('ok', { data: result, code: 200 });
} catch (error) {
return this.fail(error.message);
@ -426,7 +546,7 @@ class WarehouseService extends MainService {
return null;
}
const pickValue = (keys) => {
const pickValue = keys => {
for (const key of keys) {
if (!Object.prototype.hasOwnProperty.call(row, key)) {
continue;
@ -511,8 +631,12 @@ class WarehouseService extends MainService {
*/
async bindItem(data) {
const { service } = this;
const { id, warehouse_stock } = data || {};
try {
const result = await service.systems.stockStore.bindItem(data);
const result = await service.systems.stockStore.bindItem({
id,
warehouse_stock,
});
return this.success('绑定成功', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });
@ -526,8 +650,9 @@ class WarehouseService extends MainService {
*/
async unbindItem(data) {
const { service } = this;
const { id } = data || {};
try {
const result = await service.systems.stockStore.unbindItem(data);
const result = await service.systems.stockStore.unbindItem({ id });
return this.success('解绑成功', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });

View File

@ -0,0 +1,173 @@
'use strict';
const MainService = require('../../main');
/**
* 系统方法层:storage.stockout(非订单出库单)。
* 说明:该实现为最小可用能力,复用订单分表模型读取当前仓库的出库单与明细。
*/
class StorageStockoutService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,toOrder,listItems';
const _noNeedLog = 'list,toOrder,listItems';
const _noNeedAuth = 'list,toOrder,listItems';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 出库单列表查询。
* @param {Object} data 请求体
* @param {Object} [data.where] 查询条件
* @param {Object} [data.pagination] 分页参数
* @param {Object} [data.sort] 排序参数
* @return {Promise<Object>} 统一成功包装响应
*/
async list(data = {}) {
const { ctx } = this;
const { Op } = this.app.Sequelize;
const { pagination = {}, sort = {} } = data;
const { parsed } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
const page = Math.max(Number(pagination.page) || 1, 1);
const pageSize = Math.max(Number(pagination.pageSize) || 20, 1);
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const OrderDeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const andConditions = [
{ warehouse_id: warehouseId },
{ delete_at: null },
];
const dynamicConditions = Array.isArray(parsed && parsed.dynamicConditions) ? parsed.dynamicConditions : [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
const quickWhereCondition = parsed && parsed.rawConditionsByField && parsed.rawConditionsByField.quickWhere;
const quickValue = quickWhereCondition && Object.prototype.hasOwnProperty.call(quickWhereCondition, 'value')
? quickWhereCondition.value
: null;
if (quickValue !== null && quickValue !== undefined && String(quickValue).trim() !== '') {
const keyword = String(quickValue).trim();
andConditions.push({
[Op.or]: [
{ delivery_order_code: { [Op.like]: `%${keyword}%` } },
{ source_order_codes: { [Op.like]: `%${keyword}%` } },
{ buyer_nick: { [Op.like]: `%${keyword}%` } },
{ mobile: { [Op.like]: `%${keyword}%` } },
{ name: { [Op.like]: `%${keyword}%` } },
],
});
}
const validSortFields = [
'id',
'delivery_order_code',
'status',
'outbound_status',
'updated_at',
'create_at',
'delivery_time',
];
const sortField = validSortFields.includes(String(sort.sortField || '').trim())
? String(sort.sortField).trim()
: 'updated_at';
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const finalWhere = { [Op.and]: andConditions };
const { count, rows } = await OrderDeliveryModel.findAndCountAll({
where: finalWhere,
order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]],
limit: pageSize,
offset: (page - 1) * pageSize,
raw: true,
});
return this.success('ok', {
list: rows,
pagination: {
page,
pageSize,
total: count,
totalPages: Math.ceil(count / pageSize),
hasPrevious: page > 1,
hasNext: page < Math.ceil(count / pageSize),
},
});
}
/**
* 出库单转订单占位接口。
* @return {Promise<Object>} 统一失败包装响应
*/
async toOrder() {
return this.fail('接口暂未开放');
}
/**
* 出库单明细查询。
* @param {Object} data 请求体
* @param {number} [data.id] 出库单ID
* @param {string} [data.delivery_order_code] 出库单号
* @return {Promise<Object>} 统一成功包装响应
*/
async listItems(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const id = Number(data.id || 0);
const deliveryOrderCode = String(data.delivery_order_code || '').trim();
if (!id && !deliveryOrderCode) {
return this.fail('id 或 delivery_order_code 至少传一个');
}
const OrderDeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const where = {
warehouse_id: warehouseId,
delete_at: null,
};
if (id > 0) {
where.id = id;
} else {
where.delivery_order_code = deliveryOrderCode;
}
const order = await OrderDeliveryModel.findOne({
where,
raw: true,
});
if (!order || !order.id) {
return this.success('ok', {
order: null,
list: [],
});
}
const list = await OrderItemsModel.findAll({
where: {
order_id: order.id,
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
return this.success('ok', {
order,
list,
});
}
}
module.exports = StorageStockoutService;

View File

@ -7,6 +7,54 @@ const OrderBaseService = require('../systemMethods/order/base');
const PrinterDataBuilder = require('../../lib/printer_data_builder');
class OrderPrintSystemService extends OrderBaseService {
/**
* 判断订单是否处于锁定状态。
*
* 当前约定 print_lock_status=none 表示未锁定,其余值均视为锁定。
*
* @param {Object} orderRow 订单行。
* @return {boolean} 是否锁定。
*/
isOrderLocked(orderRow = {}) {
const lockStatus = String(orderRow && orderRow.print_lock_status || 'none').trim() || 'none';
return lockStatus !== 'none';
}
/**
* 构建波次平台打印“已锁定”短路返回。
*
* @param {Object} payload 聚合入参。
* @param {Array<Object>} payload.lockedOrders 已锁定订单列表。
* @param {Array<number>} payload.validWaveIds 命中的有效波次ID。
* @param {Array<number>} payload.missingWaveIds 未命中波次ID。
* @param {Array<Object>} payload.filteredWaveIds 被过滤波次及原因。
* @return {Object} 锁定短路返回结构。
*/
buildLockedWavePlatformResult(payload = {}) {
const requestPayload = this.isPlainObject(payload) ? payload : {};
const lockedOrders = Array.isArray(requestPayload.lockedOrders) ? requestPayload.lockedOrders : [];
const validWaveIds = Array.isArray(requestPayload.validWaveIds) ? requestPayload.validWaveIds : [];
const missingWaveIds = Array.isArray(requestPayload.missingWaveIds) ? requestPayload.missingWaveIds : [];
const filteredWaveIds = Array.isArray(requestPayload.filteredWaveIds) ? requestPayload.filteredWaveIds : [];
return {
summary: {
total_waves: 0,
total_orders: 0,
total_platforms: 0,
locked_count: lockedOrders.length,
},
waveGroups: [],
wave_ids: validWaveIds,
locked_count: lockedOrders.length,
locked_orders: lockedOrders,
ext: {
missing_wave_ids: missingWaveIds,
filtered_wave_ids: filteredWaveIds,
},
};
}
/**
* 判断当前配置是否需要补查拣货明细。
*
@ -369,6 +417,24 @@ 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 lockedOrders = validOrderRows
.filter(orderRow => this.isOrderLocked(orderRow))
.map(orderRow => ({
order_id: Number(orderRow && orderRow.id || 0),
order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(),
wave_id: Number(orderRow && orderRow.wave_id || 0),
wave_no: String(orderRow && orderRow.wave_no || '').trim(),
print_lock_status: String(orderRow && orderRow.print_lock_status || '').trim() || 'none',
}));
if (lockedOrders.length > 0) {
return this.buildLockedWavePlatformResult({
lockedOrders,
validWaveIds,
missingWaveIds,
filteredWaveIds,
});
}
const validOrderWaveIds = Array.from(new Set(validOrderRows
.map(row => Number(row && row.wave_id || 0))
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
@ -596,6 +662,8 @@ class OrderPrintSystemService extends OrderBaseService {
'status',
'outbound_status',
'print_status',
'lock_status',
'print_lock_status',
'items_count',
'items_total',
'items_weight',
@ -1155,10 +1223,16 @@ ${waveFilterSql}
sys_logistics_code: normalizedSysLogisticsCode || 'unknown',
sys_logistics_name: normalizedSysLogisticsName || 'unknown',
order_count: 0,
order_ids: [],
orders: [],
};
const orderId = Number(item && item.order_id || 0);
if (Number.isInteger(orderId) && orderId > 0) {
platformGroup.order_ids.push(orderId);
}
platformGroup.orders.push(this.isPlainObject(item && item.print_data) ? item.print_data : {});
platformGroup.order_ids = Array.from(new Set(platformGroup.order_ids));
platformGroup.order_count = platformGroup.orders.length;
platformMap.set(platformSysKey, platformGroup);

View File

@ -1840,7 +1840,7 @@ class stockStoreService extends Service {
if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) {
const { Op } = ctx.app.Sequelize;
const storeRows = await ctx.model.StoreWarehouse.findAll({
attributes: ['store_id', 'store_remask'],
attributes: [ 'store_id', 'store_remask' ],
where: {
store_id: { [Op.in]: storeIds },
warehouse_id: warehouseId,
@ -2404,7 +2404,7 @@ class stockStoreService extends Service {
const storeStock = await ctx.model.StockStore.findOne({
where: {
warehouse_id: warehouseId,
deleted_at: null,
delete_at: null,
id,
},
attributes: [
@ -2456,7 +2456,7 @@ class stockStoreService extends Service {
const storeStock = await ctx.model.StockStore.findOne({
where: {
warehouse_id: warehouseId,
deleted_at: null,
delete_at: null,
id,
},
attributes: [
@ -2553,14 +2553,18 @@ class stockStoreService extends Service {
const {
item_code, item_name, goods_code, sku_property, stock_unit,
packing_requirements, length, width, height, volume,
volume_cm3, volumeCm3,
gross_weight, net_weight, tag_price, retail_price,
is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt,
prohibited_id, brand_name, managementFlags,
enable_box_spec, box_unit, quantity_per_box,
box_gross_weight, box_net_weight, box_length,
box_width, box_height, box_volume, box_remark, id,
box_volume_m3, boxVolumeM3,
shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days,
} = data;
const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3;
const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3;
const prohibited_id_tmp = !prohibited_id ? null : parseInt(prohibited_id);
// 1. 参数验证
this.validateSaveParams(data);
@ -2621,7 +2625,7 @@ class stockStoreService extends Service {
length,
width,
height,
volume,
volume: normalizedVolume,
gross_weight,
net_weight,
tag_price,
@ -2640,7 +2644,7 @@ class stockStoreService extends Service {
box_length,
box_width,
box_height,
box_volume,
box_volume: normalizedBoxVolume,
box_remark,
shelf_life_days,
inbound_min_days,

View File

@ -4,6 +4,193 @@ const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
class EntryService extends Service {
/**
* 将费用记录筛选值归一化为 0/1。
* @param {unknown} rawValue 原始筛选值
* @return {number|null} 归一化结果,无法识别时返回 null
*/
normalizeExpenseRecordValue(rawValue) {
if (rawValue === true) return 1;
if (rawValue === false) return 0;
if (rawValue === 1 || rawValue === '1') return 1;
if (rawValue === 0 || rawValue === '0') return 0;
if (typeof rawValue === 'string') {
const normalized = rawValue.trim().toLowerCase();
if ([ 'true', 'yes', 'y' ].includes(normalized)) return 1;
if ([ 'false', 'no', 'n' ].includes(normalized)) return 0;
}
return null;
}
/**
* 归一化 expense_record 条件,兼容 eq/in/布尔值写法。
* @param {Object|number|string|boolean} condition 原始条件
* @return {Object|null} 标准化后的条件,无法识别时返回 null
*/
normalizeExpenseRecordCondition(condition) {
const isObjectCondition = condition && typeof condition === 'object' && !Array.isArray(condition);
if (!isObjectCondition) {
const normalizedValue = this.normalizeExpenseRecordValue(condition);
if (normalizedValue === null) {
return null;
}
return {
operator: 'eq',
value: normalizedValue,
};
}
const operator = String(condition.operator || 'eq').trim().toLowerCase();
const values = this.normalizeFilterValues(condition)
.map(item => this.normalizeExpenseRecordValue(item))
.filter(item => item !== null);
if (values.length === 0) {
return null;
}
if (operator === 'in') {
return {
operator: 'in',
value: [ ...new Set(values) ],
};
}
return {
operator: 'eq',
value: values[0],
};
}
/**
* 将筛选值归一化为数组。
* @param {Object} condition 条件对象
* @return {Array<unknown>} 归一化后的值数组
*/
normalizeFilterValues(condition = {}) {
const value = condition && Object.prototype.hasOwnProperty.call(condition, 'value')
? condition.value
: undefined;
if (Array.isArray(value)) {
return value;
}
if (value === undefined || value === null) {
return [];
}
return [ value ];
}
/**
* 构建入库单-库存流水 EXISTS 子查询条件。
* @param {string} fieldName 流水字段名
* @param {Object} condition 条件对象
* @return {Object|null} Sequelize.where 条件,无法构建时返回 null
*/
buildEntryStockTransactionExistsCondition(fieldName, condition = {}) {
const { app } = this;
const values = this.normalizeFilterValues(condition)
.map(item => (typeof item === 'string' ? item.trim() : item))
.filter(item => item !== '' && item !== undefined && item !== null);
if (values.length === 0) {
return null;
}
const operator = String(condition.operator || 'eq').trim().toLowerCase();
const escapedColumn = `st.${fieldName}`;
const escapedValues = values.map(item => app.Sequelize.escape(item));
let valueClause = '';
if (operator === 'in') {
valueClause = `${escapedColumn} IN (${escapedValues.join(',')})`;
} else if (operator === 'like' || operator === 'contains') {
const likeClauses = values.map(item => `${escapedColumn} LIKE ${app.Sequelize.escape(`%${String(item)}%`)}`);
valueClause = likeClauses.length === 1 ? likeClauses[0] : `(${likeClauses.join(' OR ')})`;
} else {
valueClause = `${escapedColumn} = ${escapedValues[0]}`;
}
const sql = `EXISTS (
SELECT 1
FROM wms_stock_transaction st
WHERE st.entry_order_id = wms_entry_order.id
AND ${valueClause}
)`;
return app.Sequelize.where(app.Sequelize.literal(sql), 1);
}
/**
* 预处理入库单列表筛选条件,兼容历史别名并构建扩展筛选。
* @param {Object} normalizedWhere 标准化后的 where 条件
* @return {{where: Object, extraConditions: Array<Object>, errorMessage: string}} 预处理结果
*/
preprocessEntryListWhere(normalizedWhere = {}) {
const { ctx } = this;
const whereForParse = normalizedWhere && typeof normalizedWhere === 'object'
? { ...normalizedWhere }
: {};
const extraConditions = [];
if (whereForParse.erp_remark && !whereForParse.remark) {
whereForParse.remark = whereForParse.erp_remark;
}
delete whereForParse.erp_remark;
const batchCondition = whereForParse.batch_no || whereForParse.batch;
if (batchCondition) {
const existsCondition = this.buildEntryStockTransactionExistsCondition('batch_no', batchCondition);
if (existsCondition) {
extraConditions.push(existsCondition);
}
}
delete whereForParse.batch_no;
delete whereForParse.batch;
if (whereForParse.operator_id) {
const existsCondition = this.buildEntryStockTransactionExistsCondition('operator_id', whereForParse.operator_id);
if (existsCondition) {
extraConditions.push(existsCondition);
}
}
delete whereForParse.operator_id;
if (Object.prototype.hasOwnProperty.call(whereForParse, 'expense_record')) {
const hasExpenseRecordField = Boolean(
ctx.model
&& ctx.model.EntryOrder
&& ctx.model.EntryOrder.rawAttributes
&& ctx.model.EntryOrder.rawAttributes.expense_record
);
if (!hasExpenseRecordField) {
return {
where: {},
extraConditions: [],
errorMessage: '当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级',
};
}
const normalizedExpenseRecord = this.normalizeExpenseRecordCondition(whereForParse.expense_record);
if (normalizedExpenseRecord) {
whereForParse.expense_record = normalizedExpenseRecord;
} else {
delete whereForParse.expense_record;
}
}
return {
where: whereForParse,
extraConditions,
errorMessage: '',
};
}
/**
* 入库单列表查询,复用 where 解构工具。
* @param {Object} where 筛选条件对象
@ -43,48 +230,77 @@ class EntryService extends Service {
? { ...ctx.where }
: (where && typeof where === 'object' ? { ...where } : {});
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: {
bucket: 'quick',
const {
where: parsedSourceWhere,
extraConditions,
errorMessage,
} = this.preprocessEntryListWhere(normalizedWhere);
if (errorMessage) {
return {
code: 400,
message: errorMessage,
data: {
list: [],
pagination: {
page,
pageSize,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total: 0,
pending: 0,
creating: 0,
created: 0,
completed: 0,
cancelled: 0,
},
},
});
if (!parsed.ok) {
return {
code: 400,
message: `筛选条件解析失败: ${parsed.reason}`,
data: {
list: [],
pagination: {
page,
pageSize,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total: 0,
pending: 0,
creating: 0,
created: 0,
completed: 0,
cancelled: 0,
},
},
};
}
parsedResult = parsed.result;
};
}
const parsed = parseWhereConditions({
where: parsedSourceWhere,
app,
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
if (!parsed.ok) {
return {
code: 400,
message: `筛选条件解析失败: ${parsed.reason}`,
data: {
list: [],
pagination: {
page,
pageSize,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total: 0,
pending: 0,
creating: 0,
created: 0,
completed: 0,
cancelled: 0,
},
},
};
}
const parsedResult = parsed.result;
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere
|| parsedSourceWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
@ -108,6 +324,9 @@ class EntryService extends Service {
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
if (extraConditions.length > 0) {
andConditions.push({ [Op.and]: extraConditions });
}
const finalWhere = { [Op.and]: andConditions };

View File

@ -33,7 +33,7 @@ function normalizeBoolean(value) {
if (typeof value === 'string') {
const normalized = value.trim().toLowerCase();
return [ '1', 'true', 'y', 'yes' ].includes(normalized);
return [ '1', 'true', 'y', 'yes', '是' ].includes(normalized);
}
return false;
@ -292,6 +292,30 @@ function buildPreStartAfterMap(rows, resolveKey) {
return snapshotMap;
}
/**
* 获取报表流水数据源配置。
* @param {boolean} isBySpace 是否按库位维度统计
* @return {{tableName: string, spaceSelectSql: string, spaceGroupSql: string, spaceOrderSql: string}} 配置对象
*/
function resolveTransactionSourceConfig(isBySpace) {
if (isBySpace) {
return {
tableName: 'wms_storage_transaction',
// 历史库位流水可能存在空 space_id,统一回退到 0 作为“未知库位”口径,避免统计漏数。
spaceSelectSql: 'COALESCE(t.space_id, 0) AS space_id',
spaceGroupSql: ', COALESCE(t.space_id, 0)',
spaceOrderSql: ', COALESCE(t.space_id, 0) ASC',
};
}
return {
tableName: 'wms_stock_transaction',
spaceSelectSql: '0 AS space_id',
spaceGroupSql: '',
spaceOrderSql: '',
};
}
class StorageReportService extends Service {
/**
* 加载库存报表导出所需的名称映射。
@ -451,6 +475,12 @@ class StorageReportService extends Service {
replacements.storeIds = normalizedStoreIds;
}
const detailTransactionTable = isBySpace ? 'wms_storage_transaction' : 'wms_stock_transaction';
const detailSpaceSelectSql = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id' : '0 AS space_id';
const detailInventoryTypeSelectSql = isBySpace ? 't.inventory_type' : '\'\' AS inventory_type';
const detailReceivingIdSelectSql = isBySpace ? 'NULL AS receiving_id' : 't.receiving_id';
const detailEntryOrderIdSelectSql = isBySpace ? 'NULL AS entry_order_id' : 't.entry_order_id';
const detailRows = await ctx.model.query(`
SELECT
t.id,
@ -458,22 +488,22 @@ class StorageReportService extends Service {
t.transaction_type,
t.store_id,
t.stock_id,
0 AS space_id,
${detailSpaceSelectSql},
t.quantity,
t.before_quantity,
t.after_quantity,
t.before_locked_quantity,
t.after_locked_quantity,
t.batch_no,
'' AS inventory_type,
${detailInventoryTypeSelectSql},
t.order_type,
t.order_no,
t.order_id,
t.receiving_id,
t.entry_order_id,
${detailReceivingIdSelectSql},
${detailEntryOrderIdSelectSql},
t.operator_name,
t.remark
FROM wms_stock_transaction t
FROM ${detailTransactionTable} t
WHERE ${whereClauses.join(' AND ')}
ORDER BY t.created_at ASC, t.id ASC
`, {
@ -778,16 +808,18 @@ class StorageReportService extends Service {
rangeReplacements.baseStockIds = baseStockIds;
}
const transactionSource = resolveTransactionSourceConfig(isBySpace);
const rangeRowsSql = `
SELECT
t.stock_id,
0 AS space_id,
${transactionSource.spaceSelectSql},
t.store_id,
SUM(CASE WHEN t.transaction_type = 'INBOUND' THEN t.quantity ELSE 0 END) AS inbound_total,
SUM(CASE WHEN t.transaction_type = 'OUTBOUND' THEN t.quantity ELSE 0 END) AS outbound_total
FROM wms_stock_transaction t
FROM ${transactionSource.tableName} t
WHERE ${rangeWhereClauses.join(' AND ')}
GROUP BY t.stock_id, t.store_id
GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id
`;
const rangeRows = await ctx.model.query(rangeRowsSql, {
@ -801,14 +833,14 @@ class StorageReportService extends Service {
SELECT
t.id,
t.stock_id,
0 AS space_id,
${transactionSource.spaceSelectSql},
t.store_id,
t.before_quantity,
t.after_quantity,
t.created_at
FROM wms_stock_transaction t
FROM ${transactionSource.tableName} t
WHERE ${rangeWhereClauses.join(' AND ')}
ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at ASC, t.id ASC
ORDER BY t.stock_id ASC${transactionSource.spaceOrderSql}, t.store_id ASC, t.created_at ASC, t.id ASC
`, {
replacements: rangeReplacements,
type: app.Sequelize.QueryTypes.SELECT,
@ -839,13 +871,13 @@ class StorageReportService extends Service {
SELECT
t.id,
t.stock_id,
0 AS space_id,
${transactionSource.spaceSelectSql},
t.store_id,
t.after_quantity,
t.created_at
FROM wms_stock_transaction t
FROM ${transactionSource.tableName} t
WHERE ${preStartWhereClauses.join(' AND ')}
ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at DESC, t.id DESC
ORDER BY t.stock_id ASC${transactionSource.spaceOrderSql}, t.store_id ASC, t.created_at DESC, t.id DESC
`, {
replacements: preStartReplacements,
type: app.Sequelize.QueryTypes.SELECT,

37
check_stats.ps1 Normal file
View File

@ -0,0 +1,37 @@
$targetTs = "2026-05-20 02:20:00"
# Use hex escape or similar if possible, or just standard string.
# Actually, PowerShell strings are Unicode.
$kws = @(
'print-retry-compensation',
'print_retry_compensation\.js',
'retryFailed',
'触发补打',
'任务执行完成',
'SCHEDULE',
'/__schedule\?path=D:\\wms\\app\\schedule\\print_retry_compensation\.js'
)
$stats = [ordered]@{}
foreach($k in $kws) { $stats[$k] = 0 }
Get-ChildItem logs/wms/wms-web.log* | ForEach-Object {
$fs = New-Object System.IO.FileStream($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
# The logs seem to be UTF-8
$reader = New-Object System.IO.StreamReader($fs, [System.Text.Encoding]::UTF8)
while($null -ne ($line = $reader.ReadLine())){
if($line -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'){
$ts = $matches[1]
if($ts -ge $targetTs){
foreach($k in $kws){
if($line -match $k){
$stats[$k]++
}
}
}
}
}
$reader.Close()
$fs.Dispose()
}
$stats.Keys | ForEach-Object { "$_: $($stats[$_])" }

View File

@ -198,6 +198,12 @@ module.exports = appInfo => {
config.printService = {
url: 'http://printer.wms.gztbyc.com',
};
config.printRetryCompensation = {
enable: false,
intervalMs: 60 * 1000,
batchSize: 50,
force: false,
};
return {
...config,
...userConfig,

View File

@ -0,0 +1,33 @@
'use strict';
/**
* 为入库单主表增加费用是否记录字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:新增 expense_record 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_entry_order', 'expense_record', {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '费用是否记录',
});
},
/**
* 回滚迁移:删除 expense_record 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
await queryInterface.removeColumn('wms_entry_order', 'expense_record');
},
};

View File

@ -0,0 +1,252 @@
'use strict';
/**
* 获取当前数据库已存在的表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 构建通用时间字段。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {{create_time: object, update_time: object, deleted_at: object}} 时间字段定义。
*/
const buildTimeColumns = Sequelize => ({
create_time: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
update_time: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '删除时间',
},
});
/**
* 创建单表复核任务明细表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
const createReviewTaskTable = async (queryInterface, Sequelize) => {
await queryInterface.createTable('wms_recheck_task', {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
review_no: {
type: Sequelize.STRING(64),
allowNull: false,
comment: '复核单号',
},
line_no: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 1,
comment: '明细序号',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID',
},
task_type: {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 1,
comment: '任务类型:1=散单 2=团购波次',
},
source_task_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联 wms_wave_pick_task.id',
},
wave_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '波次ID',
},
order_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '订单ID',
},
order_no: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '订单号',
},
package_seq: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 1,
comment: '包裹序号',
},
expected_waybill_no: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '预期运单号',
},
waybill_no: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '实扫运单号',
},
task_status: {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 0,
comment: '任务状态:0=待开始 1=复核中 2=完成 3=异常 9=取消',
},
scan_status: {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 0,
comment: '扫描状态:0=未扫 1=已扫 2=异常',
},
review_emp_no: {
type: Sequelize.STRING(32),
allowNull: true,
comment: '复核人工号',
},
review_emp_name: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '复核人姓名',
},
scan_emp_no: {
type: Sequelize.STRING(32),
allowNull: true,
comment: '扫描人工号',
},
scan_emp_name: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '扫描人姓名',
},
device_id: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '设备ID',
},
start_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '开始时间',
},
finish_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '完成时间',
},
scan_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '扫描时间',
},
remark: {
type: Sequelize.STRING(255),
allowNull: true,
comment: '备注',
},
ext_json: {
type: Sequelize.JSON,
allowNull: true,
comment: '扩展信息JSON',
},
...buildTimeColumns(Sequelize),
}, {
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
comment: '单表复核任务明细表',
});
await queryInterface.addIndex('wms_recheck_task', [ 'review_no', 'line_no' ], {
name: 'uk_review_no_line_no',
unique: true,
});
await queryInterface.addIndex('wms_recheck_task', [ 'review_no', 'waybill_no' ], {
name: 'uk_review_no_waybill_no',
unique: true,
});
await queryInterface.addIndex('wms_recheck_task', [ 'warehouse_id', 'task_status' ], {
name: 'idx_warehouse_task_status',
});
await queryInterface.addIndex('wms_recheck_task', [ 'warehouse_id', 'task_type' ], {
name: 'idx_warehouse_task_type',
});
await queryInterface.addIndex('wms_recheck_task', [ 'warehouse_id', 'review_no' ], {
name: 'idx_warehouse_review_no',
});
await queryInterface.addIndex('wms_recheck_task', [ 'source_task_id' ], {
name: 'idx_source_task_id',
});
await queryInterface.addIndex('wms_recheck_task', [ 'wave_id' ], {
name: 'idx_wave_id',
});
await queryInterface.addIndex('wms_recheck_task', [ 'order_id' ], {
name: 'idx_order_id',
});
await queryInterface.addIndex('wms_recheck_task', [ 'waybill_no' ], {
name: 'idx_waybill_no',
});
await queryInterface.addIndex('wms_recheck_task', [ 'review_no', 'scan_status' ], {
name: 'idx_review_no_scan_status',
});
};
/**
* 新增单表复核任务明细表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
module.exports.up = async (queryInterface, Sequelize) => {
const tableSet = await getExistingTableSet(queryInterface);
if (tableSet.has('wms_recheck_task')) {
return;
}
await createReviewTaskTable(queryInterface, Sequelize);
};
/**
* 回滚删除单表复核任务明细表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
module.exports.down = async queryInterface => {
const tableSet = await getExistingTableSet(queryInterface);
if (!tableSet.has('wms_recheck_task')) {
return;
}
await queryInterface.dropTable('wms_recheck_task');
};

View File

@ -0,0 +1,212 @@
'use strict';
/**
* 获取当前数据库已存在的表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 构建通用时间字段。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {{create_time: object, update_time: object, deleted_at: object}} 时间字段定义。
*/
const buildTimeColumns = Sequelize => ({
create_time: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
update_time: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '删除时间',
},
});
/**
* 创建打包任务主表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
const createPackTaskTable = async (queryInterface, Sequelize) => {
await queryInterface.createTable('wms_pack_task', {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
order_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '订单ID',
},
pack_mode: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '打包模式:1=散单 2=团购',
},
status: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '任务状态:0=待处理',
},
primary_packer_emp_id: {
type: Sequelize.INTEGER.UNSIGNED,
allowNull: true,
comment: '主打包人工号ID',
},
primary_packer_emp_no: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '主打包人工号',
},
primary_packer_name: {
type: Sequelize.STRING(128),
allowNull: true,
comment: '主打包人姓名',
},
packers_snapshot: {
type: Sequelize.JSON,
allowNull: true,
comment: '打包人快照:散单对象/团购数组',
},
meta: {
type: Sequelize.JSON,
allowNull: true,
comment: '扩展信息JSON',
},
...buildTimeColumns(Sequelize),
}, {
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
comment: '打包任务主表',
});
await queryInterface.addIndex('wms_pack_task', [ 'order_id' ], {
name: 'idx_order_id',
});
await queryInterface.addIndex('wms_pack_task', [ 'primary_packer_emp_id' ], {
name: 'idx_primary_packer_emp_id',
});
await queryInterface.addIndex('wms_pack_task', [ 'pack_mode', 'status' ], {
name: 'idx_pack_mode_status',
});
};
/**
* 创建打包任务-打包人关系表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
const createPackTaskPackerTable = async (queryInterface, Sequelize) => {
await queryInterface.createTable('wms_pack_task_packer', {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
pack_task_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '打包任务ID',
},
emp_id: {
type: Sequelize.INTEGER.UNSIGNED,
allowNull: false,
comment: '打包人工号ID',
},
emp_no: {
type: Sequelize.STRING(64),
allowNull: false,
comment: '打包人工号',
},
emp_name: {
type: Sequelize.STRING(128),
allowNull: false,
comment: '打包人姓名',
},
seq: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '排序序号',
},
...buildTimeColumns(Sequelize),
}, {
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
comment: '打包任务-打包人关系表',
});
await queryInterface.addIndex('wms_pack_task_packer', [ 'pack_task_id', 'emp_id' ], {
name: 'uix_pack_task_emp',
unique: true,
});
await queryInterface.addIndex('wms_pack_task_packer', [ 'emp_id' ], {
name: 'idx_emp_id',
});
await queryInterface.addIndex('wms_pack_task_packer', [ 'pack_task_id' ], {
name: 'idx_pack_task_id',
});
};
/**
* 创建打包任务相关表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
module.exports.up = async (queryInterface, Sequelize) => {
const tableSet = await getExistingTableSet(queryInterface);
if (!tableSet.has('wms_pack_task')) {
await createPackTaskTable(queryInterface, Sequelize);
}
if (!tableSet.has('wms_pack_task_packer')) {
await createPackTaskPackerTable(queryInterface, Sequelize);
}
};
/**
* 回滚删除打包任务相关表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
module.exports.down = async queryInterface => {
const tableSet = await getExistingTableSet(queryInterface);
if (tableSet.has('wms_pack_task_packer')) {
await queryInterface.dropTable('wms_pack_task_packer');
}
if (tableSet.has('wms_pack_task')) {
await queryInterface.dropTable('wms_pack_task');
}
};

View File

@ -0,0 +1,46 @@
'use strict';
/**
* 为打印记录表新增自定义打印任务编码字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
module.exports = {
/**
* 执行迁移:新增 print_task_code 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_print_record';
const columns = await queryInterface.describeTable(tableName);
if (columns.print_task_code) {
return;
}
await queryInterface.addColumn(tableName, 'print_task_code', {
type: Sequelize.TEXT,
allowNull: true,
comment: '自定义打印任务编码,多个编码以逗号分隔',
});
},
/**
* 回滚迁移:删除 print_task_code 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const tableName = 'wms_print_record';
const columns = await queryInterface.describeTable(tableName);
if (!columns.print_task_code) {
return;
}
await queryInterface.removeColumn(tableName, 'print_task_code');
},
};

View File

@ -0,0 +1,105 @@
'use strict';
/**
* 获取当前数据库已存在的表名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 获取指定表的索引名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Set<string>>} 索引名集合。
*/
const getIndexNameSet = async (queryInterface, tableName) => {
const indexes = await queryInterface.showIndex(tableName);
return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean));
};
/**
* 创建打印任务去重映射表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
const createPrintTaskMapTable = async (queryInterface, Sequelize) => {
await queryInterface.createTable('wms_print_task_map', {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
task_code: {
type: Sequelize.STRING(128),
allowNull: false,
comment: '打印任务编码',
},
print_record_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联打印记录ID',
},
provider: {
type: Sequelize.STRING(64),
allowNull: true,
comment: 'provider返回任务ID或标识',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
}, {
comment: '打印任务唯一映射表',
engine: 'InnoDB',
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
});
};
/**
* 新增打印任务唯一映射表(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
module.exports.up = async (queryInterface, Sequelize) => {
const tableName = 'wms_print_task_map';
const tableSet = await getExistingTableSet(queryInterface);
if (!tableSet.has(tableName)) {
await createPrintTaskMapTable(queryInterface, Sequelize);
}
const indexNameSet = await getIndexNameSet(queryInterface, tableName);
if (!indexNameSet.has('uix_task_code')) {
await queryInterface.addIndex(tableName, [ 'task_code' ], {
name: 'uix_task_code',
unique: true,
});
}
};
/**
* 回滚删除打印任务唯一映射表(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
module.exports.down = async queryInterface => {
const tableName = 'wms_print_task_map';
const tableSet = await getExistingTableSet(queryInterface);
if (!tableSet.has(tableName)) {
return;
}
await queryInterface.dropTable(tableName);
};

View File

@ -0,0 +1,179 @@
'use strict';
/**
* 获取打印记录表字段定义。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async queryInterface => {
return queryInterface.describeTable('wms_print_record');
};
/**
* 获取打印记录表索引名称集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 索引名称集合。
*/
const getIndexNameSet = async queryInterface => {
const indexes = await queryInterface.showIndex('wms_print_record');
return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean));
};
/**
* 执行迁移:为打印记录新增关联字段与索引(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
module.exports.up = async (queryInterface, Sequelize) => {
const tableName = 'wms_print_record';
const columns = await getTableColumns(queryInterface);
if (!columns.request_code) {
await queryInterface.addColumn(tableName, 'request_code', {
type: Sequelize.STRING(128),
allowNull: true,
comment: '请求参数码',
});
}
if (!columns.wave_id) {
await queryInterface.addColumn(tableName, 'wave_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '波次ID',
});
}
if (!columns.wave_no) {
await queryInterface.addColumn(tableName, 'wave_no', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '波次号',
});
}
if (!columns.platform_code) {
await queryInterface.addColumn(tableName, 'platform_code', {
type: Sequelize.STRING(32),
allowNull: true,
comment: '平台编码',
});
}
if (!columns.platform_name) {
await queryInterface.addColumn(tableName, 'platform_name', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '平台名称',
});
}
if (!columns.sys_logistics_code) {
await queryInterface.addColumn(tableName, 'sys_logistics_code', {
type: Sequelize.STRING(32),
allowNull: true,
comment: '系统快递编码',
});
}
if (!columns.sys_logistics_name) {
await queryInterface.addColumn(tableName, 'sys_logistics_name', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '系统快递名称',
});
}
const indexNameSet = await getIndexNameSet(queryInterface);
if (!indexNameSet.has('idx_request_code')) {
await queryInterface.addIndex(tableName, [ 'request_code' ], {
name: 'idx_request_code',
});
}
if (!indexNameSet.has('idx_wave_id')) {
await queryInterface.addIndex(tableName, [ 'wave_id' ], {
name: 'idx_wave_id',
});
}
if (!indexNameSet.has('idx_platform_code')) {
await queryInterface.addIndex(tableName, [ 'platform_code' ], {
name: 'idx_platform_code',
});
}
if (!indexNameSet.has('idx_sys_logistics_code')) {
await queryInterface.addIndex(tableName, [ 'sys_logistics_code' ], {
name: 'idx_sys_logistics_code',
});
}
if (!indexNameSet.has('idx_wave_platform_status')) {
await queryInterface.addIndex(tableName, [ 'wave_id', 'platform_code', 'status' ], {
name: 'idx_wave_platform_status',
});
}
};
/**
* 回滚迁移:移除打印记录关联字段与索引(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
module.exports.down = async queryInterface => {
const tableName = 'wms_print_record';
const indexNameSet = await getIndexNameSet(queryInterface);
if (indexNameSet.has('idx_wave_platform_status')) {
await queryInterface.removeIndex(tableName, 'idx_wave_platform_status');
}
if (indexNameSet.has('idx_sys_logistics_code')) {
await queryInterface.removeIndex(tableName, 'idx_sys_logistics_code');
}
if (indexNameSet.has('idx_platform_code')) {
await queryInterface.removeIndex(tableName, 'idx_platform_code');
}
if (indexNameSet.has('idx_wave_id')) {
await queryInterface.removeIndex(tableName, 'idx_wave_id');
}
if (indexNameSet.has('idx_request_code')) {
await queryInterface.removeIndex(tableName, 'idx_request_code');
}
const columns = await getTableColumns(queryInterface);
if (columns.sys_logistics_name) {
await queryInterface.removeColumn(tableName, 'sys_logistics_name');
}
if (columns.sys_logistics_code) {
await queryInterface.removeColumn(tableName, 'sys_logistics_code');
}
if (columns.platform_name) {
await queryInterface.removeColumn(tableName, 'platform_name');
}
if (columns.platform_code) {
await queryInterface.removeColumn(tableName, 'platform_code');
}
if (columns.wave_no) {
await queryInterface.removeColumn(tableName, 'wave_no');
}
if (columns.wave_id) {
await queryInterface.removeColumn(tableName, 'wave_id');
}
if (columns.request_code) {
await queryInterface.removeColumn(tableName, 'request_code');
}
};

View File

@ -0,0 +1,195 @@
'use strict';
/**
* 获取打印记录表字段定义。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async queryInterface => {
return queryInterface.describeTable('wms_print_record');
};
/**
* 获取打印记录表索引名称集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 索引名称集合。
*/
const getIndexNameSet = async queryInterface => {
const indexes = await queryInterface.showIndex('wms_print_record');
return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean));
};
/**
* 执行迁移:为打印记录表新增补偿重试字段与索引(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
module.exports.up = async (queryInterface, Sequelize) => {
const tableName = 'wms_print_record';
const columns = await getTableColumns(queryInterface);
if (!columns.send_status) {
await queryInterface.addColumn(tableName, 'send_status', {
type: Sequelize.STRING(32),
allowNull: false,
defaultValue: 'pending',
comment: '发送状态',
});
}
if (!columns.print_status) {
await queryInterface.addColumn(tableName, 'print_status', {
type: Sequelize.STRING(32),
allowNull: false,
defaultValue: 'unknown',
comment: '打印状态',
});
}
if (!columns.retry_count) {
await queryInterface.addColumn(tableName, 'retry_count', {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '已重试次数',
});
}
if (!columns.max_retry_count) {
await queryInterface.addColumn(tableName, 'max_retry_count', {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 3,
comment: '最大重试次数',
});
}
if (!columns.next_retry_at) {
await queryInterface.addColumn(tableName, 'next_retry_at', {
type: Sequelize.DATE,
allowNull: true,
comment: '下次重试时间',
});
}
if (!columns.last_retry_at) {
await queryInterface.addColumn(tableName, 'last_retry_at', {
type: Sequelize.DATE,
allowNull: true,
comment: '最后重试时间',
});
}
if (!columns.fail_code) {
await queryInterface.addColumn(tableName, 'fail_code', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '失败编码',
});
}
if (!columns.retry_of_print_id) {
await queryInterface.addColumn(tableName, 'retry_of_print_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '补偿来源打印记录ID',
});
}
const indexNameSet = await getIndexNameSet(queryInterface);
if (!indexNameSet.has('idx_send_status')) {
await queryInterface.addIndex(tableName, [ 'send_status' ], {
name: 'idx_send_status',
});
}
if (!indexNameSet.has('idx_print_status')) {
await queryInterface.addIndex(tableName, [ 'print_status' ], {
name: 'idx_print_status',
});
}
if (!indexNameSet.has('idx_next_retry_at')) {
await queryInterface.addIndex(tableName, [ 'next_retry_at' ], {
name: 'idx_next_retry_at',
});
}
if (!indexNameSet.has('idx_retry_of_print_id')) {
await queryInterface.addIndex(tableName, [ 'retry_of_print_id' ], {
name: 'idx_retry_of_print_id',
});
}
if (!indexNameSet.has('idx_print_status_next_retry')) {
await queryInterface.addIndex(tableName, [ 'print_status', 'next_retry_at' ], {
name: 'idx_print_status_next_retry',
});
}
};
/**
* 回滚迁移:移除打印记录表补偿重试字段与索引(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
module.exports.down = async queryInterface => {
const tableName = 'wms_print_record';
const indexNameSet = await getIndexNameSet(queryInterface);
if (indexNameSet.has('idx_print_status_next_retry')) {
await queryInterface.removeIndex(tableName, 'idx_print_status_next_retry');
}
if (indexNameSet.has('idx_retry_of_print_id')) {
await queryInterface.removeIndex(tableName, 'idx_retry_of_print_id');
}
if (indexNameSet.has('idx_next_retry_at')) {
await queryInterface.removeIndex(tableName, 'idx_next_retry_at');
}
if (indexNameSet.has('idx_print_status')) {
await queryInterface.removeIndex(tableName, 'idx_print_status');
}
if (indexNameSet.has('idx_send_status')) {
await queryInterface.removeIndex(tableName, 'idx_send_status');
}
const columns = await getTableColumns(queryInterface);
if (columns.retry_of_print_id) {
await queryInterface.removeColumn(tableName, 'retry_of_print_id');
}
if (columns.fail_code) {
await queryInterface.removeColumn(tableName, 'fail_code');
}
if (columns.last_retry_at) {
await queryInterface.removeColumn(tableName, 'last_retry_at');
}
if (columns.next_retry_at) {
await queryInterface.removeColumn(tableName, 'next_retry_at');
}
if (columns.max_retry_count) {
await queryInterface.removeColumn(tableName, 'max_retry_count');
}
if (columns.retry_count) {
await queryInterface.removeColumn(tableName, 'retry_count');
}
if (columns.print_status) {
await queryInterface.removeColumn(tableName, 'print_status');
}
if (columns.send_status) {
await queryInterface.removeColumn(tableName, 'send_status');
}
};

View File

@ -0,0 +1,45 @@
'use strict';
/**
* 获取当前数据库已存在的表名集合(兼容 showAllTables 返回字符串或对象)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Set<string>>} 表名集合。
*/
const getExistingTableSet = async queryInterface => {
const tables = await queryInterface.showAllTables();
return new Set(
tables.map(table => (typeof table === 'string' ? table : table.tableName))
);
};
/**
* 升级迁移:将 wms_review_task 重命名为 wms_recheck_task。
* 仅在旧表存在且新表不存在时执行,其他情况安全跳过。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
module.exports.up = async queryInterface => {
const sourceTable = 'wms_review_task';
const targetTable = 'wms_recheck_task';
const tableSet = await getExistingTableSet(queryInterface);
if (tableSet.has(sourceTable) && !tableSet.has(targetTable)) {
await queryInterface.renameTable(sourceTable, targetTable);
}
};
/**
* 回滚迁移:将 wms_recheck_task 重命名回 wms_review_task。
* 仅在旧表存在且新表不存在时执行,其他情况安全跳过。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
module.exports.down = async queryInterface => {
const sourceTable = 'wms_recheck_task';
const targetTable = 'wms_review_task';
const tableSet = await getExistingTableSet(queryInterface);
if (tableSet.has(sourceTable) && !tableSet.has(targetTable)) {
await queryInterface.renameTable(sourceTable, targetTable);
}
};

654
dev_out.log Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,65 @@
# 打印失败自动补偿(printRetryCompensation)操作说明
概述
- 目的:定时扫描失败或超时的打印记录,按仓库分组并批量触发补打(调用内部方法 `print.retryFailed`)。
- 实现位置:调度任务文件 [app/schedule/print_retry_compensation.js](app/schedule/print_retry_compensation.js)
- 配置位置:全局配置 `config.printRetryCompensation`(见 `config/config.default.js`)
如何开启
1. 在目标环境的配置文件中(例如 `config/config.local.js` 或部署时注入的 config),设置:
```js
// 示例(config/config.local.js)
module.exports = appInfo => {
const config = exports = {};
config.printRetryCompensation = {
enable: true, // 开启自动补偿
intervalMs: 60 * 1000, // 最小执行间隔(ms),默认 60000
batchSize: 50, // 每次扫描触发的最大打印记录数,默认 50
force: false, // 是否以强制方式触发(当前实现不放宽状态判定)
};
return config;
};
```
2. 启用后,Egg 的调度器会按文件中的 `schedule.interval`(30s)触发调度器,但实际执行受 `intervalMs` 控制(避免重复执行)。
3. 部署/重启应用使配置生效。
关键参数说明
- `enable` (boolean):是否启用自动补偿(默认 `false`)。
- `intervalMs` (number, ms):两次实际执行之间的最小间隔(默认 60000)。注意调度器仍以 30s 触发,但若距离上次执行时间 < intervalMs 将跳过本轮。
- `batchSize` (number):每次从数据库读出的最大记录数量(默认 50)。
- `force` (boolean):是否强制补打。当前最小实现中 `force` 参数会被传递到 `print.retryFailed`,但 `getRetryEligibility` 中并未放宽状态检查(注释标注为“最小实现”)。如需放宽,需要修改 `app/service/systemMethods/print.js` 中的 `getRetryEligibility` 实现。
行为与兼容性(与代码的一致性要点)
- 调度逻辑:
- 调度入口:[app/schedule/print_retry_compensation.js](app/schedule/print_retry_compensation.js)
- 查询条件:满足任一 send_status 为 `send_failed`,或 print_status 在 `['print_failed','timeout']`,且 `next_retry_at <= now`,并且 `retry_count < max_retry_count`。
- 按 `warehouse_id` 分组后,逐仓调用:
`ctx.service.systemMethods.print.retryFailed({ print_ids, warehouse_id, force })`。
- `print.retryFailed` 对 `warehouse_id` 的兼容:
- 支持显式传入 `warehouse_id`,优先使用该值。
- 若未传入 `warehouse_id`,会回退使用 `ctx.user.store_id`(接口调用者的仓库上下文)。
- 如果两者均无(例如外部无登录上下文且未传入 `warehouse_id`),方法会返回 400 错误:`warehouse_id 参数缺失,且当前上下文无可用仓库信息`。
- 返回值要点:成功返回包含 `success_count` / `failed_count` / `skipped_count`、`retried`(尝试项)和 `skipped`(跳过项)摘要;调度器依据 `flag==='success'` 判定调用是否成功。
排障要点(常见问题排查)
- 任务一直没有扫描到记录:检查数据库 `PrintRecord` 表中是否存在满足条件的行(`send_status`/`print_status`、`next_retry_at`、`retry_count < max_retry_count`)。
- 调度被频繁跳过:检查 `config.printRetryCompensation.intervalMs` 与日志中 `ctx.app._printRetryCompensationLastRunAt` 的时间差;若 `_printRetryCompensationRunning` 标识长时间为 true,进程可能在上次运行时异常退出,建议重启应用清理状态。
- 补打触发但实际发送失败:查看打印服务调用日志(`service.systems.print.index.sendToComputer` 返回值),并查看 `PrintRecord` 的 `error_message` / `fail_code` 字段。
- 快递/组件离线导致发送失败:`print` 服务会在调用前检查组件在线性(从 Redis 的 `printer:{computerId}:name:{component}:status` 读取,期望值为 `connected`)。请检查对应 Redis key 是否存在并为 `connected`。
- 打印任务编码冲突:如果出现唯一索引冲突(ER_DUP_ENTRY),日志会有 `打印任务编码冲突` 的警告,系统会按指数退避重试写入映射表。
回滚方式
- 临时回滚:在运行环境配置中将 `printRetryCompensation.enable` 设为 `false` 并重启服务,调度器将不再触发实际补偿逻辑。
- 速率/批量调整:将 `batchSize` 缩小或增大 `intervalMs`,以控制对打印服务的并发压力。
参考位置
- 调度实现:[app/schedule/print_retry_compensation.js](app/schedule/print_retry_compensation.js)
- 默认配置:[config/config.default.js](config/config.default.js)(`printRetryCompensation` 段)
- 补打实现与仓库兼容性:[app/service/systemMethods/print.js](app/service/systemMethods/print.js) 中 `retryFailed` 与 `getRetryEligibility` 方法
附注
- 本说明以当前代码实现为准(2026-05-20),如修改 `getRetryEligibility` 或补打流程,请同步更新本说明与 `methods/changes` 记录。

34
get_specific_logs.ps1 Normal file
View File

@ -0,0 +1,34 @@
$targetTs = "2026-05-20 02:20:00"
$kws = @(
'print-retry-compensation',
'print_retry_compensation\.js',
'retryFailed',
'触发补打',
'任务执行完成',
'/__schedule\?path=D:\\wms\\app\\schedule\\print_retry_compensation\.js'
)
$results = New-Object System.Collections.Generic.List[string]
Get-ChildItem logs/wms/wms-web.log* | ForEach-Object {
$fileName = $_.Name
$fs = New-Object System.IO.FileStream($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
$reader = New-Object System.IO.StreamReader($fs)
while($null -ne ($line = $reader.ReadLine())){
if($line -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'){
$ts = $matches[1]
if($ts -ge $targetTs){
foreach($k in $kws){
if($line -match $k){
$results.Add("$($fileName): $($line)")
break
}
}
}
}
}
$reader.Close()
$fs.Dispose()
}
$results | ForEach-Object { Write-Output $_ }

View File

@ -0,0 +1,16 @@
[
{
"version": "2026.05.20-system-01",
"date": "2026-05-20",
"summary": "新增订单复核模块方法:order.recheckOrder.scanWaybill、order.recheckOrder.confirmRecheck",
"methods": [
"order.recheckOrder.scanWaybill",
"order.recheckOrder.confirmRecheck"
],
"notes": [
"用途:扫码查询订单明细(scanWaybill);确认复核并落库 wms_recheck_task(confirmRecheck)。",
"scanWaybill 返回运单号、订单头、商品明细、运单信息与相关日志;confirmRecheck 将复核结果写入 wms_recheck_task 并返回复核摘要信息(order_id、recheck_status、recheck_time、review_no)。"
],
"type": "added"
}
]

View File

@ -1971,5 +1971,37 @@
"本次为向后兼容的文档增强:新增可选策略字段说明,不影响现有调用。"
],
"type": "updated"
},
{
"version": "2026.05.19-system-01",
"date": "2026-05-19",
"summary": "补充 storage.entry.list 的 expense_record 筛选语义与未迁移环境错误提示",
"methods": [
"storage.entry.list"
],
"notes": [
"在 where 参数说明中补充 expense_record 字段语义(费用是否记录)及 eq/in 支持。",
"明确 true/false、1/0、y/n、yes/no 的归一化规则与等价写法示例。",
"补充未完成表结构迁移时可能返回 400 及错误提示文案。"
],
"type": "updated"
},
{
"version": "2026.05.20-system-02",
"date": "2026-05-20",
"summary": "新增打印失败自动补偿能力:定时扫描并触发 print.retryFailed 批量补打",
"methods": [
"print.retryFailed"
],
"notes": [
"新增定时任务:app/schedule/print_retry_compensation.js,按仓库分组调用 print.retryFailed 进行批量补打。",
"配置项位置:config/config.default.js 的 printRetryCompensation,包含:enable(boolean, 默认 false)、intervalMs(毫秒,默认 60000)、batchSize(批量大小,默认 50)、force(boolean,默认 false)、maxRetryCount(number,默认 5)。",
"行为摘要:任务按 printRetryCompensation.intervalMs 频率查询 send_status=send_failed 或 print_status IN (print_failed, timeout),且 next_retry_at <= now 且 retry_count < maxRetryCount 的记录,按仓库分组并调用 print.retryFailed({ print_ids, warehouse_id, force }) 进行补打。",
"兼容性:print.retryFailed 支持显式传入 warehouse_id(调度任务会传入),当未提供时回退到 ctx.user.store_id;若两者均无则接口返回 400。",
"注意:当前实现中传入的 force 参数不会放宽对状态的判定(代码注释说明为“最小实现”),如需放宽需修改 print.getRetryEligibility 的逻辑。",
"回滚说明:1) 将 printRetryCompensation.enable 设为 false 并重启服务以停止新任务;2) 从部署包中移除或注释 app/schedule/print_retry_compensation.js 并重启服务;3) 如需从 methods/changes/system.json 中移除此变更,请通过生成对应 spec(change.version 设置为本条版本并 type='removed')并运行 npm run doc:api:update -- --spec=<spec> 来更新变更记录;4) 若调度已触发的补打需中止,请在调度或队列系统中停止对应任务或通过运维回退正在执行的补打逻辑。"
],
"module": "print",
"type": "added"
}
]

View File

@ -1,8 +1,8 @@
{
"module": "system",
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
"version": "0.0.0",
"updatedAt": "2026-05-17",
"version": "0.0.1",
"updatedAt": "2026-05-20",
"headers": [
{
"name": "platform",
@ -2593,6 +2593,132 @@
}
]
},
{
"groupName": "订单复核模块",
"module": "order.recheckOrder",
"list": [
{
"method": "order.recheckOrder.scanWaybill",
"description": "扫码查询运单并返回订单详情",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "waybill_no / waybillCode / waybill_code",
"type": "string",
"required": true,
"source": "body|query",
"description": "运单号;支持别名 waybillCode、waybill_code"
}
],
"response": [
{
"name": "waybill_no",
"type": "string",
"description": "匹配到的运单号"
},
{
"name": "order",
"type": "object",
"description": "订单头对象"
},
{
"name": "items",
"type": "array",
"description": "订单商品明细"
},
{
"name": "expresses",
"type": "array",
"description": "运单信息数组"
},
{
"name": "logs",
"type": "array",
"description": "相关操作日志"
}
],
"errors": [
{
"code": "400",
"description": "运单号不能为空"
},
{
"code": "404",
"description": "未找到对应订单"
}
]
},
{
"method": "order.recheckOrder.confirmRecheck",
"description": "确认复核并记录复核任务到 wms_recheck_task",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "waybill_no / waybillCode / waybill_code",
"type": "string",
"required": true,
"source": "body|query",
"description": "运单号,支持别名 waybillCode、waybill_code"
}
],
"response": [
{
"name": "order_id",
"type": "number",
"description": "订单 ID"
},
{
"name": "waybill_no",
"type": "string",
"description": "运单号"
},
{
"name": "recheck_status",
"type": "string",
"description": "复核结果状态"
},
{
"name": "recheck_time",
"type": "string",
"description": "复核时间(ISO 字符串)"
},
{
"name": "review_no",
"type": "string",
"description": "复核任务编号"
}
],
"errors": [
{
"code": "400",
"description": "运单号不能为空"
},
{
"code": "404",
"description": "未找到对应订单"
}
]
}
]
},
{
"groupName": "订单波次模块",
"module": "order.wave",
@ -8056,6 +8182,114 @@
"description": "保存失败或内部错误"
}
]
},
{
"method": "print.retryFailed",
"description": "失败项补打:重试指定打印记录的发送。被定时任务 print-retry-compensation 调用以批量触发失败项补打。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "print_ids",
"type": "array",
"required": true,
"source": "body",
"description": "要补打的打印记录 ID 数组",
"children": [
{
"name": "id",
"type": "number",
"description": "打印记录 ID"
}
]
},
{
"name": "force",
"type": "boolean",
"required": false,
"source": "body",
"description": "是否强制补打(当前实现仍不放宽状态判定)"
},
{
"name": "warehouse_id",
"type": "number",
"required": false,
"source": "body",
"description": "显式指定仓库 ID(调度任务推荐提供),若缺失将使用当前用户的 store_id"
}
],
"response": [
{
"name": "flag",
"type": "string",
"required": true,
"description": "调用标识,成功为 success"
},
{
"name": "code",
"type": "number",
"required": true,
"description": "业务状态码,成功通常为 200"
},
{
"name": "message",
"type": "string",
"required": true,
"description": "返回信息"
},
{
"name": "success_count",
"type": "number",
"required": false,
"description": "成功补打数量"
},
{
"name": "failed_count",
"type": "number",
"required": false,
"description": "补打失败数量"
},
{
"name": "skipped_count",
"type": "number",
"required": false,
"description": "被跳过的记录数量"
},
{
"name": "retried",
"type": "array",
"required": false,
"description": "补打尝试结果数组"
},
{
"name": "skipped",
"type": "array",
"required": false,
"description": "跳过项明细"
}
],
"errors": [
{
"code": 400,
"message": "warehouse_id 参数缺失,且当前上下文无可用仓库信息"
},
{
"code": 400,
"message": "print_ids 参数不能为空数组或不合法"
},
{
"code": 500,
"message": "内部错误"
}
]
}
]
},
@ -13472,7 +13706,7 @@
"type": "object",
"required": false,
"source": "body",
"description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status、store_id、order_type、日期区间等字段。示例:where.order_status={operator:eq,value:waiting}; where.order_type={operator:eq,value:purchase}; where.create_time_start={value:2026-03-01}。"
"description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为“当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级”。"
},
{
"name": "sort",
@ -13505,10 +13739,12 @@
"errors": [
{
"code": "400",
"message": "筛选条件格式错误",
"description": "筛选条件格式错误"
},
{
"code": "500",
"message": "查询失败",
"description": "查询失败"
}
]

41
search_logs.ps1 Normal file
View File

@ -0,0 +1,41 @@
$targetTs = "2026-05-20 02:20:00"
$kws = @(
'print-retry-compensation',
'print_retry_compensation\\.js',
'retryFailed',
'触发补打',
'任务执行完成',
'SCHEDULE /__schedule\?path=D:\\\\wms\\\\app\\\\schedule\\\\print_retry_compensation\\.js'
)
$sqlPart = "FROM `wms_print_record` AS `PrintRecord` WHERE ((`PrintRecord`.`send_status` = 'send_failed' OR `PrintRecord`.`print_status` IN ('print_failed', 'timeout'))"
$results = New-Object System.Collections.Generic.List[string]
$file = Get-Item "logs/wms/wms-web.log"
$lines = Get-Content $file.FullName
for ($i = 0; $i -lt $lines.Count; $i++) {
$line = $lines[$i]
if ($line -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})') {
$ts = $matches[1]
if ($ts -ge $targetTs) {
foreach ($k in $kws) {
if ($line -match $k) {
$item = "$($file.Name):$($i+1):$line"
$results.Add($item)
Write-Output $item
break
}
}
}
}
}
if ($results.Count -lt 5) {
$sqlSearch = $sqlPart.Replace("`", "")
for ($i = 0; $i -lt $lines.Count; $i++) {
$line = $lines[$i]
if ($line -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})') {
if ($matches[1] -ge $targetTs -and $line.Contains($sqlSearch)) {
$item = "$($file.Name):$($i+1):$line"
if (-not $results.Contains($item)) { Write-Output $item }
}
}
}
}

View File

@ -0,0 +1,255 @@
'use strict';
const assert = require('node:assert/strict');
const schedule = require('../../../app/schedule/print_retry_compensation');
describe('test/app/schedule/print_retry_compensation.test.js', () => {
it('should scan retryable records and invoke retryFailed grouped by warehouse', async () => {
assert.equal(schedule.schedule.interval, '30s');
assert.equal(schedule.schedule.type, 'worker');
assert.equal(schedule.schedule.immediate, false);
const Op = {
and: Symbol('and'),
or: Symbol('or'),
in: Symbol('in'),
lte: Symbol('lte'),
lt: Symbol('lt'),
};
const retryCalls = [];
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: {
printRetryCompensation: {
enable: true,
intervalMs: 0,
batchSize: 50,
force: false,
},
},
Sequelize: {
Op,
col(fieldName) {
return `col:${fieldName}`;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
model: {
PrintRecord: {
async findAll(options) {
assert.equal(options.limit, 50);
assert.equal(options.raw, true);
return [
{ id: 101, warehouse_id: 1 },
{ id: 102, warehouse_id: 1 },
{ id: 201, warehouse_id: 2 },
];
},
},
},
service: {
systemMethods: {
print: {
async retryFailed(data) {
retryCalls.push(data);
return {
flag: 'success',
success_count: data.print_ids.length,
failed_count: 0,
skipped_count: 0,
};
},
},
},
},
};
await schedule.task(ctx);
assert.equal(retryCalls.length, 2);
const firstCall = retryCalls[0];
const secondCall = retryCalls[1];
assert.deepEqual(firstCall, {
print_ids: [ 101, 102 ],
warehouse_id: 1,
force: false,
});
assert.deepEqual(secondCall, {
print_ids: [ 201 ],
warehouse_id: 2,
force: false,
});
assert.equal(ctx.app._printRetryCompensationRunning, false);
});
it('should skip when disabled or already running', async () => {
let findAllCount = 0;
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: {
printRetryCompensation: {
enable: false,
intervalMs: 60000,
batchSize: 10,
},
},
Sequelize: {
Op: {},
col(fieldName) {
return `col:${fieldName}`;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
model: {
PrintRecord: {
async findAll() {
findAllCount += 1;
return [];
},
},
},
service: {
systemMethods: {
print: {
async retryFailed() {
throw new Error('should not reach');
},
},
},
},
};
await schedule.task(ctx);
assert.equal(findAllCount, 0);
ctx.app.config.printRetryCompensation.enable = true;
ctx.app._printRetryCompensationRunning = true;
await schedule.task(ctx);
assert.equal(findAllCount, 0);
});
it('should include retry_count < max_retry_count in where clause', async () => {
const Op = {
and: Symbol('and'),
or: Symbol('or'),
in: Symbol('in'),
lte: Symbol('lte'),
lt: Symbol('lt'),
};
let whereClause;
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
Sequelize: { Op, col: fieldName => `col:${fieldName}` },
},
logger: { info() {}, warn() {}, error() {} },
model: {
PrintRecord: {
async findAll(options) {
whereClause = options.where;
return [];
},
},
},
service: { systemMethods: { print: { async retryFailed() {} } } },
};
await schedule.task(ctx);
const andConditions = whereClause[Op.and];
assert(Array.isArray(andConditions), 'where[Op.and] should be an array');
const retryCountCondition = andConditions.find(condition => condition && condition.retry_count);
assert(retryCountCondition, 'retry_count condition should exist in where[Op.and]');
assert.deepStrictEqual(retryCountCondition.retry_count, { [Op.lt]: 'col:max_retry_count' });
});
it('should include next_retry_at <= now in where clause', async () => {
const Op = {
and: Symbol('and'),
or: Symbol('or'),
in: Symbol('in'),
lte: Symbol('lte'),
lt: Symbol('lt'),
};
let whereClause;
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
Sequelize: { Op, col: () => {} },
},
logger: { info() {}, warn() {}, error() {} },
model: {
PrintRecord: {
async findAll(options) {
whereClause = options.where;
return [];
},
},
},
service: { systemMethods: { print: { async retryFailed() {} } } },
};
await schedule.task(ctx);
const andConditions = whereClause[Op.and];
assert(Array.isArray(andConditions), 'where[Op.and] should be an array');
const nextRetryAtCondition = andConditions.find(condition => condition && condition.next_retry_at);
assert(nextRetryAtCondition, 'next_retry_at condition should exist in where[Op.and]');
assert(nextRetryAtCondition.next_retry_at[Op.lte], 'should use lte operator');
assert(nextRetryAtCondition.next_retry_at[Op.lte] instanceof Date, 'should compare with a Date object');
});
it('should skip invalid records and not trigger retryFailed', async () => {
let retryFailedCalled = false;
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
Sequelize: { Op: {}, col: () => {} },
},
logger: { info() {}, warn() {}, error() {} },
model: {
PrintRecord: {
async findAll() {
return [
{ id: 0, warehouse_id: 1 },
{ id: 1, warehouse_id: 0 },
{ id: -1, warehouse_id: 1 },
{ id: 1, warehouse_id: -1 },
];
},
},
},
service: {
systemMethods: {
print: {
async retryFailed() {
retryFailedCalled = true;
},
},
},
},
};
await schedule.task(ctx);
assert.equal(retryFailedCalled, false, 'retryFailed should not be called for invalid records');
});
});

View File

@ -487,7 +487,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => {
assert.deepEqual(calls.sendOrderMarks, [ 'W1-P1', 'W1-P2', 'W2-P1' ]);
assert.equal(calls.printRecordUpdatePayloads.length, 0);
assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.send_status, 'sent');
assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.print_status, 'unknown');
assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.print_status, 'printed');
assert.ok(calls.printRecordStaticUpdatePayloads[0].payload.sent_time instanceof Date);
});
@ -840,10 +840,105 @@ describe('test/app/service/systemMethods/print.send.test.js', () => {
});
assert.equal(result.flag, 'success');
assert.equal(calls.orderDeliveryLockUpdates.length, 1);
assert.equal(calls.orderDeliveryLockUpdates[0].payload.print_lock_status, 'warehouse');
assert.deepEqual(calls.orderDeliveryLockUpdates[0].query.where.id, [ 101, 102 ]);
assert.equal(calls.orderDeliveryLockUpdates[0].query.where.print_lock_status, 'none');
assert.equal(calls.orderDeliveryLockUpdates.length, 2);
const lockUpdate = calls.orderDeliveryLockUpdates.find(item => item && item.payload && item.payload.print_lock_status === 'warehouse');
assert.ok(lockUpdate);
assert.deepEqual(lockUpdate.query.where.id, [ 101, 102 ]);
assert.equal(lockUpdate.query.where.print_lock_status, 'none');
const printStatusUpdate = calls.orderDeliveryLockUpdates.find(item => item && item.payload && item.payload.print_status === 'fin');
assert.ok(printStatusUpdate);
assert.deepEqual(printStatusUpdate.query.where.id, [ 101, 102 ]);
});
it('type=express 前批次成功后批次失败时应保持成功批次 print_status 回写', async () => {
let sendCount = 0;
const { ctx, calls } = createContext({
sendToComputer: async payload => {
calls.sendToComputerPayloads.push(payload);
sendCount += 1;
if (sendCount === 2) {
return {
status: 'failure',
error: '第二批次发送失败',
};
}
return {
status: 'success',
};
},
});
const service = new PrintService(ctx);
const result = await service.send({
type: 'express',
requestCode: 'REQ-PARTIAL-SUCCESS-THEN-FAIL',
printStationId: 101,
data: {
waveGroups: [
{
wave_id: 1,
wave_no: 'WAVE-PARTIAL-1',
platforms: [
{
platform: 'cainiao',
sys_logistics_code: 'STO',
order_ids: [ 201, 202 ],
orders: [
{
order_id: 201,
print_data: {
documentID: 'DOC-PARTIAL-1',
contents: [
{
marker: 'PARTIAL-1',
},
],
},
},
],
},
{
platform: 'pdd',
sys_logistics_code: 'YTO',
order_ids: [ 301 ],
orders: [
{
order_id: 301,
print_data: {
documentID: 'DOC-PARTIAL-2',
contents: [
{
marker: 'PARTIAL-2',
},
],
},
},
],
},
],
},
],
},
});
assert.equal(result.flag, 'failure');
assert.equal(result.code, 504);
assert.equal(calls.sendToComputerPayloads.length, 2);
const successfulBatchPrintStatusUpdate = calls.orderDeliveryLockUpdates.find(item => (
item
&& item.payload
&& item.payload.print_status === 'fin'
&& item.query
&& item.query.where
&& Array.isArray(item.query.where.id)
&& item.query.where.id.length === 2
&& item.query.where.id.includes(201)
&& item.query.where.id.includes(202)
));
assert.ok(successfulBatchPrintStatusUpdate);
});
it('type=express provider 成功后应回写 print_record 与 print_task_map,且回写可重入', async () => {
@ -873,7 +968,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => {
assert.equal(state.printRecordsById[9001].print_task_code, taskCode);
assert.equal(state.printRecordsById[9001].status, 'sent');
assert.equal(state.printRecordsById[9001].send_status, 'sent');
assert.equal(state.printRecordsById[9001].print_status, 'unknown');
assert.equal(state.printRecordsById[9001].print_status, 'printed');
assert.equal(calls.printRecordStaticUpdatePayloads.length, 1);
assert.equal(calls.printRecordStaticUpdatePayloads[0].payload.print_task_code, taskCode);
});
@ -936,7 +1031,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => {
assert.equal(calls.printRecordUpdatePayloads.length, 1);
assert.equal(calls.printRecordUpdatePayloads[0].payload.status, 'sent');
assert.equal(calls.printRecordUpdatePayloads[0].payload.send_status, 'sent');
assert.equal(calls.printRecordUpdatePayloads[0].payload.print_status, 'unknown');
assert.equal(calls.printRecordUpdatePayloads[0].payload.print_status, 'printed');
assert.ok(calls.printRecordUpdatePayloads[0].payload.sent_time instanceof Date);
});
@ -1084,7 +1179,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => {
assert.equal(newRecord.retry_of_print_id, sourceRecordId);
assert.equal(newRecord.status, 'sent');
assert.equal(newRecord.send_status, 'sent');
assert.equal(newRecord.print_status, 'unknown');
assert.equal(newRecord.print_status, 'printed');
assert.notEqual(newRecord.data.data.task.taskID, 'OLD_TASK_ID');
assert.equal(newRecord.data.data.task.taskID, result.retried[0].task_code);
assert.equal(state.printRecordsById[sourceRecordId].status, 'failed');

View File

@ -905,6 +905,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
sys_logistics_code: 'unknown',
sys_logistics_name: 'unknown',
order_count: 1,
order_ids: [ 12 ],
orders: [
{
platform: 'cainiao',
@ -918,6 +919,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
sys_logistics_code: 'unknown',
sys_logistics_name: 'unknown',
order_count: 1,
order_ids: [ 11 ],
orders: [
{
platform: 'jd',
@ -939,6 +941,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
sys_logistics_code: 'unknown',
sys_logistics_name: 'unknown',
order_count: 1,
order_ids: [ 21 ],
orders: [
{
platform: 'jd',
@ -966,6 +969,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
orderPrintList: [
{
wave_id: 1,
order_id: 11,
platform: 'jd',
platform_name: '京东',
sys_logistics_code: 'ZTO',
@ -974,6 +978,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
},
{
wave_id: 1,
order_id: 12,
platform: 'jd',
platform_name: '京东',
sys_logistics_code: 'YTO',
@ -982,6 +987,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
},
{
wave_id: 1,
order_id: 13,
platform: 'jd',
platform_name: '京东',
sys_logistics_code: 'ZTO',
@ -990,6 +996,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
},
{
wave_id: 1,
order_id: 14,
platform: 'jd',
platform_name: '京东',
sys_logistics_code: '',
@ -1011,6 +1018,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
sys_logistics_code: 'ZTO',
sys_logistics_name: '中通快递',
order_count: 2,
order_ids: [ 11, 13 ],
orders: [
{ order_id: 11 },
{ order_id: 13 },
@ -1025,6 +1033,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
sys_logistics_code: 'YTO',
sys_logistics_name: '圆通速递',
order_count: 1,
order_ids: [ 12 ],
orders: [
{ order_id: 12 },
],
@ -1038,6 +1047,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
sys_logistics_code: 'unknown',
sys_logistics_name: 'unknown',
order_count: 1,
order_ids: [ 14 ],
orders: [
{ order_id: 14 },
],
@ -1407,4 +1417,41 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js'
assert.ok(printText.includes('快照商品名-应展示'));
assert.ok(!printText.includes('旧商品名-不应展示'));
});
it('should return locked result when any order print_lock_status is not none', async () => {
const service = createOrderPrintServiceHarness();
service.queryWavesByIds = async () => ([
{ wave_id: 50, wave_no: 'W050' },
]);
service.queryOrdersByWaveIds = async () => ([
{
id: 501,
wave_id: 50,
wave_no: 'W050',
warehouse_id: 100000,
store_id: 1,
delivery_order_code: 'O501',
source_order_codes: 'SO501',
post_status: 'fin',
print_lock_status: 'warehouse',
},
]);
service.filterFullyAssignedExpressWaves = () => ({
validWaveIds: [ 50 ],
filteredWaveIds: [],
});
const result = await service.getWavePlatformPrintData({
waveIds: [ 50 ],
warehouseId: 100000,
});
assert.equal(result.summary.total_orders, 0);
assert.equal(result.summary.locked_count, 1);
assert.equal(result.locked_count, 1);
assert.deepEqual(result.waveGroups, []);
assert.equal(result.locked_orders[0].order_id, 501);
assert.equal(result.locked_orders[0].print_lock_status, 'warehouse');
});
});

View File

@ -25,6 +25,7 @@ function createTestContext(options = {}) {
or: '$or',
ne: '$ne',
like: '$like',
notLike: '$notLike',
gt: '$gt',
lt: '$lt',
gte: '$gte',
@ -199,6 +200,7 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js
[ 'ne', { value: 'SKU' }, { item_code: { [Op.ne]: 'SKU' } }],
[ 'like', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } }],
[ 'contains', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } }],
[ 'notlike', { value: 'SKU' }, { item_code: { [Op.notLike]: '%SKU%' } }],
[ 'startswith', { value: 'SKU' }, { item_code: { [Op.like]: 'SKU%' } }],
[ 'endswith', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU' } }],
[ 'gt', { value: 10 }, { item_code: { [Op.gt]: 10 } }],

View File

@ -0,0 +1,165 @@
'use strict';
const assert = require('node:assert/strict');
const EntryService = require('../../../../app/service/systems/storage/entry');
function createListServiceHarness() {
const Op = {
and: 'and',
or: 'or',
like: 'like',
in: 'in',
ne: 'ne',
gt: 'gt',
lt: 'lt',
gte: 'gte',
lte: 'lte',
notIn: 'notIn',
between: 'between',
notBetween: 'notBetween',
is: 'is',
not: 'not',
regexp: 'regexp',
notRegexp: 'notRegexp',
};
const calls = {
findAndCountAll: [],
findAll: [],
};
const model = {
Store: {},
EntryOrder: {
rawAttributes: {
expense_record: {
field: 'expense_record',
},
},
async findAndCountAll(options) {
calls.findAndCountAll.push(options);
return {
count: 0,
rows: [],
};
},
async findAll(options) {
calls.findAll.push(options);
return [];
},
},
};
const ctx = {
user: {
store_id: 1001,
},
model,
app: {
Sequelize: {
Op,
fn(name, column) {
return {
name,
column,
};
},
col(name) {
return name;
},
where(left, right) {
return {
left,
right,
};
},
literal(sql) {
return sql;
},
escape(value) {
if (typeof value === 'number') {
return String(value);
}
return `'${String(value)}'`;
},
},
},
};
return {
service: new EntryService(ctx),
calls,
Op,
};
}
describe('test/app/service/systems/storage.entry.list.expenseRecord.test.js', () => {
it('should push down boolean expense_record condition as eq filter', async () => {
const { service, calls, Op } = createListServiceHarness();
const result = await service.list({
expense_record: true,
}, {
page: 1,
pageSize: 10,
}, {});
assert.equal(result.code, 200);
assert.equal(calls.findAndCountAll.length, 1);
const finalWhere = calls.findAndCountAll[0].where;
const andConditions = finalWhere[Op.and];
const dynamicBucket = andConditions.find(item => item && item[Op.and]);
assert.ok(dynamicBucket, '应包含动态筛选条件');
assert.deepEqual(dynamicBucket[Op.and], [{ expense_record: 1 }]);
});
it('should support expense_record in filter with mixed bool and number values', async () => {
const { service, calls, Op } = createListServiceHarness();
const result = await service.list({
expense_record: {
operator: 'in',
value: [ true, '0', 1, false ],
},
}, {
page: 1,
pageSize: 10,
}, {});
assert.equal(result.code, 200);
assert.equal(calls.findAndCountAll.length, 1);
const finalWhere = calls.findAndCountAll[0].where;
const andConditions = finalWhere[Op.and];
const dynamicBucket = andConditions.find(item => item && item[Op.and]);
assert.ok(dynamicBucket, '应包含动态筛选条件');
assert.deepEqual(dynamicBucket[Op.and], [
{
expense_record: {
[Op.in]: [ 1, 0 ],
},
},
]);
});
it('should keep compatibility and return 400 when expense_record field is not available', async () => {
const { service } = createListServiceHarness();
delete service.ctx.model.EntryOrder.rawAttributes.expense_record;
const result = await service.list({
expense_record: {
operator: 'eq',
value: 1,
},
}, {
page: 1,
pageSize: 10,
}, {});
assert.equal(result.code, 400);
assert.match(String(result.message || ''), /expense_record 字段/);
});
});

View File

@ -226,14 +226,17 @@ describe('test/app/service/systems/storage.report.test.js', () => {
assert.equal(stockB.end_total, 4);
assert.equal(stockB.inbound_total, 4);
assert.equal(stockB.outbound_total, 0);
assert.match(calls.queries[1].sql, /FROM wms_stock_transaction t/);
assert.match(calls.queries[2].sql, /FROM wms_stock_transaction t/);
assert.match(calls.queries[2].sql, /before_quantity/);
assert.doesNotMatch(calls.queries[2].sql, /storage_id/);
assert.match(calls.queries[3].sql, /FROM wms_stock_transaction t/);
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({
const { service, calls } = createReportServiceHarness({
queryResults: [
[
{ stock_id: 301, space_id: 501, store_id: 401, quantity: 7 },
@ -283,6 +286,10 @@ describe('test/app/service/systems/storage.report.test.js', () => {
assert.equal(spaceA.end_total, 10);
assert.equal(spaceB.begin_total, 10);
assert.equal(spaceB.end_total, 12);
assert.match(calls.queries[1].sql, /FROM wms_storage_transaction t/);
assert.match(calls.queries[1].sql, /GROUP BY t.stock_id, COALESCE\(t.space_id, 0\), t.store_id/);
assert.match(calls.queries[2].sql, /FROM wms_storage_transaction t/);
assert.match(calls.queries[3].sql, /FROM wms_storage_transaction t/);
});
it('should return base space keys with zero fallback when by_space is true and interval has no transactions', async () => {