feat(wms): 工作台成员、波次范围、库存明细与报表修复等多项更新
- workbench: 工作台成员拆分 wms_workbench_member 表,下线 barcode 字段,新增绑定/移除成员接口 - order: 订单配送新增 wave_scope 波次范围字段与历史回填,自动分配快递排除备注与储位分配限制修复 - storage.transaction.list: 重写为 wms_storage_transaction 逐条明细查询,消除聚合慢查询 - stock.report: 分页默认生效、排序白名单扩充、where.stock_id 数组兼容修复 - storage.entry: quickInbound/commit 新增 noNeedNotice 通知开关 - storage.inventory.list: stock_query 支持数组多关键字并集匹配 - store: 手工单回传通知策略 notify_manual_sync - docs: 同步接口文档与变更记录、路由表;test: 补充快递排除与储位分配限制测试
This commit is contained in:
parent
b6ae8313a1
commit
95067aeb8a
@ -161,6 +161,26 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- 接口文档:`methods/system.json` 分组「站内信」(module=inbox),变更记录见 `methods/changes/system.json` 版本 `2026.08.30-inbox-group-members-groupids-array`、`2026.08.30-inbox-group-quicklist-dual-dim-filter`(修正/取代 `2026.08.30-inbox-group-quicklist-store-id`)、`2026.08.29-inbox-group-quick-list-members`
|
||||
- 索引迁移(待发布时执行):`database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js` 为 wms_inbox_group.store_id 新增索引 idx_store_id(幂等 up/down,尚未执行)
|
||||
|
||||
## 5.3 workbench(工作台绑定码 / 登录码 / token)能力速查
|
||||
|
||||
| method | 实现文件 | 函数 | 登录 | 鉴权/权限 |
|
||||
|---|---|---|---|---|
|
||||
| index.getWorkbenchBindCode | app/service/systemMethods/index.js → app/service/systems/workbench.js | getWorkbenchBindCode / getWorkbenchBindCode | 免登录 | 免权限(systemInit 声明) |
|
||||
| workbench.bind | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | bind / bindWorkbench | 需登录 | 需权限(未声明免权限) |
|
||||
| workbench.getWorkbenchInfo | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | getWorkbenchInfo / getWorkbenchInfoByToken | 免登录 | 免权限(systemInit 声明) |
|
||||
| index.LoginWorkbenchByCode | app/service/systemMethods/index.js → app/service/systems/workbench.js | LoginWorkbenchByCode / loginWorkbenchByCode | 免登录 | 免权限(systemInit 声明) |
|
||||
| workbench.resetLoginCode | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | resetLoginCode / resetLoginCode | 需登录 | 需权限(未声明免权限) |
|
||||
| workbench.removeMember | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | removeMember / removeWorkbenchMember | 免登录 | 免权限(systemInit 声明) |
|
||||
| workbench.bindMember | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | bindMember / bindWorkbenchMember | 免登录 | 免权限(systemInit 声明) |
|
||||
|
||||
- 绑定流程:设备调 `index.getWorkbenchBindCode` 拿 client_code + 绑定码(缓存 `workbench:bind:client:{clientCode}` / `workbench:bind:code:{code}`,TTL 120s)→ 管理员调 `workbench.bind`(code + 工作台ID)写入随机 64 位 token 并删除旧 `workbench:token:{旧token}` 缓存 → 设备侧长轮询(60s 超时,每秒轮询)拿到 token;超时/缓存失效时重新生成绑定码后才返回
|
||||
- token 登录:`index.LoginWorkbenchByCode` 以 `wms_workbench.login_code` 换取 token(无匹配返回 code=403 业务失败;工作台无 token 时自动生成持久化);`workbench.getWorkbenchInfo` 以 token 获取工作台信息(缓存优先、查库兜底、无信息返回 code=403 业务失败)
|
||||
- 字段:`wms_workbench` 新增 `login_code`(前缀 wblc + 随机段共 64 位,全局唯一索引 uk_login_code)、`token`(随机 64 位,索引 idx_token);`workbench.create` 自动生成 login_code;`workbench.update` 不受理 login_code/token 传入;`workbench.list` 返回 login_code、不返回 token
|
||||
- 成员副表:`wms_workbench_member`(工作台成员/用户登录,user_id 可空兼容非系统账号用户、user_name 名称快照、软删除);`workbench.bindMember` 免登录免鉴权(入参 userId 可空 + userName 姓名必填 + 工作台 token)新增成员行;`workbench.removeMember` 免登录免鉴权(入参行 ids + 工作台 token)按 token 解析工作台后仅软删除归属该工作台的成员行
|
||||
- 403 口径:/system 网关不支持方法内设置 HTTP 状态码,按现有惯例返回 `flag=failure、code=403` 业务失败(与 stock/warehouse.js 同款)
|
||||
- 接口文档:`methods/system.json` 分组「工作台模块」(module=workbench)与「基础模块」(module=index),变更记录见 `methods/changes/system.json` 版本 `2026.09.03-workbench-login-code-token`、`2026.09.03-workbench-member-remove`、`2026.09.03-workbench-member-bind`
|
||||
- 迁移:`database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js`(幂等 up/down,已在开发库执行;生产库待发布时按标准流程执行)
|
||||
|
||||
## method结束
|
||||
|
||||
## 6. 全量 Service Method 能力清单(自动扫描)
|
||||
@ -172,7 +192,7 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- 临时清单输出:temp/tmp-service-method-inventory.md
|
||||
|
||||
<!-- SERVICE_METHOD_INVENTORY:BEGIN -->
|
||||
自动生成时间: 2026-09-03T09:03:55.176Z
|
||||
自动生成时间: 2026-09-03T09:57:21.473Z
|
||||
|
||||
扫描范围: app/service/**/*.js
|
||||
文件数: 203
|
||||
@ -274,7 +294,7 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- app/service/systemMethods/order/archiveOrder.js (2)
|
||||
- list, detail
|
||||
- app/service/systemMethods/order/base.js (57)
|
||||
- maskListSensitiveValue, isInterceptedOrderStatus, isLockedOrderStatus, assertOrderNotIntercepted, getWarehouseId, getOrderLogOperator, getOrderLogWarehouseId, normalizePagination, normalizeWhereInput, normalizeOrderIds, isMergeableWhereCondition, mergeWhereObjects, getModuleConfig, getDefaultWhere, getBadgeCountCacheKey, formatBadgeCountValue, formatWeightTypeLabel, formatCreateChannelLabel, normalizeWaveScanResult, normalizeWaveStrategyVersion, normalizeLockStatusFlag, normalizeOrderListItem, getBadgeCountByModule, getOrderModel, resolveOrderTableType, getOrderModelByTableType, getOrderItemsModelByTableType, getOrderExpressesByOrderId, normalizeOrderListRow, attachOrderExpressNumbers, attachOrderWaveIndex, extractOrderListExpressVirtualFilter, extractBuyerMessageHasVirtualFilter, extractStockQueryVirtualFilter, extractWaveIndexVirtualFilter, extractWaveScopeVirtualFilter, findOrderIdsByWaveIndexCondition, in, buildWaveScopeWhereCondition, buildBuyerMessageHasCondition, appendConditionToWhere, normalizeExpressFilterValues, findOrderIdsByExpressNumbers, findOrderIdsByStockQuery, appendOrderIdsFilterToWhere, buildListOrder, buildWhere, listByModule, detail, attachStockDetailsToOrderItems, getOrderOperationLogs, resolveReviewStep, normalizeReviewOrderIds, buildOrderWhere, buildReviewOrderWhere, updateReviewOrder, updateOrderInspectionState
|
||||
- maskListSensitiveValue, isInterceptedOrderStatus, isLockedOrderStatus, assertOrderNotIntercepted, getWarehouseId, getOrderLogOperator, getOrderLogWarehouseId, normalizePagination, normalizeWhereInput, normalizeOrderIds, isMergeableWhereCondition, mergeWhereObjects, getModuleConfig, getDefaultWhere, getBadgeCountCacheKey, formatBadgeCountValue, formatWeightTypeLabel, formatCreateChannelLabel, normalizeWaveScanResult, normalizeWaveStrategyVersion, normalizeLockStatusFlag, normalizeOrderListItem, getBadgeCountByModule, getOrderModel, resolveOrderTableType, getOrderModelByTableType, getOrderItemsModelByTableType, getOrderExpressesByOrderId, normalizeOrderListRow, attachOrderExpressNumbers, attachOrderWaveIndex, extractOrderListExpressVirtualFilter, extractBuyerMessageHasVirtualFilter, extractStockQueryVirtualFilter, extractWaveIndexVirtualFilter, extractWaveScopeVirtualFilter, findOrderIdsByWaveIndexCondition, in, buildWaveScopeFilterCondition, buildBuyerMessageHasCondition, appendConditionToWhere, normalizeExpressFilterValues, findOrderIdsByExpressNumbers, findOrderIdsByStockQuery, appendOrderIdsFilterToWhere, buildListOrder, buildWhere, listByModule, detail, attachStockDetailsToOrderItems, getOrderOperationLogs, resolveReviewStep, normalizeReviewOrderIds, buildOrderWhere, buildReviewOrderWhere, updateReviewOrder, updateOrderInspectionState
|
||||
- app/service/systemMethods/order/deliveryExpectionOrder.js (2)
|
||||
- list, detail
|
||||
- app/service/systemMethods/order/deliveryOrder.js (5)
|
||||
@ -395,8 +415,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo, getBatchFieldValue, hasBatchField, normalizeBatchString, getCurrentWarehouseCode, batchUpdateSpaceInfo, exportRackSpaces
|
||||
- app/service/systemMethods/waybill/warehouse.js (9)
|
||||
- list, detail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
|
||||
- app/service/systemMethods/workbench.js (11)
|
||||
- list, detail, create, update, delete, business, bindCamera, checkBarcode, bind, getWorkbenchInfo, resetLoginCode
|
||||
- app/service/systemMethods/workbench.js (12)
|
||||
- list, detail, create, update, delete, business, bindCamera, bind, getWorkbenchInfo, resetLoginCode, removeMember, bindMember
|
||||
- app/service/systems/account_platform.js (11)
|
||||
- getActiveInclude, getPrimaryRoleBinding, formatActiveContext, switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext
|
||||
- app/service/systems/afterSale.js (29)
|
||||
@ -573,8 +593,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- closeFinishedWaves
|
||||
- app/service/systems/waybill.js (5)
|
||||
- toOrder, list, detail, export, buildWaybillExportFile
|
||||
- app/service/systems/workbench.js (44)
|
||||
- list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _countWaveOrdersCached, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, checkBarcodeExists, getWorkbenchBindClientCacheKey, getWorkbenchBindCodeCacheKey, getWorkbenchTokenCacheKey, generateRandomChars, generateWorkbenchToken, generateWorkbenchLoginCode, normalizeWorkbenchBindCode, generateUniqueWorkbenchLoginCode, createUniqueWorkbenchClientCode, createUniqueWorkbenchBindCode, buildWorkbenchBindState, getWorkbenchBindRemainingSeconds, setWorkbenchBindState, createWorkbenchBindSession, refreshWorkbenchBindCode, formatWorkbenchBindData, waitForWorkbenchBindComplete, getWorkbenchBindCode, formatWorkbenchTokenInfo, bindWorkbench, getWorkbenchInfoByToken, loginWorkbenchByCode, resetLoginCode
|
||||
- app/service/systems/workbench.js (47)
|
||||
- list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _countWaveOrdersCached, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, getWorkbenchBindClientCacheKey, getWorkbenchBindCodeCacheKey, getWorkbenchTokenCacheKey, generateRandomChars, generateWorkbenchToken, generateWorkbenchLoginCode, normalizeWorkbenchBindCode, generateUniqueWorkbenchLoginCode, createUniqueWorkbenchClientCode, createUniqueWorkbenchBindCode, buildWorkbenchBindState, getWorkbenchBindRemainingSeconds, setWorkbenchBindState, createWorkbenchBindSession, refreshWorkbenchBindCode, formatWorkbenchBindData, waitForWorkbenchBindComplete, getWorkbenchBindCode, formatWorkbenchTokenInfo, bindWorkbench, getWorkbenchInfoByToken, loginWorkbenchByCode, resetLoginCode, resolveWorkbenchByToken, normalizeWorkbenchMemberIds, removeWorkbenchMember, bindWorkbenchMember
|
||||
- app/service/warehouse.js (7)
|
||||
- resolveWarehouseMethod, getWarehouseMethodService, dispatchWarehouseMethod, validateWarehouseParams, parseJsonBody, normalizeSignFields, processRequest
|
||||
- app/service/warehouseMethods/inbox.js (2)
|
||||
@ -590,3 +610,9 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
module.exports = app => {
|
||||
const { Sequelize, model } = app;
|
||||
const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT, JSON } = Sequelize;
|
||||
const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT, TINYINT, JSON } = Sequelize;
|
||||
|
||||
// 状态机枚举定义
|
||||
const StatusEnum = {
|
||||
@ -425,6 +425,12 @@ module.exports = app => {
|
||||
defaultValue: '',
|
||||
comment: '波次号,空字符串表示未分配',
|
||||
},
|
||||
wave_scope: {
|
||||
type: TINYINT(4),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '波次范围:0未分配波次 1大团购 2散单 3小团购',
|
||||
},
|
||||
grab_operator_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: true,
|
||||
|
||||
@ -253,6 +253,14 @@ module.exports = app => {
|
||||
max: 720,
|
||||
description: '售后单设为等待外部反馈后,默认多少小时需二次跟进。具体类型可在代码枚举中覆盖',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'notify_manual_sync',
|
||||
name: '是否通知手工单回传',
|
||||
type: 'flag',
|
||||
default: 0,
|
||||
required: false,
|
||||
description: '手工单同步回传后是否通知货主(订单同步完成通知),默认否',
|
||||
}),
|
||||
]);
|
||||
const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => {
|
||||
result[field.key] = field;
|
||||
|
||||
@ -20,11 +20,6 @@ module.exports = app => {
|
||||
allowNull: false,
|
||||
comment: '工作台名称(用户自定义)',
|
||||
},
|
||||
barcode: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '工作台条码(用户自定义,仓库内唯一)',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
@ -82,13 +77,19 @@ module.exports = app => {
|
||||
comment: '工作台表',
|
||||
indexes: [
|
||||
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
|
||||
{ name: 'idx_barcode', fields: [ 'barcode' ] },
|
||||
{ name: 'uk_warehouse_barcode', unique: true, fields: [ 'warehouse_id', 'barcode', 'deleted_at' ] },
|
||||
{ name: 'uk_login_code', unique: true, fields: [ 'login_code' ] },
|
||||
{ name: 'idx_token', fields: [ 'token' ] },
|
||||
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
Workbench.associate = () => {
|
||||
app.model.Workbench.hasMany(app.model.WorkbenchMember, {
|
||||
foreignKey: 'workbench_id',
|
||||
sourceKey: 'id',
|
||||
as: 'members',
|
||||
});
|
||||
};
|
||||
|
||||
return Workbench;
|
||||
};
|
||||
|
||||
71
app/model/workbench_member.js
Normal file
71
app/model/workbench_member.js
Normal file
@ -0,0 +1,71 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, DATE } = app.Sequelize;
|
||||
|
||||
const WorkbenchMember = app.model.define('workbench_member', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
workbench_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '工作台ID,关联 wms_workbench.id',
|
||||
},
|
||||
user_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '账号ID,关联 wms_account.id;非系统账号用户为 NULL',
|
||||
},
|
||||
user_name: {
|
||||
type: STRING(128),
|
||||
allowNull: true,
|
||||
comment: '成员名称快照(非系统账号用户显示名)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_workbench_member',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '工作台成员/用户登录副表',
|
||||
indexes: [
|
||||
{ name: 'idx_workbench_id', fields: [ 'workbench_id' ] },
|
||||
{ name: 'idx_user_id', fields: [ 'user_id' ] },
|
||||
],
|
||||
});
|
||||
|
||||
WorkbenchMember.associate = () => {
|
||||
app.model.WorkbenchMember.belongsTo(app.model.Workbench, {
|
||||
foreignKey: 'workbench_id',
|
||||
targetKey: 'id',
|
||||
as: 'workbench',
|
||||
});
|
||||
app.model.WorkbenchMember.belongsTo(app.model.Account, {
|
||||
foreignKey: 'user_id',
|
||||
targetKey: 'id',
|
||||
as: 'user',
|
||||
});
|
||||
};
|
||||
|
||||
return WorkbenchMember;
|
||||
};
|
||||
@ -1130,8 +1130,8 @@ class OrderBaseService extends MainService {
|
||||
|
||||
/**
|
||||
* 提取 wave_scope(波次范围)虚拟筛选条件。
|
||||
* 将其从 where 中移除并解析为波次范围值集合,后续通过 wms_wave_batch 反查波次ID注入条件。
|
||||
* 取值约定:0=未分配波次,1=团购,2=散单;value 支持单个值或数组(多选)。
|
||||
* 将其从 where 中移除并解析为波次范围值集合,后续直接生成订单表 wave_scope 字段过滤。
|
||||
* 取值约定:0=未分配波次,1=大团购,2=散单,3=小团购;value 支持单个值或数组(多选)。
|
||||
* @param {Object} whereInput 标准化后的 where 条件。
|
||||
* @return {{ where: Object, waveScope: number[]|null }} 清洗后的 where 与波次范围值集合。
|
||||
*/
|
||||
@ -1163,8 +1163,8 @@ class OrderBaseService extends MainService {
|
||||
));
|
||||
|
||||
for (const scope of normalizedScopes) {
|
||||
if (!Number.isInteger(scope) || scope < 0 || scope > 2) {
|
||||
throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(团购)/2(散单)');
|
||||
if (!Number.isInteger(scope) || scope < 0 || scope > 3) {
|
||||
throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(大团购)/2(散单)/3(小团购)');
|
||||
}
|
||||
}
|
||||
|
||||
@ -1240,80 +1240,28 @@ class OrderBaseService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据波次范围(wave_scope)构建订单表 wave_id 过滤条件。
|
||||
* 0(未分配波次)直接生成 wave_id = 0;1(团购)/2(散单)先查 wms_wave_batch
|
||||
* 得到对应 wave_type 的波次ID集合,再生成 wave_id in (...)。
|
||||
* @param {Array<number>} waveScopes 波次范围值集合(0/1/2)。
|
||||
* @param {number|string} [warehouseId] 仓库ID。
|
||||
* @return {Promise<Object|null>} Sequelize 条件,无有效范围时返回 null。
|
||||
* 根据波次范围(wave_scope)构建订单表 wave_scope 字段过滤条件。
|
||||
* 订单表已冗余 wave_scope 字段(写入波次时维护),直接按字段过滤,
|
||||
* 无需再反查 wms_wave_batch。
|
||||
* @param {Array<number>} waveScopes 波次范围值集合(0/1/2/3)。
|
||||
* @return {Object|null} Sequelize 条件,无有效范围时返回 null。
|
||||
*/
|
||||
async buildWaveScopeWhereCondition(waveScopes = [], warehouseId = this.getWarehouseId()) {
|
||||
const contextWarehouseId = this.getWarehouseId();
|
||||
|
||||
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
|
||||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||||
}
|
||||
|
||||
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
|
||||
&& String(warehouseId) !== String(contextWarehouseId)) {
|
||||
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
|
||||
}
|
||||
|
||||
buildWaveScopeFilterCondition(waveScopes = []) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const normalizedScopes = Array.from(new Set(
|
||||
(Array.isArray(waveScopes) ? waveScopes : [ waveScopes ])
|
||||
.filter(scope => scope !== undefined && scope !== null && scope !== '')
|
||||
.map(scope => Number(scope))
|
||||
)).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 2);
|
||||
)).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 3);
|
||||
|
||||
if (normalizedScopes.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const waveTypeScopes = normalizedScopes.filter(scope => scope === 1 || scope === 2);
|
||||
const conditions = [];
|
||||
|
||||
if (normalizedScopes.includes(0)) {
|
||||
conditions.push({ wave_id: 0 });
|
||||
}
|
||||
|
||||
if (waveTypeScopes.length > 0) {
|
||||
const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch;
|
||||
const waveIds = [];
|
||||
if (waveBatchModel && typeof waveBatchModel.findAll === 'function') {
|
||||
const waveRows = await waveBatchModel.findAll({
|
||||
attributes: [ 'wave_id' ],
|
||||
where: {
|
||||
warehouse_id: contextWarehouseId,
|
||||
wave_type: {
|
||||
[Op.in]: waveTypeScopes,
|
||||
},
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
for (const row of Array.isArray(waveRows) ? waveRows : []) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
if (waveId > 0) {
|
||||
waveIds.push(waveId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 空集合时 Op.in: [] 生成恒假条件,保证团购/散单无波次时结果为空
|
||||
conditions.push({
|
||||
wave_id: {
|
||||
[Op.in]: Array.from(new Set(waveIds)),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (conditions.length === 1) {
|
||||
return conditions[0];
|
||||
}
|
||||
|
||||
return {
|
||||
[Op.or]: conditions,
|
||||
wave_scope: {
|
||||
[Op.in]: normalizedScopes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@ -1750,7 +1698,7 @@ class OrderBaseService extends MainService {
|
||||
}
|
||||
|
||||
if (waveScope) {
|
||||
const waveScopeCondition = await this.buildWaveScopeWhereCondition(waveScope, contextWarehouseId);
|
||||
const waveScopeCondition = this.buildWaveScopeFilterCondition(waveScope);
|
||||
queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition);
|
||||
}
|
||||
|
||||
|
||||
@ -755,6 +755,34 @@ class WaveService extends OrderBaseService {
|
||||
return errno === 1062 || code === 'ER_DUP_ENTRY';
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据波次元信息推导订单 wave_scope(波次范围)。
|
||||
*
|
||||
* 口径:
|
||||
* - wave_type=1 且 source=0 → 1(大团购);
|
||||
* - wave_type=1 且 source=2 → 3(小团购);
|
||||
* - 其余(散单等)→ 2(散单)。
|
||||
* 未分配波次(wave_id=0)由调用方直接置 0。
|
||||
*
|
||||
* @param {number|string} waveType 波次类型(1-团购 2-散单)。
|
||||
* @param {number|string} source 波次来源(0-普通 1-管理后台策略 2-PDA策略)。
|
||||
* @return {number} wave_scope:1-大团购 2-散单 3-小团购。
|
||||
*/
|
||||
resolveWaveScopeByWaveMeta(waveType, source) {
|
||||
const normalizedWaveType = Number(waveType) === 2 ? 2 : 1;
|
||||
const normalizedSource = [ 0, 1, 2 ].includes(Number(source)) ? Number(source) : 0;
|
||||
|
||||
if (normalizedWaveType === 1 && normalizedSource === 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (normalizedWaveType === 1 && normalizedSource === 2) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
return 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增一条“已就绪”波次批次记录,并返回自增 wave_id。
|
||||
*
|
||||
@ -1042,6 +1070,7 @@ class WaveService extends OrderBaseService {
|
||||
await model.update({
|
||||
wave_id: waveId,
|
||||
wave_no: waveNo,
|
||||
wave_scope: this.resolveWaveScopeByWaveMeta(1, normalizedSource),
|
||||
grab_operator_id: grabOperatorId,
|
||||
grab_operator: claimOperator,
|
||||
}, {
|
||||
@ -1839,10 +1868,14 @@ class WaveService extends OrderBaseService {
|
||||
'source',
|
||||
'keyword',
|
||||
'task_no',
|
||||
'wave_no',
|
||||
'pick_mode',
|
||||
'review_status',
|
||||
'pick_user_id',
|
||||
'review_user_id',
|
||||
'pick_user_name',
|
||||
'review_user_name',
|
||||
'claim_operator',
|
||||
'cart_id',
|
||||
'start_time_start',
|
||||
'start_time_end',
|
||||
@ -1893,7 +1926,11 @@ class WaveService extends OrderBaseService {
|
||||
'strategy_id',
|
||||
'pick_user_id',
|
||||
'review_user_id',
|
||||
'pick_user_name',
|
||||
'review_user_name',
|
||||
'claim_operator',
|
||||
'task_no',
|
||||
'wave_no',
|
||||
'cart_id',
|
||||
'keyword',
|
||||
'start_time_start',
|
||||
@ -1956,6 +1993,47 @@ class WaveService extends OrderBaseService {
|
||||
replacements.whereTaskNo = `%${normalizedTaskNo}%`;
|
||||
}
|
||||
|
||||
const appendNameCondition = (fieldKey, columnName, replacementKey) => {
|
||||
const raw = normalizedWhere[fieldKey];
|
||||
if (raw === undefined || raw === null || raw === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 支持操作符对象:{ operator: 'like' | 'notlike' | 'eq', value },默认 like
|
||||
let operator = 'like';
|
||||
let value = raw;
|
||||
if (this.isPlainObject(raw)) {
|
||||
operator = String(raw.operator || 'like').trim().toLowerCase();
|
||||
value = raw.value;
|
||||
}
|
||||
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return;
|
||||
}
|
||||
const normalizedValue = String(value).trim();
|
||||
if (!normalizedValue) {
|
||||
throw new Error(`${fieldKey} 参数不合法`);
|
||||
}
|
||||
|
||||
if (operator === 'eq') {
|
||||
conditions.push(`${columnName} = :${replacementKey}`);
|
||||
replacements[replacementKey] = normalizedValue;
|
||||
} else if (operator === 'notlike') {
|
||||
conditions.push(`(${columnName} NOT LIKE :${replacementKey} OR ${columnName} IS NULL)`);
|
||||
replacements[replacementKey] = `%${normalizedValue}%`;
|
||||
} else if (operator !== 'like') {
|
||||
throw new Error(`${fieldKey} 不支持的 operator: ${operator}`);
|
||||
} else {
|
||||
conditions.push(`${columnName} LIKE :${replacementKey}`);
|
||||
replacements[replacementKey] = `%${normalizedValue}%`;
|
||||
}
|
||||
};
|
||||
|
||||
appendNameCondition('pick_user_name', 't.pick_user_name', 'wherePickUserName');
|
||||
appendNameCondition('review_user_name', 't.review_user_name', 'whereReviewUserName');
|
||||
appendNameCondition('claim_operator', 't.claim_operator', 'whereClaimOperator');
|
||||
appendNameCondition('wave_no', 't.batch_no_array', 'whereWaveNo');
|
||||
|
||||
const keyword = normalizedWhere.keyword;
|
||||
if (keyword !== undefined && keyword !== null && keyword !== '') {
|
||||
const normalizedKeyword = String(keyword).trim();
|
||||
@ -4744,6 +4822,8 @@ class WaveService extends OrderBaseService {
|
||||
t.current_cart_code_snapshot,
|
||||
c.cart_name AS cart_name,
|
||||
t.batch_no,
|
||||
t.claim_operator_id,
|
||||
t.claim_operator,
|
||||
t.device_id,
|
||||
t.start_time,
|
||||
t.finish_time,
|
||||
@ -4930,6 +5010,8 @@ class WaveService extends OrderBaseService {
|
||||
current_cart_code_snapshot: String(item && item.current_cart_code_snapshot || '').trim(),
|
||||
cart_name: String(item && item.cart_name || '').trim(),
|
||||
batch_no: String(item && item.batch_no || '').trim(),
|
||||
claim_operator_id: Number(item && item.claim_operator_id || 0) || null,
|
||||
claim_operator: String(item && item.claim_operator || '').trim() || null,
|
||||
device_id: String(item && item.device_id || '').trim(),
|
||||
start_time: item && item.start_time || null,
|
||||
start_at: item && item.start_time || null,
|
||||
@ -7231,6 +7313,7 @@ class WaveService extends OrderBaseService {
|
||||
await orderModel.update({
|
||||
wave_id: waveId,
|
||||
wave_no: waveNo,
|
||||
wave_scope: this.resolveWaveScopeByWaveMeta(2, 0),
|
||||
grab_operator_id: grabOperatorId,
|
||||
grab_operator: grabOperator,
|
||||
}, {
|
||||
@ -7453,6 +7536,7 @@ class WaveService extends OrderBaseService {
|
||||
const orderUpdateResult = await orderModel.update({
|
||||
wave_id: 0,
|
||||
wave_no: '',
|
||||
wave_scope: 0,
|
||||
wave_strategy_version: 0,
|
||||
wave_scan_result: 0,
|
||||
}, {
|
||||
@ -8544,6 +8628,7 @@ class WaveService extends OrderBaseService {
|
||||
const orderUpdateResult = await orderModel.update({
|
||||
wave_id: 0,
|
||||
wave_no: '',
|
||||
wave_scope: 0,
|
||||
wave_strategy_version: 0,
|
||||
wave_scan_result: 0,
|
||||
}, {
|
||||
@ -10993,6 +11078,7 @@ class WaveService extends OrderBaseService {
|
||||
await orderModel.update({
|
||||
wave_id: waveId,
|
||||
wave_no: waveNo,
|
||||
wave_scope: this.resolveWaveScopeByWaveMeta(waveType, source),
|
||||
grab_operator_id: claimOperatorId,
|
||||
grab_operator: claimOperator,
|
||||
}, {
|
||||
@ -12851,6 +12937,7 @@ class WaveService extends OrderBaseService {
|
||||
await orderModel.update({
|
||||
wave_id: 0,
|
||||
wave_no: '',
|
||||
wave_scope: 0,
|
||||
wave_strategy_version: 0,
|
||||
wave_scan_result: 0,
|
||||
}, {
|
||||
|
||||
@ -23,7 +23,7 @@ class StockReportMethodService extends MainService {
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field)
|
||||
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field;白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total)
|
||||
* @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order)
|
||||
* @param {string|Date} [data.where.start_time] 开始时间
|
||||
* @param {string|Date} [data.where.end_time] 结束时间
|
||||
@ -32,6 +32,7 @@ class StockReportMethodService extends MainService {
|
||||
* @param {number|number[]} [data.where.stock_id] 商品库存ID(单数)
|
||||
* @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数)
|
||||
* @param {string} [data.where.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配)
|
||||
* @param {Object} [data.pagination] 分页参数 { page, pageSize }(兼容 page_size);也支持顶层 data.page / data.pageSize / data.page_size(与其他 list 一致,顶层值优先);未传或非法时默认 { page: 1, pageSize: 20 },响应始终返回 data.pagination 分页信息
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async search(data = {}) {
|
||||
@ -51,10 +52,10 @@ class StockReportMethodService extends MainService {
|
||||
sortOrder: whereSortOrderCamel,
|
||||
} = whereValue;
|
||||
|
||||
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||
// 兼容 stock_id(单数,支持数组)和 stock_ids(数组)
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
: (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null);
|
||||
|
||||
const { sort = {} } = data;
|
||||
const {
|
||||
@ -64,10 +65,25 @@ class StockReportMethodService extends MainService {
|
||||
sortOrder: sortOrderCamel,
|
||||
} = sort || {};
|
||||
|
||||
// 分页参数:与项目其他 list 接口保持一致——
|
||||
// 支持 data.pagination { page, pageSize }(pageSize 兼容 page_size),
|
||||
// 同时兼容顶层 data.page(分页)与 data.pageSize / data.page_size(分页大小,顶层值优先)
|
||||
const { pagination: inputPagination, page: topLevelPage, pageSize: topLevelPageSize, page_size: topLevelPageSizeSnake } = data;
|
||||
const pagination = {
|
||||
...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}),
|
||||
};
|
||||
if (topLevelPage !== undefined) {
|
||||
pagination.page = topLevelPage;
|
||||
}
|
||||
const resolvedTopLevelPageSize = topLevelPageSize !== undefined ? topLevelPageSize : topLevelPageSizeSnake;
|
||||
if (resolvedTopLevelPageSize !== undefined) {
|
||||
pagination.pageSize = resolvedTopLevelPageSize;
|
||||
}
|
||||
|
||||
const result = await service.systems.storage.report.search(startTime, endTime, bySpace, storeIds, {
|
||||
sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField,
|
||||
sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder,
|
||||
}, 'warehouse', stockIds, keyword);
|
||||
}, 'warehouse', stockIds, keyword, pagination);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
@ -109,10 +125,10 @@ class StockReportMethodService extends MainService {
|
||||
? warehouseIdsRaw
|
||||
: (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined);
|
||||
|
||||
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||
// 兼容 stock_id(单数,支持数组)和 stock_ids(数组)
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
: (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null);
|
||||
|
||||
const { sort = {} } = data;
|
||||
const {
|
||||
@ -180,10 +196,10 @@ class StockReportMethodService extends MainService {
|
||||
? warehouseIdsRaw
|
||||
: (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined);
|
||||
|
||||
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||
// 兼容 stock_id(单数,支持数组)和 stock_ids(数组)
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
: (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null);
|
||||
|
||||
const { sort = {} } = data;
|
||||
const {
|
||||
@ -290,10 +306,10 @@ class StockReportMethodService extends MainService {
|
||||
sortOrder: whereSortOrderCamel,
|
||||
} = whereValue;
|
||||
|
||||
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||
// 兼容 stock_id(单数,支持数组)和 stock_ids(数组)
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
: (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null);
|
||||
|
||||
const { sort = {} } = data;
|
||||
const {
|
||||
|
||||
@ -166,12 +166,13 @@ class entryService extends MainService {
|
||||
* 提交确认完成导入/PDA 直接入库(从 storage.entry 模块暴露)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.entry_order_id 入库单 ID
|
||||
* @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async commit(data = {}) {
|
||||
const { service } = this;
|
||||
const { entry_order_id } = data || {};
|
||||
const result = await service.systems.inboundDirectLog.commit(entry_order_id);
|
||||
const { entry_order_id, noNeedNotice = 0 } = data || {};
|
||||
const result = await service.systems.inboundDirectLog.commit(entry_order_id, noNeedNotice);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
@ -229,12 +230,13 @@ class entryService extends MainService {
|
||||
* 快捷直入/虚拟入库(system method 包装层)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 入库单ID
|
||||
* @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async quickInbound(data = {}) {
|
||||
const { service } = this;
|
||||
const { id } = data;
|
||||
const result = await service.systems.storage.entry.quickInbound({ id });
|
||||
const { id, noNeedNotice = 0 } = data;
|
||||
const result = await service.systems.storage.entry.quickInbound({ id, noNeedNotice });
|
||||
if (result && result.code === 200) {
|
||||
return this.success(result.message || 'ok', result);
|
||||
}
|
||||
|
||||
@ -51,8 +51,10 @@ class InventoryMethodService extends MainService {
|
||||
/**
|
||||
* 提取 stock_query 虚拟筛选条件(与订单查询一致)。
|
||||
* 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。
|
||||
* 兼容 value 为字符串或数组的场景(如 { operator: 'contains', value: ['A', 'B'] }),
|
||||
* 数组按多关键字处理,由底层 service 取并集解析 stock_id。
|
||||
* @param {Object} whereInput 原始 where 条件。
|
||||
* @return {{ where: Object, stockQuery: string }} 清洗后的 where 与 stock_query 值。
|
||||
* @return {{ where: Object, stockQuery: string|string[] }} 清洗后的 where 与 stock_query 值。
|
||||
*/
|
||||
extractStockQueryVirtualFilter(whereInput = {}) {
|
||||
const normalizedWhere = this.isPlainObject(whereInput)
|
||||
@ -71,6 +73,14 @@ class InventoryMethodService extends MainService {
|
||||
? stockQueryCondition.value
|
||||
: stockQueryCondition;
|
||||
|
||||
// value 为数组时逐项清洗为字符串数组(多关键字并集搜索)
|
||||
if (Array.isArray(rawValue)) {
|
||||
const stockQuery = rawValue
|
||||
.map(item => String(item).trim())
|
||||
.filter(Boolean);
|
||||
return { where: normalizedWhere, stockQuery };
|
||||
}
|
||||
|
||||
const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : '';
|
||||
|
||||
return { where: normalizedWhere, stockQuery };
|
||||
@ -80,7 +90,7 @@ class InventoryMethodService extends MainService {
|
||||
* 库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件
|
||||
* @param {Object} [data.where.stock_query] 虚拟筛选字段:按商品编码(item_code)/名称(item_name)/货物编码(goods_code)/条码(barcode)/SKU ID 模糊匹配,如 { operator: 'like', value: '111' }
|
||||
* @param {Object} [data.where.stock_query] 虚拟筛选字段:按商品编码(item_code)/名称(item_name)/货物编码(goods_code)/条码(barcode)/SKU ID 模糊匹配,如 { operator: 'like', value: '111' };value 支持数组(如 { operator: 'contains', value: ['111'] }),多关键字取并集匹配
|
||||
* @param {Object} [data.pagination] 分页参数 { page, pageSize }
|
||||
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
|
||||
* @param {boolean} [data.group_by_batch=false] 是否按批次查询
|
||||
|
||||
@ -2,32 +2,316 @@
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
const STORAGE_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_transaction_export_task_';
|
||||
const STORAGE_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
|
||||
class StorageTransactionService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list';
|
||||
const _noNeedLog = 'list';
|
||||
const _noNeedAuth = 'list';
|
||||
const _noNeedRight = 'list,export,exportTaskProgress';
|
||||
const _noNeedLog = 'list,export,exportTaskProgress';
|
||||
const _noNeedAuth = 'list,export,exportTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 出入库记录列表查询,支持 where 条件、分页、排序。
|
||||
* 解析 list/export 通用过滤入参(where 白名单字段 + 时间区间 + keyword)。
|
||||
* @param {Object} data 请求体
|
||||
* @return {Object} 归一化后的过滤参数
|
||||
*/
|
||||
_parseListFilters(data = {}) {
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
const { keyword: topKeyword } = data;
|
||||
const {
|
||||
transaction_type: transactionType,
|
||||
stock_id: stockIdRaw,
|
||||
stock_ids: stockIdsRaw,
|
||||
space_id: spaceId,
|
||||
store_id: storeIdRaw,
|
||||
store_ids: storeIdsRaw,
|
||||
order_type: orderType,
|
||||
order_no: orderNo,
|
||||
batch_no: batchNo,
|
||||
inventory_type: inventoryType,
|
||||
operator_name: operatorName,
|
||||
order_id: orderId,
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
created_at: createdAt,
|
||||
keyword: whereKeyword,
|
||||
} = whereValue;
|
||||
|
||||
// created_at 支持 between:规范化后 value 为 [start, end] 数组
|
||||
const createdRange = Array.isArray(createdAt) ? createdAt : [];
|
||||
const resolvedStartTime = startTime ?? createdRange[0] ?? null;
|
||||
const resolvedEndTime = endTime ?? createdRange[1] ?? null;
|
||||
|
||||
// 兼容 stock_id(单数)与 stock_ids(数组),store_id 同理
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
const storeIds = storeIdsRaw !== undefined
|
||||
? storeIdsRaw
|
||||
: (storeIdRaw !== undefined ? [ storeIdRaw ] : null);
|
||||
const keyword = topKeyword ?? whereKeyword ?? '';
|
||||
|
||||
// 仓库ID 由服务端从当前上下文注入,禁止前端传参
|
||||
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||
|
||||
return {
|
||||
warehouseId,
|
||||
startTime: resolvedStartTime,
|
||||
endTime: resolvedEndTime,
|
||||
storeIds,
|
||||
stockIds,
|
||||
spaceId,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
inventoryType,
|
||||
operatorName,
|
||||
orderId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 库位维度出入库流水逐条明细列表(wms_storage_transaction)。
|
||||
* 支持 where 条件、keyword 快捷搜索、分页、排序;仓库ID由服务端从当前上下文自动注入。
|
||||
* group_by_batch 参数已废弃:本接口不再聚合,恒返回逐条明细。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件
|
||||
* @param {Object} [data.where.created_at] 创建时间区间(operator: between,value: [start, end])
|
||||
* @param {Object} [data.pagination] 分页参数 { page, pageSize }
|
||||
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
|
||||
* @param {boolean} [data.group_by_batch=false] 是否按批次查询明细
|
||||
* @param {string} [data.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const { service } = this;
|
||||
const { pagination, sort, group_by_batch, keyword } = data;
|
||||
this.prepareWhereContext(data);
|
||||
const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch, keyword);
|
||||
const { pagination = {}, sort = {} } = data;
|
||||
const filters = this._parseListFilters(data);
|
||||
const result = await service.systems.stockTransaction.list({
|
||||
...filters,
|
||||
sort,
|
||||
pagination,
|
||||
});
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交库位流水导出异步任务。
|
||||
* 与 list 使用相同查询条件(where/sort/keyword),异步执行,立即返回任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 查询条件(与 list 完全一致)
|
||||
* @param {Object} [data.sort] 排序参数(与 list 完全一致)
|
||||
* @param {string} [data.keyword] 商品关键字(与 list 完全一致)
|
||||
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
|
||||
*/
|
||||
async export(data = {}) {
|
||||
const { service } = this;
|
||||
const { sort = {} } = data;
|
||||
const filters = this._parseListFilters(data);
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.stockTransaction.exportStorageList({
|
||||
...filters,
|
||||
sort,
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询库位流水导出任务进度。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async exportTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cdnUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成库位流水导出任务ID。
|
||||
* @return {string} 导出任务ID
|
||||
*/
|
||||
generateExportTaskId() {
|
||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `storage_transaction_export_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化库位流水导出任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {string} 归一化后的任务ID
|
||||
*/
|
||||
normalizeExportTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取库位流水导出任务缓存键。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
return `${STORAGE_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入库位流水导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @param {Object} payload 任务状态载荷
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||||
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[storage.transaction.export] 写入导出任务缓存失败: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取库位流水导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {Promise<Object|null>} 任务缓存
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[storage.transaction.export] 读取导出任务缓存失败: ${errorMessage}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StorageTransactionService;
|
||||
|
||||
@ -5,10 +5,10 @@ const MainService = require('../main');
|
||||
class WorkbenchService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'business,getWorkbenchInfo';
|
||||
const _noNeedRight = 'list,detail,checkBarcode,business,getWorkbenchInfo';
|
||||
const _noNeedLog = 'list,detail,checkBarcode,getWorkbenchInfo';
|
||||
const _noNeedAuth = 'list,detail,checkBarcode,business,getWorkbenchInfo';
|
||||
const _noNeedLogin = 'business,getWorkbenchInfo,removeMember,bindMember';
|
||||
const _noNeedRight = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember';
|
||||
const _noNeedLog = 'list,detail,getWorkbenchInfo,removeMember,bindMember';
|
||||
const _noNeedAuth = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -121,25 +121,6 @@ class WorkbenchService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查条码是否已存在
|
||||
* @param data
|
||||
*/
|
||||
async checkBarcode(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { barcode, excludeId } = data || {};
|
||||
if (!barcode) return this.fail('条码不能为空');
|
||||
const exists = await service.systems.workbench.checkBarcodeExists(
|
||||
String(barcode).trim(),
|
||||
excludeId ? parseInt(excludeId) : undefined
|
||||
);
|
||||
return this.success('ok', { exists });
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台绑定:校验缓存绑定码与工作台ID,写入随机 token(需登录、需权限)
|
||||
* @param data - { code, id }
|
||||
@ -197,6 +178,48 @@ class WorkbenchService extends MainService {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除工作台成员(免登录、免鉴权,以工作台 token 鉴权)
|
||||
* @param data - { ids, token }
|
||||
*/
|
||||
async removeMember(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.workbench.removeWorkbenchMember(data || {});
|
||||
if (result && result.success) {
|
||||
return this.success('移除成功', result);
|
||||
}
|
||||
const statusCode = result && result.statusCode;
|
||||
return this.fail(
|
||||
result && result.message ? result.message : '移除成员失败',
|
||||
statusCode ? { code: statusCode } : undefined
|
||||
);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定工作台成员(免登录、免鉴权,以工作台 token 鉴权)
|
||||
* @param data - { userId | user_id, userName | user_name | name, token }
|
||||
*/
|
||||
async bindMember(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.workbench.bindWorkbenchMember(data || {});
|
||||
if (result && result.success) {
|
||||
return this.success('绑定成功', result);
|
||||
}
|
||||
const statusCode = result && result.statusCode;
|
||||
return this.fail(
|
||||
result && result.message ? result.message : '绑定成员失败',
|
||||
statusCode ? { code: statusCode } : undefined
|
||||
);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WorkbenchService;
|
||||
|
||||
@ -787,9 +787,10 @@ class InboundDirectLogService extends Service {
|
||||
* 先调用 qimenEntrySync 进行奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存。
|
||||
* 同步失败则只写 FAILED 状态 + 操作日志,不写库存。
|
||||
* @param {number} entryOrderId 入库单 ID
|
||||
* @param {number} [noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0)
|
||||
* @return {Promise<Object>} code/data/message 结构
|
||||
*/
|
||||
async commit(entryOrderId) {
|
||||
async commit(entryOrderId, noNeedNotice = 0) {
|
||||
const { ctx, app } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
const entryOrderIdNum = Number(entryOrderId) || 0;
|
||||
@ -1213,11 +1214,13 @@ class InboundDirectLogService extends Service {
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
// 入库完成通知货主(失败不影响主流程)
|
||||
try {
|
||||
await this.notifyEntryOrderCompleted(eo);
|
||||
} catch (noticeErr) {
|
||||
ctx.logger.warn('[inbound_direct_log.commit] 入库完成通知货主失败,不影响业务', noticeErr);
|
||||
// 入库完成通知货主(失败不影响主流程);noNeedNotice=1 时跳过通知
|
||||
if (Number(noNeedNotice) !== 1) {
|
||||
try {
|
||||
await this.notifyEntryOrderCompleted(eo);
|
||||
} catch (noticeErr) {
|
||||
ctx.logger.warn('[inbound_direct_log.commit] 入库完成通知货主失败,不影响业务', noticeErr);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (transaction && typeof transaction.rollback === 'function') {
|
||||
|
||||
@ -308,6 +308,46 @@ async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, ord
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断货主是否开启「手工单回传通知」。
|
||||
* 读取货主-仓库签约策略 policy_config.notify_manual_sync,未配置默认否。
|
||||
*
|
||||
* @param {object} service 服务实例。
|
||||
* @param {number} warehouseId 仓库 ID。
|
||||
* @param {number} storeId 货主 ID。
|
||||
* @return {Promise<boolean>} true=发送通知,false=不发送通知。
|
||||
*/
|
||||
async function isManualSyncNoticeEnabledInternal(service, warehouseId, storeId) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const normalizedStoreId = Number(storeId || 0);
|
||||
if (normalizedWarehouseId <= 0 || normalizedStoreId <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const storeWarehouseService = service
|
||||
&& service.ctx
|
||||
&& service.ctx.service
|
||||
&& service.ctx.service.systems
|
||||
&& service.ctx.service.systems.storeWarehouse;
|
||||
|
||||
if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') {
|
||||
service.ctx.logger.warn('[OrderAsyncService.isManualSyncNoticeEnabled] storeWarehouse 服务不可用,按默认否处理', {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
storeId: normalizedStoreId,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const contractConfig = await storeWarehouseService.getContractConfig(normalizedWarehouseId, normalizedStoreId);
|
||||
const policyConfig = contractConfig && contractConfig.policy_config;
|
||||
return !!(policyConfig && Number(policyConfig.notify_manual_sync) === 1);
|
||||
} catch (error) {
|
||||
service.ctx.logger.warn('[OrderAsyncService.isManualSyncNoticeEnabled] 读取合约策略失败,按默认否处理: %s', String((error && error.message) || error || '').trim());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function sendManualSyncNoticeInternal(service, syncResult = {}, context = {}) {
|
||||
const rawNoticeService = service && service.ctx && service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.notice;
|
||||
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
|
||||
@ -732,7 +772,27 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
|
||||
success_count: 1,
|
||||
failed_count: 0,
|
||||
};
|
||||
const noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context);
|
||||
|
||||
const manualSyncNoticeEnabled = await isManualSyncNoticeEnabledInternal(
|
||||
service,
|
||||
warehouseId,
|
||||
Number(orderRow && orderRow.store_id) || 0
|
||||
);
|
||||
let noticeResult;
|
||||
if (!manualSyncNoticeEnabled) {
|
||||
service.ctx.logger.info(`[OrderAsyncService.processManualOrder] 货主未开启手工单回传通知,跳过通知 orderId=${orderId}`);
|
||||
noticeResult = {
|
||||
success: true,
|
||||
message: '货主未开启手工单回传通知,跳过通知',
|
||||
data: {
|
||||
mode: 'skipped',
|
||||
warehouseId,
|
||||
storeId: Number(orderRow && orderRow.store_id) || 0,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context);
|
||||
}
|
||||
|
||||
if (!noticeResult || noticeResult.success !== true) {
|
||||
const noticeMessage = String(noticeResult && noticeResult.message || '通知发送失败').trim() || '通知发送失败';
|
||||
|
||||
@ -932,7 +932,7 @@ class OrderExportService extends OrderBaseService {
|
||||
}
|
||||
|
||||
if (waveScope) {
|
||||
const waveScopeCondition = await this.buildWaveScopeWhereCondition(waveScope, warehouseId);
|
||||
const waveScopeCondition = this.buildWaveScopeFilterCondition(waveScope);
|
||||
queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition);
|
||||
}
|
||||
|
||||
|
||||
@ -451,7 +451,7 @@ class OrderPackingService extends Service {
|
||||
{
|
||||
model: ctx.model.Workbench,
|
||||
as: 'workbench',
|
||||
attributes: [ 'id', 'name', 'type', 'barcode' ],
|
||||
attributes: [ 'id', 'name', 'type' ],
|
||||
},
|
||||
{
|
||||
model: ctx.model.PackTaskVideo,
|
||||
@ -491,7 +491,6 @@ class OrderPackingService extends Service {
|
||||
deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null,
|
||||
workbench_name: plain.workbench?.name || null,
|
||||
workbench_type: plain.workbench?.type || null,
|
||||
workbench_barcode: plain.workbench?.barcode || null,
|
||||
has_video: rawVideos.length > 0 ? 1 : 2,
|
||||
video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2,
|
||||
videos: rawVideos.map(v => ({
|
||||
@ -615,7 +614,7 @@ class OrderPackingService extends Service {
|
||||
if (workbenchIds.length > 0) {
|
||||
const workbenches = await ctx.model.Workbench.findAll({
|
||||
where: { id: { [Op.in]: workbenchIds } },
|
||||
attributes: [ 'id', 'name', 'type', 'barcode' ],
|
||||
attributes: [ 'id', 'name', 'type' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const wb of workbenches) {
|
||||
@ -886,7 +885,7 @@ class OrderPackingService extends Service {
|
||||
{
|
||||
model: ctx.model.Workbench,
|
||||
as: 'workbench',
|
||||
attributes: [ 'id', 'name', 'type', 'barcode' ],
|
||||
attributes: [ 'id', 'name', 'type' ],
|
||||
},
|
||||
{
|
||||
model: ctx.model.PackTaskVideo,
|
||||
@ -928,7 +927,6 @@ class OrderPackingService extends Service {
|
||||
deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null,
|
||||
workbench_name: plain.workbench?.name || null,
|
||||
workbench_type: plain.workbench?.type || null,
|
||||
workbench_barcode: plain.workbench?.barcode || null,
|
||||
has_video: rawVideos.length > 0 ? 1 : 2,
|
||||
video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2,
|
||||
videos: rawVideos.map(v => ({
|
||||
|
||||
@ -193,124 +193,188 @@ class StockTransactionService extends Service {
|
||||
return ctx.model.StockTransaction.create(payload, options);
|
||||
}
|
||||
|
||||
async list(pageParams = {}, sortParams = {}, groupByBatch = false, keyword = '') {
|
||||
/**
|
||||
* 查询库位维度出入库流水逐条明细(wms_storage_transaction)。
|
||||
* 与 stock.transaction.list 形态一致:裸 SQL 列白名单 + COUNT 分页 + 排序白名单,
|
||||
* 不做聚合,仅查询当前仓库数据,并关联商品信息(stockItem)。
|
||||
* @param {Object} [options] 查询选项
|
||||
* @param {number} options.warehouseId 仓库ID(必填,由 method 层从当前上下文注入)
|
||||
* @param {string|Date|null} [options.startTime] 开始时间(闭区间下限,created_at >= startTime)
|
||||
* @param {string|Date|null} [options.endTime] 结束时间(闭区间上限,created_at <= endTime)
|
||||
* @param {Array<number|string>} [options.storeIds] 货主ID数组
|
||||
* @param {Array<number|string>} [options.stockIds] 商品库存ID数组
|
||||
* @param {number} [options.spaceId] 库位ID
|
||||
* @param {string} [options.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode/SKU ID 模糊匹配)
|
||||
* @param {string} [options.transactionType] 流水类型(INBOUND/OUTBOUND/TRANSFER_OUT/TRANSFER_IN/LOCK/UNLOCK)
|
||||
* @param {string} [options.orderType] 单据类型
|
||||
* @param {string} [options.orderNo] 单据号(模糊匹配)
|
||||
* @param {string} [options.batchNo] 批次号
|
||||
* @param {string} [options.inventoryType] 库存类型(ZP/CC/JS/XS/ZT/DJ/FP)
|
||||
* @param {string} [options.operatorName] 操作人姓名(模糊匹配)
|
||||
* @param {number} [options.orderId] 发货单ID
|
||||
* @param {Object} [options.sort] 排序参数 { sortField, sortOrder }
|
||||
* @param {Object} [options.pagination] 分页参数 { page, pageSize }
|
||||
* @return {Promise<Object>} { list, pagination }
|
||||
*/
|
||||
async list(options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op, fn, col, literal } = app.Sequelize;
|
||||
const {
|
||||
warehouseId,
|
||||
startTime,
|
||||
endTime,
|
||||
storeIds: rawStoreIds,
|
||||
stockIds: rawStockIds,
|
||||
spaceId,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
inventoryType,
|
||||
operatorName,
|
||||
orderId,
|
||||
sort = {},
|
||||
pagination = {},
|
||||
} = options;
|
||||
|
||||
const warehouseId = ctx.user.store_id;
|
||||
const { page = 1, pageSize = 20 } = pageParams;
|
||||
const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams;
|
||||
if (!warehouseId) {
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page: 1, pageSize: 20, total: 0, totalPages: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
// 基础条件:当前仓库
|
||||
const baseWhere = {
|
||||
[Op.and]: [
|
||||
{ warehouse_id: warehouseId },
|
||||
],
|
||||
};
|
||||
|
||||
// keyword 快捷搜索:按 item_code + barcode 匹配,解析为 stock_id IN 条件
|
||||
// keyword 快捷搜索:解析为 stock_id IN 条件,无匹配时直接返回空列表
|
||||
let stockIds = Array.isArray(rawStockIds)
|
||||
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
const normalizedKeyword = String(keyword || '').trim();
|
||||
if (normalizedKeyword) {
|
||||
const stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', warehouseId);
|
||||
if (stockIds.length > 0) {
|
||||
baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } });
|
||||
} else {
|
||||
// keyword 无匹配结果,直接返回空列表
|
||||
if (normalizedKeyword && stockIds.length === 0) {
|
||||
stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', Number(warehouseId));
|
||||
if (stockIds.length === 0) {
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page, pageSize, total: 0, totalPages: 0 },
|
||||
pagination: { page: 1, pageSize: 20, total: 0, totalPages: 0 },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 动态 where 条件
|
||||
const parsed = ctx.whereParsed;
|
||||
if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) {
|
||||
baseWhere[Op.and].push(...parsed.dynamicConditions);
|
||||
}
|
||||
const { whereSQL, replacements } = this._buildStorageTransactionWhere({
|
||||
warehouseId,
|
||||
startTime,
|
||||
endTime,
|
||||
storeIds: rawStoreIds,
|
||||
stockIds,
|
||||
spaceId,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
inventoryType,
|
||||
operatorName,
|
||||
orderId,
|
||||
});
|
||||
|
||||
// 排序白名单,非法字段回退默认排序(created_at DESC)
|
||||
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id', 'space_id' ]);
|
||||
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
|
||||
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
|
||||
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
|
||||
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
|
||||
|
||||
// 分页
|
||||
const page = Math.max(1, Number(pagination.page) || 1);
|
||||
const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20));
|
||||
const offset = (page - 1) * pageSize;
|
||||
const limit = pageSize;
|
||||
|
||||
if (groupByBatch) {
|
||||
// 按批次明细:保持原有逻辑
|
||||
const { count: total, rows } = await ctx.model.StockTransaction.findAndCountAll({
|
||||
where: baseWhere,
|
||||
order: [[ sortField, sortOrder ]],
|
||||
offset,
|
||||
limit,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.StockWarehouse,
|
||||
as: 'stockItem',
|
||||
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
// 查询总数
|
||||
const countResult = await ctx.model.query(
|
||||
`SELECT COUNT(*) AS total FROM wms_storage_transaction t ${whereSQL}`,
|
||||
{
|
||||
replacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
const total = countResult && countResult[0] ? Number(countResult[0].total) : 0;
|
||||
|
||||
const list = rows.map(item => {
|
||||
const row = item.get({ plain: true });
|
||||
row.created_at = row.created_at ? app.formatDate(row.created_at) : '';
|
||||
return row;
|
||||
});
|
||||
|
||||
return {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 不按批次:按 stock_id + transaction_type + warehouse/store + order_type 合并
|
||||
const groupFields = [ 'stock_id', 'transaction_type', 'warehouse_id', 'store_id', 'order_type' ];
|
||||
|
||||
// 先查总数(分组后的组数)
|
||||
const countResult = await ctx.model.StockTransaction.count({
|
||||
where: baseWhere,
|
||||
group: groupFields,
|
||||
});
|
||||
const total = Array.isArray(countResult) ? countResult.length : countResult;
|
||||
|
||||
// 查分组数据
|
||||
const rows = await ctx.model.StockTransaction.findAll({
|
||||
where: baseWhere,
|
||||
attributes: [
|
||||
'stock_id',
|
||||
'transaction_type',
|
||||
'warehouse_id',
|
||||
'store_id',
|
||||
'order_type',
|
||||
[ fn('SUM', col('stock_transaction.quantity')), 'quantity' ],
|
||||
[ fn('MIN', col('stock_transaction.created_at')), 'first_created_at' ],
|
||||
[ fn('MAX', col('stock_transaction.created_at')), 'last_created_at' ],
|
||||
[ fn('COUNT', col('stock_transaction.id')), 'record_count' ],
|
||||
],
|
||||
group: groupFields,
|
||||
order: [[ literal('last_created_at'), sortOrder ]],
|
||||
offset,
|
||||
limit,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.StockWarehouse,
|
||||
as: 'stockItem',
|
||||
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
raw: true,
|
||||
nest: true,
|
||||
// 明细白名单:显式列出列名,避免模型整行序列化引入未预期字段
|
||||
const rows = await ctx.model.query(`
|
||||
SELECT
|
||||
t.id,
|
||||
t.created_at,
|
||||
t.transaction_type,
|
||||
t.warehouse_id,
|
||||
t.store_id,
|
||||
t.stock_id,
|
||||
t.storage_id,
|
||||
t.space_id,
|
||||
t.quantity,
|
||||
t.before_quantity,
|
||||
t.after_quantity,
|
||||
t.before_locked_quantity,
|
||||
t.after_locked_quantity,
|
||||
t.before_intercept_locked_quantity,
|
||||
t.after_intercept_locked_quantity,
|
||||
t.batch_no,
|
||||
t.inventory_type,
|
||||
t.order_type,
|
||||
t.order_no,
|
||||
t.order_id,
|
||||
t.source_order_codes,
|
||||
t.operator_id,
|
||||
t.operator_name,
|
||||
t.remark,
|
||||
sw.id AS sw_id,
|
||||
sw.item_code AS sw_item_code,
|
||||
sw.item_name AS sw_item_name,
|
||||
sw.sku_property AS sw_sku_property,
|
||||
sw.stock_unit AS sw_stock_unit
|
||||
FROM wms_storage_transaction t
|
||||
LEFT JOIN wms_stock_warehouse sw ON sw.id = t.stock_id
|
||||
${whereSQL}
|
||||
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
|
||||
LIMIT :limit OFFSET :offset
|
||||
`, {
|
||||
replacements: { ...replacements, limit: pageSize, offset },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
|
||||
const list = rows.map(row => {
|
||||
row.first_created_at = row.first_created_at ? app.formatDate(row.first_created_at) : '';
|
||||
row.last_created_at = row.last_created_at ? app.formatDate(row.last_created_at) : '';
|
||||
return row;
|
||||
});
|
||||
const safeRows = Array.isArray(rows) ? rows : [];
|
||||
const list = safeRows.map(item => ({
|
||||
id: Number(item.id),
|
||||
created_at: item.created_at ? app.formatDate(item.created_at) : '',
|
||||
transaction_type: item.transaction_type || '',
|
||||
warehouse_id: Number(item.warehouse_id) || 0,
|
||||
store_id: Number(item.store_id) || 0,
|
||||
stock_id: Number(item.stock_id) || 0,
|
||||
storage_id: Number(item.storage_id) || 0,
|
||||
space_id: Number(item.space_id) || 0,
|
||||
quantity: Number(item.quantity) || 0,
|
||||
before_quantity: Number(item.before_quantity) || 0,
|
||||
after_quantity: Number(item.after_quantity) || 0,
|
||||
before_locked_quantity: Number(item.before_locked_quantity) || 0,
|
||||
after_locked_quantity: Number(item.after_locked_quantity) || 0,
|
||||
before_intercept_locked_quantity: Number(item.before_intercept_locked_quantity) || 0,
|
||||
after_intercept_locked_quantity: Number(item.after_intercept_locked_quantity) || 0,
|
||||
batch_no: item.batch_no || '',
|
||||
inventory_type: item.inventory_type || '',
|
||||
order_type: item.order_type || '',
|
||||
order_no: item.order_no || '',
|
||||
order_id: Number(item.order_id) || 0,
|
||||
source_order_codes: item.source_order_codes || '',
|
||||
operator_id: item.operator_id || '',
|
||||
operator_name: item.operator_name || '',
|
||||
remark: item.remark || '',
|
||||
stockItem: item.sw_id !== null && item.sw_id !== undefined
|
||||
? {
|
||||
id: Number(item.sw_id) || 0,
|
||||
item_code: item.sw_item_code || '',
|
||||
item_name: item.sw_item_name || '',
|
||||
sku_property: item.sw_sku_property || '',
|
||||
stock_unit: item.sw_stock_unit || '',
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
|
||||
return {
|
||||
list,
|
||||
@ -323,6 +387,121 @@ class StockTransactionService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装库位维度流水查询条件白名单(wms_storage_transaction)。
|
||||
* 所有条件显式拼装,避免动态 where 注入未知字段;list 与导出共用。
|
||||
* @param {Object} params 归一化后的查询参数
|
||||
* @param {number} params.warehouseId 仓库ID
|
||||
* @param {string|Date|null} [params.startTime] 开始时间
|
||||
* @param {string|Date|null} [params.endTime] 结束时间
|
||||
* @param {Array<number|string>} [params.storeIds] 货主ID数组
|
||||
* @param {Array<number>} [params.stockIds] 商品库存ID数组
|
||||
* @param {number} [params.spaceId] 库位ID
|
||||
* @param {string} [params.transactionType] 流水类型
|
||||
* @param {string} [params.orderType] 单据类型
|
||||
* @param {string} [params.orderNo] 单据号(模糊)
|
||||
* @param {string} [params.batchNo] 批次号
|
||||
* @param {string} [params.inventoryType] 库存类型
|
||||
* @param {string} [params.operatorName] 操作人(模糊)
|
||||
* @param {number} [params.orderId] 发货单ID
|
||||
* @return {{whereSQL: string, replacements: Object}} WHERE 子句与查询参数
|
||||
*/
|
||||
_buildStorageTransactionWhere({
|
||||
warehouseId,
|
||||
startTime,
|
||||
endTime,
|
||||
storeIds: rawStoreIds,
|
||||
stockIds,
|
||||
spaceId,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
inventoryType,
|
||||
operatorName,
|
||||
orderId,
|
||||
} = {}) {
|
||||
const whereClauses = [ 't.warehouse_id = :warehouseId' ];
|
||||
const replacements = { warehouseId: Number(warehouseId) };
|
||||
|
||||
if (startTime !== undefined && startTime !== null && startTime !== '') {
|
||||
const startMs = new Date(startTime).getTime();
|
||||
if (!Number.isNaN(startMs)) {
|
||||
whereClauses.push('t.created_at >= :startTime');
|
||||
replacements.startTime = startTime;
|
||||
}
|
||||
}
|
||||
|
||||
if (endTime !== undefined && endTime !== null && endTime !== '') {
|
||||
const endMs = new Date(endTime).getTime();
|
||||
if (!Number.isNaN(endMs)) {
|
||||
whereClauses.push('t.created_at <= :endTime');
|
||||
replacements.endTime = endTime;
|
||||
}
|
||||
}
|
||||
|
||||
const storeIds = Array.isArray(rawStoreIds)
|
||||
? rawStoreIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
if (storeIds.length > 0) {
|
||||
whereClauses.push('t.store_id IN (:storeIds)');
|
||||
replacements.storeIds = storeIds;
|
||||
}
|
||||
|
||||
const normalizedStockIds = Array.isArray(stockIds) ? stockIds : [];
|
||||
if (normalizedStockIds.length > 0) {
|
||||
whereClauses.push('t.stock_id IN (:stockIds)');
|
||||
replacements.stockIds = normalizedStockIds;
|
||||
}
|
||||
|
||||
const normalizedSpaceId = Number(spaceId);
|
||||
if (Number.isInteger(normalizedSpaceId) && normalizedSpaceId > 0) {
|
||||
whereClauses.push('t.space_id = :spaceId');
|
||||
replacements.spaceId = normalizedSpaceId;
|
||||
}
|
||||
|
||||
if (transactionType) {
|
||||
whereClauses.push('t.transaction_type = :transactionType');
|
||||
replacements.transactionType = String(transactionType).trim();
|
||||
}
|
||||
|
||||
if (orderType) {
|
||||
whereClauses.push('t.order_type = :orderType');
|
||||
replacements.orderType = String(orderType).trim();
|
||||
}
|
||||
|
||||
if (orderNo) {
|
||||
whereClauses.push('t.order_no LIKE :orderNo');
|
||||
replacements.orderNo = `%${String(orderNo).trim()}%`;
|
||||
}
|
||||
|
||||
if (batchNo) {
|
||||
whereClauses.push('t.batch_no = :batchNo');
|
||||
replacements.batchNo = String(batchNo).trim();
|
||||
}
|
||||
|
||||
if (inventoryType) {
|
||||
whereClauses.push('t.inventory_type = :inventoryType');
|
||||
replacements.inventoryType = String(inventoryType).trim();
|
||||
}
|
||||
|
||||
if (operatorName) {
|
||||
whereClauses.push('t.operator_name LIKE :operatorName');
|
||||
replacements.operatorName = `%${String(operatorName).trim()}%`;
|
||||
}
|
||||
|
||||
const normalizedOrderId = Number(orderId);
|
||||
if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) {
|
||||
whereClauses.push('t.order_id = :orderId');
|
||||
replacements.orderId = normalizedOrderId;
|
||||
}
|
||||
|
||||
return {
|
||||
whereSQL: `WHERE ${whereClauses.join(' AND ')}`,
|
||||
replacements,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据关键字解析匹配的 stock_id 列表。
|
||||
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。
|
||||
@ -932,6 +1111,180 @@ class StockTransactionService extends Service {
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出库位维度出入库流水明细为 Excel(wms_storage_transaction)。
|
||||
* 与 list 使用相同查询条件,但不分页(导出上限 50000 条)。
|
||||
* @param {Object} options 查询参数(与 list 一致,忽略 pagination)
|
||||
* @return {Promise<Object>} Excel 导出结果 { url, filename }
|
||||
*/
|
||||
async exportStorageList(options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const {
|
||||
warehouseId,
|
||||
startTime,
|
||||
endTime,
|
||||
storeIds: rawStoreIds,
|
||||
stockIds: rawStockIds,
|
||||
spaceId,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
inventoryType,
|
||||
operatorName,
|
||||
orderId,
|
||||
sort = {},
|
||||
} = options;
|
||||
|
||||
// keyword 快捷搜索:解析为 stock_id IN 条件,无匹配时导出空表
|
||||
let stockIds = Array.isArray(rawStockIds)
|
||||
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
const normalizedKeyword = String(keyword || '').trim();
|
||||
let keywordResolvedEmpty = false;
|
||||
if (normalizedKeyword && stockIds.length === 0) {
|
||||
stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', Number(warehouseId));
|
||||
if (stockIds.length === 0) {
|
||||
keywordResolvedEmpty = true;
|
||||
}
|
||||
}
|
||||
|
||||
let whereSQL;
|
||||
let replacements;
|
||||
if (keywordResolvedEmpty) {
|
||||
whereSQL = 'WHERE 1 = 0';
|
||||
replacements = {};
|
||||
} else {
|
||||
({ whereSQL, replacements } = this._buildStorageTransactionWhere({
|
||||
warehouseId,
|
||||
startTime,
|
||||
endTime,
|
||||
storeIds: rawStoreIds,
|
||||
stockIds,
|
||||
spaceId,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
inventoryType,
|
||||
operatorName,
|
||||
orderId,
|
||||
}));
|
||||
}
|
||||
|
||||
// 排序白名单,与 list 一致
|
||||
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id', 'space_id' ]);
|
||||
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
|
||||
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
|
||||
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
|
||||
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
|
||||
|
||||
const EXPORT_MAX = 50000;
|
||||
const rows = await ctx.model.query(`
|
||||
SELECT
|
||||
t.id,
|
||||
t.created_at,
|
||||
t.transaction_type,
|
||||
t.warehouse_id,
|
||||
t.store_id,
|
||||
t.stock_id,
|
||||
t.storage_id,
|
||||
t.space_id,
|
||||
t.quantity,
|
||||
t.before_quantity,
|
||||
t.after_quantity,
|
||||
t.before_locked_quantity,
|
||||
t.after_locked_quantity,
|
||||
t.before_intercept_locked_quantity,
|
||||
t.after_intercept_locked_quantity,
|
||||
t.batch_no,
|
||||
t.inventory_type,
|
||||
t.order_type,
|
||||
t.order_no,
|
||||
t.order_id,
|
||||
t.source_order_codes,
|
||||
t.operator_id,
|
||||
t.operator_name,
|
||||
t.remark
|
||||
FROM wms_storage_transaction t
|
||||
${whereSQL}
|
||||
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
|
||||
LIMIT ${EXPORT_MAX}
|
||||
`, {
|
||||
replacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
|
||||
const safeRows = Array.isArray(rows) ? rows : [];
|
||||
const excelRows = safeRows.map((item, index) => ({
|
||||
序号: index + 1,
|
||||
创建时间: item.created_at ? app.formatDate(item.created_at) : '',
|
||||
流水类型: item.transaction_type || '',
|
||||
仓库ID: Number(item.warehouse_id) || 0,
|
||||
货主ID: Number(item.store_id) || 0,
|
||||
商品ID: Number(item.stock_id) || 0,
|
||||
库位库存ID: Number(item.storage_id) || 0,
|
||||
库位ID: Number(item.space_id) || 0,
|
||||
库存变动量: Number(item.quantity) || 0,
|
||||
库存变更前: Number(item.before_quantity) || 0,
|
||||
库存变更后: Number(item.after_quantity) || 0,
|
||||
锁定变更前: Number(item.before_locked_quantity) || 0,
|
||||
锁定变更后: Number(item.after_locked_quantity) || 0,
|
||||
拦截锁定变更前: Number(item.before_intercept_locked_quantity) || 0,
|
||||
拦截锁定变更后: Number(item.after_intercept_locked_quantity) || 0,
|
||||
批次号: item.batch_no || '',
|
||||
库存类型: item.inventory_type || '',
|
||||
单据类型: item.order_type || '',
|
||||
单据号: item.order_no || '',
|
||||
发货单ID: Number(item.order_id) || 0,
|
||||
来源订单号: item.source_order_codes || '',
|
||||
操作人ID: item.operator_id || '',
|
||||
操作人: item.operator_name || '',
|
||||
备注: item.remark || '',
|
||||
}));
|
||||
|
||||
const warehouseIdForPath = Number(warehouseId) || 'unknown';
|
||||
|
||||
return await ctx.service.systems.excel.generateAndUpload({
|
||||
filename: `库位流水_${warehouseIdForPath}_${Date.now()}.xlsx`,
|
||||
dir: `exports/storage/transaction/${warehouseIdForPath}`,
|
||||
category: 'document',
|
||||
sheets: [
|
||||
{
|
||||
name: '库位流水',
|
||||
columns: [
|
||||
{ header: '序号', key: '序号' },
|
||||
{ header: '创建时间', key: '创建时间' },
|
||||
{ header: '流水类型', key: '流水类型' },
|
||||
{ header: '仓库ID', key: '仓库ID' },
|
||||
{ header: '货主ID', key: '货主ID' },
|
||||
{ header: '商品ID', key: '商品ID' },
|
||||
{ header: '库位库存ID', key: '库位库存ID' },
|
||||
{ header: '库位ID', key: '库位ID' },
|
||||
{ header: '库存变动量', key: '库存变动量' },
|
||||
{ header: '库存变更前', key: '库存变更前' },
|
||||
{ header: '库存变更后', key: '库存变更后' },
|
||||
{ header: '锁定变更前', key: '锁定变更前' },
|
||||
{ header: '锁定变更后', key: '锁定变更后' },
|
||||
{ header: '拦截锁定变更前', key: '拦截锁定变更前' },
|
||||
{ header: '拦截锁定变更后', key: '拦截锁定变更后' },
|
||||
{ header: '批次号', key: '批次号' },
|
||||
{ header: '库存类型', key: '库存类型' },
|
||||
{ header: '单据类型', key: '单据类型' },
|
||||
{ header: '单据号', key: '单据号' },
|
||||
{ header: '发货单ID', key: '发货单ID' },
|
||||
{ header: '来源订单号', key: '来源订单号' },
|
||||
{ header: '操作人ID', key: '操作人ID' },
|
||||
{ header: '操作人', key: '操作人' },
|
||||
{ header: '备注', key: '备注' },
|
||||
],
|
||||
rows: excelRows,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StockTransactionService;
|
||||
|
||||
@ -9,6 +9,10 @@ const Service = require('egg').Service;
|
||||
const STOCK_DETAIL_CACHE_KEY_PREFIX = 'cache:stock_detail';
|
||||
/** 仓库商品详情缓存默认 TTL(秒) */
|
||||
const DEFAULT_STOCK_DETAIL_CACHE_TTL = 300;
|
||||
/** 缓存读取并发批大小 */
|
||||
const CACHE_READ_BATCH_SIZE = 200;
|
||||
/** 缓存写入并发批大小 */
|
||||
const CACHE_WRITE_BATCH_SIZE = 100;
|
||||
|
||||
class StockWarehouseService extends Service {
|
||||
/**
|
||||
@ -47,19 +51,25 @@ class StockWarehouseService extends Service {
|
||||
const cacheHits = new Map();
|
||||
const missedStockIds = [];
|
||||
|
||||
// 第一步:逐个查缓存
|
||||
for (const stockId of uniqueStockIds) {
|
||||
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
|
||||
try {
|
||||
const cached = await app.getCacheAsync(cacheKey);
|
||||
if (cached !== null && cached !== undefined) {
|
||||
cacheHits.set(stockId, cached);
|
||||
} else {
|
||||
missedStockIds.push(stockId);
|
||||
// 第一步:分批并发查缓存(避免逐个串行 await 叠加 N 次 Redis 往返延迟)
|
||||
for (let i = 0; i < uniqueStockIds.length; i += CACHE_READ_BATCH_SIZE) {
|
||||
const batch = uniqueStockIds.slice(i, i + CACHE_READ_BATCH_SIZE);
|
||||
const batchResults = await Promise.all(batch.map(async stockId => {
|
||||
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
|
||||
try {
|
||||
const cached = await app.getCacheAsync(cacheKey);
|
||||
return { stockId, cached, hit: cached !== null && cached !== undefined };
|
||||
} catch {
|
||||
// 缓存读取异常时降级为查数据库
|
||||
return { stockId, cached: null, hit: false };
|
||||
}
|
||||
}));
|
||||
for (const item of batchResults) {
|
||||
if (item.hit) {
|
||||
cacheHits.set(item.stockId, item.cached);
|
||||
} else {
|
||||
missedStockIds.push(item.stockId);
|
||||
}
|
||||
} catch {
|
||||
// 缓存读取异常时降级为查数据库
|
||||
missedStockIds.push(stockId);
|
||||
}
|
||||
}
|
||||
|
||||
@ -131,7 +141,8 @@ class StockWarehouseService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 组装每个 stock 的完整详情
|
||||
// 组装每个 stock 的完整详情,并收集缓存写入任务
|
||||
const cacheWriteTasks = [];
|
||||
for (const row of stockRows) {
|
||||
const detail = {
|
||||
id: row.id,
|
||||
@ -152,27 +163,31 @@ class StockWarehouseService extends Service {
|
||||
};
|
||||
dbResults.set(row.id, detail);
|
||||
|
||||
// 第三步:写入缓存
|
||||
const cacheKey = this._buildStockDetailCacheKey(warehouseId, row.id);
|
||||
try {
|
||||
await app.setCacheAsync(cacheKey, detail, cacheTTL);
|
||||
} catch {
|
||||
// 缓存写入失败不影响主流程
|
||||
}
|
||||
// 第三步:写入缓存(收集任务,稍后统一分批并发执行)
|
||||
cacheWriteTasks.push({
|
||||
key: this._buildStockDetailCacheKey(warehouseId, row.id),
|
||||
value: detail,
|
||||
ttl: cacheTTL,
|
||||
});
|
||||
}
|
||||
|
||||
// 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透
|
||||
for (const stockId of missedStockIds) {
|
||||
if (!dbResults.has(stockId)) {
|
||||
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
|
||||
try {
|
||||
cacheWriteTasks.push({
|
||||
key: this._buildStockDetailCacheKey(warehouseId, stockId),
|
||||
value: null,
|
||||
// 用较短的 TTL 缓存空结果,避免缓存穿透
|
||||
await app.setCacheAsync(cacheKey, null, Math.min(cacheTTL, 60));
|
||||
} catch {
|
||||
// 忽略缓存写入失败
|
||||
}
|
||||
ttl: Math.min(cacheTTL, 60),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 分批并发写缓存(缓存写入失败不影响主流程)
|
||||
for (let i = 0; i < cacheWriteTasks.length; i += CACHE_WRITE_BATCH_SIZE) {
|
||||
const batch = cacheWriteTasks.slice(i, i + CACHE_WRITE_BATCH_SIZE);
|
||||
await Promise.all(batch.map(task => app.setCacheAsync(task.key, task.value, task.ttl).catch(() => {})));
|
||||
}
|
||||
}
|
||||
|
||||
// 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序
|
||||
|
||||
@ -1521,11 +1521,13 @@ class EntryService extends Service {
|
||||
* 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 入库单ID
|
||||
* @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0)
|
||||
* @return {Promise<Object>} code/data/message 结构
|
||||
*/
|
||||
async quickInbound(data = {}) {
|
||||
const { ctx, app } = this;
|
||||
const orderId = Number(data.id || 0);
|
||||
const noNeedNotice = Number(data.noNeedNotice) || 0;
|
||||
|
||||
if (!orderId) {
|
||||
return {
|
||||
@ -1892,11 +1894,13 @@ class EntryService extends Service {
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
// 入库完成通知货主(失败不影响主流程)
|
||||
try {
|
||||
await ctx.service.systems.inboundDirectLog.notifyEntryOrderCompleted(eo);
|
||||
} catch (noticeErr) {
|
||||
ctx.logger.warn('[storage.entry.quickInbound] 入库完成通知货主失败,不影响业务', noticeErr);
|
||||
// 入库完成通知货主(失败不影响主流程);noNeedNotice=1 时跳过通知
|
||||
if (noNeedNotice !== 1) {
|
||||
try {
|
||||
await ctx.service.systems.inboundDirectLog.notifyEntryOrderCompleted(eo);
|
||||
} catch (noticeErr) {
|
||||
ctx.logger.warn('[storage.entry.quickInbound] 入库完成通知货主失败,不影响业务', noticeErr);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (transaction && typeof transaction.rollback === 'function') {
|
||||
|
||||
@ -1229,7 +1229,7 @@ class InventoryService extends Service {
|
||||
* @param {string} [sortParams.sortField='created_at'] 排序字段(明细模式支持 wms_storage 真实列;汇总模式仅支持 quantity/locked_quantity/available_quantity/batch_count/first_inbound_time/last_inbound_time/production_date/expiry_date,其余回退 last_inbound_time)
|
||||
* @param {string} [sortParams.sortOrder='DESC'] 排序方向
|
||||
* @param {boolean} [groupByBatch=false] 是否按批次明细返回
|
||||
* @param {string} [stockQuery=''] 商品快捷搜索关键字(来自 where.stock_query,按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,解析为 stock_id 过滤)
|
||||
* @param {string|string[]} [stockQuery=''] 商品快捷搜索关键字(来自 where.stock_query,按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,解析为 stock_id 过滤;支持数组,多关键字取并集)
|
||||
* @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果
|
||||
*/
|
||||
async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false, stockQuery = '') {
|
||||
@ -1265,11 +1265,20 @@ class InventoryService extends Service {
|
||||
}
|
||||
|
||||
// stock_query 快捷搜索:按商品编码/名称/货物编码/条码/SKU ID 解析为 stock_id IN 条件
|
||||
const normalizedKeyword = String(stockQuery || '').trim();
|
||||
if (normalizedKeyword) {
|
||||
const stockIds = await this.resolveStockQueryToStockIds(normalizedKeyword, warehouseId);
|
||||
if (stockIds.length > 0) {
|
||||
baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } });
|
||||
// 兼容单关键字(字符串)与多关键字(数组):多关键字逐项解析后取 stock_id 并集
|
||||
const stockQueryKeywords = (Array.isArray(stockQuery) ? stockQuery : [ stockQuery ])
|
||||
.map(keyword => String(keyword || '').trim())
|
||||
.filter(Boolean);
|
||||
if (stockQueryKeywords.length > 0) {
|
||||
const stockIdSet = new Set();
|
||||
for (const keyword of stockQueryKeywords) {
|
||||
const matchedStockIds = await this.resolveStockQueryToStockIds(keyword, warehouseId);
|
||||
for (const stockId of matchedStockIds) {
|
||||
stockIdSet.add(stockId);
|
||||
}
|
||||
}
|
||||
if (stockIdSet.size > 0) {
|
||||
baseWhere[Op.and].push({ stock_id: { [Op.in]: [ ...stockIdSet ] } });
|
||||
} else {
|
||||
// stock_query 无匹配结果,直接返回空列表
|
||||
return {
|
||||
|
||||
@ -3098,8 +3098,25 @@ class ReceivingService extends Service {
|
||||
if (barcodes.length > 0) {
|
||||
updateData.barcode = barcodes.join(';');
|
||||
}
|
||||
if (stockWarehouse.gross_weight !== undefined && stockWarehouse.gross_weight !== null) {
|
||||
updateData.weight = stockWarehouse.gross_weight;
|
||||
// 毛重处理:stock_warehouse 有毛重时以商品毛重为准;
|
||||
// 毛重为 0 时,用收货明细的重量回写覆盖 stock_warehouse 的毛重
|
||||
const swGrossWeight = Number(stockWarehouse.gross_weight) || 0;
|
||||
const detailWeight = Number(receivingDetail.weight) || 0;
|
||||
if (swGrossWeight > 0) {
|
||||
updateData.weight = swGrossWeight;
|
||||
} else if (detailWeight > 0) {
|
||||
try {
|
||||
await app.model.StockWarehouse.update({
|
||||
gross_weight: detailWeight,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: systemProductId },
|
||||
});
|
||||
updateData.weight = detailWeight;
|
||||
} catch (weightErr) {
|
||||
// 毛重回写失败仅记录日志,不阻断绑定业务
|
||||
ctx.logger.warn('[receiving.bindDetailProduct] 回写商品毛重失败,不影响业务', weightErr);
|
||||
}
|
||||
}
|
||||
if (stockWarehouse.enable_box_spec) {
|
||||
updateData.boxes_per_pallet = stockWarehouse.quantity_per_box || receivingDetail.boxes_per_pallet || 0;
|
||||
|
||||
@ -134,12 +134,15 @@ function formatTransactionType(transactionType) {
|
||||
return rawType;
|
||||
}
|
||||
|
||||
const SORT_FIELD_WHITE_LIST = new Set([ 'begin_total', 'inbound_total', 'outbound_total', 'end_total' ]);
|
||||
const SORT_FIELD_WHITE_LIST = new Set([ 'stock_id', 'item_code', 'item_name', 'begin_total', 'inbound_total', 'outbound_total', 'end_total' ]);
|
||||
|
||||
/** 字符串排序字段集合(按字典序比较),其余白名单字段按数值比较 */
|
||||
const STRING_SORT_FIELD_SET = new Set([ 'item_code', 'item_name' ]);
|
||||
|
||||
/**
|
||||
* 归一化排序参数。
|
||||
* @param {Object|null|undefined} sort 排序入参
|
||||
* @param {string} [sort.sortField] 排序字段
|
||||
* @param {string} [sort.sortField] 排序字段(白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total)
|
||||
* @param {string} [sort.sortOrder] 排序顺序
|
||||
* @return {{sortField: string, sortOrder: 'ASC'|'DESC'}|null} 合法排序参数
|
||||
*/
|
||||
@ -202,12 +205,19 @@ function sortReportList(list, isBySpace, sort) {
|
||||
|
||||
const { sortField, sortOrder } = normalizedSort;
|
||||
const direction = sortOrder === 'DESC' ? -1 : 1;
|
||||
const isStringSort = STRING_SORT_FIELD_SET.has(sortField);
|
||||
|
||||
return list.sort((a, b) => {
|
||||
const aValue = toNumber(a[sortField]);
|
||||
const bValue = toNumber(b[sortField]);
|
||||
if (aValue !== bValue) {
|
||||
return (aValue - bValue) * direction;
|
||||
let cmp;
|
||||
if (isStringSort) {
|
||||
cmp = String(a[sortField] || '').localeCompare(String(b[sortField] || ''));
|
||||
} else {
|
||||
const aValue = toNumber(a[sortField]);
|
||||
const bValue = toNumber(b[sortField]);
|
||||
cmp = aValue === bValue ? 0 : aValue - bValue;
|
||||
}
|
||||
if (cmp !== 0) {
|
||||
return cmp * direction;
|
||||
}
|
||||
return compareByDefaultOrder(a, b, isBySpace);
|
||||
});
|
||||
@ -296,6 +306,56 @@ function buildPreStartAfterMap(rows, resolveKey) {
|
||||
return snapshotMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 SQL WHERE 子句数组中的表别名 t. 重绑定为指定别名,便于在派生表子查询中复用同一组条件。
|
||||
* @param {string[]} clauses WHERE 子句数组
|
||||
* @param {string} alias 目标表别名
|
||||
* @return {string[]} 重绑定后的子句数组
|
||||
*/
|
||||
function rebindTableAlias(clauses, alias) {
|
||||
return clauses.map(clause => String(clause).replace(/\bt\./g, `${alias}.`));
|
||||
}
|
||||
|
||||
/** 默认分页每页条数 */
|
||||
const DEFAULT_PAGE_SIZE = 20;
|
||||
/** 导出全量分页大小(导出必须全量,避免默认分页截断汇总与明细) */
|
||||
const EXPORT_FULL_PAGE_SIZE = 1000000;
|
||||
|
||||
/**
|
||||
* 对已排序的结果列表做内存分页切片。
|
||||
* 分页参数未传或非法时回退默认分页:page=1、pageSize=20。
|
||||
* @param {Object[]} list 已排序列表
|
||||
* @param {Object|null|undefined} pagination 分页参数 { page, pageSize }(兼容 page_size)
|
||||
* @return {{items: Object[], meta: {page: number, pageSize: number, total: number, totalPages: number, hasPrevious: boolean, hasNext: boolean}}} 分页结果
|
||||
*/
|
||||
function paginateList(list, pagination) {
|
||||
const hasPagination = pagination && typeof pagination === 'object';
|
||||
const rawPage = hasPagination ? Number(pagination.page) : NaN;
|
||||
const rawPageSize = hasPagination
|
||||
? Number(pagination.pageSize !== undefined ? pagination.pageSize : pagination.page_size)
|
||||
: NaN;
|
||||
|
||||
const page = Number.isInteger(rawPage) && rawPage >= 1 ? rawPage : 1;
|
||||
const pageSize = Number.isInteger(rawPageSize) && rawPageSize >= 1 ? rawPageSize : DEFAULT_PAGE_SIZE;
|
||||
|
||||
const total = Array.isArray(list) ? list.length : 0;
|
||||
const totalPages = Math.ceil(total / pageSize) || 1;
|
||||
const offset = (page - 1) * pageSize;
|
||||
const items = list.slice(offset, offset + pageSize);
|
||||
|
||||
return {
|
||||
items,
|
||||
meta: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages,
|
||||
hasPrevious: page > 1,
|
||||
hasNext: page < totalPages,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取报表流水数据源配置。
|
||||
* @param {boolean} isBySpace 是否按库位维度统计
|
||||
@ -526,7 +586,8 @@ class StorageReportService extends Service {
|
||||
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '') {
|
||||
const { ctx, app } = this;
|
||||
const isStoreMode = searchMode === 'store';
|
||||
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword);
|
||||
// 导出必须全量:显式传大分页,避免默认分页(pageSize=20)截断汇总与明细白名单
|
||||
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword, { page: 1, pageSize: EXPORT_FULL_PAGE_SIZE });
|
||||
if (!searchResult || searchResult.code !== 200) {
|
||||
return searchResult;
|
||||
}
|
||||
@ -577,6 +638,17 @@ class StorageReportService extends Service {
|
||||
replacements.excludeLockType = 'LOCK';
|
||||
}
|
||||
|
||||
// 明细商品范围与汇总对齐:keyword/stock_ids 过滤后的汇总 stock 白名单同步作用于明细,
|
||||
// 避免导出与汇总无关商品的变更记录
|
||||
const summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
if (summaryStockIds.length === 0) {
|
||||
// 汇总无数据时明细也不应导出任何流水
|
||||
whereClauses.push('0 = 1');
|
||||
} else {
|
||||
whereClauses.push('t.stock_id IN (:detailStockIds)');
|
||||
replacements.detailStockIds = summaryStockIds;
|
||||
}
|
||||
|
||||
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';
|
||||
@ -620,7 +692,6 @@ class StorageReportService extends Service {
|
||||
const detailEntryOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.entry_order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const detailOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
|
||||
const summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const summaryStoreIds = [ ...new Set(summaryList.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||||
const summarySpaceIds = isBySpace
|
||||
? [ ...new Set(summaryList.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ]
|
||||
@ -849,7 +920,7 @@ class StorageReportService extends Service {
|
||||
* 1) 期初优先取 start_time 之前最后一条流水的 after_quantity。
|
||||
* 2) 若 start_time 之前无流水,期初回退到区间内首条流水的 before_quantity。
|
||||
* 3) 期末取区间内末条流水的 after_quantity。
|
||||
* 4) 若维度键在区间内仍无流水,期初/期末统一回退为 0。
|
||||
* 4) 若维度键在区间内无流水,期末回退到期初(库存未变动,保持“期末 = 期初 + 入库 - 出库”恒等)。
|
||||
* 5) by_space=false 时按 stock_id+store_id 维度输出;by_space=true 时按 stock_id+space_id+store_id 维度输出。
|
||||
*
|
||||
* @param {string|Date|null} startTime 开始时间(闭区间下限)
|
||||
@ -862,9 +933,10 @@ class StorageReportService extends Service {
|
||||
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||||
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤),与 keyword 互斥
|
||||
* @param {string} [keyword=''] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配),与 stockIds 互斥
|
||||
* @param {Object|null} [pagination=null] 分页参数 { page, pageSize }(兼容 page_size);未传或非法时默认 page=1、pageSize=20,仅对当前页行加载名称信息
|
||||
* @return {Promise<Object>} code/data/message 结构
|
||||
*/
|
||||
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '') {
|
||||
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '', pagination = null) {
|
||||
const { ctx, app } = this;
|
||||
const isStoreMode = searchMode === 'store';
|
||||
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
|
||||
@ -934,11 +1006,11 @@ class StorageReportService extends Service {
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: [] },
|
||||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||||
};
|
||||
}
|
||||
} else if (stockIds !== null && stockIds !== undefined) {
|
||||
const rawIds = Array.isArray(stockIds) ? stockIds : [ stockIds ];
|
||||
const rawIds = Array.isArray(stockIds) ? stockIds.flat() : [ stockIds ];
|
||||
resolvedStockIds = [ ...new Set(
|
||||
rawIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
) ];
|
||||
@ -946,7 +1018,7 @@ class StorageReportService extends Service {
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: [] },
|
||||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -969,7 +1041,9 @@ class StorageReportService extends Service {
|
||||
sw.id AS stock_id,
|
||||
sw.store_id,
|
||||
sw.warehouse_id,
|
||||
sw.quantity
|
||||
sw.quantity,
|
||||
sw.item_code,
|
||||
sw.item_name
|
||||
FROM wms_stock_warehouse sw
|
||||
WHERE ${baseWhereClauses.join(' AND ')}
|
||||
`, {
|
||||
@ -987,7 +1061,7 @@ class StorageReportService extends Service {
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: [] },
|
||||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||||
};
|
||||
}
|
||||
} else {
|
||||
@ -1007,8 +1081,11 @@ class StorageReportService extends Service {
|
||||
COALESCE(s.space_id, 0) AS space_id,
|
||||
s.store_id,
|
||||
s.warehouse_id,
|
||||
SUM(s.quantity) AS quantity
|
||||
SUM(s.quantity) AS quantity,
|
||||
MAX(sw.item_code) AS item_code,
|
||||
MAX(sw.item_name) AS item_name
|
||||
FROM wms_storage s
|
||||
LEFT JOIN wms_stock_warehouse sw ON sw.id = s.stock_id
|
||||
WHERE ${baseWhereClauses.join(' AND ')}
|
||||
GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id, s.warehouse_id
|
||||
`, {
|
||||
@ -1053,7 +1130,7 @@ class StorageReportService extends Service {
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: [] },
|
||||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||||
};
|
||||
}
|
||||
|
||||
@ -1082,18 +1159,43 @@ class StorageReportService extends Service {
|
||||
|
||||
const safeRangeRows = Array.isArray(rangeRows) ? rangeRows : [];
|
||||
|
||||
// 区间内首/末条快照:在 SQL 端按维度键聚合取极值行,每组仅返回 1 行
|
||||
// (before_quantity 取首条、after_quantity 取末条),避免把区间内全部流水明细拉回 Node 内存归并。
|
||||
// 兼容 MySQL 5.7:不使用窗口函数,采用派生表聚合 MIN/MAX(created_at) + 标量子查询取极值 id 回表。
|
||||
const intervalEdgeRows = await ctx.model.query(`
|
||||
SELECT
|
||||
t.id,
|
||||
t.stock_id,
|
||||
${transactionSource.spaceSelectSql},
|
||||
t.store_id,
|
||||
t.before_quantity,
|
||||
t.after_quantity,
|
||||
t.created_at
|
||||
FROM ${transactionSource.tableName} t
|
||||
WHERE ${rangeWhereClauses.join(' AND ')}
|
||||
ORDER BY t.stock_id ASC${transactionSource.spaceOrderSql}, t.store_id ASC, t.created_at ASC, t.id ASC
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
ft.before_quantity,
|
||||
lt.after_quantity,
|
||||
ft.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
${transactionSource.spaceSelectSql},
|
||||
t.store_id,
|
||||
MIN(t.created_at) AS _min_ct,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM ${transactionSource.tableName} t
|
||||
WHERE ${rangeWhereClauses.join(' AND ')}
|
||||
GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id
|
||||
) g
|
||||
LEFT JOIN ${transactionSource.tableName} ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id)
|
||||
FROM ${transactionSource.tableName} t2
|
||||
WHERE ${rebindTableAlias(rangeWhereClauses, 't2').join(' AND ')}${isBySpace ? ' AND COALESCE(t2.space_id, 0) = g.space_id' : ''}
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN ${transactionSource.tableName} lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM ${transactionSource.tableName} t3
|
||||
WHERE ${rebindTableAlias(rangeWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''}
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC
|
||||
`, {
|
||||
replacements: rangeReplacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
@ -1120,17 +1222,33 @@ class StorageReportService extends Service {
|
||||
preStartReplacements.baseStockIds = rangeReplacements.baseStockIds;
|
||||
}
|
||||
|
||||
// start_time 之前的期初快照:SQL 端按维度键聚合取最新一条流水,每组仅返回 1 行,
|
||||
// 避免把全部历史流水明细拉回 Node 内存归并。兼容 MySQL 5.7(聚合 + 标量子查询取极值 id 回表)。
|
||||
preStartSnapshotRows = await ctx.model.query(`
|
||||
SELECT
|
||||
t.id,
|
||||
t.stock_id,
|
||||
${transactionSource.spaceSelectSql},
|
||||
t.store_id,
|
||||
t.after_quantity,
|
||||
t.created_at
|
||||
FROM ${transactionSource.tableName} t
|
||||
WHERE ${preStartWhereClauses.join(' AND ')}
|
||||
ORDER BY t.stock_id ASC${transactionSource.spaceOrderSql}, t.store_id ASC, t.created_at DESC, t.id DESC
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
lt.after_quantity,
|
||||
lt.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
${transactionSource.spaceSelectSql},
|
||||
t.store_id,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM ${transactionSource.tableName} t
|
||||
WHERE ${preStartWhereClauses.join(' AND ')}
|
||||
GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id
|
||||
) g
|
||||
LEFT JOIN ${transactionSource.tableName} lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM ${transactionSource.tableName} t3
|
||||
WHERE ${rebindTableAlias(preStartWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''}
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC
|
||||
`, {
|
||||
replacements: preStartReplacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
@ -1192,7 +1310,8 @@ class StorageReportService extends Service {
|
||||
beginTotal = toNumber(snapshot && snapshot.begin_total);
|
||||
}
|
||||
|
||||
const endTotal = hasSnapshot ? toNumber(snapshot && snapshot.end_total) : 0;
|
||||
// 区间内无流水时,期末回退到期初,保证“期末 = 期初 + 入库 - 出库”恒等
|
||||
const endTotal = hasSnapshot ? toNumber(snapshot && snapshot.end_total) : beginTotal;
|
||||
|
||||
return {
|
||||
start_time: startTime || null,
|
||||
@ -1206,16 +1325,24 @@ class StorageReportService extends Service {
|
||||
outbound_total: toNumber(rangeSum && rangeSum.outbound_total),
|
||||
store_name: '',
|
||||
warehouse_name: '',
|
||||
item_name: '',
|
||||
// item_code/item_name 取快照查询结果,供按 item_code/item_name 排序使用;
|
||||
// 最终展示值以 getStockDetails 为准(本字段作为回退)
|
||||
item_name: row.item_name || '',
|
||||
barcode: '',
|
||||
item_code: '',
|
||||
item_code: row.item_code || '',
|
||||
};
|
||||
})
|
||||
.filter(item => item.stock_id > 0 && item.store_id > 0);
|
||||
|
||||
const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
||||
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
|
||||
const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ];
|
||||
// 先按最终规则排序,再做分页切片:仅对当前页行填充名称信息,
|
||||
// 避免全量 SKU 的商品详情缓存/DB 查询(大数据量下为耗时大头)。
|
||||
sortReportList(groupedList, false, sort);
|
||||
const pageResult = paginateList(groupedList, pagination);
|
||||
const pageItems = pageResult.items;
|
||||
|
||||
const groupedStockIds = [ ...new Set(pageItems.map(item => item.stock_id).filter(Boolean)) ];
|
||||
const storeIdList = [ ...new Set(pageItems.map(item => item.store_id).filter(Boolean)) ];
|
||||
const warehouseIdList = [ ...new Set(pageItems.map(item => item.warehouse_id).filter(Boolean)) ];
|
||||
|
||||
// 复用 getStockDetails 获取商品名称和条码
|
||||
// store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品
|
||||
@ -1272,7 +1399,7 @@ class StorageReportService extends Service {
|
||||
|
||||
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
|
||||
|
||||
const list = groupedList
|
||||
const list = pageItems
|
||||
.map(item => {
|
||||
const stock = stockMap.get(item.stock_id) || {};
|
||||
const store = storeMap.get(item.store_id) || {};
|
||||
@ -1283,20 +1410,16 @@ class StorageReportService extends Service {
|
||||
...item,
|
||||
store_name: store.company_name || '',
|
||||
warehouse_name: warehouse.company_name || '',
|
||||
item_name: stock.item_name || '',
|
||||
item_code: stock.item_code || '',
|
||||
item_name: stock.item_name || item.item_name || '',
|
||||
item_code: stock.item_code || item.item_code || '',
|
||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||
};
|
||||
});
|
||||
|
||||
sortReportList(list, false, sort);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: {
|
||||
list,
|
||||
},
|
||||
data: { list, pagination: pageResult.meta },
|
||||
};
|
||||
}
|
||||
|
||||
@ -1317,6 +1440,8 @@ class StorageReportService extends Service {
|
||||
store_id: storeId,
|
||||
warehouse_id: whId,
|
||||
quantity: toNumber(row.quantity),
|
||||
item_code: row.item_code || '',
|
||||
item_name: row.item_name || '',
|
||||
});
|
||||
}
|
||||
|
||||
@ -1337,6 +1462,8 @@ class StorageReportService extends Service {
|
||||
store_id: storeId,
|
||||
warehouse_id: whId,
|
||||
quantity: 0,
|
||||
item_code: '',
|
||||
item_name: '',
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1346,7 +1473,7 @@ class StorageReportService extends Service {
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: [] },
|
||||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||||
};
|
||||
}
|
||||
|
||||
@ -1419,9 +1546,10 @@ class StorageReportService extends Service {
|
||||
outbound_total: 0,
|
||||
store_name: '',
|
||||
warehouse_name: '',
|
||||
item_name: '',
|
||||
// item_code/item_name 取库存快照查询结果,供按 item_code/item_name 排序使用
|
||||
item_name: row.item_name || '',
|
||||
barcode: '',
|
||||
item_code: '',
|
||||
item_code: row.item_code || '',
|
||||
space_name: '',
|
||||
});
|
||||
}
|
||||
@ -1432,7 +1560,8 @@ class StorageReportService extends Service {
|
||||
: snapshot.has_snapshot
|
||||
? toNumber(snapshot.begin_total)
|
||||
: 0;
|
||||
const endTotal = snapshot.has_snapshot ? toNumber(snapshot.end_total) : 0;
|
||||
// 区间内无流水时,期末回退到期初,保证“期末 = 期初 + 入库 - 出库”恒等
|
||||
const endTotal = snapshot.has_snapshot ? toNumber(snapshot.end_total) : beginTotal;
|
||||
current.begin_total += beginTotal;
|
||||
current.end_total += endTotal;
|
||||
current.inbound_total += toNumber(rangeSum.inbound_total);
|
||||
@ -1440,11 +1569,17 @@ class StorageReportService extends Service {
|
||||
}
|
||||
|
||||
const groupedList = [ ...groupedMap.values() ];
|
||||
const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
||||
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
|
||||
const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ];
|
||||
|
||||
// 先按最终规则排序,再做分页切片:仅对当前页行填充名称信息,避免全量 SKU 详情查询
|
||||
sortReportList(groupedList, isBySpace, sort);
|
||||
const pageResult = paginateList(groupedList, pagination);
|
||||
const pageItems = pageResult.items;
|
||||
|
||||
const groupedStockIds = [ ...new Set(pageItems.map(item => item.stock_id).filter(Boolean)) ];
|
||||
const storeIdList = [ ...new Set(pageItems.map(item => item.store_id).filter(Boolean)) ];
|
||||
const warehouseIdList = [ ...new Set(pageItems.map(item => item.warehouse_id).filter(Boolean)) ];
|
||||
const spaceIds = isBySpace
|
||||
? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ]
|
||||
? [ ...new Set(pageItems.map(item => item.space_id).filter(id => Number(id) > 0)) ]
|
||||
: [];
|
||||
|
||||
// 复用 getStockDetails 获取商品名称和条码
|
||||
@ -1512,7 +1647,7 @@ class StorageReportService extends Service {
|
||||
const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ]));
|
||||
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
|
||||
|
||||
const list = groupedList
|
||||
const list = pageItems
|
||||
.map(item => {
|
||||
const stock = stockMap.get(item.stock_id) || {};
|
||||
const store = storeMap.get(item.store_id) || {};
|
||||
@ -1524,8 +1659,8 @@ class StorageReportService extends Service {
|
||||
...item,
|
||||
store_name: store.company_name || '',
|
||||
warehouse_name: warehouse.company_name || '',
|
||||
item_name: stock.item_name || '',
|
||||
item_code: stock.item_code || '',
|
||||
item_name: stock.item_name || item.item_name || '',
|
||||
item_code: stock.item_code || item.item_code || '',
|
||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||
};
|
||||
|
||||
@ -1536,14 +1671,10 @@ class StorageReportService extends Service {
|
||||
return merged;
|
||||
});
|
||||
|
||||
sortReportList(list, isBySpace, sort);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: {
|
||||
list,
|
||||
},
|
||||
data: { list, pagination: pageResult.meta },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -351,7 +351,6 @@ class WorkbenchService extends Service {
|
||||
*/
|
||||
PACK_OPLOG_FIELD_WHITELIST = new Set([
|
||||
'pack_mode',
|
||||
'status',
|
||||
'pack_quantity',
|
||||
'item_quantity',
|
||||
'sku_count',
|
||||
@ -364,7 +363,6 @@ class WorkbenchService extends Service {
|
||||
*/
|
||||
PACK_OPLOG_FIELD_LABEL = {
|
||||
pack_mode: '打包模式',
|
||||
status: '任务状态',
|
||||
pack_quantity: '打包数量',
|
||||
item_quantity: '商品总数量',
|
||||
sku_count: '商品种类数',
|
||||
@ -377,15 +375,16 @@ class WorkbenchService extends Service {
|
||||
*/
|
||||
PACK_OPLOG_VALUE_LABEL = {
|
||||
pack_mode: { 1: '散单', 2: '团购' },
|
||||
status: { 0: '待处理', 1: '打包中', 2: '已完成', 3: '异常' },
|
||||
};
|
||||
|
||||
/**
|
||||
* 构建打包操作日志的变更描述。
|
||||
* 工作台展示名称而非 ID(名称缺失时降级为 ID)。
|
||||
* @param {Object} packData 打包数据
|
||||
* @param {string} [workbenchName] 工作台名称
|
||||
* @returns {string} 变更描述
|
||||
*/
|
||||
_buildPackChangeSummary(packData) {
|
||||
_buildPackChangeSummary(packData, workbenchName) {
|
||||
const whitelist = this.PACK_OPLOG_FIELD_WHITELIST;
|
||||
const fieldLabel = this.PACK_OPLOG_FIELD_LABEL;
|
||||
const valueLabel = this.PACK_OPLOG_VALUE_LABEL;
|
||||
@ -394,9 +393,14 @@ class WorkbenchService extends Service {
|
||||
for (const [ key, value ] of Object.entries(packData)) {
|
||||
if (!whitelist.has(key) || value === undefined || value === null) continue;
|
||||
const label = fieldLabel[key] || key;
|
||||
const valStr = (valueLabel[key] && valueLabel[key][value] !== undefined)
|
||||
? valueLabel[key][value]
|
||||
: String(value);
|
||||
let valStr;
|
||||
if (key === 'workbench_id') {
|
||||
valStr = workbenchName || String(value);
|
||||
} else {
|
||||
valStr = (valueLabel[key] && valueLabel[key][value] !== undefined)
|
||||
? valueLabel[key][value]
|
||||
: String(value);
|
||||
}
|
||||
parts.push(`${label}: ${valStr}`);
|
||||
}
|
||||
return parts.join(',');
|
||||
@ -416,8 +420,9 @@ class WorkbenchService extends Service {
|
||||
* @param {number} options.isSandan 是否散单(1=散单 0=团购)
|
||||
* @param {Object} options.packData 打包数据(用于变更描述)
|
||||
* @param {Array<Object>} options.users 打包人员列表
|
||||
* @param {string} [options.workbenchName] 工作台名称(日志展示用,缺失时展示工作台ID)
|
||||
*/
|
||||
async _writePackOperationLog({ warehouseId, orderId, waveId, waveNo, isSandan, packData, users }) {
|
||||
async _writePackOperationLog({ warehouseId, orderId, waveId, waveNo, isSandan, packData, users, workbenchName }) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
@ -431,7 +436,7 @@ class WorkbenchService extends Service {
|
||||
name: users && users[0] ? (users[0].real_name || '') : null,
|
||||
};
|
||||
|
||||
const changeSummary = this._buildPackChangeSummary(packData);
|
||||
const changeSummary = this._buildPackChangeSummary(packData, workbenchName);
|
||||
const operationCode = isSandan === 1 ? 'ORDER_PACK' : 'ORDER_PACK_GROUP';
|
||||
const isFinish = Number(packData && packData.status) >= 2;
|
||||
const actionText = isFinish ? '打包完成' : '开始打包';
|
||||
@ -673,15 +678,17 @@ class WorkbenchService extends Service {
|
||||
throw new Error(`订单已被拦截,无法打包 [${deliveryOrderCode}]`);
|
||||
}
|
||||
|
||||
// 步骤3:获取工作台 device_ids
|
||||
// 步骤3:获取工作台 device_ids 与名称(名称用于操作日志展示)
|
||||
let deviceIds = null;
|
||||
let workbenchName = '';
|
||||
if (validWorkbenchId) {
|
||||
try {
|
||||
const wb = await ctx.model.Workbench.findByPk(validWorkbenchId, {
|
||||
attributes: ['device_ids'],
|
||||
attributes: [ 'name', 'device_ids' ],
|
||||
raw: true,
|
||||
});
|
||||
deviceIds = wb && wb.device_ids ? wb.device_ids : null;
|
||||
workbenchName = (wb && wb.name) || '';
|
||||
} catch (_err) { /* ignore */ }
|
||||
}
|
||||
|
||||
@ -759,6 +766,10 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
|
||||
// 步骤6:创建新的打包任务
|
||||
// 设备端未传/非法 status 一律归一化为 1(打包中),避免 NaN 入库与日志异常
|
||||
const parsedPackStatus = Number.parseInt(packStatus, 10);
|
||||
const normalizedPackStatus = Number.isFinite(parsedPackStatus) ? parsedPackStatus : 1;
|
||||
|
||||
const packData = {
|
||||
order_id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
@ -767,12 +778,12 @@ class WorkbenchService extends Service {
|
||||
wave_no: actualWaveNo,
|
||||
waybill_code: null, // 后续可从 order_express 补
|
||||
pack_mode: isSandan === 0 ? 2 : 1, // 1=散单 2=团购
|
||||
status: packStatus !== undefined ? parseInt(packStatus) : 1,
|
||||
status: normalizedPackStatus,
|
||||
pack_quantity: waveTotalOrders !== undefined ? parseInt(waveTotalOrders) || 0 : 1,
|
||||
item_quantity: itemsTotal !== undefined ? parseInt(itemsTotal) || 0 : (orderRow.items_total || 0),
|
||||
sku_count: itemsCount !== undefined ? parseInt(itemsCount) || 0 : (orderRow.item_count || 0),
|
||||
start_time: new Date(packTimeMs),
|
||||
end_time: packStatus >= 2 ? new Date(packTimeMs) : null,
|
||||
end_time: normalizedPackStatus >= 2 ? new Date(packTimeMs) : null,
|
||||
device_ids: deviceIds,
|
||||
};
|
||||
|
||||
@ -889,6 +900,7 @@ class WorkbenchService extends Service {
|
||||
isSandan,
|
||||
packData,
|
||||
users,
|
||||
workbenchName,
|
||||
});
|
||||
|
||||
const result = {
|
||||
@ -1021,6 +1033,15 @@ class WorkbenchService extends Service {
|
||||
});
|
||||
|
||||
// 写入完成操作日志(团购批量写波次订单,操作人取自任务记录 operator_text)
|
||||
let workbenchName = '';
|
||||
try {
|
||||
const wb = await ctx.model.Workbench.findByPk(validWorkbenchId, {
|
||||
attributes: [ 'name' ],
|
||||
raw: true,
|
||||
});
|
||||
workbenchName = (wb && wb.name) || '';
|
||||
} catch (_err) { /* ignore */ }
|
||||
|
||||
const operatorText = String(lastTask.operator_text || '');
|
||||
await this._writePackOperationLog({
|
||||
warehouseId,
|
||||
@ -1038,6 +1059,7 @@ class WorkbenchService extends Service {
|
||||
wave_no: lastTask.wave_no,
|
||||
},
|
||||
users: operatorText ? [{ real_name: operatorText }] : [],
|
||||
workbenchName,
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@ -0,0 +1,86 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_workbench_member';
|
||||
|
||||
/**
|
||||
* Migration: create wms_workbench_member(工作台成员/用户登录副表)
|
||||
* - user_id 允许为空:非系统账号用户(如未注册 wms_account 的硬件操作员)以 NULL 记录,名称存 user_name 快照。
|
||||
* - 软删除(deleted_at),移除成员通过 workbench.removeMember 完成。
|
||||
*
|
||||
* Idempotent: 表已存在时跳过创建。
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:创建工作台成员副表与索引。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === TABLE_NAME);
|
||||
if (exists) return;
|
||||
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
workbench_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '工作台ID,关联 wms_workbench.id',
|
||||
},
|
||||
user_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '账号ID,关联 wms_account.id;非系统账号用户为 NULL',
|
||||
},
|
||||
user_name: {
|
||||
type: Sequelize.STRING(128),
|
||||
allowNull: true,
|
||||
comment: '成员名称快照(非系统账号用户显示名)',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
});
|
||||
|
||||
// 按工作台查询成员
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'workbench_id' ], {
|
||||
name: 'idx_workbench_id',
|
||||
});
|
||||
|
||||
// 按账号反查成员
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'user_id' ], {
|
||||
name: 'idx_user_id',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行回滚迁移:删除工作台成员副表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,77 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_workbench';
|
||||
|
||||
async function indexExists(queryInterface, tableName, indexName) {
|
||||
const indexes = await queryInterface.showIndex(tableName);
|
||||
return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName);
|
||||
}
|
||||
|
||||
async function dropIndexIfExists(queryInterface, tableName, indexName) {
|
||||
if (await indexExists(queryInterface, tableName, indexName)) {
|
||||
await queryInterface.removeIndex(tableName, indexName);
|
||||
console.log(`[idx] ${tableName}.${indexName} 已删除`);
|
||||
}
|
||||
}
|
||||
|
||||
async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) {
|
||||
if (await indexExists(queryInterface, tableName, indexName)) {
|
||||
console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`);
|
||||
return;
|
||||
}
|
||||
await queryInterface.addIndex(tableName, options.fields, {
|
||||
name: indexName,
|
||||
unique: !!options.unique,
|
||||
});
|
||||
console.log(`[idx] ${tableName}.${indexName} 已创建`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Migration: remove barcode from wms_workbench(工作台条码字段未使用,下线)
|
||||
* - 删除列 barcode VARCHAR(100)
|
||||
* - 删除索引 idx_barcode、uk_warehouse_barcode(仓库级唯一条码索引)
|
||||
*
|
||||
* Idempotent: 通过 describeTable / showIndex 判断后仅删除存在部分。
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:先删索引,再删 barcode 列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
up: async queryInterface => {
|
||||
await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_warehouse_barcode');
|
||||
await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_barcode');
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (columns.barcode) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'barcode');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行回滚迁移:恢复 barcode 列与索引。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!columns.barcode) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'barcode', {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '工作台条码(用户自定义,仓库内唯一)',
|
||||
});
|
||||
}
|
||||
|
||||
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_barcode', {
|
||||
fields: [ 'barcode' ],
|
||||
});
|
||||
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_warehouse_barcode', {
|
||||
fields: [ 'warehouse_id', 'barcode', 'deleted_at' ],
|
||||
unique: true,
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,105 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单表增加 wave_scope(波次范围)字段。
|
||||
*
|
||||
* 取值约定(与 order 工作台虚拟筛选 wave_scope 一致):
|
||||
* - 0 = 未分配波次
|
||||
* - 1 = 团购
|
||||
* - 2 = 散单
|
||||
* 默认 0。
|
||||
*
|
||||
* 覆盖范围:
|
||||
* - 基表 wms_order_delivery;
|
||||
* - 全部仓库分表 wms_order_delivery_{wh}(current)及
|
||||
* _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。
|
||||
*
|
||||
* 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js
|
||||
* 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。
|
||||
*/
|
||||
|
||||
const BASE_TABLE = 'wms_order_delivery';
|
||||
|
||||
const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/;
|
||||
|
||||
const COLUMN_NAME = 'wave_scope';
|
||||
|
||||
/**
|
||||
* 列举库内全部订单分表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<string[]>} 分表名列表。
|
||||
*/
|
||||
async function listOrderShards(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
|
||||
+ 'ORDER BY TABLE_NAME'
|
||||
);
|
||||
return (rows || [])
|
||||
.map(row => String(row.tableName || row.TABLE_NAME || ''))
|
||||
.filter(name => SHARD_PATTERN.test(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断列是否已存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function columnExists(queryInterface, tableName, columnName) {
|
||||
const described = await queryInterface.describeTable(tableName);
|
||||
return Boolean(described && described[columnName]);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为基表与全部分表增加 wave_scope 列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 构造器。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
if (await columnExists(queryInterface, tableName, COLUMN_NAME)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'exists' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(tableName, COLUMN_NAME, {
|
||||
type: Sequelize.TINYINT(4),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '波次范围:0未分配波次 1团购 2散单',
|
||||
});
|
||||
results.push({ tableName, action: 'added' });
|
||||
}
|
||||
|
||||
console.log('[20260905100000-add-wave-scope-to-order-delivery] up results:', JSON.stringify(results));
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除 base 与全部分表的 wave_scope 列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'missing' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, COLUMN_NAME);
|
||||
results.push({ tableName, action: 'removed' });
|
||||
}
|
||||
|
||||
console.log('[20260905100000-add-wave-scope-to-order-delivery] down results:', JSON.stringify(results));
|
||||
},
|
||||
};
|
||||
102
database/migrations/20260905130000-backfill-order-wave-scope.js
Normal file
102
database/migrations/20260905130000-backfill-order-wave-scope.js
Normal file
@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 存量订单回填 wave_scope(波次范围)字段。
|
||||
*
|
||||
* 口径(与波次生成写入逻辑 resolveWaveScopeByWaveMeta 一致):
|
||||
* - 0 = 未分配波次(wave_id = 0,默认值无需更新);
|
||||
* - 1 = 大团购:wms_wave_batch.wave_type = 1 且 source = 0;
|
||||
* - 3 = 小团购:wms_wave_batch.wave_type = 1 且 source = 2;
|
||||
* - 2 = 散单:其余有波次的订单(wave_type = 2,或 wave_type = 1 且 source = 1,
|
||||
* 或 wave_id 指向的波次已不存在)。
|
||||
*
|
||||
* 覆盖范围:基表 wms_order_delivery 与全部仓库分表
|
||||
* (current/history/dispatch/outsourced)。
|
||||
*
|
||||
* 幂等:按 CASE 规则全量覆盖写入,重复执行结果一致。
|
||||
*/
|
||||
|
||||
const BASE_TABLE = 'wms_order_delivery';
|
||||
|
||||
const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/;
|
||||
|
||||
/**
|
||||
* 列举库内全部订单分表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<string[]>} 分表名列表。
|
||||
*/
|
||||
async function listOrderShards(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
|
||||
+ 'ORDER BY TABLE_NAME'
|
||||
);
|
||||
return (rows || [])
|
||||
.map(row => String(row.tableName || row.TABLE_NAME || ''))
|
||||
.filter(name => SHARD_PATTERN.test(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取受影响行数。
|
||||
* @param {*} updateResult query 返回结果。
|
||||
* @return {number} 受影响行数。
|
||||
*/
|
||||
function extractAffectedRows(updateResult) {
|
||||
if (Array.isArray(updateResult)) {
|
||||
const meta = updateResult[1];
|
||||
return Number(meta && (meta.affectedRows || meta.affectedCount || meta.rowCount) || 0);
|
||||
}
|
||||
if (updateResult && typeof updateResult === 'object') {
|
||||
return Number(updateResult.affectedRows || updateResult.affectedCount || updateResult.rowCount || 0);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:按波次类型/来源回填 wave_scope。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
const updateResult = await queryInterface.sequelize.query(`
|
||||
UPDATE \`${tableName}\` o
|
||||
LEFT JOIN wms_wave_batch wb ON wb.wave_id = o.wave_id
|
||||
SET o.wave_scope = CASE
|
||||
WHEN wb.wave_type = 1 AND wb.source = 0 THEN 1
|
||||
WHEN wb.wave_type = 1 AND wb.source = 2 THEN 3
|
||||
ELSE 2
|
||||
END
|
||||
WHERE o.wave_id > 0
|
||||
`);
|
||||
results.push({ tableName, affectedRows: extractAffectedRows(updateResult) });
|
||||
}
|
||||
|
||||
console.log('[20260905130000-backfill-order-wave-scope] up results:', JSON.stringify(results));
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:将已分配波次订单的 wave_scope 重置为 0(未回填状态)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
const updateResult = await queryInterface.sequelize.query(`
|
||||
UPDATE \`${tableName}\`
|
||||
SET wave_scope = 0
|
||||
WHERE wave_id > 0
|
||||
`);
|
||||
results.push({ tableName, affectedRows: extractAffectedRows(updateResult) });
|
||||
}
|
||||
|
||||
console.log('[20260905130000-backfill-order-wave-scope] down results:', JSON.stringify(results));
|
||||
},
|
||||
};
|
||||
@ -1,4 +1,183 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.09.05-storageTransaction-list-detail",
|
||||
"date": "2026-09-05",
|
||||
"summary": "storage.transaction.list 实现纠正:原实现错误查询 wms_stock_transaction 并按商品+单据类型聚合(合并模式),现改为查询 wms_storage_transaction 的逐条流水明细(与 stock.transaction.list 形态一致:裸 SQL 列白名单 + COUNT 分页 + 排序白名单)。聚合查询移除后,生产单仓库 160 万行聚合慢查询(约 9s)不复存在;明细查询实测 COUNT 约 0.2s。",
|
||||
"methods": [
|
||||
"storage.transaction.list"
|
||||
],
|
||||
"notes": [
|
||||
"代码变更:systems/stock_transaction.js list() 由 ORM 聚合查询重写为 wms_storage_transaction 裸 SQL 逐条明细(列白名单含 storage_id/space_id/inventory_type/source_order_codes/before/after_intercept_locked_quantity,LEFT JOIN wms_stock_warehouse 返回 stockItem);systemMethods/storage/transaction.js 解构 whereValue 逐字段传参,warehouse_id 由服务端从 ctx.user.store_id 注入。",
|
||||
"行为变更:group_by_batch 参数废弃,恒返回逐条明细;原合并模式响应(quantity 合计/first_created_at/last_created_at/record_count)不再返回。",
|
||||
"where 支持字段:transaction_type、stock_id/stock_ids、space_id、store_id/store_ids、order_type、order_no(模糊)、batch_no、inventory_type、operator_name(模糊)、order_id、created_at(between)与 start_time/end_time;keyword 支持顶层或 where 内。",
|
||||
"排序白名单:created_at、quantity、stock_id、store_id、warehouse_id、space_id,非法回退 created_at DESC;pageSize 上限 200。",
|
||||
"前端调用方需按逐条明细结构适配(原合并模式渲染逻辑作废)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.04-storage.entry.quickInbound-noneed-notice",
|
||||
"date": "2026-09-04",
|
||||
"type": "enhanced",
|
||||
"summary": "storage.entry.quickInbound 新增参数 noNeedNotice(默认 0):0 时快捷直入完成后通知货主,1 时跳过通知,通知失败仍不影响入库主流程。",
|
||||
"methods": [
|
||||
"storage.entry.quickInbound"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/storage/entry.js:quickInbound 解析 data.noNeedNotice(默认 0)并透传底层 quickInbound({ id, noNeedNotice })",
|
||||
"app/service/systems/storage/entry.js:quickInbound(data) 解析 data.noNeedNotice(Number 归一化),事务提交后仅当 noNeedNotice !== 1 时调用 notifyEntryOrderCompleted",
|
||||
"methods/system.json:storage.entry.quickInbound 新增 noNeedNotice 参数说明与 description 补充;版本 0.3.83 -> 0.3.84(docMeta.version),updatedAt 保持 2026-09-04",
|
||||
"无数据库 schema 变更,未执行任何写库操作"
|
||||
],
|
||||
"module": "storage.entry"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.04-storage.entry.commit-noneed-notice",
|
||||
"date": "2026-09-04",
|
||||
"type": "enhanced",
|
||||
"summary": "storage.entry.commit 新增参数 noNeedNotice(默认 0):0 时入库完成后通知货主,1 时跳过通知,通知失败仍不影响入库主流程。",
|
||||
"methods": [
|
||||
"storage.entry.commit"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/storage/entry.js:commit 解析 data.noNeedNotice(默认 0)并透传底层 inboundDirectLog.commit(entry_order_id, noNeedNotice)",
|
||||
"app/service/systems/inbound_direct_log.js:commit(entryOrderId, noNeedNotice = 0),事务提交后仅当 Number(noNeedNotice) !== 1 时调用 notifyEntryOrderCompleted(字符串 '1' 也兼容)",
|
||||
"methods/system.json:storage.entry.commit 新增 noNeedNotice 参数说明与 description 补充;版本 0.3.82 -> 0.3.83(docMeta.version),updatedAt 保持 2026-09-04",
|
||||
"无数据库 schema 变更,未执行任何写库操作"
|
||||
],
|
||||
"module": "storage.entry"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.04-stock.report.export-stock-id-fix",
|
||||
"date": "2026-09-04",
|
||||
"type": "fixed",
|
||||
"summary": "修复 stock.report.export(含 search/searchStore/exportStore)where.stock_id 传数组时导出空白的问题:单数 stock_id 现兼容数组,避免被再包裹一层导致嵌套数组归一化为 NaN 全量过滤;同时修复默认分页上线后导出内部 search 被截断为第一页 20 条导致汇总/明细缺数据的回归。",
|
||||
"methods": [
|
||||
"stock.report.search",
|
||||
"stock.report.searchStore",
|
||||
"stock.report.export",
|
||||
"stock.report.exportStore"
|
||||
],
|
||||
"notes": [
|
||||
"根因:where.stock_id 传数组时 systemMethods 层 [ stockIdRaw ] 再包一层形成嵌套数组,systems 层 Number(嵌套数组)=NaN 被全部过滤 → 汇总空 → 导出空白",
|
||||
"app/service/systemMethods/stock/report.js:search/searchStore/export/exportStore 四处 stock_id 解析兼容数组(Array.isArray ? 原样 : 包单元素)",
|
||||
"app/service/systems/storage/report.js:search 中 stockIds 归一化改用 flat() 防御嵌套;export 内部调用 search 显式传全量分页 { page: 1, pageSize: 1000000 }(新增常量 EXPORT_FULL_PAGE_SIZE),避免默认分页截断",
|
||||
"methods/system.json:search/searchStore 的 stock_id 描述补充“兼容数组”;export/exportStore 的 where 描述补充 stock_id/stock_ids/keyword,export 新增 export_mode 参数说明;版本 0.3.81 -> 0.3.82(docMeta.version),updatedAt 保持 2026-09-04",
|
||||
"验证:开发库 where.stock_id 传 20 个 ID 的 search 返回 20 行;export 同条件任务成功并产出 832KB Excel(非空白);无数据库 schema 变更,未执行任何写库操作"
|
||||
],
|
||||
"module": "stock.report"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.04-stock.report.search-sort-fields",
|
||||
"date": "2026-09-04",
|
||||
"type": "enhanced",
|
||||
"summary": "stock.report.search 排序白名单扩充:新增 stock_id、item_code、item_name(与 begin_total、inbound_total、outbound_total、end_total 共 7 个字段),item_code/item_name 按字典序、其余按数值排序,与其他列表页面的 sort.sortField/sortOrder 用法保持一致。",
|
||||
"methods": [
|
||||
"stock.report.search",
|
||||
"stock.report.searchStore",
|
||||
"stock.report.export",
|
||||
"stock.report.exportStore"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/storage/report.js:SORT_FIELD_WHITE_LIST 扩充为 7 字段;新增 STRING_SORT_FIELD_SET(item_code/item_name 字典序比较,localeCompare),其余字段数值比较;by_space=false 分支 baseStockRows 查询新增 sw.item_code/sw.item_name,groupedList 行携带(供排序与展示回退);by_space=true 分支 baseStorageRows LEFT JOIN wms_stock_warehouse sw ON sw.id=s.stock_id 取 MAX(sw.item_code)/MAX(sw.item_name);两分支最终 item_name/item_code 展示优先 getStockDetails,回退快照值",
|
||||
"app/service/systemMethods/stock/report.js:search JSDoc 同步白名单",
|
||||
"methods/system.json:search/searchStore/export/exportStore 的 sort 参数描述同步新白名单;版本 0.3.80 -> 0.3.81(docMeta.version),updatedAt 更新为 2026-09-04",
|
||||
"无数据库 schema 变更,未执行任何写库操作"
|
||||
],
|
||||
"module": "stock.report"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.03-stock.report.search-default-pagination",
|
||||
"date": "2026-09-03",
|
||||
"type": "updated",
|
||||
"summary": "stock.report.search 分页改为默认生效:不传 data.pagination 或传非法分页时,默认按 page=1、pageSize=20 返回第一页,响应始终携带 data.pagination 分页信息(原为未传时全量返回)。分页参数同时支持顶层 page/pageSize/page_size(与其他 list 接口一致,顶层值优先)。",
|
||||
"methods": [
|
||||
"stock.report.search"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/storage/report.js:paginateList 改为默认分页语义(未传/非法回退 page=1、pageSize=20,新增模块常量 DEFAULT_PAGE_SIZE=20);两个输出分支(by_space=false/true)响应 data.pagination 恒返回;200 空列表 early return 同步携带 pagination 元信息(total=0)",
|
||||
"app/service/systemMethods/stock/report.js:search 分页参数解析与其他 list 一致——data.pagination 优先,兼容顶层 data.page 与 data.pageSize / data.page_size(顶层值覆盖 pagination 对象);searchStore(货主侧)暂不支持分页,行为不变",
|
||||
"methods/system.json:pagination 参数与 data.list/data.pagination 响应描述更新为默认分页语义,data.pagination required 改为 true,新增 page/pageSize 顶层兼容参数条目;版本 0.3.78 -> 0.3.80(docMeta.version),updatedAt 保持 2026-09-03",
|
||||
"无数据库 schema 变更,未执行任何写库操作"
|
||||
],
|
||||
"module": "stock.report"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.03-stock.report.search-pagination",
|
||||
"date": "2026-09-03",
|
||||
"type": "enhanced",
|
||||
"summary": "stock.report.search 新增分页支持:请求体 data.pagination = { page, pageSize } 时,先按现有排序规则排序再切片,仅对当前页行加载名称信息,响应 data.pagination 返回分页元信息;未传或非法分页保持全量返回(向后兼容)。",
|
||||
"methods": [
|
||||
"stock.report.search"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/storage/report.js:新增模块函数 paginateList(归一化 page/pageSize,非法/未传返回 null 表示不分页);search 方法新增 pagination 入参,两个输出分支(by_space=false/true)均改为 sortReportList 先排序 → paginateList 切片 → 仅对 pageItems 加载名称信息(getStockDetails/Store/LocationSpace 只查当前页),分页时响应 data.pagination = { page, pageSize, total, totalPages, hasPrevious, hasNext }",
|
||||
"app/service/systemMethods/stock/report.js:search 透传 data.pagination(JSDoc 同步);searchStore(货主侧)暂不支持分页",
|
||||
"性能背景:生产实测全仓 33353 SKU 无分页约 4.6~8.8s,其中 getStockDetails 名称加载为耗时大头;分页后仅当前页触发缓存/DB 查询",
|
||||
"methods/system.json:stock.report.search 新增 pagination/pagination.page/pagination.pageSize 参数与 data.pagination 响应字段;版本 0.3.77 -> 0.3.78(docMeta.version),updatedAt 保持 2026-09-03",
|
||||
"无数据库 schema 变更,未执行任何写库操作"
|
||||
],
|
||||
"module": "stock.report"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.03-workbench-barcode-removed",
|
||||
"date": "2026-09-03",
|
||||
"type": "removed",
|
||||
"summary": "下线工作台条码 barcode 相关字段(未使用):wms_workbench 删除 barcode 列及 idx_barcode、uk_warehouse_barcode 索引;workbench.list 移除 barcode 筛选与列表项、workbench.create/update 不再接收 barcode;workbench.checkBarcode 接口整体移除(方法、权限白名单、文档条目同步删除);order.packing.list / order.packing.detail 响应移除 workbench_barcode 字段(源列已删,恒为 null 无意义)。",
|
||||
"methods": [
|
||||
"workbench.list",
|
||||
"workbench.create",
|
||||
"workbench.update",
|
||||
"workbench.getWorkbenchInfo",
|
||||
"workbench.checkBarcode",
|
||||
"order.packing.list",
|
||||
"order.packing.detail"
|
||||
],
|
||||
"notes": [
|
||||
"database/migrations/20260903180000-remove-barcode-from-wms-workbench.js:先删 uk_warehouse_barcode、idx_barcode 索引再删 barcode 列(幂等 describeTable/showIndex 判断),up/down 对称(down 恢复列与索引),已在开发库执行并验证(wms_workbench 现为 12 列)",
|
||||
"app/model/workbench.js:移除 barcode 字段定义与 idx_barcode、uk_warehouse_barcode 索引声明",
|
||||
"app/service/systems/workbench.js:list 移除 where.barcode 筛选;create/update 移除 barcode 处理;删除 checkBarcodeExists;formatWorkbenchTokenInfo 移除 barcode 输出",
|
||||
"app/service/systemMethods/workbench.js:删除 checkBarcode 方法,systemInit 免权限/免日志/免鉴权白名单移除 checkBarcode",
|
||||
"app/service/systems/order_packing.js:list/detail 扁平化输出移除 workbench_barcode 字段",
|
||||
"methods/system.json:工作台模块删除 workbench.checkBarcode 条目、list/create/update/getWorkbenchInfo 条目按无 barcode 形态重写;订单打包模块 order.packing.list / order.packing.detail description 移除 workbench_barcode 说明;版本 0.3.76 -> 0.3.77(docMeta.version),updatedAt 保持 2026-09-03",
|
||||
"本次未执行任何直接 DDL/写库操作;仅通过迁移文件在开发库(127.0.0.1:3307)执行 schema 变更并验证;生产库迁移需发布时按标准流程执行"
|
||||
],
|
||||
"module": "workbench"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.03-workbench-member-bind",
|
||||
"date": "2026-09-03",
|
||||
"type": "enhanced",
|
||||
"summary": "新增接口 workbench.bindMember(免登录、免鉴权):入参用户ID(可为空,兼容非系统账号用户)+ 姓名(必填非空)+ 工作台 token,按 token 解析工作台后在 wms_workbench_member 副表新增成员行(user_id 空时仅存 user_name 姓名快照),返回新建成员行(id/workbench_id/user_id/user_name);token 无效返回失败 code=403。与已上线的 workbench.removeMember 构成成员增删闭环。",
|
||||
"methods": [
|
||||
"workbench.bindMember"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/workbench.js:新增 bindWorkbenchMember(token 校验 → 姓名必填校验 → 用户ID归一化(空/非正整数处理)→ resolveWorkbenchByToken 解析工作台 → WorkbenchMember.create),复用既有 resolveWorkbenchByToken 缓存优先逻辑",
|
||||
"app/service/systemMethods/workbench.js:新增 bindMember 薄出口,systemInit 免登录/免权限/免日志/免鉴权声明补充 bindMember",
|
||||
"methods/system.json:工作台模块新增 workbench.bindMember 条目;版本 0.3.75 -> 0.3.76(docMeta.version),updatedAt 保持 2026-09-03",
|
||||
"无数据库 schema 变更(复用 wms_workbench_member 表),未执行任何写库操作"
|
||||
],
|
||||
"module": "workbench"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.03-workbench-member-remove",
|
||||
"date": "2026-09-03",
|
||||
"type": "enhanced",
|
||||
"summary": "工作台新增成员/用户登录副表 wms_workbench_member(id/workbench_id/user_id/user_name/created_at/updated_at/deleted_at,user_id 允许为空以兼容非系统账号用户,user_name 存名称快照;索引 idx_workbench_id/idx_user_id)。新增接口 workbench.removeMember(免登录、免鉴权):入参成员行 ids 与工作台 token,按 token 解析工作台后仅软删除归属于该工作台的成员行,返回 removed 数量与 ids 列表;token 无效返回失败 code=403,无可移除成员返回 code=404。",
|
||||
"methods": [
|
||||
"workbench.removeMember"
|
||||
],
|
||||
"notes": [
|
||||
"database/migrations/20260903150000-create-wms-workbench-member.js:创建 wms_workbench_member 表(幂等 showAllTables 判断)+ idx_workbench_id/idx_user_id 索引,up/down 对称,已在开发库执行并验证(user_id 列 IS_NULLABLE=YES)",
|
||||
"app/model/workbench_member.js:新增 WorkbenchMember 模型(paranoid 软删除),associate 声明 belongsTo Workbench(as workbench)与 belongsTo Account(as user)",
|
||||
"app/model/workbench.js:associate 新增 Workbench.hasMany(WorkbenchMember, as members)",
|
||||
"app/service/systems/workbench.js:新增 resolveWorkbenchByToken(缓存 workbench:token:{token} 优先、查库兜底并回填缓存)、normalizeWorkbenchMemberIds(数组/单值/逗号串,去重仅正整数)、removeWorkbenchMember(token 解析工作台后软删除归属成员行)",
|
||||
"app/service/systemMethods/workbench.js:新增 removeMember 薄出口,systemInit 免登录/免权限/免日志/免鉴权声明补充 removeMember",
|
||||
"methods/system.json:工作台模块新增 workbench.removeMember 条目;版本 0.3.74 -> 0.3.75(docMeta.version),updatedAt 保持 2026-09-03",
|
||||
"本次未执行任何直接 DDL/写库操作;仅通过迁移文件在开发库(127.0.0.1:3307)执行 schema 变更并验证表结构;生产库迁移需发布时按标准流程执行"
|
||||
],
|
||||
"module": "workbench"
|
||||
},
|
||||
{
|
||||
"version": "2026.09.03-workbench-login-code-token",
|
||||
"date": "2026-09-03",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
91
script/backfill-batch-no-array.cjs
Normal file
91
script/backfill-batch-no-array.cjs
Normal file
@ -0,0 +1,91 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 回填 wms_wave_pick_task.batch_no_array。
|
||||
*
|
||||
* 从 wms_wave_pick_task_wave 按 task_id 聚合 wave_no(逗号分隔,按 id 升序),
|
||||
* 只更新 batch_no_array 为空的记录,幂等可重复执行。
|
||||
*
|
||||
* 用法:
|
||||
* 开发:node script/backfill-batch-no-array.cjs
|
||||
* 生产:$env:NODE_ENV='production'; node script/backfill-batch-no-array.cjs
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
// 放大 GROUP_CONCAT 上限(任务最多 20 波次,避免截断)
|
||||
await s.query('SET SESSION group_concat_max_len = 1048576');
|
||||
|
||||
const [ updateResult ] = await s.query(`
|
||||
UPDATE wms_wave_pick_task t
|
||||
JOIN (
|
||||
SELECT
|
||||
tw.task_id,
|
||||
GROUP_CONCAT(tw.wave_no ORDER BY tw.id ASC SEPARATOR ',') AS wave_nos
|
||||
FROM wms_wave_pick_task_wave tw
|
||||
WHERE tw.wave_no IS NOT NULL AND tw.wave_no <> ''
|
||||
GROUP BY tw.task_id
|
||||
) w ON w.task_id = t.id
|
||||
SET t.batch_no_array = w.wave_nos,
|
||||
t.update_time = NOW()
|
||||
WHERE t.batch_no_array IS NULL OR t.batch_no_array = ''
|
||||
`);
|
||||
|
||||
console.log('1) task_wave 聚合回填行数:', JSON.stringify(updateResult && updateResult.affectedRows !== undefined
|
||||
? updateResult.affectedRows
|
||||
: null));
|
||||
|
||||
// 回退 2:task_wave 无记录的任务,用主表 wave_id 关联 wms_wave_batch.wave_no
|
||||
const [ updateResult2 ] = await s.query(`
|
||||
UPDATE wms_wave_pick_task t
|
||||
JOIN wms_wave_batch wb ON wb.wave_id = t.wave_id
|
||||
SET t.batch_no_array = wb.wave_no,
|
||||
t.update_time = NOW()
|
||||
WHERE (t.batch_no_array IS NULL OR t.batch_no_array = '')
|
||||
AND t.wave_id > 0
|
||||
AND wb.wave_no IS NOT NULL AND wb.wave_no <> ''
|
||||
`);
|
||||
|
||||
console.log('2) wave_id→wms_wave_batch 回填行数:', JSON.stringify(updateResult2 && updateResult2.affectedRows !== undefined
|
||||
? updateResult2.affectedRows
|
||||
: null));
|
||||
|
||||
// 回退 3:仍为空的散单老数据,用主表 batch_no 兜底
|
||||
const [ updateResult3 ] = await s.query(`
|
||||
UPDATE wms_wave_pick_task t
|
||||
SET t.batch_no_array = t.batch_no,
|
||||
t.update_time = NOW()
|
||||
WHERE (t.batch_no_array IS NULL OR t.batch_no_array = '')
|
||||
AND t.batch_no IS NOT NULL AND t.batch_no <> ''
|
||||
`);
|
||||
|
||||
console.log('3) batch_no 兜底回填行数:', JSON.stringify(updateResult3 && updateResult3.affectedRows !== undefined
|
||||
? updateResult3.affectedRows
|
||||
: null));
|
||||
|
||||
const [ remaining ] = await s.query(
|
||||
"SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE batch_no_array IS NULL OR batch_no_array = ''"
|
||||
);
|
||||
console.log('回填后仍为空的任务数:', JSON.stringify(remaining));
|
||||
|
||||
const [ sample ] = await s.query(
|
||||
"SELECT id, task_no, batch_no_array FROM wms_wave_pick_task "
|
||||
+ "WHERE id IN (259, 258, 251, 249) ORDER BY id DESC"
|
||||
);
|
||||
console.log('抽样核验:', JSON.stringify(sample, null, 2));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
51
script/tmp-check-batch-no-array-backfill-scope.cjs
Normal file
51
script/tmp-check-batch-no-array-backfill-scope.cjs
Normal file
@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 回填 wms_wave_pick_task.batch_no_array(生产只读预检)。
|
||||
*
|
||||
* 从 wms_wave_pick_task_wave 按 task_id 聚合 wave_no(逗号分隔,按 id 升序),
|
||||
* 只更新 batch_no_array IS NULL 的任务,幂等可重复执行。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const q = async (sql, repl) => {
|
||||
const rows = await s.query(sql, { replacements: repl, type: Sequelize.QueryTypes.SELECT });
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
};
|
||||
|
||||
const total = await q('SELECT COUNT(*) AS c FROM wms_wave_pick_task');
|
||||
console.log('A. 任务总数:', JSON.stringify(total));
|
||||
|
||||
const nullable = await q("SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE batch_no_array IS NULL OR batch_no_array = ''");
|
||||
console.log('B. batch_no_array 为空的任务数:', JSON.stringify(nullable));
|
||||
|
||||
const backfillable = await q(
|
||||
"SELECT COUNT(DISTINCT tw.task_id) AS c FROM wms_wave_pick_task_wave tw "
|
||||
+ "INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id "
|
||||
+ "WHERE tw.wave_no IS NOT NULL AND tw.wave_no <> '' "
|
||||
+ "AND (t.batch_no_array IS NULL OR t.batch_no_array = '')"
|
||||
);
|
||||
console.log('C. 可回填的任务数(有 wave 记录且 batch_no_array 为空):', JSON.stringify(backfillable));
|
||||
|
||||
const byWaveRows = await q(
|
||||
"SELECT task_id, COUNT(*) AS c FROM wms_wave_pick_task_wave "
|
||||
+ "WHERE wave_no IS NOT NULL AND wave_no <> '' GROUP BY task_id ORDER BY c DESC LIMIT 5"
|
||||
);
|
||||
console.log('D. 单任务最多波次记录数样例:', JSON.stringify(byWaveRows));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
55
script/tmp-check-claim-backfill-source.cjs
Normal file
55
script/tmp-check-claim-backfill-source.cjs
Normal file
@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本:核实生产库历史任务的领料人回填来源。
|
||||
* 1) wms_wave_batch 波次表 claim 字段现状;
|
||||
* 2) order_operation_log 中 ORDER_WAVE_CLAIM 领料日志数量与样例。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const q = async sql => {
|
||||
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
};
|
||||
|
||||
const waveClaim = await q(
|
||||
"SELECT wave_id, wave_no, claim_operator, claim_time FROM wms_wave_batch "
|
||||
+ "WHERE wave_no IN ('B2026081500040','B2026081500038','B2026081500084','B2026081500075','B2026081500023','B2026081500022','B2026081500085') "
|
||||
+ "ORDER BY wave_id DESC"
|
||||
);
|
||||
console.log('A. 波次表 claim 现状:', JSON.stringify(waveClaim, null, 2));
|
||||
|
||||
const claimLogTotal = await q(
|
||||
"SELECT COUNT(*) AS c FROM order_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM'"
|
||||
);
|
||||
console.log('B. 领料日志总数:', JSON.stringify(claimLogTotal));
|
||||
|
||||
const claimLogSample = await q(
|
||||
"SELECT id, business_id, operation_code, operator_id, operator_name, message, create_time "
|
||||
+ "FROM order_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM' "
|
||||
+ "ORDER BY id DESC LIMIT 10"
|
||||
);
|
||||
console.log('C. 领料日志最近10条:', JSON.stringify(claimLogSample, null, 2));
|
||||
|
||||
const taskClaim = await q(
|
||||
"SELECT id, task_no, pick_mode, source, claim_operator_id, claim_operator FROM wms_wave_pick_task "
|
||||
+ "WHERE id IN (259, 251, 229) ORDER BY id DESC"
|
||||
);
|
||||
console.log('D. 任务表 claim 现状:', JSON.stringify(taskClaim, null, 2));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
48
script/tmp-check-claim-backfill-source2.cjs
Normal file
48
script/tmp-check-claim-backfill-source2.cjs
Normal file
@ -0,0 +1,48 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本 v2:核实生产库历史领料人回填来源(wms_operation_log)。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const q = async sql => {
|
||||
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
};
|
||||
|
||||
const claimLogTotal = await q(
|
||||
"SELECT COUNT(*) AS c, COUNT(DISTINCT warehouse_id) AS wh "
|
||||
+ "FROM wms_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM'"
|
||||
);
|
||||
console.log('A. 领料日志总数/仓库数:', JSON.stringify(claimLogTotal));
|
||||
|
||||
const claimLogSample = await q(
|
||||
"SELECT id, business_type, business_id, operation_code, operator_id, operator_name, message, warehouse_id, created_at "
|
||||
+ "FROM wms_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM' "
|
||||
+ "ORDER BY id DESC LIMIT 5"
|
||||
);
|
||||
console.log('B. 领料日志最近5条:', JSON.stringify(claimLogSample, null, 2));
|
||||
|
||||
const claimLogByOperator = await q(
|
||||
"SELECT operator_id, operator_name, COUNT(*) AS c FROM wms_operation_log "
|
||||
+ "WHERE operation_code = 'ORDER_WAVE_CLAIM' GROUP BY operator_id, operator_name "
|
||||
+ "ORDER BY c DESC LIMIT 10"
|
||||
);
|
||||
console.log('C. 领料日志按操作人分布:', JSON.stringify(claimLogByOperator, null, 2));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
341
script/tmp-verify-report-edge-sql.cjs
Normal file
341
script/tmp-verify-report-edge-sql.cjs
Normal file
@ -0,0 +1,341 @@
|
||||
/**
|
||||
* 临时验证脚本:对比 stock.report.search 改造后的 SQL(聚合极值)与旧 SQL(全量明细+JS归并)在开发库的结果等价性。
|
||||
* 用法:node script/tmp-verify-report-edge-sql.cjs
|
||||
* 验证完成后可删除。
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
|
||||
function buildOldEdgeMap(rows, keyFn) {
|
||||
const map = new Map();
|
||||
for (const row of rows) {
|
||||
const key = keyFn(row);
|
||||
if (!map.has(key)) {
|
||||
map.set(key, {
|
||||
first_before: row.before_quantity,
|
||||
last_after: row.after_quantity,
|
||||
});
|
||||
} else {
|
||||
map.get(key).last_after = row.after_quantity;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function buildOldPreStartMap(rows, keyFn) {
|
||||
const latest = new Map();
|
||||
for (const row of rows) {
|
||||
const key = keyFn(row);
|
||||
if (!key) continue;
|
||||
const ct = new Date(row.created_at).getTime();
|
||||
const id = Number(row.id);
|
||||
const cur = latest.get(key);
|
||||
if (!cur || ct > cur.ct || (ct === cur.ct && id > cur.id)) {
|
||||
latest.set(key, { after_quantity: row.after_quantity, ct, id });
|
||||
}
|
||||
}
|
||||
const map = new Map();
|
||||
for (const [ key, v ] of latest.entries()) {
|
||||
map.set(key, v.after_quantity);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function diffMaps(label, oldMap, newMap) {
|
||||
const keys = new Set([ ...oldMap.keys(), ...newMap.keys() ]);
|
||||
const diffs = [];
|
||||
for (const key of keys) {
|
||||
const a = oldMap.get(key);
|
||||
const b = newMap.get(key);
|
||||
const isScalarOld = a === null || typeof a !== 'object';
|
||||
const isScalarNew = b === null || typeof b !== 'object';
|
||||
if (isScalarOld || isScalarNew) {
|
||||
const av = Number(a === undefined || a === null ? 0 : a);
|
||||
const bv = Number(b === undefined || b === null ? 0 : b);
|
||||
if (av !== bv) {
|
||||
diffs.push(`${key}: old=${JSON.stringify(a)} new=${JSON.stringify(b)}`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const aFirst = a.first_before === undefined ? null : a.first_before;
|
||||
const aLast = a.last_after === undefined ? null : a.last_after;
|
||||
const bFirst = b.first_before === undefined ? null : b.first_before;
|
||||
const bLast = b.last_after === undefined ? null : b.last_after;
|
||||
if (Number(aFirst) !== Number(bFirst) || Number(aLast) !== Number(bLast)) {
|
||||
diffs.push(`${key}: old=(${aFirst},${aLast}) new=(${bFirst},${bLast})`);
|
||||
}
|
||||
}
|
||||
console.log(`[${label}] old keys=${oldMap.size}, new keys=${newMap.size}, diffs=${diffs.length}`);
|
||||
diffs.slice(0, 10).forEach(d => console.log(' DIFF ' + d));
|
||||
return diffs.length === 0;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const configFactory = require(path.join(projectRoot, 'config', 'config.local.js'));
|
||||
const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-debug' }) : configFactory;
|
||||
const client = config.mysql.clients.wms;
|
||||
|
||||
const connection = await mysql.createConnection({
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: 'utf8mb4',
|
||||
});
|
||||
|
||||
try {
|
||||
const startTime = '2026-08-01 00:00:00';
|
||||
const endTime = '2026-08-31 23:59:59';
|
||||
// by_space=false 分支用更宽区间(覆盖区间内有流水的场景)
|
||||
const wideStart = '2026-05-01 00:00:00';
|
||||
const wideEnd = '2026-09-03 00:00:00';
|
||||
|
||||
// ============ by_space=false(wms_stock_transaction) ============
|
||||
const warehouseId = 1000028;
|
||||
const oldRangeParams = [ warehouseId, wideStart, wideEnd ];
|
||||
|
||||
const oldIntervalRows = (await connection.query(
|
||||
`SELECT t.id, t.stock_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at ASC, t.id ASC`,
|
||||
oldRangeParams
|
||||
))[0];
|
||||
|
||||
const newIntervalRows = (await connection.query(
|
||||
`SELECT
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
ft.before_quantity,
|
||||
lt.after_quantity,
|
||||
ft.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
0 AS space_id,
|
||||
t.store_id,
|
||||
MIN(t.created_at) AS _min_ct,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id)
|
||||
FROM wms_stock_transaction t2
|
||||
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
|
||||
AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM wms_stock_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
|
||||
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC`,
|
||||
[ warehouseId, wideStart, wideEnd, warehouseId, wideStart, wideEnd, warehouseId, wideStart, wideEnd ]
|
||||
))[0];
|
||||
|
||||
const oldEdge = buildOldEdgeMap(oldIntervalRows, r => `${r.stock_id}_${r.store_id}`);
|
||||
const newEdge = new Map(newIntervalRows.map(r => [
|
||||
`${r.stock_id}_${r.store_id}`,
|
||||
{ first_before: r.before_quantity, last_after: r.after_quantity },
|
||||
]));
|
||||
const edgeOk = diffMaps('edge by_space=false', oldEdge, newEdge);
|
||||
|
||||
// 旧 preStart(全量历史 + JS 归并)
|
||||
const oldPreRows = (await connection.query(
|
||||
`SELECT t.id, t.stock_id, t.store_id, t.after_quantity, t.created_at
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at < ?
|
||||
ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at DESC, t.id DESC`,
|
||||
[ warehouseId, startTime ]
|
||||
))[0];
|
||||
|
||||
const newPreRows = (await connection.query(
|
||||
`SELECT
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
lt.after_quantity,
|
||||
lt.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
0 AS space_id,
|
||||
t.store_id,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at < ?
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM wms_stock_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at < ?
|
||||
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC`,
|
||||
[ warehouseId, startTime, warehouseId, startTime ]
|
||||
))[0];
|
||||
|
||||
const oldPre = buildOldPreStartMap(oldPreRows, r => `${r.stock_id}_${r.store_id}`);
|
||||
const newPre = new Map(newPreRows.map(r => [ `${r.stock_id}_${r.store_id}`, r.after_quantity ]));
|
||||
const preOk = diffMaps('preStart by_space=false', oldPre, newPre);
|
||||
|
||||
// ============ by_space=true(wms_storage_transaction) ============
|
||||
const whRows = (await connection.query(
|
||||
'SELECT warehouse_id, COUNT(*) AS cnt FROM wms_storage_transaction GROUP BY warehouse_id ORDER BY cnt DESC LIMIT 1'
|
||||
))[0];
|
||||
const storageWh = Number(whRows[0] && whRows[0].warehouse_id) || 0;
|
||||
console.log(`storage_transaction max warehouse_id=${storageWh}`);
|
||||
|
||||
const oldSpaceRows = (await connection.query(
|
||||
`SELECT t.id, t.stock_id, COALESCE(t.space_id, 0) AS space_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at
|
||||
FROM wms_storage_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
ORDER BY t.stock_id ASC, COALESCE(t.space_id, 0) ASC, t.store_id ASC, t.created_at ASC, t.id ASC`,
|
||||
[ storageWh, startTime, endTime ]
|
||||
))[0];
|
||||
|
||||
const newSpaceRows = (await connection.query(
|
||||
`SELECT
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
ft.before_quantity,
|
||||
lt.after_quantity,
|
||||
ft.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
COALESCE(t.space_id, 0) AS space_id,
|
||||
t.store_id,
|
||||
MIN(t.created_at) AS _min_ct,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM wms_storage_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_storage_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id)
|
||||
FROM wms_storage_transaction t2
|
||||
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
|
||||
AND t2.stock_id = g.stock_id AND COALESCE(t2.space_id, 0) = g.space_id AND t2.store_id = g.store_id
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_storage_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM wms_storage_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
|
||||
AND t3.stock_id = g.stock_id AND COALESCE(t3.space_id, 0) = g.space_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC`,
|
||||
[ storageWh, startTime, endTime, storageWh, startTime, endTime, storageWh, startTime, endTime ]
|
||||
))[0];
|
||||
|
||||
const oldSpaceEdge = buildOldEdgeMap(oldSpaceRows, r => `${r.stock_id}_${r.space_id}_${r.store_id}`);
|
||||
const newSpaceEdge = new Map(newSpaceRows.map(r => [
|
||||
`${r.stock_id}_${r.space_id}_${r.store_id}`,
|
||||
{ first_before: r.before_quantity, last_after: r.after_quantity },
|
||||
]));
|
||||
const spaceEdgeOk = diffMaps('edge by_space=true', oldSpaceEdge, newSpaceEdge);
|
||||
|
||||
const oldSpacePreRows = (await connection.query(
|
||||
`SELECT t.id, t.stock_id, COALESCE(t.space_id, 0) AS space_id, t.store_id, t.after_quantity, t.created_at
|
||||
FROM wms_storage_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at < ?
|
||||
ORDER BY t.stock_id ASC, COALESCE(t.space_id, 0) ASC, t.store_id ASC, t.created_at DESC, t.id DESC`,
|
||||
[ storageWh, startTime ]
|
||||
))[0];
|
||||
|
||||
const newSpacePreRows = (await connection.query(
|
||||
`SELECT
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
lt.after_quantity,
|
||||
lt.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
COALESCE(t.space_id, 0) AS space_id,
|
||||
t.store_id,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM wms_storage_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at < ?
|
||||
GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_storage_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM wms_storage_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at < ?
|
||||
AND t3.stock_id = g.stock_id AND COALESCE(t3.space_id, 0) = g.space_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC`,
|
||||
[ storageWh, startTime, storageWh, startTime ]
|
||||
))[0];
|
||||
|
||||
const oldSpacePre = buildOldPreStartMap(oldSpacePreRows, r => `${r.stock_id}_${r.space_id}_${r.store_id}`);
|
||||
const newSpacePre = new Map(newSpacePreRows.map(r => [ `${r.stock_id}_${r.space_id}_${r.store_id}`, r.after_quantity ]));
|
||||
const spacePreOk = diffMaps('preStart by_space=true', oldSpacePre, newSpacePre);
|
||||
|
||||
// ============ EXPLAIN 新 intervalEdge SQL ============
|
||||
const explainRows = (await connection.query(
|
||||
`EXPLAIN
|
||||
SELECT
|
||||
g.stock_id, g.space_id, g.store_id, ft.before_quantity, lt.after_quantity, ft.created_at
|
||||
FROM (
|
||||
SELECT t.stock_id, 0 AS space_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id) FROM wms_stock_transaction t2
|
||||
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
|
||||
AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id) FROM wms_stock_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
|
||||
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)`,
|
||||
[ warehouseId, startTime, endTime, warehouseId, startTime, endTime, warehouseId, startTime, endTime ]
|
||||
))[0];
|
||||
console.log('--- EXPLAIN new intervalEdge ---');
|
||||
explainRows.forEach(r => console.log(` ${r.id} | ${r.select_type} | ${r.table} | type=${r.type} | possible_keys=${r.possible_keys} | key=${r.key} | rows=${r.rows}`));
|
||||
|
||||
const allOk = edgeOk && preOk && spaceEdgeOk && spacePreOk;
|
||||
console.log(allOk ? '\n=== ALL PASS ===' : '\n=== FAIL ===');
|
||||
process.exit(allOk ? 0 : 1);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
})().catch(err => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user